]> git.ipfire.org Git - thirdparty/util-linux.git/blame - misc-utils/logger.c
logger: always update header when read from stdin
[thirdparty/util-linux.git] / misc-utils / logger.c
CommitLineData
6dbe3af9
KZ
1/*
2 * Copyright (c) 1983, 1993
3 * The Regents of the University of California. All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 * must display the following acknowledgement:
15 * This product includes software developed by the University of
16 * California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
7eda085c 32 *
b50945d4 33 * 1999-02-22 Arkadiusz Miśkiewicz <misiek@pld.ORG.PL>
7eda085c
KZ
34 * - added Native Language Support
35 * Sun Mar 21 1999 - Arnaldo Carvalho de Melo <acme@conectiva.com.br>
36 * - fixed strerr(errno) in gettext calls
6dbe3af9
KZ
37 */
38
6dbe3af9 39#include <errno.h>
047e2888 40#include <limits.h>
6dbe3af9
KZ
41#include <unistd.h>
42#include <stdlib.h>
5ec85227 43#include <sys/time.h>
6dbe3af9
KZ
44#include <stdio.h>
45#include <ctype.h>
46#include <string.h>
7eda085c
KZ
47#include <sys/types.h>
48#include <sys/socket.h>
66ee8158 49#include <sys/un.h>
912d6b98
WJE
50#include <arpa/inet.h>
51#include <netdb.h>
b363e86d 52#include <getopt.h>
019b9702 53#include <pwd.h>
27a9eb53 54#include <signal.h>
eaac9f88 55#include <sys/uio.h>
b363e86d 56
633493be 57#include "all-io.h"
b363e86d 58#include "c.h"
c05a80ca 59#include "closestream.h"
7eda085c 60#include "nls.h"
52a49e9a 61#include "pathnames.h"
b363e86d 62#include "strutils.h"
4b670c01 63#include "xalloc.h"
4299ed1c
KZ
64#include "strv.h"
65#include "list.h"
7f22751b 66#include "pwdutils.h"
6dbe3af9
KZ
67
68#define SYSLOG_NAMES
69#include <syslog.h>
70
ebff016a 71#ifdef HAVE_LIBSYSTEMD
03190b73 72# define SD_JOURNAL_SUPPRESS_LOCATION
d77dc29e 73# include <systemd/sd-daemon.h>
4b670c01
SK
74# include <systemd/sd-journal.h>
75#endif
76
87ee2658
ST
77#ifdef HAVE_SYS_TIMEX_H
78# include <sys/timex.h>
79#endif
80
68265d07
SK
81enum {
82 TYPE_UDP = (1 << 1),
83 TYPE_TCP = (1 << 2),
84 ALL_TYPES = TYPE_UDP | TYPE_TCP
85};
86
d77dc29e
SK
87enum {
88 AF_UNIX_ERRORS_OFF = 0,
89 AF_UNIX_ERRORS_ON,
90 AF_UNIX_ERRORS_AUTO
91};
92
98920f80 93enum {
4b670c01 94 OPT_PRIO_PREFIX = CHAR_MAX + 1,
4de2e8a0
SK
95 OPT_JOURNALD,
96 OPT_RFC3164,
d77dc29e 97 OPT_RFC5424,
3f51c10b 98 OPT_SOCKET_ERRORS,
55f5bc66 99 OPT_MSGID,
fd343a05 100 OPT_NOACT,
b6b67955 101 OPT_ID,
4299ed1c
KZ
102 OPT_STRUCTURED_DATA_ID,
103 OPT_STRUCTURED_DATA_PARAM,
b6b67955 104 OPT_OCTET_COUNT
98920f80
DJ
105};
106
4299ed1c
KZ
107/* rfc5424 structured data */
108struct structured_data {
109 char *id; /* SD-ID */
110 char **params; /* array with SD-PARAMs */
111
112 struct list_head sds;
113};
114
cfa77d26
SK
115struct logger_ctl {
116 int fd;
cfa77d26 117 int pri;
59c6ac0b 118 pid_t pid; /* zero when unwanted */
2b3f40c5 119 char *hdr; /* the syslog header (based on protocol) */
c8598d8a 120 char const *tag;
4ba84b0a 121 char *login;
55f5bc66 122 char *msgid;
c95d3209 123 char *unix_socket; /* -u <path> or default to _PATH_DEVLOG */
c68a1cb4
SK
124 char *server;
125 char *port;
126 int socket_type;
f68b8aa7 127 size_t max_message_size;
4299ed1c
KZ
128 struct list_head user_sds; /* user defined rfc5424 structured data */
129 struct list_head reserved_sds; /* standard rfc5424 structured data */
130
2b3f40c5 131 void (*syslogfp)(struct logger_ctl *ctl);
4299ed1c 132
4de2e8a0 133 unsigned int
d77dc29e 134 unix_socket_errors:1, /* whether to report or not errors */
fd343a05 135 noact:1, /* do not write to sockets */
9e930041 136 prio_prefix:1, /* read priority from input */
d77dc29e
SK
137 stderr_printout:1, /* output message to stderr */
138 rfc5424_time:1, /* include time stamp */
139 rfc5424_tq:1, /* include time quality markup */
ae6846b8 140 rfc5424_host:1, /* include hostname */
b6b67955
AB
141 skip_empty_lines:1, /* do not send empty lines when processing files */
142 octet_count:1; /* use RFC6587 octet counting */
cfa77d26
SK
143};
144
e92d55e6 145#define is_connected(_ctl) ((_ctl)->fd >= 0)
caf6ac6e
KZ
146static void logger_reopen(struct logger_ctl *ctl);
147
ef5fb280
KZ
148/*
149 * For tests we want to be able to control datetime outputs
150 */
151#ifdef TEST_LOGGER
152static inline int logger_gettimeofday(struct timeval *tv, struct timezone *tz)
153{
154 char *str = getenv("LOGGER_TEST_TIMEOFDAY");
155 uintmax_t sec, usec;
156
157 if (str && sscanf(str, "%ju.%ju", &sec, &usec) == 2) {
158 tv->tv_sec = sec;
159 tv->tv_usec = usec;
98e90a49 160 return tv->tv_sec >= 0 && tv->tv_usec >= 0 ? 0 : -EINVAL;
ef5fb280
KZ
161 }
162
163 return gettimeofday(tv, tz);
164}
165
166static inline char *logger_xgethostname(void)
167{
168 char *str = getenv("LOGGER_TEST_HOSTNAME");
169 return str ? xstrdup(str) : xgethostname();
170}
171
172static inline pid_t logger_getpid(void)
173{
174 char *str = getenv("LOGGER_TEST_GETPID");
175 unsigned int pid;
176
177 if (str && sscanf(str, "%u", &pid) == 1)
178 return pid;
179 return getpid();
180}
181
182
183#undef HAVE_NTP_GETTIME /* force to default non-NTP */
184
185#else /* !TEST_LOGGER */
186# define logger_gettimeofday(x, y) gettimeofday(x, y)
187# define logger_xgethostname xgethostname
188# define logger_getpid getpid
189#endif
190
191
f5fceb40 192static int decode(const char *name, const CODE *codetab)
82054b1d 193{
f5fceb40 194 register const CODE *c;
82054b1d 195
4d7d1af6
SK
196 if (name == NULL || *name == '\0')
197 return -1;
198 if (isdigit(*name)) {
199 int num;
200 char *end = NULL;
201
8d341322 202 errno = 0;
4d7d1af6
SK
203 num = strtol(name, &end, 10);
204 if (errno || name == end || (end && *end))
205 return -1;
206 for (c = codetab; c->c_name; c++)
207 if (num == c->c_val)
208 return num;
209 return -1;
210 }
82054b1d
DR
211 for (c = codetab; c->c_name; c++)
212 if (!strcasecmp(name, c->c_name))
213 return (c->c_val);
214
215 return -1;
216}
217
218static int pencode(char *s)
219{
2e0fd22d
SK
220 int facility, level;
221 char *separator;
222
7241dda1
KZ
223 assert(s);
224
2e0fd22d
SK
225 separator = strchr(s, '.');
226 if (separator) {
227 *separator = '\0';
228 facility = decode(s, facilitynames);
229 if (facility < 0)
230 errx(EXIT_FAILURE, _("unknown facility name: %s"), s);
231 s = ++separator;
232 } else
233 facility = LOG_USER;
234 level = decode(s, prioritynames);
235 if (level < 0)
236 errx(EXIT_FAILURE, _("unknown priority name: %s"), s);
9a13f968
SK
237 if (facility == LOG_KERN)
238 facility = LOG_USER; /* kern is forbidden */
2e0fd22d 239 return ((level & LOG_PRIMASK) | (facility & LOG_FACMASK));
82054b1d
DR
240}
241
fc20393c 242static int unix_socket(struct logger_ctl *ctl, const char *path, int *socket_type)
fe6999da 243{
4813a521 244 int fd = -1, i, type = -1;
fe6999da 245 static struct sockaddr_un s_addr; /* AF_UNIX address of local logger */
7eda085c 246
68265d07
SK
247 if (strlen(path) >= sizeof(s_addr.sun_path))
248 errx(EXIT_FAILURE, _("openlog %s: pathname too long"), path);
7eda085c 249
fe6999da 250 s_addr.sun_family = AF_UNIX;
68265d07
SK
251 strcpy(s_addr.sun_path, path);
252
253 for (i = 2; i; i--) {
254 int st = -1;
49999d6a 255
fc20393c 256 if (i == 2 && *socket_type & TYPE_UDP) {
68265d07 257 st = SOCK_DGRAM;
fc20393c
KZ
258 type = TYPE_UDP;
259 }
260 if (i == 1 && *socket_type & TYPE_TCP) {
68265d07 261 st = SOCK_STREAM;
fc20393c
KZ
262 type = TYPE_TCP;
263 }
68265d07
SK
264 if (st == -1 || (fd = socket(AF_UNIX, st, 0)) == -1)
265 continue;
fe6999da
SK
266 if (connect(fd, (struct sockaddr *)&s_addr, sizeof(s_addr)) == -1) {
267 close(fd);
68265d07 268 continue;
fe6999da 269 }
68265d07 270 break;
fe6999da 271 }
7eda085c 272
d77dc29e
SK
273 if (i == 0) {
274 if (ctl->unix_socket_errors)
275 err(EXIT_FAILURE, _("socket %s"), path);
28bad822 276
e92d55e6 277 /* write_output() will try to reconnect */
28bad822 278 return -1;
d77dc29e 279 }
fc20393c
KZ
280
281 /* replace ALL_TYPES with the real TYPE_* */
282 if (type > 0 && type != *socket_type)
283 *socket_type = type;
fe6999da 284 return fd;
7eda085c
KZ
285}
286
fc20393c 287static int inet_socket(const char *servername, const char *port, int *socket_type)
68265d07 288{
fc20393c 289 int fd, errcode, i, type = -1;
24f4db69 290 struct addrinfo hints, *res;
68265d07
SK
291 const char *p = port;
292
293 for (i = 2; i; i--) {
294 memset(&hints, 0, sizeof(hints));
fc20393c 295 if (i == 2 && *socket_type & TYPE_UDP) {
68265d07 296 hints.ai_socktype = SOCK_DGRAM;
fc20393c 297 type = TYPE_UDP;
68265d07
SK
298 if (port == NULL)
299 p = "syslog";
300 }
fc20393c 301 if (i == 1 && *socket_type & TYPE_TCP) {
68265d07 302 hints.ai_socktype = SOCK_STREAM;
fc20393c 303 type = TYPE_TCP;
68265d07
SK
304 if (port == NULL)
305 p = "syslog-conn";
306 }
307 if (hints.ai_socktype == 0)
308 continue;
309 hints.ai_family = AF_UNSPEC;
310 errcode = getaddrinfo(servername, p, &hints, &res);
311 if (errcode != 0)
4ce393f4 312 errx(EXIT_FAILURE, _("failed to resolve name %s port %s: %s"),
68265d07
SK
313 servername, p, gai_strerror(errcode));
314 if ((fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol)) == -1) {
315 freeaddrinfo(res);
316 continue;
317 }
318 if (connect(fd, res->ai_addr, res->ai_addrlen) == -1) {
319 freeaddrinfo(res);
320 close(fd);
321 continue;
322 }
24f4db69 323
68265d07
SK
324 freeaddrinfo(res);
325 break;
326 }
912d6b98 327
68265d07 328 if (i == 0)
4ce393f4 329 errx(EXIT_FAILURE, _("failed to connect to %s port %s"), servername, p);
49999d6a 330
fc20393c
KZ
331 /* replace ALL_TYPES with the real TYPE_* */
332 if (type > 0 && type != *socket_type)
333 *socket_type = type;
912d6b98
WJE
334 return fd;
335}
68265d07 336
ebff016a 337#ifdef HAVE_LIBSYSTEMD
fd343a05 338static int journald_entry(struct logger_ctl *ctl, FILE *fp)
4b670c01
SK
339{
340 struct iovec *iovec;
341 char *buf = NULL;
342 ssize_t sz;
1c4a2600 343 int n, lines = 0, vectors = 8, ret = 0, msgline = -1;
4b670c01
SK
344 size_t dummy = 0;
345
346 iovec = xmalloc(vectors * sizeof(struct iovec));
1c4a2600 347 while (1) {
4b670c01
SK
348 buf = NULL;
349 sz = getline(&buf, &dummy, fp);
f1f5f21e
SK
350 if (sz == -1 ||
351 (sz = rtrim_whitespace((unsigned char *) buf)) == 0) {
4e5411f6 352 free(buf);
4b670c01 353 break;
4e5411f6 354 }
1c4a2600
KZ
355
356 if (strncmp(buf, "MESSAGE=", 8) == 0) {
357 if (msgline == -1)
358 msgline = lines; /* remember the first message */
359 else {
360 char *p = xrealloc(iovec[msgline].iov_base,
361 iovec[msgline].iov_len + sz - 8 + 2);
362
363 iovec[msgline].iov_base = p;
364 p += iovec[msgline].iov_len;
365 *p++ = '\n';
366 memcpy(p, buf + 8, sz - 8);
367 free(buf);
368
369 iovec[msgline].iov_len += sz - 8 + 1;
370 continue;
371 }
372 }
373
4b670c01
SK
374 if (lines == vectors) {
375 vectors *= 2;
047e2888
SK
376 if (IOV_MAX < vectors)
377 errx(EXIT_FAILURE, _("maximum input lines (%d) exceeded"), IOV_MAX);
4b670c01
SK
378 iovec = xrealloc(iovec, vectors * sizeof(struct iovec));
379 }
380 iovec[lines].iov_base = buf;
381 iovec[lines].iov_len = sz;
1c4a2600 382 ++lines;
4b670c01 383 }
fd343a05
KZ
384
385 if (!ctl->noact)
386 ret = sd_journal_sendv(iovec, lines);
387 if (ctl->stderr_printout) {
388 for (n = 0; n < lines; n++)
389 fprintf(stderr, "%s\n", (char *) iovec[n].iov_base);
390 }
4b670c01
SK
391 for (n = 0; n < lines; n++)
392 free(iovec[n].iov_base);
393 free(iovec);
394 return ret;
395}
396#endif
397
3070ca77
RG
398/* this creates a timestamp based on current time according to the
399 * fine rules of RFC3164, most importantly it ensures in a portable
400 * way that the month day is correctly written (with a SP instead
401 * of a leading 0). The function uses a static buffer which is
402 * overwritten on the next call (just like ctime() does).
403 */
c8598d8a 404static char const *rfc3164_current_time(void)
3070ca77
RG
405{
406 static char time[32];
407 struct timeval tv;
3160589d 408 struct tm tm;
c8598d8a 409 static char const * const monthnames[] = {
9a13f968
SK
410 "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
411 "Sep", "Oct", "Nov", "Dec"
412 };
3070ca77 413
ef5fb280 414 logger_gettimeofday(&tv, NULL);
3160589d 415 localtime_r(&tv.tv_sec, &tm);
3070ca77 416 snprintf(time, sizeof(time),"%s %2d %2.2d:%2.2d:%2.2d",
3160589d
SK
417 monthnames[tm.tm_mon], tm.tm_mday,
418 tm.tm_hour, tm.tm_min, tm.tm_sec);
3070ca77
RG
419 return time;
420}
421
17c8aa1d 422#define next_iovec(ary, idx) __extension__ ({ \
b9710f1f 423 assert(ARRAY_SIZE(ary) > (size_t)idx); \
17c8aa1d
KZ
424 assert(idx >= 0); \
425 &ary[idx++]; \
426})
427
428#define iovec_add_string(ary, idx, str, len) \
429 do { \
430 struct iovec *v = next_iovec(ary, idx); \
431 v->iov_base = (void *) str; \
432 v->iov_len = len ? len : strlen(str); \
433 } while (0)
434
435#define iovec_memcmp(ary, idx, str, len) \
436 memcmp((ary)[(idx) - 1].iov_base, str, len)
437
940a14a3 438/* writes generated buffer to desired destination. For TCP syslog,
b6b67955
AB
439 * we use RFC6587 octet-stuffing (unless octet-counting is selected).
440 * This is not great, but doing full blown RFC5425 (TLS) looks like
441 * it is too much for the logger utility. If octet-counting is
442 * selected, we use that.
940a14a3 443 */
caf6ac6e 444static void write_output(struct logger_ctl *ctl, const char *const msg)
4be84306 445{
17c8aa1d
KZ
446 struct iovec iov[4];
447 int iovlen = 0;
448 char *octet = NULL;
449
e92d55e6
KZ
450 /* initial connect failed? */
451 if (!ctl->noact && !is_connected(ctl))
452 logger_reopen(ctl);
453
17c8aa1d
KZ
454 /* 1) octen count */
455 if (ctl->octet_count) {
456 size_t len = xasprintf(&octet, "%zu ", strlen(ctl->hdr) + strlen(msg));
457 iovec_add_string(iov, iovlen, octet, len);
458 }
459
460 /* 2) header */
461 iovec_add_string(iov, iovlen, ctl->hdr, 0);
462
463 /* 3) message */
464 iovec_add_string(iov, iovlen, msg, 0);
fd343a05 465
e92d55e6 466 if (!ctl->noact && is_connected(ctl)) {
2ec100a1 467 struct msghdr message = { 0 };
4199e989 468#ifdef SCM_CREDENTIALS
27a9eb53
KZ
469 struct cmsghdr *cmhp;
470 struct ucred *cred;
471 union {
472 struct cmsghdr cmh;
473 char control[CMSG_SPACE(sizeof(struct ucred))];
474 } cbuf;
4199e989 475#endif
17c8aa1d
KZ
476
477 /* 4) add extra \n to make sure message is terminated */
478 if ((ctl->socket_type == TYPE_TCP) && !ctl->octet_count)
479 iovec_add_string(iov, iovlen, "\n", 1);
94a28496 480
2ec100a1
SK
481 message.msg_iov = iov;
482 message.msg_iovlen = iovlen;
94a28496 483
4199e989 484#ifdef SCM_CREDENTIALS
27a9eb53
KZ
485 /* syslog/journald may follow local socket credentials rather
486 * than in the message PID. If we use --id as root than we can
487 * force kernel to accept another valid PID than the real logger(1)
488 * PID.
489 */
490 if (ctl->pid && !ctl->server && ctl->pid != getpid()
491 && geteuid() == 0 && kill(ctl->pid, 0) == 0) {
492
2ec100a1
SK
493 message.msg_control = cbuf.control;
494 message.msg_controllen = CMSG_SPACE(sizeof(struct ucred));
27a9eb53 495
2ec100a1 496 cmhp = CMSG_FIRSTHDR(&message);
27a9eb53
KZ
497 cmhp->cmsg_len = CMSG_LEN(sizeof(struct ucred));
498 cmhp->cmsg_level = SOL_SOCKET;
499 cmhp->cmsg_type = SCM_CREDENTIALS;
500 cred = (struct ucred *) CMSG_DATA(cmhp);
501
502 cred->pid = ctl->pid;
503 }
4199e989 504#endif
caf6ac6e
KZ
505 /* Note that logger(1) maybe executed for long time (as pipe
506 * reader) and connection endpoint (syslogd) may be restarted.
507 *
508 * The libc syslog() function reconnects on failed send().
509 * Let's do the same to be robust. [kzak -- Oct 2017]
87ac63c9
KZ
510 *
511 * MSG_NOSIGNAL is POSIX.1-2008 compatible, but it for example
73afd3f8 512 * not supported by apple-darwin15.6.0.
caf6ac6e 513 */
87ac63c9
KZ
514#ifndef MSG_NOSIGNAL
515# define MSG_NOSIGNAL 0
516#endif
caf6ac6e
KZ
517 if (sendmsg(ctl->fd, &message, MSG_NOSIGNAL) < 0) {
518 logger_reopen(ctl);
519 if (sendmsg(ctl->fd, &message, MSG_NOSIGNAL) < 0)
520 warn(_("send message failed"));
521 }
fd343a05 522 }
17c8aa1d
KZ
523
524 if (ctl->stderr_printout) {
525 /* make sure it's terminated for stderr */
526 if (iovec_memcmp(iov, iovlen, "\n", 1) != 0)
527 iovec_add_string(iov, iovlen, "\n", 1);
528
529 ignore_result( writev(STDERR_FILENO, iov, iovlen) );
530 }
531
532 free(octet);
4be84306
RG
533}
534
d5f93061 535#define NILVALUE "-"
2b3f40c5 536static void syslog_rfc3164_header(struct logger_ctl *const ctl)
195c3603 537{
d5f93061 538 char pid[30], *hostname;
d8b616c2 539
77c3bd5b 540 *pid = '\0';
59c6ac0b
KZ
541 if (ctl->pid)
542 snprintf(pid, sizeof(pid), "[%d]", ctl->pid);
852feb72 543
ef5fb280 544 if ((hostname = logger_xgethostname())) {
d5f93061
SK
545 char *dot = strchr(hostname, '.');
546 if (dot)
547 *dot = '\0';
548 } else
549 hostname = xstrdup(NILVALUE);
852feb72 550
2a82207f
KZ
551 xasprintf(&ctl->hdr, "<%d>%.15s %s %.200s%s: ",
552 ctl->pri, rfc3164_current_time(), hostname, ctl->tag, pid);
852feb72
KZ
553
554 free(hostname);
7eda085c
KZ
555}
556
4299ed1c
KZ
557static inline struct list_head *get_user_structured_data(struct logger_ctl *ctl)
558{
559 return &ctl->user_sds;
560}
561
562static inline struct list_head *get_reserved_structured_data(struct logger_ctl *ctl)
563{
564 return &ctl->reserved_sds;
565}
566
567static int has_structured_data_id(struct list_head *ls, const char *id)
568{
569 struct list_head *p;
570
571 if (!ls || list_empty(ls))
572 return 0;
573
574 list_for_each(p, ls) {
575 struct structured_data *sd = list_entry(p, struct structured_data, sds);
576 if (sd->id && strcmp(sd->id, id) == 0)
577 return 1;
578 }
579
580 return 0;
581}
582
583static void add_structured_data_id(struct list_head *ls, const char *id)
584{
585 struct structured_data *sd;
586
587 assert(id);
588
589 if (has_structured_data_id(ls, id))
590 errx(EXIT_FAILURE, _("structured data ID '%s' is not unique"), id);
591
592 sd = xcalloc(1, sizeof(*sd));
593 INIT_LIST_HEAD(&sd->sds);
594 sd->id = xstrdup(id);
595
596 list_add_tail(&sd->sds, ls);
597}
598
599static void add_structured_data_param(struct list_head *ls, const char *param)
600{
601 struct structured_data *sd;
602
603 if (list_empty(ls))
426cdc0a 604 errx(EXIT_FAILURE, _("--sd-id was not specified for --sd-param %s"), param);
4299ed1c
KZ
605
606 assert(param);
607
608 sd = list_last_entry(ls, struct structured_data, sds);
609
610 if (strv_extend(&sd->params, param))
611 err_oom();
612}
613
e71d44a4
KZ
614static void __attribute__ ((__format__ (__printf__, 2, 3)))
615 add_structured_data_paramf(struct list_head *ls, const char *fmt, ...)
4299ed1c
KZ
616{
617 struct structured_data *sd;
618 va_list ap;
619 int x;
620
621 assert(!list_empty(ls));
622 assert(fmt);
623
624 sd = list_last_entry(ls, struct structured_data, sds);
625 va_start(ap, fmt);
626 x = strv_extendv(&sd->params, fmt, ap);
627 va_end(ap);
628
629 if (x)
630 err_oom();
631}
632
633static char *strdup_structured_data(struct structured_data *sd)
634{
635 char *res, *tmp;
636
637 if (strv_isempty(sd->params))
638 return NULL;
639
640 xasprintf(&res, "[%s %s]", sd->id,
641 (tmp = strv_join(sd->params, " ")));
642 free(tmp);
643 return res;
644}
645
646static char *strdup_structured_data_list(struct list_head *ls)
647{
648 struct list_head *p;
649 char *res = NULL;
650
651 list_for_each(p, ls) {
652 struct structured_data *sd = list_entry(p, struct structured_data, sds);
653 char *one = strdup_structured_data(sd);
654 char *tmp = res;
655
656 if (!one)
657 continue;
8420463b 658 res = strconcat(tmp, one);
4299ed1c
KZ
659 free(tmp);
660 free(one);
661 }
662
663 return res;
664}
665
666static char *get_structured_data_string(struct logger_ctl *ctl)
667{
668 char *sys = NULL, *usr = NULL, *res;
669
670 if (!list_empty(&ctl->reserved_sds))
671 sys = strdup_structured_data_list(&ctl->reserved_sds);
672 if (!list_empty(&ctl->user_sds))
673 usr = strdup_structured_data_list(&ctl->user_sds);
674
675 if (sys && usr) {
8420463b 676 res = strconcat(sys, usr);
4299ed1c
KZ
677 free(sys);
678 free(usr);
679 } else
680 res = sys ? sys : usr;
681
682 return res;
683}
684
685static int valid_structured_data_param(const char *str)
686{
6ab10df2 687 char *s;
4299ed1c
KZ
688 char *eq = strchr(str, '='),
689 *qm1 = strchr(str, '"'),
6ab10df2 690 *qm2 = qm1 ? ul_strchr_escaped(qm1 + 1, '"') : NULL;
4299ed1c 691
6ab10df2
KZ
692 /* something is missing */
693 if (!eq || !qm1 || !qm2)
4299ed1c
KZ
694 return 0;
695
6ab10df2
KZ
696 /* ']' need to be escaped */
697 for (s = qm1 + 1; s && *s; ) {
698 char *p = strchr(s, ']');
699 if (!p)
700 break;
701 if (p > qm2 || p == ul_strchr_escaped(s, ']'))
702 return 0;
703 s = p + 1;
704 }
705
706 /* '\' is allowed only before '[]"\' chars */
707 for (s = qm1 + 1; s && *s; ) {
708 char *p = strchr(s, '\\');
709 if (!p)
710 break;
711 if (!strchr("[]\"\\", *(p + 1)))
712 return 0;
713 s = p + 1;
714 if (*s == '\\')
715 s++;
716 }
717
4299ed1c
KZ
718 /* foo="bar" */
719 return eq > str && eq < qm1 && eq + 1 == qm1 && qm1 < qm2 && *(qm2 + 1) == '\0';
720}
721
722/* SD-ID format:
723 * name@<private enterprise number>, e.g., "ourSDID@32473"
724 */
725static int valid_structured_data_id(const char *str)
726{
727 char *at = strchr(str, '@');
728 const char *p;
729
730 /* standardized IDs without @<digits> */
731 if (!at && (strcmp(str, "timeQuality") == 0 ||
732 strcmp(str, "origin") == 0 ||
733 strcmp(str, "meta") == 0))
734 return 1;
735
736 if (!at || at == str || !*(at + 1))
737 return 0;
6d8a31f6
KZ
738
739 /* <digits> or <digits>.<digits>[...] */
740 for (p = at + 1; p && *p; p++) {
741 const char *end;
742
743 if (isdigit_strend(p, &end))
744 break; /* only digits in the string */
745
746 if (end == NULL || end == p ||
747 *end != '.' || *(end + 1) == '\0')
748 return 0;
749 p = end;
750 }
4299ed1c
KZ
751
752 /* check for forbidden chars in the <name> */
753 for (p = str; p < at; p++) {
754 if (*p == '[' || *p == '=' || *p == '"' || *p == '@')
755 return 0;
bae57b5a 756 if (isblank((unsigned char) *p) || iscntrl((unsigned char) *p))
4299ed1c
KZ
757 return 0;
758 }
759 return 1;
760}
761
762
763/* Some field mappings may be controversial, thus I give the reason
4826184b
RG
764 * why this specific mapping was used:
765 * APP-NAME <-- tag
766 * Some may argue that "logger" is a better fit, but we think
767 * this is better inline of what other implementations do. In
768 * rsyslog, for example, the TAG value is populated from APP-NAME.
769 * PROCID <-- pid
770 * This is a relatively straightforward interpretation from
771 * RFC5424, sect. 6.2.6.
55f5bc66 772 * MSGID <-- msgid (from --msgid)
4826184b
RG
773 * One may argue that the string "logger" would be better suited
774 * here so that a receiver can identify the sender process.
775 * However, this does not sound like a good match to RFC5424,
55f5bc66 776 * sect. 6.2.7.
4826184b
RG
777 * Note that appendix A.1 of RFC5424 does not provide clear guidance
778 * of how these fields should be used. This is the case because the
779 * IETF working group couldn't arrive at a clear agreement when we
780 * specified RFC5424. The rest of the field mappings should be
781 * pretty clear from RFC5424. -- Rainer Gerhards, 2015-03-10
782 */
2b3f40c5 783static void syslog_rfc5424_header(struct logger_ctl *const ctl)
4de2e8a0 784{
9a13f968
SK
785 char *time;
786 char *hostname;
c8598d8a 787 char const *app_name = ctl->tag;
9a13f968
SK
788 char *procid;
789 char *const msgid = xstrdup(ctl->msgid ? ctl->msgid : NILVALUE);
4299ed1c
KZ
790 char *structured = NULL;
791 struct list_head *sd;
9a13f968 792
4de2e8a0 793 if (ctl->rfc5424_time) {
4826184b 794 struct timeval tv;
f6b6beaf 795 struct tm tm;
9a13f968 796
ef5fb280 797 logger_gettimeofday(&tv, NULL);
f6b6beaf 798 if (localtime_r(&tv.tv_sec, &tm) != NULL) {
852feb72 799 char fmt[64];
2f267611 800 const size_t i = strftime(fmt, sizeof(fmt),
f6b6beaf 801 "%Y-%m-%dT%H:%M:%S.%%06u%z ", &tm);
2f267611 802 /* patch TZ info to comply with RFC3339 (we left SP at end) */
9a13f968
SK
803 fmt[i - 1] = fmt[i - 2];
804 fmt[i - 2] = fmt[i - 3];
805 fmt[i - 3] = ':';
4826184b 806 xasprintf(&time, fmt, tv.tv_usec);
4de2e8a0
SK
807 } else
808 err(EXIT_FAILURE, _("localtime() failed"));
4826184b 809 } else
7ff6948e 810 time = xstrdup(NILVALUE);
852feb72 811
4de2e8a0 812 if (ctl->rfc5424_host) {
ef5fb280 813 if (!(hostname = logger_xgethostname()))
d5f93061 814 hostname = xstrdup(NILVALUE);
4de2e8a0
SK
815 /* Arbitrary looking 'if (var < strlen()) checks originate from
816 * RFC 5424 - 6 Syslog Message Format definition. */
817 if (255 < strlen(hostname))
818 errx(EXIT_FAILURE, _("hostname '%s' is too long"),
819 hostname);
4826184b 820 } else
7ff6948e 821 hostname = xstrdup(NILVALUE);
852feb72 822
2b3f40c5
RG
823 if (48 < strlen(ctl->tag))
824 errx(EXIT_FAILURE, _("tag '%s' is too long"), ctl->tag);
852feb72 825
59c6ac0b 826 if (ctl->pid)
4826184b
RG
827 xasprintf(&procid, "%d", ctl->pid);
828 else
7ff6948e 829 procid = xstrdup(NILVALUE);
4826184b 830
4299ed1c
KZ
831 sd = get_reserved_structured_data(ctl);
832
9e930041 833 /* time quality structured data (maybe overwritten by --sd-id timeQuality) */
4299ed1c
KZ
834 if (ctl->rfc5424_tq && !has_structured_data_id(sd, "timeQuality")) {
835
836 add_structured_data_id(sd, "timeQuality");
837 add_structured_data_param(sd, "tzKnown=\"1\"");
838
7d3a07d8
KZ
839#ifdef HAVE_NTP_GETTIME
840 struct ntptimeval ntptv;
9a13f968 841
4299ed1c
KZ
842 if (ntp_gettime(&ntptv) == TIME_OK) {
843 add_structured_data_param(sd, "isSynced=\"1\"");
844 add_structured_data_paramf(sd, "syncAccuracy=\"%ld\"", ntptv.maxerror);
845 } else
87ee2658 846#endif
4299ed1c
KZ
847 add_structured_data_paramf(sd, "isSynced=\"0\"");
848 }
849
850 /* convert all structured data to string */
851 structured = get_structured_data_string(ctl);
852 if (!structured)
853 structured = xstrdup(NILVALUE);
852feb72 854
2a82207f
KZ
855 xasprintf(&ctl->hdr, "<%d>1 %s %s %s %s %s %s ",
856 ctl->pri,
857 time,
858 hostname,
859 app_name,
860 procid,
861 msgid,
862 structured);
852feb72 863
4826184b 864 free(time);
852feb72 865 free(hostname);
4826184b
RG
866 /* app_name points to ctl->tag, do NOT free! */
867 free(procid);
868 free(msgid);
4299ed1c 869 free(structured);
4de2e8a0
SK
870}
871
eb2306e6 872static void parse_rfc5424_flags(struct logger_ctl *ctl, char *s)
4de2e8a0
SK
873{
874 char *in, *tok;
875
eb2306e6 876 in = s;
4de2e8a0
SK
877 while ((tok = strtok(in, ","))) {
878 in = NULL;
879 if (!strcmp(tok, "notime")) {
880 ctl->rfc5424_time = 0;
881 ctl->rfc5424_tq = 0;
882 } else if (!strcmp(tok, "notq"))
883 ctl->rfc5424_tq = 0;
884 else if (!strcmp(tok, "nohost"))
885 ctl->rfc5424_host = 0;
886 else
887 warnx(_("ignoring unknown option argument: %s"), tok);
888 }
889}
890
eb2306e6 891static int parse_unix_socket_errors_flags(char *s)
d77dc29e 892{
eb2306e6 893 if (!strcmp(s, "off"))
d77dc29e 894 return AF_UNIX_ERRORS_OFF;
eb2306e6 895 if (!strcmp(s, "on"))
d77dc29e 896 return AF_UNIX_ERRORS_ON;
eb2306e6 897 if (!strcmp(s, "auto"))
d77dc29e 898 return AF_UNIX_ERRORS_AUTO;
eb2306e6 899 warnx(_("invalid argument: %s: using automatic errors"), s);
d77dc29e
SK
900 return AF_UNIX_ERRORS_AUTO;
901}
902
2b3f40c5 903static void syslog_local_header(struct logger_ctl *const ctl)
cfa77d26 904{
3070ca77 905 char pid[32];
1d575033 906
59c6ac0b
KZ
907 if (ctl->pid)
908 snprintf(pid, sizeof(pid), "[%d]", ctl->pid);
1d575033
SK
909 else
910 pid[0] = '\0';
911
2a82207f
KZ
912 xasprintf(&ctl->hdr, "<%d>%s %s%s: ", ctl->pri, rfc3164_current_time(),
913 ctl->tag, pid);
2b3f40c5
RG
914}
915
916static void generate_syslog_header(struct logger_ctl *const ctl)
917{
918 free(ctl->hdr);
2d4c226d 919 ctl->hdr = NULL;
2b3f40c5 920 ctl->syslogfp(ctl);
cfa77d26
SK
921}
922
caf6ac6e
KZ
923/* just open, nothing else */
924static void __logger_open(struct logger_ctl *ctl)
c68a1cb4
SK
925{
926 if (ctl->server) {
fc20393c 927 ctl->fd = inet_socket(ctl->server, ctl->port, &ctl->socket_type);
4a8919a4
PP
928 } else {
929 if (!ctl->unix_socket)
930 ctl->unix_socket = _PATH_DEVLOG;
7dc20804 931
fc20393c 932 ctl->fd = unix_socket(ctl, ctl->unix_socket, &ctl->socket_type);
4a8919a4 933 }
caf6ac6e
KZ
934}
935
936/* open and initialize relevant @ctl tuff */
937static void logger_open(struct logger_ctl *ctl)
938{
939 __logger_open(ctl);
940
941 if (!ctl->syslogfp)
942 ctl->syslogfp = ctl->server ? syslog_rfc5424_header :
943 syslog_local_header;
9a13f968 944 if (!ctl->tag)
4ba84b0a 945 ctl->tag = ctl->login = xgetlogin();
7f22751b
ÉN
946 if (!ctl->tag)
947 ctl->tag = "<someone>";
c68a1cb4
SK
948}
949
caf6ac6e
KZ
950/* re-open; usually after failed connection */
951static void logger_reopen(struct logger_ctl *ctl)
952{
953 if (ctl->fd != -1)
954 close(ctl->fd);
955 ctl->fd = -1;
956
957 __logger_open(ctl);
958}
959
960static void logger_command_line(struct logger_ctl *ctl, char **argv)
c68a1cb4 961{
2b3f40c5
RG
962 /* note: we never re-generate the syslog header here, even if we
963 * generate multiple messages. If so, we think it is the right thing
964 * to do to report them with the same timestamp, as the user actually
965 * intended to send a single message.
966 */
f68b8aa7 967 char *const buf = xmalloc(ctl->max_message_size + 1);
c68a1cb4 968 char *p = buf;
f68b8aa7 969 const char *endp = buf + ctl->max_message_size - 1;
c68a1cb4
SK
970 size_t len;
971
972 while (*argv) {
973 len = strlen(*argv);
974 if (endp < p + len && p != buf) {
2b3f40c5 975 write_output(ctl, buf);
c68a1cb4
SK
976 p = buf;
977 }
f68b8aa7
RG
978 if (ctl->max_message_size < len) {
979 (*argv)[ctl->max_message_size] = '\0'; /* truncate */
2b3f40c5 980 write_output(ctl, *argv++);
c68a1cb4
SK
981 continue;
982 }
983 if (p != buf)
984 *p++ = ' ';
985 memmove(p, *argv++, len);
986 *(p += len) = '\0';
987 }
988 if (p != buf)
2b3f40c5 989 write_output(ctl, buf);
c3dd2ecd 990 free(buf);
c68a1cb4
SK
991}
992
993static void logger_stdin(struct logger_ctl *ctl)
994{
31fb9453 995 /* note: we re-generate the syslog header for each log message to
7db029e5 996 * update header timestamps and to reflect possible priority changes.
7db029e5 997 */
c68a1cb4 998 int default_priority = ctl->pri;
58e4ee08 999 char *buf = xmalloc(ctl->max_message_size + 2 + 2);
b9ef27f5
RG
1000 int pri;
1001 int c;
1002 size_t i;
1003
1004 c = getchar();
1005 while (c != EOF) {
1006 i = 0;
da0788fb
SK
1007 if (ctl->prio_prefix && c == '<') {
1008 pri = 0;
1009 buf[i++] = c;
1010 while (isdigit(c = getchar()) && pri <= 191) {
1011 buf[i++] = c;
1012 pri = pri * 10 + c - '0';
1013 }
1014 if (c != EOF && c != '\n')
b9ef27f5 1015 buf[i++] = c;
da0788fb
SK
1016 if (c == '>' && 0 <= pri && pri <= 191) {
1017 /* valid RFC PRI values */
1018 i = 0;
02f85939
KZ
1019 if ((pri & LOG_FACMASK) == 0)
1020 pri |= (default_priority & LOG_FACMASK);
da0788fb
SK
1021 ctl->pri = pri;
1022 } else
1023 ctl->pri = default_priority;
1024
da0788fb
SK
1025 if (c != EOF && c != '\n')
1026 c = getchar();
b9ef27f5
RG
1027 }
1028
58e4ee08 1029 while (c != EOF && c != '\n' && i < ctl->max_message_size) {
b9ef27f5
RG
1030 buf[i++] = c;
1031 c = getchar();
1032 }
1033 buf[i] = '\0';
1034
96ccdc00
KZ
1035 if (i > 0 || !ctl->skip_empty_lines) {
1036 generate_syslog_header(ctl);
ae6846b8 1037 write_output(ctl, buf);
96ccdc00 1038 }
b9ef27f5 1039
9a13f968 1040 if (c == '\n') /* discard line terminator */
b9ef27f5 1041 c = getchar();
c68a1cb4 1042 }
8b318eb2
KZ
1043
1044 free(buf);
c68a1cb4
SK
1045}
1046
46ee14df 1047static void logger_close(const struct logger_ctl *ctl)
c68a1cb4 1048{
9b83e7a4 1049 if (ctl->fd != -1 && close(ctl->fd) != 0)
1d575033 1050 err(EXIT_FAILURE, _("close failed"));
2b3f40c5 1051 free(ctl->hdr);
4ba84b0a 1052 free(ctl->login);
c68a1cb4
SK
1053}
1054
86be6a32 1055static void __attribute__((__noreturn__)) usage(void)
b363e86d 1056{
86be6a32 1057 FILE *out = stdout;
925aa9e8 1058 fputs(USAGE_HEADER, out);
4ce393f4 1059 fprintf(out, _(" %s [options] [<message>]\n"), program_invocation_short_name);
2da49186 1060
451dbcfa
BS
1061 fputs(USAGE_SEPARATOR, out);
1062 fputs(_("Enter messages into the system log.\n"), out);
1063
925aa9e8 1064 fputs(USAGE_OPTIONS, out);
3f51c10b
SK
1065 fputs(_(" -i log the logger command's PID\n"), out);
1066 fputs(_(" --id[=<id>] log the given <id>, or otherwise the PID\n"), out);
d0e875ff 1067 fputs(_(" -f, --file <file> log the contents of this file\n"), out);
ae6846b8 1068 fputs(_(" -e, --skip-empty do not log empty lines when processing files\n"), out);
fd343a05 1069 fputs(_(" --no-act do everything except the write the log\n"), out);
d0e875ff 1070 fputs(_(" -p, --priority <prio> mark given message with this priority\n"), out);
b6b67955 1071 fputs(_(" --octet-count use rfc6587 octet counting\n"), out);
d0e875ff
KZ
1072 fputs(_(" --prio-prefix look for a prefix on every line read from stdin\n"), out);
1073 fputs(_(" -s, --stderr output message to standard error as well\n"), out);
f68b8aa7 1074 fputs(_(" -S, --size <size> maximum size for a single message\n"), out);
d0e875ff
KZ
1075 fputs(_(" -t, --tag <tag> mark every line with this tag\n"), out);
1076 fputs(_(" -n, --server <name> write to this remote syslog server\n"), out);
1c722759 1077 fputs(_(" -P, --port <port> use this port for UDP or TCP connection\n"), out);
d0e875ff
KZ
1078 fputs(_(" -T, --tcp use TCP only\n"), out);
1079 fputs(_(" -d, --udp use UDP only\n"), out);
1080 fputs(_(" --rfc3164 use the obsolete BSD syslog protocol\n"), out);
2cb40465 1081 fputs(_(" --rfc5424[=<snip>] use the syslog protocol (the default for remote);\n"
d0e875ff 1082 " <snip> can be notime, or notq, and/or nohost\n"), out);
4299ed1c
KZ
1083 fputs(_(" --sd-id <id> rfc5424 structured data ID\n"), out);
1084 fputs(_(" --sd-param <data> rfc5424 structured data name=value\n"), out);
8fce3924 1085 fputs(_(" --msgid <msgid> set rfc5424 message id field\n"), out);
d0e875ff 1086 fputs(_(" -u, --socket <socket> write to this Unix socket\n"), out);
d77dc29e
SK
1087 fputs(_(" --socket-errors[=<on|off|auto>]\n"
1088 " print connection errors when using Unix sockets\n"), out);
ebff016a 1089#ifdef HAVE_LIBSYSTEMD
4b670c01
SK
1090 fputs(_(" --journald[=<file>] write journald entry\n"), out);
1091#endif
925aa9e8
KZ
1092
1093 fputs(USAGE_SEPARATOR, out);
f45f3ec3
RM
1094 printf(USAGE_HELP_OPTIONS(26));
1095 printf(USAGE_MAN_TAIL("logger(1)"));
b363e86d 1096
86be6a32 1097 exit(EXIT_SUCCESS);
b363e86d
SK
1098}
1099
6dbe3af9
KZ
1100/*
1101 * logger -- read and log utility
1102 *
1103 * Reads from an input and arranges to write the result on the system
1104 * log.
1105 */
195c3603
KZ
1106int main(int argc, char **argv)
1107{
cfa77d26
SK
1108 struct logger_ctl ctl = {
1109 .fd = -1,
59c6ac0b 1110 .pid = 0,
d0b6c4bf 1111 .pri = LOG_USER | LOG_NOTICE,
c68a1cb4 1112 .prio_prefix = 0,
cfa77d26 1113 .tag = NULL,
c68a1cb4 1114 .unix_socket = NULL,
d77dc29e 1115 .unix_socket_errors = 0,
c68a1cb4
SK
1116 .server = NULL,
1117 .port = NULL,
2b3f40c5 1118 .hdr = NULL,
55f5bc66 1119 .msgid = NULL,
4de2e8a0 1120 .socket_type = ALL_TYPES,
f68b8aa7 1121 .max_message_size = 1024,
4de2e8a0
SK
1122 .rfc5424_time = 1,
1123 .rfc5424_tq = 1,
1124 .rfc5424_host = 1,
ae6846b8 1125 .skip_empty_lines = 0
cfa77d26 1126 };
c68a1cb4 1127 int ch;
3d9f4b1d 1128 int stdout_reopened = 0;
d77dc29e 1129 int unix_socket_errors_mode = AF_UNIX_ERRORS_AUTO;
ebff016a 1130#ifdef HAVE_LIBSYSTEMD
4b670c01
SK
1131 FILE *jfd = NULL;
1132#endif
b363e86d 1133 static const struct option longopts[] = {
9a13f968
SK
1134 { "id", optional_argument, 0, OPT_ID },
1135 { "stderr", no_argument, 0, 's' },
1136 { "file", required_argument, 0, 'f' },
fd343a05 1137 { "no-act", no_argument, 0, OPT_NOACT, },
9a13f968
SK
1138 { "priority", required_argument, 0, 'p' },
1139 { "tag", required_argument, 0, 't' },
1140 { "socket", required_argument, 0, 'u' },
d77dc29e 1141 { "socket-errors", required_argument, 0, OPT_SOCKET_ERRORS },
9a13f968
SK
1142 { "udp", no_argument, 0, 'd' },
1143 { "tcp", no_argument, 0, 'T' },
1144 { "server", required_argument, 0, 'n' },
1145 { "port", required_argument, 0, 'P' },
1146 { "version", no_argument, 0, 'V' },
1147 { "help", no_argument, 0, 'h' },
b6b67955 1148 { "octet-count", no_argument, 0, OPT_OCTET_COUNT },
9a13f968
SK
1149 { "prio-prefix", no_argument, 0, OPT_PRIO_PREFIX },
1150 { "rfc3164", no_argument, 0, OPT_RFC3164 },
1151 { "rfc5424", optional_argument, 0, OPT_RFC5424 },
1152 { "size", required_argument, 0, 'S' },
1153 { "msgid", required_argument, 0, OPT_MSGID },
1154 { "skip-empty", no_argument, 0, 'e' },
4299ed1c
KZ
1155 { "sd-id", required_argument, 0, OPT_STRUCTURED_DATA_ID },
1156 { "sd-param", required_argument, 0, OPT_STRUCTURED_DATA_PARAM },
ebff016a 1157#ifdef HAVE_LIBSYSTEMD
9a13f968 1158 { "journald", optional_argument, 0, OPT_JOURNALD },
4b670c01 1159#endif
9a13f968 1160 { NULL, 0, 0, 0 }
b363e86d 1161 };
7eda085c
KZ
1162
1163 setlocale(LC_ALL, "");
1164 bindtextdomain(PACKAGE, LOCALEDIR);
1165 textdomain(PACKAGE);
2c308875 1166 close_stdout_atexit();
6dbe3af9 1167
4299ed1c
KZ
1168 INIT_LIST_HEAD(&ctl.user_sds);
1169 INIT_LIST_HEAD(&ctl.reserved_sds);
1170
ae6846b8 1171 while ((ch = getopt_long(argc, argv, "ef:ip:S:st:u:dTn:P:Vh",
49999d6a 1172 longopts, NULL)) != -1) {
98920f80 1173 switch (ch) {
6dbe3af9 1174 case 'f': /* file to log */
49999d6a 1175 if (freopen(optarg, "r", stdin) == NULL)
3d9f4b1d
SK
1176 err(EXIT_FAILURE, _("file %s"), optarg);
1177 stdout_reopened = 1;
6dbe3af9 1178 break;
ae6846b8
RG
1179 case 'e':
1180 ctl.skip_empty_lines = 1;
1181 break;
6dbe3af9 1182 case 'i': /* log process id also */
ef5fb280 1183 ctl.pid = logger_getpid();
3f51c10b
SK
1184 break;
1185 case OPT_ID:
aab5b444 1186 if (optarg) {
e598686d
KZ
1187 const char *p = optarg;
1188
1189 if (*p == '=')
1190 p++;
59c6ac0b
KZ
1191 ctl.pid = strtoul_or_err(optarg, _("failed to parse id"));
1192 } else
ef5fb280 1193 ctl.pid = logger_getpid();
6dbe3af9
KZ
1194 break;
1195 case 'p': /* priority */
cfa77d26 1196 ctl.pri = pencode(optarg);
6dbe3af9
KZ
1197 break;
1198 case 's': /* log to standard error */
35d36197 1199 ctl.stderr_printout = 1;
6dbe3af9
KZ
1200 break;
1201 case 't': /* tag */
cfa77d26 1202 ctl.tag = optarg;
6dbe3af9 1203 break;
7eda085c 1204 case 'u': /* unix socket */
c68a1cb4 1205 ctl.unix_socket = optarg;
7eda085c 1206 break;
f68b8aa7
RG
1207 case 'S': /* max message size */
1208 ctl.max_message_size = strtosize_or_err(optarg,
1209 _("failed to parse message size"));
1210 break;
66ee8158 1211 case 'd':
c68a1cb4 1212 ctl.socket_type = TYPE_UDP;
68265d07
SK
1213 break;
1214 case 'T':
c68a1cb4 1215 ctl.socket_type = TYPE_TCP;
66ee8158 1216 break;
68265d07 1217 case 'n':
c68a1cb4 1218 ctl.server = optarg;
912d6b98 1219 break;
68265d07 1220 case 'P':
c68a1cb4 1221 ctl.port = optarg;
912d6b98 1222 break;
b6b67955
AB
1223 case OPT_OCTET_COUNT:
1224 ctl.octet_count = 1;
1225 break;
98920f80 1226 case OPT_PRIO_PREFIX:
c68a1cb4 1227 ctl.prio_prefix = 1;
98920f80 1228 break;
4de2e8a0 1229 case OPT_RFC3164:
2b3f40c5 1230 ctl.syslogfp = syslog_rfc3164_header;
4de2e8a0
SK
1231 break;
1232 case OPT_RFC5424:
2b3f40c5 1233 ctl.syslogfp = syslog_rfc5424_header;
4de2e8a0
SK
1234 if (optarg)
1235 parse_rfc5424_flags(&ctl, optarg);
1236 break;
55f5bc66 1237 case OPT_MSGID:
9a13f968 1238 if (strchr(optarg, ' '))
8fce3924 1239 errx(EXIT_FAILURE, _("--msgid cannot contain space"));
55f5bc66
RG
1240 ctl.msgid = optarg;
1241 break;
ebff016a 1242#ifdef HAVE_LIBSYSTEMD
4b670c01
SK
1243 case OPT_JOURNALD:
1244 if (optarg) {
1245 jfd = fopen(optarg, "r");
1246 if (!jfd)
1247 err(EXIT_FAILURE, _("cannot open %s"),
1248 optarg);
1249 } else
1250 jfd = stdin;
1251 break;
1252#endif
d77dc29e
SK
1253 case OPT_SOCKET_ERRORS:
1254 unix_socket_errors_mode = parse_unix_socket_errors_flags(optarg);
1255 break;
fd343a05
KZ
1256 case OPT_NOACT:
1257 ctl.noact = 1;
1258 break;
4299ed1c
KZ
1259 case OPT_STRUCTURED_DATA_ID:
1260 if (!valid_structured_data_id(optarg))
1261 errx(EXIT_FAILURE, _("invalid structured data ID: '%s'"), optarg);
1262 add_structured_data_id(get_user_structured_data(&ctl), optarg);
1263 break;
1264 case OPT_STRUCTURED_DATA_PARAM:
1265 if (!valid_structured_data_param(optarg))
1266 errx(EXIT_FAILURE, _("invalid structured data parameter: '%s'"), optarg);
1267 add_structured_data_param(get_user_structured_data(&ctl), optarg);
1268 break;
2c308875
KZ
1269
1270 case 'V':
1271 print_version(EXIT_SUCCESS);
1272 case 'h':
1273 usage();
6dbe3af9 1274 default:
677ec86c 1275 errtryhelp(EXIT_FAILURE);
6dbe3af9 1276 }
49999d6a 1277 }
6dbe3af9
KZ
1278 argc -= optind;
1279 argv += optind;
3d9f4b1d
SK
1280 if (stdout_reopened && argc)
1281 warnx(_("--file <file> and <message> are mutually exclusive, message is ignored"));
ebff016a 1282#ifdef HAVE_LIBSYSTEMD
4b670c01 1283 if (jfd) {
fd343a05 1284 int ret = journald_entry(&ctl, jfd);
4b670c01
SK
1285 if (stdin != jfd)
1286 fclose(jfd);
047e2888 1287 if (ret)
54fefa07 1288 errx(EXIT_FAILURE, _("journald entry could not be written"));
047e2888 1289 return EXIT_SUCCESS;
4b670c01
SK
1290 }
1291#endif
4299ed1c 1292
11026083 1293 /* user overwrites built-in SD-ELEMENT */
4299ed1c
KZ
1294 if (has_structured_data_id(get_user_structured_data(&ctl), "timeQuality"))
1295 ctl.rfc5424_tq = 0;
1296
d77dc29e
SK
1297 switch (unix_socket_errors_mode) {
1298 case AF_UNIX_ERRORS_OFF:
1299 ctl.unix_socket_errors = 0;
1300 break;
1301 case AF_UNIX_ERRORS_ON:
1302 ctl.unix_socket_errors = 1;
1303 break;
1304 case AF_UNIX_ERRORS_AUTO:
bcf7e149 1305 ctl.unix_socket_errors = ctl.noact || ctl.stderr_printout;
d77dc29e 1306#ifdef HAVE_LIBSYSTEMD
bcf7e149 1307 ctl.unix_socket_errors |= !!sd_booted();
d77dc29e
SK
1308#endif
1309 break;
1310 default:
1311 abort();
1312 }
c68a1cb4 1313 logger_open(&ctl);
96ccdc00
KZ
1314 if (0 < argc) {
1315 generate_syslog_header(&ctl);
c68a1cb4 1316 logger_command_line(&ctl, argv);
96ccdc00 1317 } else
c68a1cb4
SK
1318 /* Note. --file <arg> reopens stdin making the below
1319 * function to be used for file inputs. */
1320 logger_stdin(&ctl);
96ccdc00 1321
c68a1cb4 1322 logger_close(&ctl);
49999d6a 1323 return EXIT_SUCCESS;
6dbe3af9 1324}