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