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