]> git.ipfire.org Git - thirdparty/util-linux.git/blob - misc-utils/logger.c
logger: allow to reconnect on initial failed connect too
[thirdparty/util-linux.git] / misc-utils / logger.c
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.
32 *
33 * 1999-02-22 Arkadiusz Miƛkiewicz <misiek@pld.ORG.PL>
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
37 */
38
39 #include <errno.h>
40 #include <limits.h>
41 #include <unistd.h>
42 #include <stdlib.h>
43 #include <sys/time.h>
44 #include <stdio.h>
45 #include <ctype.h>
46 #include <string.h>
47 #include <sys/types.h>
48 #include <sys/socket.h>
49 #include <sys/un.h>
50 #include <arpa/inet.h>
51 #include <netdb.h>
52 #include <getopt.h>
53 #include <pwd.h>
54 #include <signal.h>
55 #include <sys/uio.h>
56
57 #include "all-io.h"
58 #include "c.h"
59 #include "closestream.h"
60 #include "nls.h"
61 #include "pathnames.h"
62 #include "strutils.h"
63 #include "xalloc.h"
64 #include "strv.h"
65 #include "list.h"
66
67 #define SYSLOG_NAMES
68 #include <syslog.h>
69
70 #ifdef HAVE_LIBSYSTEMD
71 # include <systemd/sd-daemon.h>
72 # include <systemd/sd-journal.h>
73 #endif
74
75 #ifdef HAVE_SYS_TIMEX_H
76 # include <sys/timex.h>
77 #endif
78
79 enum {
80 TYPE_UDP = (1 << 1),
81 TYPE_TCP = (1 << 2),
82 ALL_TYPES = TYPE_UDP | TYPE_TCP
83 };
84
85 enum {
86 AF_UNIX_ERRORS_OFF = 0,
87 AF_UNIX_ERRORS_ON,
88 AF_UNIX_ERRORS_AUTO
89 };
90
91 enum {
92 OPT_PRIO_PREFIX = CHAR_MAX + 1,
93 OPT_JOURNALD,
94 OPT_RFC3164,
95 OPT_RFC5424,
96 OPT_SOCKET_ERRORS,
97 OPT_MSGID,
98 OPT_NOACT,
99 OPT_ID,
100 OPT_STRUCTURED_DATA_ID,
101 OPT_STRUCTURED_DATA_PARAM,
102 OPT_OCTET_COUNT
103 };
104
105 /* rfc5424 structured data */
106 struct structured_data {
107 char *id; /* SD-ID */
108 char **params; /* array with SD-PARAMs */
109
110 struct list_head sds;
111 };
112
113 struct logger_ctl {
114 int fd;
115 int pri;
116 pid_t pid; /* zero when unwanted */
117 char *hdr; /* the syslog header (based on protocol) */
118 char const *tag;
119 char *msgid;
120 char *unix_socket; /* -u <path> or default to _PATH_DEVLOG */
121 char *server;
122 char *port;
123 int socket_type;
124 size_t max_message_size;
125 struct list_head user_sds; /* user defined rfc5424 structured data */
126 struct list_head reserved_sds; /* standard rfc5424 structured data */
127
128 void (*syslogfp)(struct logger_ctl *ctl);
129
130 unsigned int
131 unix_socket_errors:1, /* whether to report or not errors */
132 noact:1, /* do not write to sockets */
133 prio_prefix:1, /* read priority from input */
134 stderr_printout:1, /* output message to stderr */
135 rfc5424_time:1, /* include time stamp */
136 rfc5424_tq:1, /* include time quality markup */
137 rfc5424_host:1, /* include hostname */
138 skip_empty_lines:1, /* do not send empty lines when processing files */
139 octet_count:1; /* use RFC6587 octet counting */
140 };
141
142 #define is_connected(_ctl) ((_ctl)->fd >= 0)
143 static void logger_reopen(struct logger_ctl *ctl);
144
145 /*
146 * For tests we want to be able to control datetime outputs
147 */
148 #ifdef TEST_LOGGER
149 static 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;
157 return tv->tv_sec >= 0 && tv->tv_usec >= 0 ? 0 : -EINVAL;
158 }
159
160 return gettimeofday(tv, tz);
161 }
162
163 static inline char *logger_xgethostname(void)
164 {
165 char *str = getenv("LOGGER_TEST_HOSTNAME");
166 return str ? xstrdup(str) : xgethostname();
167 }
168
169 static 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
189 static int decode(const char *name, const CODE *codetab)
190 {
191 register const CODE *c;
192
193 if (name == NULL || *name == '\0')
194 return -1;
195 if (isdigit(*name)) {
196 int num;
197 char *end = NULL;
198
199 errno = 0;
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 }
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
215 static int pencode(char *s)
216 {
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);
232 if (facility == LOG_KERN)
233 facility = LOG_USER; /* kern is forbidden */
234 return ((level & LOG_PRIMASK) | (facility & LOG_FACMASK));
235 }
236
237 static int unix_socket(struct logger_ctl *ctl, const char *path, int *socket_type)
238 {
239 int fd, i, type = -1;
240 static struct sockaddr_un s_addr; /* AF_UNIX address of local logger */
241
242 if (strlen(path) >= sizeof(s_addr.sun_path))
243 errx(EXIT_FAILURE, _("openlog %s: pathname too long"), path);
244
245 s_addr.sun_family = AF_UNIX;
246 strcpy(s_addr.sun_path, path);
247
248 for (i = 2; i; i--) {
249 int st = -1;
250
251 if (i == 2 && *socket_type & TYPE_UDP) {
252 st = SOCK_DGRAM;
253 type = TYPE_UDP;
254 }
255 if (i == 1 && *socket_type & TYPE_TCP) {
256 st = SOCK_STREAM;
257 type = TYPE_TCP;
258 }
259 if (st == -1 || (fd = socket(AF_UNIX, st, 0)) == -1)
260 continue;
261 if (connect(fd, (struct sockaddr *)&s_addr, sizeof(s_addr)) == -1) {
262 close(fd);
263 continue;
264 }
265 break;
266 }
267
268 if (i == 0) {
269 if (ctl->unix_socket_errors)
270 err(EXIT_FAILURE, _("socket %s"), path);
271
272 /* write_output() will try to reconnect */
273 return -1;
274 }
275
276 /* replace ALL_TYPES with the real TYPE_* */
277 if (type > 0 && type != *socket_type)
278 *socket_type = type;
279 return fd;
280 }
281
282 static int inet_socket(const char *servername, const char *port, int *socket_type)
283 {
284 int fd, errcode, i, type = -1;
285 struct addrinfo hints, *res;
286 const char *p = port;
287
288 for (i = 2; i; i--) {
289 memset(&hints, 0, sizeof(hints));
290 if (i == 2 && *socket_type & TYPE_UDP) {
291 hints.ai_socktype = SOCK_DGRAM;
292 type = TYPE_UDP;
293 if (port == NULL)
294 p = "syslog";
295 }
296 if (i == 1 && *socket_type & TYPE_TCP) {
297 hints.ai_socktype = SOCK_STREAM;
298 type = TYPE_TCP;
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)
307 errx(EXIT_FAILURE, _("failed to resolve name %s port %s: %s"),
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 }
318
319 freeaddrinfo(res);
320 break;
321 }
322
323 if (i == 0)
324 errx(EXIT_FAILURE, _("failed to connect to %s port %s"), servername, p);
325
326 /* replace ALL_TYPES with the real TYPE_* */
327 if (type > 0 && type != *socket_type)
328 *socket_type = type;
329 return fd;
330 }
331
332 #ifdef HAVE_LIBSYSTEMD
333 static int journald_entry(struct logger_ctl *ctl, FILE *fp)
334 {
335 struct iovec *iovec;
336 char *buf = NULL;
337 ssize_t sz;
338 int n, lines, vectors = 8, ret = 0;
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);
345 if (sz == -1 ||
346 (sz = rtrim_whitespace((unsigned char *) buf)) == 0) {
347 free(buf);
348 break;
349 }
350 if (lines == vectors) {
351 vectors *= 2;
352 if (IOV_MAX < vectors)
353 errx(EXIT_FAILURE, _("maximum input lines (%d) exceeded"), IOV_MAX);
354 iovec = xrealloc(iovec, vectors * sizeof(struct iovec));
355 }
356 iovec[lines].iov_base = buf;
357 iovec[lines].iov_len = sz;
358 }
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 }
366 for (n = 0; n < lines; n++)
367 free(iovec[n].iov_base);
368 free(iovec);
369 return ret;
370 }
371 #endif
372
373 static char const *xgetlogin(void)
374 {
375 char const *cp;
376 struct passwd *pw;
377
378 if (!(cp = getlogin()) || !*cp)
379 cp = (pw = getpwuid(geteuid()))? pw->pw_name : "<someone>";
380 return cp;
381 }
382
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 */
389 static char const *rfc3164_current_time(void)
390 {
391 static char time[32];
392 struct timeval tv;
393 struct tm *tm;
394 static char const * const monthnames[] = {
395 "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
396 "Sep", "Oct", "Nov", "Dec"
397 };
398
399 logger_gettimeofday(&tv, NULL);
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,
403 tm->tm_hour, tm->tm_min, tm->tm_sec);
404 return time;
405 }
406
407 #define next_iovec(ary, idx) __extension__ ({ \
408 assert(ARRAY_SIZE(ary) > (size_t)idx); \
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
423 /* writes generated buffer to desired destination. For TCP syslog,
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.
428 */
429 static void write_output(struct logger_ctl *ctl, const char *const msg)
430 {
431 struct iovec iov[4];
432 int iovlen = 0;
433 char *octet = NULL;
434
435 /* initial connect failed? */
436 if (!ctl->noact && !is_connected(ctl))
437 logger_reopen(ctl);
438
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);
450
451 if (!ctl->noact && is_connected(ctl)) {
452 struct msghdr message = { 0 };
453 #ifdef SCM_CREDENTIALS
454 struct cmsghdr *cmhp;
455 struct ucred *cred;
456 union {
457 struct cmsghdr cmh;
458 char control[CMSG_SPACE(sizeof(struct ucred))];
459 } cbuf;
460 #endif
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);
465
466 message.msg_iov = iov;
467 message.msg_iovlen = iovlen;
468
469 #ifdef SCM_CREDENTIALS
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
478 message.msg_control = cbuf.control;
479 message.msg_controllen = CMSG_SPACE(sizeof(struct ucred));
480
481 cmhp = CMSG_FIRSTHDR(&message);
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 }
489 #endif
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]
495 *
496 * MSG_NOSIGNAL is POSIX.1-2008 compatible, but it for example
497 * no suported by apple-darwin15.6.0.
498 */
499 #ifndef MSG_NOSIGNAL
500 # define MSG_NOSIGNAL 0
501 #endif
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 }
507 }
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);
518 }
519
520 #define NILVALUE "-"
521 static void syslog_rfc3164_header(struct logger_ctl *const ctl)
522 {
523 char pid[30], *hostname;
524
525 *pid = '\0';
526 if (ctl->fd < 0)
527 return;
528 if (ctl->pid)
529 snprintf(pid, sizeof(pid), "[%d]", ctl->pid);
530
531 if ((hostname = logger_xgethostname())) {
532 char *dot = strchr(hostname, '.');
533 if (dot)
534 *dot = '\0';
535 } else
536 hostname = xstrdup(NILVALUE);
537
538 xasprintf(&ctl->hdr, "<%d>%.15s %s %.200s%s: ",
539 ctl->pri, rfc3164_current_time(), hostname, ctl->tag, pid);
540
541 free(hostname);
542 }
543
544 static inline struct list_head *get_user_structured_data(struct logger_ctl *ctl)
545 {
546 return &ctl->user_sds;
547 }
548
549 static inline struct list_head *get_reserved_structured_data(struct logger_ctl *ctl)
550 {
551 return &ctl->reserved_sds;
552 }
553
554 static int has_structured_data_id(struct list_head *ls, const char *id)
555 {
556 struct list_head *p;
557
558 if (!ls || list_empty(ls))
559 return 0;
560
561 list_for_each(p, ls) {
562 struct structured_data *sd = list_entry(p, struct structured_data, sds);
563 if (sd->id && strcmp(sd->id, id) == 0)
564 return 1;
565 }
566
567 return 0;
568 }
569
570 static void add_structured_data_id(struct list_head *ls, const char *id)
571 {
572 struct structured_data *sd;
573
574 assert(id);
575
576 if (has_structured_data_id(ls, id))
577 errx(EXIT_FAILURE, _("structured data ID '%s' is not unique"), id);
578
579 sd = xcalloc(1, sizeof(*sd));
580 INIT_LIST_HEAD(&sd->sds);
581 sd->id = xstrdup(id);
582
583 list_add_tail(&sd->sds, ls);
584 }
585
586 static void add_structured_data_param(struct list_head *ls, const char *param)
587 {
588 struct structured_data *sd;
589
590 if (list_empty(ls))
591 errx(EXIT_FAILURE, _("--sd-id was not specified for --sd-param %s"), param);
592
593 assert(param);
594
595 sd = list_last_entry(ls, struct structured_data, sds);
596
597 if (strv_extend(&sd->params, param))
598 err_oom();
599 }
600
601 static void add_structured_data_paramf(struct list_head *ls, const char *fmt, ...)
602 {
603 struct structured_data *sd;
604 va_list ap;
605 int x;
606
607 assert(!list_empty(ls));
608 assert(fmt);
609
610 sd = list_last_entry(ls, struct structured_data, sds);
611 va_start(ap, fmt);
612 x = strv_extendv(&sd->params, fmt, ap);
613 va_end(ap);
614
615 if (x)
616 err_oom();
617 }
618
619 static char *strdup_structured_data(struct structured_data *sd)
620 {
621 char *res, *tmp;
622
623 if (strv_isempty(sd->params))
624 return NULL;
625
626 xasprintf(&res, "[%s %s]", sd->id,
627 (tmp = strv_join(sd->params, " ")));
628 free(tmp);
629 return res;
630 }
631
632 static char *strdup_structured_data_list(struct list_head *ls)
633 {
634 struct list_head *p;
635 char *res = NULL;
636
637 list_for_each(p, ls) {
638 struct structured_data *sd = list_entry(p, struct structured_data, sds);
639 char *one = strdup_structured_data(sd);
640 char *tmp = res;
641
642 if (!one)
643 continue;
644 res = strappend(tmp, one);
645 free(tmp);
646 free(one);
647 }
648
649 return res;
650 }
651
652 static char *get_structured_data_string(struct logger_ctl *ctl)
653 {
654 char *sys = NULL, *usr = NULL, *res;
655
656 if (!list_empty(&ctl->reserved_sds))
657 sys = strdup_structured_data_list(&ctl->reserved_sds);
658 if (!list_empty(&ctl->user_sds))
659 usr = strdup_structured_data_list(&ctl->user_sds);
660
661 if (sys && usr) {
662 res = strappend(sys, usr);
663 free(sys);
664 free(usr);
665 } else
666 res = sys ? sys : usr;
667
668 return res;
669 }
670
671 static int valid_structured_data_param(const char *str)
672 {
673 char *eq = strchr(str, '='),
674 *qm1 = strchr(str, '"'),
675 *qm2 = qm1 ? strchr(qm1 + 1, '"') : NULL;
676
677 if (!eq || !qm1 || !qm2) /* something is missing */
678 return 0;
679
680 /* foo="bar" */
681 return eq > str && eq < qm1 && eq + 1 == qm1 && qm1 < qm2 && *(qm2 + 1) == '\0';
682 }
683
684 /* SD-ID format:
685 * name@<private enterprise number>, e.g., "ourSDID@32473"
686 */
687 static int valid_structured_data_id(const char *str)
688 {
689 char *at = strchr(str, '@');
690 const char *p;
691
692 /* standardized IDs without @<digits> */
693 if (!at && (strcmp(str, "timeQuality") == 0 ||
694 strcmp(str, "origin") == 0 ||
695 strcmp(str, "meta") == 0))
696 return 1;
697
698 if (!at || at == str || !*(at + 1))
699 return 0;
700
701 /* <digits> or <digits>.<digits>[...] */
702 for (p = at + 1; p && *p; p++) {
703 const char *end;
704
705 if (isdigit_strend(p, &end))
706 break; /* only digits in the string */
707
708 if (end == NULL || end == p ||
709 *end != '.' || *(end + 1) == '\0')
710 return 0;
711 p = end;
712 }
713
714 /* check for forbidden chars in the <name> */
715 for (p = str; p < at; p++) {
716 if (*p == '[' || *p == '=' || *p == '"' || *p == '@')
717 return 0;
718 if (isblank((unsigned char) *p) || iscntrl((unsigned char) *p))
719 return 0;
720 }
721 return 1;
722 }
723
724
725 /* Some field mappings may be controversial, thus I give the reason
726 * why this specific mapping was used:
727 * APP-NAME <-- tag
728 * Some may argue that "logger" is a better fit, but we think
729 * this is better inline of what other implementations do. In
730 * rsyslog, for example, the TAG value is populated from APP-NAME.
731 * PROCID <-- pid
732 * This is a relatively straightforward interpretation from
733 * RFC5424, sect. 6.2.6.
734 * MSGID <-- msgid (from --msgid)
735 * One may argue that the string "logger" would be better suited
736 * here so that a receiver can identify the sender process.
737 * However, this does not sound like a good match to RFC5424,
738 * sect. 6.2.7.
739 * Note that appendix A.1 of RFC5424 does not provide clear guidance
740 * of how these fields should be used. This is the case because the
741 * IETF working group couldn't arrive at a clear agreement when we
742 * specified RFC5424. The rest of the field mappings should be
743 * pretty clear from RFC5424. -- Rainer Gerhards, 2015-03-10
744 */
745 static void syslog_rfc5424_header(struct logger_ctl *const ctl)
746 {
747 char *time;
748 char *hostname;
749 char const *app_name = ctl->tag;
750 char *procid;
751 char *const msgid = xstrdup(ctl->msgid ? ctl->msgid : NILVALUE);
752 char *structured = NULL;
753 struct list_head *sd;
754
755 if (ctl->fd < 0)
756 return;
757
758 if (ctl->rfc5424_time) {
759 struct timeval tv;
760 struct tm *tm;
761
762 logger_gettimeofday(&tv, NULL);
763 if ((tm = localtime(&tv.tv_sec)) != NULL) {
764 char fmt[64];
765 const size_t i = strftime(fmt, sizeof(fmt),
766 "%Y-%m-%dT%H:%M:%S.%%06u%z ", tm);
767 /* patch TZ info to comply with RFC3339 (we left SP at end) */
768 fmt[i - 1] = fmt[i - 2];
769 fmt[i - 2] = fmt[i - 3];
770 fmt[i - 3] = ':';
771 xasprintf(&time, fmt, tv.tv_usec);
772 } else
773 err(EXIT_FAILURE, _("localtime() failed"));
774 } else
775 time = xstrdup(NILVALUE);
776
777 if (ctl->rfc5424_host) {
778 if (!(hostname = logger_xgethostname()))
779 hostname = xstrdup(NILVALUE);
780 /* Arbitrary looking 'if (var < strlen()) checks originate from
781 * RFC 5424 - 6 Syslog Message Format definition. */
782 if (255 < strlen(hostname))
783 errx(EXIT_FAILURE, _("hostname '%s' is too long"),
784 hostname);
785 } else
786 hostname = xstrdup(NILVALUE);
787
788 if (48 < strlen(ctl->tag))
789 errx(EXIT_FAILURE, _("tag '%s' is too long"), ctl->tag);
790
791 if (ctl->pid)
792 xasprintf(&procid, "%d", ctl->pid);
793 else
794 procid = xstrdup(NILVALUE);
795
796 sd = get_reserved_structured_data(ctl);
797
798 /* time quality structured data (maybe overwritten by --sd-id timeQuality) */
799 if (ctl->rfc5424_tq && !has_structured_data_id(sd, "timeQuality")) {
800
801 add_structured_data_id(sd, "timeQuality");
802 add_structured_data_param(sd, "tzKnown=\"1\"");
803
804 #ifdef HAVE_NTP_GETTIME
805 struct ntptimeval ntptv;
806
807 if (ntp_gettime(&ntptv) == TIME_OK) {
808 add_structured_data_param(sd, "isSynced=\"1\"");
809 add_structured_data_paramf(sd, "syncAccuracy=\"%ld\"", ntptv.maxerror);
810 } else
811 #endif
812 add_structured_data_paramf(sd, "isSynced=\"0\"");
813 }
814
815 /* convert all structured data to string */
816 structured = get_structured_data_string(ctl);
817 if (!structured)
818 structured = xstrdup(NILVALUE);
819
820 xasprintf(&ctl->hdr, "<%d>1 %s %s %s %s %s %s ",
821 ctl->pri,
822 time,
823 hostname,
824 app_name,
825 procid,
826 msgid,
827 structured);
828
829 free(time);
830 free(hostname);
831 /* app_name points to ctl->tag, do NOT free! */
832 free(procid);
833 free(msgid);
834 free(structured);
835 }
836
837 static void parse_rfc5424_flags(struct logger_ctl *ctl, char *s)
838 {
839 char *in, *tok;
840
841 in = s;
842 while ((tok = strtok(in, ","))) {
843 in = NULL;
844 if (!strcmp(tok, "notime")) {
845 ctl->rfc5424_time = 0;
846 ctl->rfc5424_tq = 0;
847 } else if (!strcmp(tok, "notq"))
848 ctl->rfc5424_tq = 0;
849 else if (!strcmp(tok, "nohost"))
850 ctl->rfc5424_host = 0;
851 else
852 warnx(_("ignoring unknown option argument: %s"), tok);
853 }
854 }
855
856 static int parse_unix_socket_errors_flags(char *s)
857 {
858 if (!strcmp(s, "off"))
859 return AF_UNIX_ERRORS_OFF;
860 if (!strcmp(s, "on"))
861 return AF_UNIX_ERRORS_ON;
862 if (!strcmp(s, "auto"))
863 return AF_UNIX_ERRORS_AUTO;
864 warnx(_("invalid argument: %s: using automatic errors"), s);
865 return AF_UNIX_ERRORS_AUTO;
866 }
867
868 static void syslog_local_header(struct logger_ctl *const ctl)
869 {
870 char pid[32];
871
872 if (ctl->pid)
873 snprintf(pid, sizeof(pid), "[%d]", ctl->pid);
874 else
875 pid[0] = '\0';
876
877 xasprintf(&ctl->hdr, "<%d>%s %s%s: ", ctl->pri, rfc3164_current_time(),
878 ctl->tag, pid);
879 }
880
881 static void generate_syslog_header(struct logger_ctl *const ctl)
882 {
883 free(ctl->hdr);
884 ctl->syslogfp(ctl);
885 }
886
887 /* just open, nothing else */
888 static void __logger_open(struct logger_ctl *ctl)
889 {
890 if (ctl->server) {
891 ctl->fd = inet_socket(ctl->server, ctl->port, &ctl->socket_type);
892 } else {
893 if (!ctl->unix_socket)
894 ctl->unix_socket = _PATH_DEVLOG;
895
896 ctl->fd = unix_socket(ctl, ctl->unix_socket, &ctl->socket_type);
897 }
898 }
899
900 /* open and initialize relevant @ctl tuff */
901 static void logger_open(struct logger_ctl *ctl)
902 {
903 __logger_open(ctl);
904
905 if (!ctl->syslogfp)
906 ctl->syslogfp = ctl->server ? syslog_rfc5424_header :
907 syslog_local_header;
908 if (!ctl->tag)
909 ctl->tag = xgetlogin();
910
911 generate_syslog_header(ctl);
912 }
913
914 /* re-open; usually after failed connection */
915 static void logger_reopen(struct logger_ctl *ctl)
916 {
917 if (ctl->fd != -1)
918 close(ctl->fd);
919 ctl->fd = -1;
920
921 __logger_open(ctl);
922 }
923
924 static void logger_command_line(struct logger_ctl *ctl, char **argv)
925 {
926 /* note: we never re-generate the syslog header here, even if we
927 * generate multiple messages. If so, we think it is the right thing
928 * to do to report them with the same timestamp, as the user actually
929 * intended to send a single message.
930 */
931 char *const buf = xmalloc(ctl->max_message_size + 1);
932 char *p = buf;
933 const char *endp = buf + ctl->max_message_size - 1;
934 size_t len;
935
936 while (*argv) {
937 len = strlen(*argv);
938 if (endp < p + len && p != buf) {
939 write_output(ctl, buf);
940 p = buf;
941 }
942 if (ctl->max_message_size < len) {
943 (*argv)[ctl->max_message_size] = '\0'; /* truncate */
944 write_output(ctl, *argv++);
945 continue;
946 }
947 if (p != buf)
948 *p++ = ' ';
949 memmove(p, *argv++, len);
950 *(p += len) = '\0';
951 }
952 if (p != buf)
953 write_output(ctl, buf);
954 free(buf);
955 }
956
957 static void logger_stdin(struct logger_ctl *ctl)
958 {
959 /* note: we re-generate the syslog header for each log message to
960 * update header timestamps and to reflect possible priority changes.
961 * The initial header is generated by logger_open().
962 */
963 int has_header = 1;
964 int default_priority = ctl->pri;
965 int last_pri = default_priority;
966 size_t max_usrmsg_size = ctl->max_message_size - strlen(ctl->hdr);
967 char *const buf = xmalloc(max_usrmsg_size + 2 + 2);
968 int pri;
969 int c;
970 size_t i;
971
972 c = getchar();
973 while (c != EOF) {
974 i = 0;
975 if (ctl->prio_prefix && c == '<') {
976 pri = 0;
977 buf[i++] = c;
978 while (isdigit(c = getchar()) && pri <= 191) {
979 buf[i++] = c;
980 pri = pri * 10 + c - '0';
981 }
982 if (c != EOF && c != '\n')
983 buf[i++] = c;
984 if (c == '>' && 0 <= pri && pri <= 191) {
985 /* valid RFC PRI values */
986 i = 0;
987 if (pri < 8) /* kern facility is forbidden */
988 pri |= 8;
989 ctl->pri = pri;
990 } else
991 ctl->pri = default_priority;
992
993 if (ctl->pri != last_pri) {
994 has_header = 0;
995 max_usrmsg_size =
996 ctl->max_message_size - strlen(ctl->hdr);
997 last_pri = ctl->pri;
998 }
999 if (c != EOF && c != '\n')
1000 c = getchar();
1001 }
1002
1003 while (c != EOF && c != '\n' && i < max_usrmsg_size) {
1004 buf[i++] = c;
1005 c = getchar();
1006 }
1007 buf[i] = '\0';
1008
1009 if (i > 0 || !ctl->skip_empty_lines) {
1010 if (!has_header)
1011 generate_syslog_header(ctl);
1012 write_output(ctl, buf);
1013 has_header = 0;
1014 }
1015
1016 if (c == '\n') /* discard line terminator */
1017 c = getchar();
1018 }
1019
1020 free(buf);
1021 }
1022
1023 static void logger_close(const struct logger_ctl *ctl)
1024 {
1025 if (ctl->fd != -1 && close(ctl->fd) != 0)
1026 err(EXIT_FAILURE, _("close failed"));
1027 free(ctl->hdr);
1028 }
1029
1030 static void __attribute__((__noreturn__)) usage(void)
1031 {
1032 FILE *out = stdout;
1033 fputs(USAGE_HEADER, out);
1034 fprintf(out, _(" %s [options] [<message>]\n"), program_invocation_short_name);
1035
1036 fputs(USAGE_SEPARATOR, out);
1037 fputs(_("Enter messages into the system log.\n"), out);
1038
1039 fputs(USAGE_OPTIONS, out);
1040 fputs(_(" -i log the logger command's PID\n"), out);
1041 fputs(_(" --id[=<id>] log the given <id>, or otherwise the PID\n"), out);
1042 fputs(_(" -f, --file <file> log the contents of this file\n"), out);
1043 fputs(_(" -e, --skip-empty do not log empty lines when processing files\n"), out);
1044 fputs(_(" --no-act do everything except the write the log\n"), out);
1045 fputs(_(" -p, --priority <prio> mark given message with this priority\n"), out);
1046 fputs(_(" --octet-count use rfc6587 octet counting\n"), out);
1047 fputs(_(" --prio-prefix look for a prefix on every line read from stdin\n"), out);
1048 fputs(_(" -s, --stderr output message to standard error as well\n"), out);
1049 fputs(_(" -S, --size <size> maximum size for a single message\n"), out);
1050 fputs(_(" -t, --tag <tag> mark every line with this tag\n"), out);
1051 fputs(_(" -n, --server <name> write to this remote syslog server\n"), out);
1052 fputs(_(" -P, --port <port> use this port for UDP or TCP connection\n"), out);
1053 fputs(_(" -T, --tcp use TCP only\n"), out);
1054 fputs(_(" -d, --udp use UDP only\n"), out);
1055 fputs(_(" --rfc3164 use the obsolete BSD syslog protocol\n"), out);
1056 fputs(_(" --rfc5424[=<snip>] use the syslog protocol (the default for remote);\n"
1057 " <snip> can be notime, or notq, and/or nohost\n"), out);
1058 fputs(_(" --sd-id <id> rfc5424 structured data ID\n"), out);
1059 fputs(_(" --sd-param <data> rfc5424 structured data name=value\n"), out);
1060 fputs(_(" --msgid <msgid> set rfc5424 message id field\n"), out);
1061 fputs(_(" -u, --socket <socket> write to this Unix socket\n"), out);
1062 fputs(_(" --socket-errors[=<on|off|auto>]\n"
1063 " print connection errors when using Unix sockets\n"), out);
1064 #ifdef HAVE_LIBSYSTEMD
1065 fputs(_(" --journald[=<file>] write journald entry\n"), out);
1066 #endif
1067
1068 fputs(USAGE_SEPARATOR, out);
1069 printf(USAGE_HELP_OPTIONS(26));
1070 printf(USAGE_MAN_TAIL("logger(1)"));
1071
1072 exit(EXIT_SUCCESS);
1073 }
1074
1075 /*
1076 * logger -- read and log utility
1077 *
1078 * Reads from an input and arranges to write the result on the system
1079 * log.
1080 */
1081 int main(int argc, char **argv)
1082 {
1083 struct logger_ctl ctl = {
1084 .fd = -1,
1085 .pid = 0,
1086 .pri = LOG_USER | LOG_NOTICE,
1087 .prio_prefix = 0,
1088 .tag = NULL,
1089 .unix_socket = NULL,
1090 .unix_socket_errors = 0,
1091 .server = NULL,
1092 .port = NULL,
1093 .hdr = NULL,
1094 .msgid = NULL,
1095 .socket_type = ALL_TYPES,
1096 .max_message_size = 1024,
1097 .rfc5424_time = 1,
1098 .rfc5424_tq = 1,
1099 .rfc5424_host = 1,
1100 .skip_empty_lines = 0
1101 };
1102 int ch;
1103 int stdout_reopened = 0;
1104 int unix_socket_errors_mode = AF_UNIX_ERRORS_AUTO;
1105 #ifdef HAVE_LIBSYSTEMD
1106 FILE *jfd = NULL;
1107 #endif
1108 static const struct option longopts[] = {
1109 { "id", optional_argument, 0, OPT_ID },
1110 { "stderr", no_argument, 0, 's' },
1111 { "file", required_argument, 0, 'f' },
1112 { "no-act", no_argument, 0, OPT_NOACT, },
1113 { "priority", required_argument, 0, 'p' },
1114 { "tag", required_argument, 0, 't' },
1115 { "socket", required_argument, 0, 'u' },
1116 { "socket-errors", required_argument, 0, OPT_SOCKET_ERRORS },
1117 { "udp", no_argument, 0, 'd' },
1118 { "tcp", no_argument, 0, 'T' },
1119 { "server", required_argument, 0, 'n' },
1120 { "port", required_argument, 0, 'P' },
1121 { "version", no_argument, 0, 'V' },
1122 { "help", no_argument, 0, 'h' },
1123 { "octet-count", no_argument, 0, OPT_OCTET_COUNT },
1124 { "prio-prefix", no_argument, 0, OPT_PRIO_PREFIX },
1125 { "rfc3164", no_argument, 0, OPT_RFC3164 },
1126 { "rfc5424", optional_argument, 0, OPT_RFC5424 },
1127 { "size", required_argument, 0, 'S' },
1128 { "msgid", required_argument, 0, OPT_MSGID },
1129 { "skip-empty", no_argument, 0, 'e' },
1130 { "sd-id", required_argument, 0, OPT_STRUCTURED_DATA_ID },
1131 { "sd-param", required_argument, 0, OPT_STRUCTURED_DATA_PARAM },
1132 #ifdef HAVE_LIBSYSTEMD
1133 { "journald", optional_argument, 0, OPT_JOURNALD },
1134 #endif
1135 { NULL, 0, 0, 0 }
1136 };
1137
1138 setlocale(LC_ALL, "");
1139 bindtextdomain(PACKAGE, LOCALEDIR);
1140 textdomain(PACKAGE);
1141 atexit(close_stdout);
1142
1143 INIT_LIST_HEAD(&ctl.user_sds);
1144 INIT_LIST_HEAD(&ctl.reserved_sds);
1145
1146 while ((ch = getopt_long(argc, argv, "ef:ip:S:st:u:dTn:P:Vh",
1147 longopts, NULL)) != -1) {
1148 switch (ch) {
1149 case 'f': /* file to log */
1150 if (freopen(optarg, "r", stdin) == NULL)
1151 err(EXIT_FAILURE, _("file %s"), optarg);
1152 stdout_reopened = 1;
1153 break;
1154 case 'e':
1155 ctl.skip_empty_lines = 1;
1156 break;
1157 case 'i': /* log process id also */
1158 ctl.pid = logger_getpid();
1159 break;
1160 case OPT_ID:
1161 if (optarg) {
1162 const char *p = optarg;
1163
1164 if (*p == '=')
1165 p++;
1166 ctl.pid = strtoul_or_err(optarg, _("failed to parse id"));
1167 } else
1168 ctl.pid = logger_getpid();
1169 break;
1170 case 'p': /* priority */
1171 ctl.pri = pencode(optarg);
1172 break;
1173 case 's': /* log to standard error */
1174 ctl.stderr_printout = 1;
1175 break;
1176 case 't': /* tag */
1177 ctl.tag = optarg;
1178 break;
1179 case 'u': /* unix socket */
1180 ctl.unix_socket = optarg;
1181 break;
1182 case 'S': /* max message size */
1183 ctl.max_message_size = strtosize_or_err(optarg,
1184 _("failed to parse message size"));
1185 break;
1186 case 'd':
1187 ctl.socket_type = TYPE_UDP;
1188 break;
1189 case 'T':
1190 ctl.socket_type = TYPE_TCP;
1191 break;
1192 case 'n':
1193 ctl.server = optarg;
1194 break;
1195 case 'P':
1196 ctl.port = optarg;
1197 break;
1198 case 'V':
1199 printf(UTIL_LINUX_VERSION);
1200 exit(EXIT_SUCCESS);
1201 case 'h':
1202 usage();
1203 case OPT_OCTET_COUNT:
1204 ctl.octet_count = 1;
1205 break;
1206 case OPT_PRIO_PREFIX:
1207 ctl.prio_prefix = 1;
1208 break;
1209 case OPT_RFC3164:
1210 ctl.syslogfp = syslog_rfc3164_header;
1211 break;
1212 case OPT_RFC5424:
1213 ctl.syslogfp = syslog_rfc5424_header;
1214 if (optarg)
1215 parse_rfc5424_flags(&ctl, optarg);
1216 break;
1217 case OPT_MSGID:
1218 if (strchr(optarg, ' '))
1219 errx(EXIT_FAILURE, _("--msgid cannot contain space"));
1220 ctl.msgid = optarg;
1221 break;
1222 #ifdef HAVE_LIBSYSTEMD
1223 case OPT_JOURNALD:
1224 if (optarg) {
1225 jfd = fopen(optarg, "r");
1226 if (!jfd)
1227 err(EXIT_FAILURE, _("cannot open %s"),
1228 optarg);
1229 } else
1230 jfd = stdin;
1231 break;
1232 #endif
1233 case OPT_SOCKET_ERRORS:
1234 unix_socket_errors_mode = parse_unix_socket_errors_flags(optarg);
1235 break;
1236 case OPT_NOACT:
1237 ctl.noact = 1;
1238 break;
1239 case OPT_STRUCTURED_DATA_ID:
1240 if (!valid_structured_data_id(optarg))
1241 errx(EXIT_FAILURE, _("invalid structured data ID: '%s'"), optarg);
1242 add_structured_data_id(get_user_structured_data(&ctl), optarg);
1243 break;
1244 case OPT_STRUCTURED_DATA_PARAM:
1245 if (!valid_structured_data_param(optarg))
1246 errx(EXIT_FAILURE, _("invalid structured data parameter: '%s'"), optarg);
1247 add_structured_data_param(get_user_structured_data(&ctl), optarg);
1248 break;
1249 default:
1250 errtryhelp(EXIT_FAILURE);
1251 }
1252 }
1253 argc -= optind;
1254 argv += optind;
1255 if (stdout_reopened && argc)
1256 warnx(_("--file <file> and <message> are mutually exclusive, message is ignored"));
1257 #ifdef HAVE_LIBSYSTEMD
1258 if (jfd) {
1259 int ret = journald_entry(&ctl, jfd);
1260 if (stdin != jfd)
1261 fclose(jfd);
1262 if (ret)
1263 errx(EXIT_FAILURE, _("journald entry could not be written"));
1264 return EXIT_SUCCESS;
1265 }
1266 #endif
1267
1268 /* user overwrites build-in SD-ELEMENT */
1269 if (has_structured_data_id(get_user_structured_data(&ctl), "timeQuality"))
1270 ctl.rfc5424_tq = 0;
1271
1272 switch (unix_socket_errors_mode) {
1273 case AF_UNIX_ERRORS_OFF:
1274 ctl.unix_socket_errors = 0;
1275 break;
1276 case AF_UNIX_ERRORS_ON:
1277 ctl.unix_socket_errors = 1;
1278 break;
1279 case AF_UNIX_ERRORS_AUTO:
1280 ctl.unix_socket_errors = ctl.noact || ctl.stderr_printout;
1281 #ifdef HAVE_LIBSYSTEMD
1282 ctl.unix_socket_errors |= !!sd_booted();
1283 #endif
1284 break;
1285 default:
1286 abort();
1287 }
1288 logger_open(&ctl);
1289 if (0 < argc)
1290 logger_command_line(&ctl, argv);
1291 else
1292 /* Note. --file <arg> reopens stdin making the below
1293 * function to be used for file inputs. */
1294 logger_stdin(&ctl);
1295 logger_close(&ctl);
1296 return EXIT_SUCCESS;
1297 }