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