2 * Copyright (c) 1983, 1993
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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.
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
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
47 #include <sys/types.h>
48 #include <sys/socket.h>
50 #include <arpa/inet.h>
59 #include "closestream.h"
61 #include "pathnames.h"
71 #ifdef HAVE_LIBSYSTEMD
72 # define SD_JOURNAL_SUPPRESS_LOCATION
73 # include <systemd/sd-daemon.h>
74 # include <systemd/sd-journal.h>
77 #ifdef HAVE_SYS_TIMEX_H
78 # include <sys/timex.h>
84 ALL_TYPES
= TYPE_UDP
| TYPE_TCP
88 AF_UNIX_ERRORS_OFF
= 0,
94 OPT_PRIO_PREFIX
= CHAR_MAX
+ 1,
102 OPT_STRUCTURED_DATA_ID
,
103 OPT_STRUCTURED_DATA_PARAM
,
107 /* rfc5424 structured data */
108 struct structured_data
{
109 char *id
; /* SD-ID */
110 char **params
; /* array with SD-PARAMs */
112 struct list_head sds
;
118 pid_t pid
; /* zero when unwanted */
119 char *hdr
; /* the syslog header (based on protocol) */
123 char *unix_socket
; /* -u <path> or default to _PATH_DEVLOG */
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 */
131 void (*syslogfp
)(struct logger_ctl
*ctl
);
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 */
145 #define is_connected(_ctl) ((_ctl)->fd >= 0)
146 static void logger_reopen(struct logger_ctl
*ctl
);
149 * For tests we want to be able to control datetime outputs
152 static inline int logger_gettimeofday(struct timeval
*tv
, struct timezone
*tz
)
154 char *str
= getenv("LOGGER_TEST_TIMEOFDAY");
158 if (sscanf(str
, "%ju.%ju", &sec
, &usec
) != 2)
164 if (tv
->tv_sec
>= 0 && tv
->tv_usec
>= 0)
170 return gettimeofday(tv
, tz
);
177 static inline char *logger_xgethostname(void)
179 char *str
= getenv("LOGGER_TEST_HOSTNAME");
180 return str
? xstrdup(str
) : xgethostname();
183 static inline pid_t
logger_getpid(void)
185 char *str
= getenv("LOGGER_TEST_GETPID");
188 if (str
&& sscanf(str
, "%u", &pid
) == 1)
194 #undef HAVE_NTP_GETTIME /* force to default non-NTP */
196 #else /* !TEST_LOGGER */
197 # define logger_gettimeofday(x, y) gettimeofday(x, y)
198 # define logger_xgethostname xgethostname
199 # define logger_getpid getpid
203 static int decode(const char *name
, const CODE
*codetab
)
205 register const CODE
*c
;
207 if (name
== NULL
|| *name
== '\0')
209 if (isdigit(*name
)) {
214 num
= strtol(name
, &end
, 10);
215 if (errno
|| name
== end
|| (end
&& *end
))
217 for (c
= codetab
; c
->c_name
; c
++)
222 for (c
= codetab
; c
->c_name
; c
++)
223 if (!strcasecmp(name
, c
->c_name
))
229 static int pencode(char *s
)
236 separator
= strchr(s
, '.');
239 facility
= decode(s
, facilitynames
);
241 errx(EXIT_FAILURE
, _("unknown facility name: %s"), s
);
245 level
= decode(s
, prioritynames
);
247 errx(EXIT_FAILURE
, _("unknown priority name: %s"), s
);
248 if (facility
== LOG_KERN
)
249 facility
= LOG_USER
; /* kern is forbidden */
250 return ((level
& LOG_PRIMASK
) | (facility
& LOG_FACMASK
));
253 static int unix_socket(struct logger_ctl
*ctl
, const char *path
, int *socket_type
)
255 int fd
= -1, i
, type
= -1;
256 static struct sockaddr_un s_addr
; /* AF_UNIX address of local logger */
258 if (strlen(path
) >= sizeof(s_addr
.sun_path
))
259 errx(EXIT_FAILURE
, _("openlog %s: pathname too long"), path
);
261 s_addr
.sun_family
= AF_UNIX
;
262 xstrncpy(s_addr
.sun_path
, path
, sizeof(s_addr
.sun_path
));
264 for (i
= 2; i
; i
--) {
267 if (i
== 2 && *socket_type
& TYPE_UDP
) {
271 if (i
== 1 && *socket_type
& TYPE_TCP
) {
275 if (st
== -1 || (fd
= socket(AF_UNIX
, st
, 0)) == -1)
277 if (connect(fd
, (struct sockaddr
*)&s_addr
, sizeof(s_addr
)) == -1) {
285 if (ctl
->unix_socket_errors
)
286 err(EXIT_FAILURE
, _("socket %s"), path
);
288 /* write_output() will try to reconnect */
292 /* replace ALL_TYPES with the real TYPE_* */
293 if (type
> 0 && type
!= *socket_type
)
298 static int inet_socket(const char *servername
, const char *port
, int *socket_type
)
300 int fd
, errcode
, i
, type
= -1;
301 struct addrinfo hints
, *res
;
302 const char *p
= port
;
304 for (i
= 2; i
; i
--) {
305 memset(&hints
, 0, sizeof(hints
));
306 if (i
== 2 && *socket_type
& TYPE_UDP
) {
307 hints
.ai_socktype
= SOCK_DGRAM
;
312 if (i
== 1 && *socket_type
& TYPE_TCP
) {
313 hints
.ai_socktype
= SOCK_STREAM
;
318 if (hints
.ai_socktype
== 0)
320 hints
.ai_family
= AF_UNSPEC
;
321 errcode
= getaddrinfo(servername
, p
, &hints
, &res
);
323 errx(EXIT_FAILURE
, _("failed to resolve name %s port %s: %s"),
324 servername
, p
, gai_strerror(errcode
));
325 if ((fd
= socket(res
->ai_family
, res
->ai_socktype
, res
->ai_protocol
)) == -1) {
329 if (connect(fd
, res
->ai_addr
, res
->ai_addrlen
) == -1) {
340 errx(EXIT_FAILURE
, _("failed to connect to %s port %s"), servername
, p
);
342 /* replace ALL_TYPES with the real TYPE_* */
343 if (type
> 0 && type
!= *socket_type
)
348 #ifdef HAVE_LIBSYSTEMD
349 static int journald_entry(struct logger_ctl
*ctl
, FILE *fp
)
354 int n
, lines
= 0, vectors
= 8, ret
= 0, msgline
= -1;
357 iovec
= xreallocarray(NULL
, vectors
, sizeof(struct iovec
));
360 sz
= getline(&buf
, &dummy
, fp
);
362 (sz
= rtrim_whitespace((unsigned char *) buf
)) == 0) {
367 if (strncmp(buf
, "MESSAGE=", 8) == 0) {
369 msgline
= lines
; /* remember the first message */
371 char *p
= xrealloc(iovec
[msgline
].iov_base
,
372 iovec
[msgline
].iov_len
+ sz
- 8 + 2);
374 iovec
[msgline
].iov_base
= p
;
375 p
+= iovec
[msgline
].iov_len
;
377 memcpy(p
, buf
+ 8, sz
- 8);
380 iovec
[msgline
].iov_len
+= sz
- 8 + 1;
385 if (lines
== vectors
) {
387 if (IOV_MAX
< vectors
)
388 errx(EXIT_FAILURE
, _("maximum input lines (%d) exceeded"), IOV_MAX
);
389 iovec
= xreallocarray(iovec
, vectors
, sizeof(struct iovec
));
391 iovec
[lines
].iov_base
= buf
;
392 iovec
[lines
].iov_len
= sz
;
397 ret
= sd_journal_sendv(iovec
, lines
);
398 if (ctl
->stderr_printout
) {
399 for (n
= 0; n
< lines
; n
++)
400 fprintf(stderr
, "%s\n", (char *) iovec
[n
].iov_base
);
402 for (n
= 0; n
< lines
; n
++)
403 free(iovec
[n
].iov_base
);
409 /* this creates a timestamp based on current time according to the
410 * fine rules of RFC3164, most importantly it ensures in a portable
411 * way that the month day is correctly written (with a SP instead
412 * of a leading 0). The function uses a static buffer which is
413 * overwritten on the next call (just like ctime() does).
415 static char const *rfc3164_current_time(void)
417 static char time
[32];
421 static char const * const monthnames
[] = {
422 "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
423 "Sep", "Oct", "Nov", "Dec"
426 ret
= logger_gettimeofday(&tv
, NULL
);
428 err(EXIT_FAILURE
, _("gettimeofday() failed"));
429 localtime_r(&tv
.tv_sec
, &tm
);
430 snprintf(time
, sizeof(time
),"%s %2d %2.2d:%2.2d:%2.2d",
431 monthnames
[tm
.tm_mon
], tm
.tm_mday
,
432 tm
.tm_hour
, tm
.tm_min
, tm
.tm_sec
);
436 #define next_iovec(ary, idx) __extension__ ({ \
437 assert(ARRAY_SIZE(ary) > (size_t)idx); \
442 #define iovec_add_string(ary, idx, str, len) \
444 struct iovec *v = next_iovec(ary, idx); \
445 v->iov_base = (void *) str; \
446 v->iov_len = len ? len : strlen(str); \
449 #define iovec_memcmp(ary, idx, str, len) \
450 memcmp((ary)[(idx) - 1].iov_base, str, len)
452 /* writes generated buffer to desired destination. For TCP syslog,
453 * we use RFC6587 octet-stuffing (unless octet-counting is selected).
454 * This is not great, but doing full blown RFC5425 (TLS) looks like
455 * it is too much for the logger utility. If octet-counting is
456 * selected, we use that.
458 static void write_output(struct logger_ctl
*ctl
, const char *const msg
)
464 /* initial connect failed? */
465 if (!ctl
->noact
&& !is_connected(ctl
))
469 if (ctl
->octet_count
) {
470 size_t len
= xasprintf(&octet
, "%zu ", strlen(ctl
->hdr
) + strlen(msg
));
471 iovec_add_string(iov
, iovlen
, octet
, len
);
475 iovec_add_string(iov
, iovlen
, ctl
->hdr
, 0);
478 iovec_add_string(iov
, iovlen
, msg
, 0);
480 if (!ctl
->noact
&& is_connected(ctl
)) {
481 struct msghdr message
= { 0 };
482 #ifdef SCM_CREDENTIALS
483 struct cmsghdr
*cmhp
;
487 char control
[CMSG_SPACE(sizeof(struct ucred
))];
488 } cbuf
= { .control
= { 0 } };
491 /* 4) add extra \n to make sure message is terminated */
492 if ((ctl
->socket_type
== TYPE_TCP
) && !ctl
->octet_count
)
493 iovec_add_string(iov
, iovlen
, "\n", 1);
495 message
.msg_iov
= iov
;
496 message
.msg_iovlen
= iovlen
;
498 #ifdef SCM_CREDENTIALS
499 /* syslog/journald may follow local socket credentials rather
500 * than in the message PID. If we use --id as root than we can
501 * force kernel to accept another valid PID than the real logger(1)
504 if (ctl
->pid
&& !ctl
->server
&& ctl
->pid
!= getpid()
505 && geteuid() == 0 && kill(ctl
->pid
, 0) == 0) {
507 message
.msg_control
= cbuf
.control
;
508 message
.msg_controllen
= CMSG_SPACE(sizeof(struct ucred
));
510 cmhp
= CMSG_FIRSTHDR(&message
);
511 cmhp
->cmsg_len
= CMSG_LEN(sizeof(struct ucred
));
512 cmhp
->cmsg_level
= SOL_SOCKET
;
513 cmhp
->cmsg_type
= SCM_CREDENTIALS
;
514 cred
= (struct ucred
*) CMSG_DATA(cmhp
);
516 cred
->pid
= ctl
->pid
;
519 /* Note that logger(1) maybe executed for long time (as pipe
520 * reader) and connection endpoint (syslogd) may be restarted.
522 * The libc syslog() function reconnects on failed send().
523 * Let's do the same to be robust. [kzak -- Oct 2017]
525 * MSG_NOSIGNAL is POSIX.1-2008 compatible, but it for example
526 * not supported by apple-darwin15.6.0.
529 # define MSG_NOSIGNAL 0
531 if (sendmsg(ctl
->fd
, &message
, MSG_NOSIGNAL
) < 0) {
533 if (sendmsg(ctl
->fd
, &message
, MSG_NOSIGNAL
) < 0)
534 warn(_("send message failed"));
538 if (ctl
->stderr_printout
) {
539 /* make sure it's terminated for stderr */
540 if (iovec_memcmp(iov
, iovlen
, "\n", 1) != 0)
541 iovec_add_string(iov
, iovlen
, "\n", 1);
543 ignore_result( writev(STDERR_FILENO
, iov
, iovlen
) );
550 static void syslog_rfc3164_header(struct logger_ctl
*const ctl
)
552 char pid
[30], *hostname
;
556 snprintf(pid
, sizeof(pid
), "[%d]", ctl
->pid
);
558 if ((hostname
= logger_xgethostname())) {
559 char *dot
= strchr(hostname
, '.');
563 hostname
= xstrdup(NILVALUE
);
565 xasprintf(&ctl
->hdr
, "<%d>%.15s %s %.200s%s: ",
566 ctl
->pri
, rfc3164_current_time(), hostname
, ctl
->tag
, pid
);
571 static inline struct list_head
*get_user_structured_data(struct logger_ctl
*ctl
)
573 return &ctl
->user_sds
;
576 static inline struct list_head
*get_reserved_structured_data(struct logger_ctl
*ctl
)
578 return &ctl
->reserved_sds
;
581 static int has_structured_data_id(struct list_head
*ls
, const char *id
)
585 if (!ls
|| list_empty(ls
))
588 list_for_each(p
, ls
) {
589 struct structured_data
*sd
= list_entry(p
, struct structured_data
, sds
);
590 if (sd
->id
&& strcmp(sd
->id
, id
) == 0)
597 static void add_structured_data_id(struct list_head
*ls
, const char *id
)
599 struct structured_data
*sd
;
603 if (has_structured_data_id(ls
, id
))
604 errx(EXIT_FAILURE
, _("structured data ID '%s' is not unique"), id
);
606 sd
= xcalloc(1, sizeof(*sd
));
607 INIT_LIST_HEAD(&sd
->sds
);
608 sd
->id
= xstrdup(id
);
610 list_add_tail(&sd
->sds
, ls
);
613 static void add_structured_data_param(struct list_head
*ls
, const char *param
)
615 struct structured_data
*sd
;
618 errx(EXIT_FAILURE
, _("--sd-id was not specified for --sd-param %s"), param
);
622 sd
= list_last_entry(ls
, struct structured_data
, sds
);
624 if (strv_extend(&sd
->params
, param
))
628 static void __attribute__ ((__format__ (__printf__
, 2, 3)))
629 add_structured_data_paramf(struct list_head
*ls
, const char *fmt
, ...)
631 struct structured_data
*sd
;
635 assert(!list_empty(ls
));
638 sd
= list_last_entry(ls
, struct structured_data
, sds
);
640 x
= strv_extendv(&sd
->params
, fmt
, ap
);
647 static char *strdup_structured_data(struct structured_data
*sd
)
651 if (strv_isempty(sd
->params
))
654 xasprintf(&res
, "[%s %s]", sd
->id
,
655 (tmp
= strv_join(sd
->params
, " ")));
660 static char *strdup_structured_data_list(struct list_head
*ls
)
665 list_for_each(p
, ls
) {
666 struct structured_data
*sd
= list_entry(p
, struct structured_data
, sds
);
667 char *one
= strdup_structured_data(sd
);
672 res
= strconcat(tmp
, one
);
680 static char *get_structured_data_string(struct logger_ctl
*ctl
)
682 char *sys
= NULL
, *usr
= NULL
, *res
;
684 if (!list_empty(&ctl
->reserved_sds
))
685 sys
= strdup_structured_data_list(&ctl
->reserved_sds
);
686 if (!list_empty(&ctl
->user_sds
))
687 usr
= strdup_structured_data_list(&ctl
->user_sds
);
690 res
= strconcat(sys
, usr
);
694 res
= sys
? sys
: usr
;
699 static int valid_structured_data_param(const char *str
)
702 char *eq
= strchr(str
, '='),
703 *qm1
= strchr(str
, '"'),
704 *qm2
= qm1
? ul_strchr_escaped(qm1
+ 1, '"') : NULL
;
706 /* something is missing */
707 if (!eq
|| !qm1
|| !qm2
)
710 /* ']' need to be escaped */
711 for (s
= qm1
+ 1; s
&& *s
; ) {
712 char *p
= strchr(s
, ']');
715 if (p
> qm2
|| p
== ul_strchr_escaped(s
, ']'))
720 /* '\' is allowed only before '[]"\' chars */
721 for (s
= qm1
+ 1; s
&& *s
; ) {
722 char *p
= strchr(s
, '\\');
725 if (!strchr("[]\"\\", *(p
+ 1)))
733 return eq
> str
&& eq
< qm1
&& eq
+ 1 == qm1
&& qm1
< qm2
&& *(qm2
+ 1) == '\0';
737 * name@<private enterprise number>, e.g., "ourSDID@32473"
739 static int valid_structured_data_id(const char *str
)
741 char *at
= strchr(str
, '@');
744 /* standardized IDs without @<digits> */
745 if (!at
&& (strcmp(str
, "timeQuality") == 0 ||
746 strcmp(str
, "origin") == 0 ||
747 strcmp(str
, "meta") == 0))
750 if (!at
|| at
== str
|| !*(at
+ 1))
753 /* <digits> or <digits>.<digits>[...] */
754 for (p
= at
+ 1; p
&& *p
; p
++) {
757 if (isdigit_strend(p
, &end
))
758 break; /* only digits in the string */
760 if (end
== NULL
|| end
== p
||
761 *end
!= '.' || *(end
+ 1) == '\0')
766 /* check for forbidden chars in the <name> */
767 for (p
= str
; p
< at
; p
++) {
768 if (*p
== '[' || *p
== '=' || *p
== '"' || *p
== '@')
770 if (isblank((unsigned char) *p
) || iscntrl((unsigned char) *p
))
777 /* Some field mappings may be controversial, thus I give the reason
778 * why this specific mapping was used:
780 * Some may argue that "logger" is a better fit, but we think
781 * this is better inline of what other implementations do. In
782 * rsyslog, for example, the TAG value is populated from APP-NAME.
784 * This is a relatively straightforward interpretation from
785 * RFC5424, sect. 6.2.6.
786 * MSGID <-- msgid (from --msgid)
787 * One may argue that the string "logger" would be better suited
788 * here so that a receiver can identify the sender process.
789 * However, this does not sound like a good match to RFC5424,
791 * Note that appendix A.1 of RFC5424 does not provide clear guidance
792 * of how these fields should be used. This is the case because the
793 * IETF working group couldn't arrive at a clear agreement when we
794 * specified RFC5424. The rest of the field mappings should be
795 * pretty clear from RFC5424. -- Rainer Gerhards, 2015-03-10
797 static void syslog_rfc5424_header(struct logger_ctl
*const ctl
)
802 char const *app_name
= ctl
->tag
;
804 char *const msgid
= xstrdup(ctl
->msgid
? ctl
->msgid
: NILVALUE
);
805 char *structured
= NULL
;
806 struct list_head
*sd
;
808 if (ctl
->rfc5424_time
) {
812 ret
= logger_gettimeofday(&tv
, NULL
);
814 err(EXIT_FAILURE
, _("gettimeofday() failed"));
815 if (localtime_r(&tv
.tv_sec
, &tm
) != NULL
) {
817 const size_t i
= strftime(fmt
, sizeof(fmt
),
818 "%Y-%m-%dT%H:%M:%S.%%06jd%z ", &tm
);
819 /* patch TZ info to comply with RFC3339 (we left SP at end) */
820 fmt
[i
- 1] = fmt
[i
- 2];
821 fmt
[i
- 2] = fmt
[i
- 3];
823 xasprintf(&time
, fmt
, (intmax_t) tv
.tv_usec
);
825 err(EXIT_FAILURE
, _("localtime() failed"));
827 time
= xstrdup(NILVALUE
);
829 if (ctl
->rfc5424_host
) {
830 if (!(hostname
= logger_xgethostname()))
831 hostname
= xstrdup(NILVALUE
);
832 /* Arbitrary looking 'if (var < strlen()) checks originate from
833 * RFC 5424 - 6 Syslog Message Format definition. */
834 if (255 < strlen(hostname
))
835 errx(EXIT_FAILURE
, _("hostname '%s' is too long"),
838 hostname
= xstrdup(NILVALUE
);
840 if (48 < strlen(ctl
->tag
))
841 errx(EXIT_FAILURE
, _("tag '%s' is too long"), ctl
->tag
);
844 xasprintf(&procid
, "%d", ctl
->pid
);
846 procid
= xstrdup(NILVALUE
);
848 sd
= get_reserved_structured_data(ctl
);
850 /* time quality structured data (maybe overwritten by --sd-id timeQuality) */
851 if (ctl
->rfc5424_tq
&& !has_structured_data_id(sd
, "timeQuality")) {
853 add_structured_data_id(sd
, "timeQuality");
854 add_structured_data_param(sd
, "tzKnown=\"1\"");
856 #ifdef HAVE_NTP_GETTIME
857 struct ntptimeval ntptv
;
859 if (ntp_gettime(&ntptv
) == TIME_OK
) {
860 add_structured_data_param(sd
, "isSynced=\"1\"");
861 add_structured_data_paramf(sd
, "syncAccuracy=\"%ld\"", ntptv
.maxerror
);
864 add_structured_data_paramf(sd
, "isSynced=\"0\"");
867 /* convert all structured data to string */
868 structured
= get_structured_data_string(ctl
);
870 structured
= xstrdup(NILVALUE
);
872 xasprintf(&ctl
->hdr
, "<%d>1 %s %s %s %s %s %s ",
883 /* app_name points to ctl->tag, do NOT free! */
889 static void parse_rfc5424_flags(struct logger_ctl
*ctl
, char *s
)
894 while ((tok
= strtok(in
, ","))) {
896 if (!strcmp(tok
, "notime")) {
897 ctl
->rfc5424_time
= 0;
899 } else if (!strcmp(tok
, "notq"))
901 else if (!strcmp(tok
, "nohost"))
902 ctl
->rfc5424_host
= 0;
904 warnx(_("ignoring unknown option argument: %s"), tok
);
908 static int parse_unix_socket_errors_flags(char *s
)
910 if (!strcmp(s
, "off"))
911 return AF_UNIX_ERRORS_OFF
;
912 if (!strcmp(s
, "on"))
913 return AF_UNIX_ERRORS_ON
;
914 if (!strcmp(s
, "auto"))
915 return AF_UNIX_ERRORS_AUTO
;
916 warnx(_("invalid argument: %s: using automatic errors"), s
);
917 return AF_UNIX_ERRORS_AUTO
;
920 static void syslog_local_header(struct logger_ctl
*const ctl
)
925 snprintf(pid
, sizeof(pid
), "[%d]", ctl
->pid
);
929 xasprintf(&ctl
->hdr
, "<%d>%s %s%s: ", ctl
->pri
, rfc3164_current_time(),
933 static void generate_syslog_header(struct logger_ctl
*const ctl
)
940 /* just open, nothing else */
941 static void __logger_open(struct logger_ctl
*ctl
)
944 ctl
->fd
= inet_socket(ctl
->server
, ctl
->port
, &ctl
->socket_type
);
946 if (!ctl
->unix_socket
)
947 ctl
->unix_socket
= _PATH_DEVLOG
;
949 ctl
->fd
= unix_socket(ctl
, ctl
->unix_socket
, &ctl
->socket_type
);
953 /* open and initialize relevant @ctl tuff */
954 static void logger_open(struct logger_ctl
*ctl
)
959 ctl
->syslogfp
= ctl
->server
? syslog_rfc5424_header
:
962 ctl
->tag
= ctl
->login
= xgetlogin();
964 ctl
->tag
= "<someone>";
967 /* re-open; usually after failed connection */
968 static void logger_reopen(struct logger_ctl
*ctl
)
977 static void logger_command_line(struct logger_ctl
*ctl
, char **argv
)
979 /* note: we never re-generate the syslog header here, even if we
980 * generate multiple messages. If so, we think it is the right thing
981 * to do to report them with the same timestamp, as the user actually
982 * intended to send a single message.
984 char *const buf
= xmalloc(ctl
->max_message_size
+ 1);
986 const char *endp
= buf
+ ctl
->max_message_size
- 1;
991 if (endp
< p
+ len
&& p
!= buf
) {
992 write_output(ctl
, buf
);
995 if (ctl
->max_message_size
< len
) {
996 (*argv
)[ctl
->max_message_size
] = '\0'; /* truncate */
997 write_output(ctl
, *argv
++);
1002 memmove(p
, *argv
++, len
);
1006 write_output(ctl
, buf
);
1010 static void logger_stdin(struct logger_ctl
*ctl
)
1012 /* note: we re-generate the syslog header for each log message to
1013 * update header timestamps and to reflect possible priority changes.
1015 int default_priority
= ctl
->pri
;
1016 char *buf
= xmalloc(ctl
->max_message_size
+ 2 + 2);
1024 if (ctl
->prio_prefix
&& c
== '<') {
1027 while (isdigit(c
= getchar()) && pri
<= 191) {
1029 pri
= pri
* 10 + c
- '0';
1031 if (c
!= EOF
&& c
!= '\n')
1033 if (c
== '>' && 0 <= pri
&& pri
<= 191) {
1034 /* valid RFC PRI values */
1036 if ((pri
& LOG_FACMASK
) == 0)
1037 pri
|= (default_priority
& LOG_FACMASK
);
1040 ctl
->pri
= default_priority
;
1042 if (c
!= EOF
&& c
!= '\n')
1046 while (c
!= EOF
&& c
!= '\n' && i
< ctl
->max_message_size
) {
1052 if (i
> 0 || !ctl
->skip_empty_lines
) {
1053 generate_syslog_header(ctl
);
1054 write_output(ctl
, buf
);
1057 if (c
== '\n') /* discard line terminator */
1064 static void logger_close(const struct logger_ctl
*ctl
)
1066 if (ctl
->fd
!= -1 && close(ctl
->fd
) != 0)
1067 err(EXIT_FAILURE
, _("close failed"));
1072 static void __attribute__((__noreturn__
)) usage(void)
1075 fputs(USAGE_HEADER
, out
);
1076 fprintf(out
, _(" %s [options] [<message>]\n"), program_invocation_short_name
);
1078 fputs(USAGE_SEPARATOR
, out
);
1079 fputs(_("Enter messages into the system log.\n"), out
);
1081 fputs(USAGE_OPTIONS
, out
);
1082 fputs(_(" -i log the logger command's PID\n"), out
);
1083 fputs(_(" --id[=<id>] log the given <id>, or otherwise the PID\n"), out
);
1084 fputs(_(" -f, --file <file> log the contents of this file\n"), out
);
1085 fputs(_(" -e, --skip-empty do not log empty lines when processing files\n"), out
);
1086 fputs(_(" --no-act do everything except the write the log\n"), out
);
1087 fputs(_(" -p, --priority <prio> mark given message with this priority\n"), out
);
1088 fputs(_(" --octet-count use rfc6587 octet counting\n"), out
);
1089 fputs(_(" --prio-prefix look for a prefix on every line read from stdin\n"), out
);
1090 fputs(_(" -s, --stderr output message to standard error as well\n"), out
);
1091 fputs(_(" -S, --size <size> maximum size for a single message\n"), out
);
1092 fputs(_(" -t, --tag <tag> mark every line with this tag\n"), out
);
1093 fputs(_(" -n, --server <name> write to this remote syslog server\n"), out
);
1094 fputs(_(" -P, --port <port> use this port for UDP or TCP connection\n"), out
);
1095 fputs(_(" -T, --tcp use TCP only\n"), out
);
1096 fputs(_(" -d, --udp use UDP only\n"), out
);
1097 fputs(_(" --rfc3164 use the obsolete BSD syslog protocol\n"), out
);
1098 fputs(_(" --rfc5424[=<snip>] use the syslog protocol (the default for remote);\n"
1099 " <snip> can be notime, or notq, and/or nohost\n"), out
);
1100 fputs(_(" --sd-id <id> rfc5424 structured data ID\n"), out
);
1101 fputs(_(" --sd-param <data> rfc5424 structured data name=value\n"), out
);
1102 fputs(_(" --msgid <msgid> set rfc5424 message id field\n"), out
);
1103 fputs(_(" -u, --socket <socket> write to this Unix socket\n"), out
);
1104 fputs(_(" --socket-errors[=<on|off|auto>]\n"
1105 " print connection errors when using Unix sockets\n"), out
);
1106 #ifdef HAVE_LIBSYSTEMD
1107 fputs(_(" --journald[=<file>] write journald entry\n"), out
);
1110 fputs(USAGE_SEPARATOR
, out
);
1111 fprintf(out
, USAGE_HELP_OPTIONS(26));
1112 fprintf(out
, USAGE_MAN_TAIL("logger(1)"));
1118 * logger -- read and log utility
1120 * Reads from an input and arranges to write the result on the system
1123 int main(int argc
, char **argv
)
1125 struct logger_ctl ctl
= {
1128 .pri
= LOG_USER
| LOG_NOTICE
,
1131 .unix_socket
= NULL
,
1132 .unix_socket_errors
= 0,
1137 .socket_type
= ALL_TYPES
,
1138 .max_message_size
= 1024,
1142 .skip_empty_lines
= 0
1145 int stdout_reopened
= 0;
1146 int unix_socket_errors_mode
= AF_UNIX_ERRORS_AUTO
;
1147 #ifdef HAVE_LIBSYSTEMD
1150 static const struct option longopts
[] = {
1151 { "id", optional_argument
, 0, OPT_ID
},
1152 { "stderr", no_argument
, 0, 's' },
1153 { "file", required_argument
, 0, 'f' },
1154 { "no-act", no_argument
, 0, OPT_NOACT
, },
1155 { "priority", required_argument
, 0, 'p' },
1156 { "tag", required_argument
, 0, 't' },
1157 { "socket", required_argument
, 0, 'u' },
1158 { "socket-errors", required_argument
, 0, OPT_SOCKET_ERRORS
},
1159 { "udp", no_argument
, 0, 'd' },
1160 { "tcp", no_argument
, 0, 'T' },
1161 { "server", required_argument
, 0, 'n' },
1162 { "port", required_argument
, 0, 'P' },
1163 { "version", no_argument
, 0, 'V' },
1164 { "help", no_argument
, 0, 'h' },
1165 { "octet-count", no_argument
, 0, OPT_OCTET_COUNT
},
1166 { "prio-prefix", no_argument
, 0, OPT_PRIO_PREFIX
},
1167 { "rfc3164", no_argument
, 0, OPT_RFC3164
},
1168 { "rfc5424", optional_argument
, 0, OPT_RFC5424
},
1169 { "size", required_argument
, 0, 'S' },
1170 { "msgid", required_argument
, 0, OPT_MSGID
},
1171 { "skip-empty", no_argument
, 0, 'e' },
1172 { "sd-id", required_argument
, 0, OPT_STRUCTURED_DATA_ID
},
1173 { "sd-param", required_argument
, 0, OPT_STRUCTURED_DATA_PARAM
},
1174 #ifdef HAVE_LIBSYSTEMD
1175 { "journald", optional_argument
, 0, OPT_JOURNALD
},
1180 setlocale(LC_ALL
, "");
1181 bindtextdomain(PACKAGE
, LOCALEDIR
);
1182 textdomain(PACKAGE
);
1183 close_stdout_atexit();
1185 INIT_LIST_HEAD(&ctl
.user_sds
);
1186 INIT_LIST_HEAD(&ctl
.reserved_sds
);
1188 while ((ch
= getopt_long(argc
, argv
, "ef:ip:S:st:u:dTn:P:Vh",
1189 longopts
, NULL
)) != -1) {
1191 case 'f': /* file to log */
1192 if (freopen(optarg
, "r", stdin
) == NULL
)
1193 err(EXIT_FAILURE
, _("file %s"), optarg
);
1194 stdout_reopened
= 1;
1197 ctl
.skip_empty_lines
= 1;
1199 case 'i': /* log process id also */
1200 ctl
.pid
= logger_getpid();
1204 const char *p
= optarg
;
1208 ctl
.pid
= strtoul_or_err(optarg
, _("failed to parse id"));
1210 ctl
.pid
= logger_getpid();
1212 case 'p': /* priority */
1213 ctl
.pri
= pencode(optarg
);
1215 case 's': /* log to standard error */
1216 ctl
.stderr_printout
= 1;
1221 case 'u': /* unix socket */
1222 ctl
.unix_socket
= optarg
;
1224 case 'S': /* max message size */
1225 ctl
.max_message_size
= strtosize_or_err(optarg
,
1226 _("failed to parse message size"));
1229 ctl
.socket_type
= TYPE_UDP
;
1232 ctl
.socket_type
= TYPE_TCP
;
1235 ctl
.server
= optarg
;
1240 case OPT_OCTET_COUNT
:
1241 ctl
.octet_count
= 1;
1243 case OPT_PRIO_PREFIX
:
1244 ctl
.prio_prefix
= 1;
1247 ctl
.syslogfp
= syslog_rfc3164_header
;
1250 ctl
.syslogfp
= syslog_rfc5424_header
;
1252 parse_rfc5424_flags(&ctl
, optarg
);
1255 if (strchr(optarg
, ' '))
1256 errx(EXIT_FAILURE
, _("--msgid cannot contain space"));
1259 #ifdef HAVE_LIBSYSTEMD
1262 jfd
= fopen(optarg
, "r");
1264 err(EXIT_FAILURE
, _("cannot open %s"),
1270 case OPT_SOCKET_ERRORS
:
1271 unix_socket_errors_mode
= parse_unix_socket_errors_flags(optarg
);
1276 case OPT_STRUCTURED_DATA_ID
:
1277 if (!valid_structured_data_id(optarg
))
1278 errx(EXIT_FAILURE
, _("invalid structured data ID: '%s'"), optarg
);
1279 add_structured_data_id(get_user_structured_data(&ctl
), optarg
);
1281 case OPT_STRUCTURED_DATA_PARAM
:
1282 if (!valid_structured_data_param(optarg
))
1283 errx(EXIT_FAILURE
, _("invalid structured data parameter: '%s'"), optarg
);
1284 add_structured_data_param(get_user_structured_data(&ctl
), optarg
);
1288 print_version(EXIT_SUCCESS
);
1292 errtryhelp(EXIT_FAILURE
);
1297 if (stdout_reopened
&& argc
)
1298 warnx(_("--file <file> and <message> are mutually exclusive, message is ignored"));
1299 #ifdef HAVE_LIBSYSTEMD
1301 int ret
= journald_entry(&ctl
, jfd
);
1305 errx(EXIT_FAILURE
, _("journald entry could not be written"));
1306 return EXIT_SUCCESS
;
1310 /* user overwrites built-in SD-ELEMENT */
1311 if (has_structured_data_id(get_user_structured_data(&ctl
), "timeQuality"))
1314 switch (unix_socket_errors_mode
) {
1315 case AF_UNIX_ERRORS_OFF
:
1316 ctl
.unix_socket_errors
= 0;
1318 case AF_UNIX_ERRORS_ON
:
1319 ctl
.unix_socket_errors
= 1;
1321 case AF_UNIX_ERRORS_AUTO
:
1322 ctl
.unix_socket_errors
= ctl
.noact
|| ctl
.stderr_printout
;
1323 #ifdef HAVE_LIBSYSTEMD
1324 ctl
.unix_socket_errors
|= !!sd_booted();
1332 generate_syslog_header(&ctl
);
1333 logger_command_line(&ctl
, argv
);
1335 /* Note. --file <arg> reopens stdin making the below
1336 * function to be used for file inputs. */
1340 return EXIT_SUCCESS
;