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