1 /* vi: set sw=4 ts=4: */
3 * Mini syslogd implementation for busybox
5 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
7 * Copyright (C) 2000 by Karl M. Hegbloom <karlheg@debian.org>
9 * "circular buffer" Copyright (C) 2001 by Gennady Feldman <gfeldman@gena01.com>
11 * Maintainer: Gennady Feldman <gfeldman@gena01.com> as of Mar 12, 2001
13 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
16 //usage:#define syslogd_trivial_usage
18 //usage:#define syslogd_full_usage "\n\n"
19 //usage: "System logging utility\n"
20 //usage: IF_NOT_FEATURE_SYSLOGD_CFG(
21 //usage: "(this version of syslogd ignores /etc/syslog.conf)\n"
24 //usage: "\n -n Run in foreground"
25 //usage: "\n -O FILE Log to FILE (default:/var/log/messages)"
26 //usage: "\n -l N Log only messages more urgent than prio N (1-8)"
27 //usage: "\n -S Smaller output"
28 //usage: IF_FEATURE_ROTATE_LOGFILE(
29 //usage: "\n -s SIZE Max size (KB) before rotation (default:200KB, 0=off)"
30 //usage: "\n -b N N rotated logs to keep (default:1, max=99, 0=purge)"
32 //usage: IF_FEATURE_REMOTE_LOG(
33 //usage: "\n -R HOST[:PORT] Log to IP or hostname on PORT (default PORT=514/UDP)"
34 //usage: "\n -L Log locally and via network (default is network only if -R)"
36 //usage: IF_FEATURE_SYSLOGD_DUP(
37 //usage: "\n -D Drop duplicates"
39 //usage: IF_FEATURE_IPC_SYSLOG(
40 /* NB: -Csize shouldn't have space (because size is optional) */
41 //usage: "\n -C[size_kb] Log to shared mem buffer (use logread to read it)"
43 //usage: IF_FEATURE_SYSLOGD_CFG(
44 //usage: "\n -f FILE Use FILE as config (default:/etc/syslog.conf)"
46 /* //usage: "\n -m MIN Minutes between MARK lines (default:20, 0=off)" */
48 //usage:#define syslogd_example_usage
49 //usage: "$ syslogd -R masterlog:514\n"
50 //usage: "$ syslogd -R 192.168.1.1:601\n"
53 * Done in syslogd_and_logger.c:
56 #define SYSLOG_NAMES_CONST
63 #if ENABLE_FEATURE_REMOTE_LOG
64 #include <netinet/in.h>
67 #if ENABLE_FEATURE_IPC_SYSLOG
76 /* MARK code is not very useful, is bloat, and broken:
77 * can deadlock if alarmed to make MARK while writing to IPC buffer
78 * (semaphores are down but do_mark routine tries to down them again) */
81 /* Write locking does not seem to be useful either */
85 MAX_READ = CONFIG_FEATURE_SYSLOGD_READ_BUFFER_SIZE,
86 DNS_WAIT_SEC = 2 * 60,
89 /* Semaphore operation structures */
91 int32_t size; /* size of data - 1 */
92 int32_t tail; /* end of message list */
93 char data[1]; /* data/messages */
96 #if ENABLE_FEATURE_REMOTE_LOG
99 unsigned last_dns_resolve;
100 len_and_sockaddr *remoteAddr;
101 const char *remoteHostname;
105 typedef struct logFile_t {
108 #if ENABLE_FEATURE_ROTATE_LOGFILE
114 #if ENABLE_FEATURE_SYSLOGD_CFG
115 typedef struct logRule_t {
116 uint8_t enabled_facility_priomap[LOG_NFACILITIES];
117 struct logFile_t *file;
118 struct logRule_t *next;
122 /* Allows us to have smaller initializer. Ugly. */
125 /* interval between marks in seconds */ \
126 /*int markInterval;*/ \
127 /* level of messages to be logged */ \
129 IF_FEATURE_ROTATE_LOGFILE( \
130 /* max size of file before rotation */ \
131 unsigned logFileSize; \
132 /* number of rotated message files */ \
133 unsigned logFileRotate; \
135 IF_FEATURE_IPC_SYSLOG( \
136 int shmid; /* ipc shared memory id */ \
137 int s_semid; /* ipc semaphore id */ \
139 struct sembuf SMwup[1]; \
140 struct sembuf SMwdn[3]; \
142 IF_FEATURE_SYSLOGD_CFG( \
143 logRule_t *log_rules; \
146 struct init_globals {
153 #if ENABLE_FEATURE_REMOTE_LOG
154 llist_t *remoteHosts;
156 #if ENABLE_FEATURE_IPC_SYSLOG
157 struct shbuf_ds *shbuf;
159 time_t last_log_time;
160 /* localhost's name. We print only first 64 chars */
163 /* We recv into recvbuf... */
164 char recvbuf[MAX_READ * (1 + ENABLE_FEATURE_SYSLOGD_DUP)];
165 /* ...then copy to parsebuf, escaping control chars */
166 /* (can grow x2 max) */
167 char parsebuf[MAX_READ*2];
168 /* ...then sprintf into printbuf, adding timestamp (15 chars),
169 * host (64), fac.prio (20) to the message */
170 /* (growth by: 15 + 64 + 20 + delims = ~110) */
171 char printbuf[MAX_READ*2 + 128];
174 static const struct init_globals init_data = {
176 .path = "/var/log/messages",
180 .markInterval = 20 * 60,
183 #if ENABLE_FEATURE_ROTATE_LOGFILE
184 .logFileSize = 200 * 1024,
187 #if ENABLE_FEATURE_IPC_SYSLOG
190 .shm_size = ((CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE)*1024), /* default shm size */
191 .SMwup = { {1, -1, IPC_NOWAIT} },
192 .SMwdn = { {0, 0}, {1, 0}, {1, +1} },
196 #define G (*ptr_to_globals)
197 #define INIT_G() do { \
198 SET_PTR_TO_GLOBALS(memcpy(xzalloc(sizeof(G)), &init_data, sizeof(init_data))); \
204 OPTBIT_mark = 0, // -m
206 OPTBIT_outfile, // -O
207 OPTBIT_loglevel, // -l
209 IF_FEATURE_ROTATE_LOGFILE(OPTBIT_filesize ,) // -s
210 IF_FEATURE_ROTATE_LOGFILE(OPTBIT_rotatecnt ,) // -b
211 IF_FEATURE_REMOTE_LOG( OPTBIT_remotelog ,) // -R
212 IF_FEATURE_REMOTE_LOG( OPTBIT_locallog ,) // -L
213 IF_FEATURE_IPC_SYSLOG( OPTBIT_circularlog,) // -C
214 IF_FEATURE_SYSLOGD_DUP( OPTBIT_dup ,) // -D
215 IF_FEATURE_SYSLOGD_CFG( OPTBIT_cfg ,) // -f
217 OPT_mark = 1 << OPTBIT_mark ,
218 OPT_nofork = 1 << OPTBIT_nofork ,
219 OPT_outfile = 1 << OPTBIT_outfile ,
220 OPT_loglevel = 1 << OPTBIT_loglevel,
221 OPT_small = 1 << OPTBIT_small ,
222 OPT_filesize = IF_FEATURE_ROTATE_LOGFILE((1 << OPTBIT_filesize )) + 0,
223 OPT_rotatecnt = IF_FEATURE_ROTATE_LOGFILE((1 << OPTBIT_rotatecnt )) + 0,
224 OPT_remotelog = IF_FEATURE_REMOTE_LOG( (1 << OPTBIT_remotelog )) + 0,
225 OPT_locallog = IF_FEATURE_REMOTE_LOG( (1 << OPTBIT_locallog )) + 0,
226 OPT_circularlog = IF_FEATURE_IPC_SYSLOG( (1 << OPTBIT_circularlog)) + 0,
227 OPT_dup = IF_FEATURE_SYSLOGD_DUP( (1 << OPTBIT_dup )) + 0,
228 OPT_cfg = IF_FEATURE_SYSLOGD_CFG( (1 << OPTBIT_cfg )) + 0,
230 #define OPTION_STR "m:nO:l:S" \
231 IF_FEATURE_ROTATE_LOGFILE("s:" ) \
232 IF_FEATURE_ROTATE_LOGFILE("b:" ) \
233 IF_FEATURE_REMOTE_LOG( "R:" ) \
234 IF_FEATURE_REMOTE_LOG( "L" ) \
235 IF_FEATURE_IPC_SYSLOG( "C::") \
236 IF_FEATURE_SYSLOGD_DUP( "D" ) \
237 IF_FEATURE_SYSLOGD_CFG( "f:" )
238 #define OPTION_DECL *opt_m, *opt_l \
239 IF_FEATURE_ROTATE_LOGFILE(,*opt_s) \
240 IF_FEATURE_ROTATE_LOGFILE(,*opt_b) \
241 IF_FEATURE_IPC_SYSLOG( ,*opt_C = NULL) \
242 IF_FEATURE_SYSLOGD_CFG( ,*opt_f = NULL)
243 #define OPTION_PARAM &opt_m, &(G.logFile.path), &opt_l \
244 IF_FEATURE_ROTATE_LOGFILE(,&opt_s) \
245 IF_FEATURE_ROTATE_LOGFILE(,&opt_b) \
246 IF_FEATURE_REMOTE_LOG( ,&remoteAddrList) \
247 IF_FEATURE_IPC_SYSLOG( ,&opt_C) \
248 IF_FEATURE_SYSLOGD_CFG( ,&opt_f)
251 #if ENABLE_FEATURE_SYSLOGD_CFG
252 static const CODE* find_by_name(char *name, const CODE* c_set)
254 for (; c_set->c_name; c_set++) {
255 if (strcmp(name, c_set->c_name) == 0)
261 static const CODE* find_by_val(int val, const CODE* c_set)
263 for (; c_set->c_name; c_set++) {
264 if (c_set->c_val == val)
270 #if ENABLE_FEATURE_SYSLOGD_CFG
271 static void parse_syslogdcfg(const char *file)
275 /* tok[0] set of selectors */
276 /* tok[1] file name */
277 /* tok[2] has to be NULL */
281 parser = config_open2(file ? file : "/etc/syslog.conf",
282 file ? xfopen_for_read : fopen_or_warn_stdin);
284 /* didn't find default /etc/syslog.conf */
285 /* proceed as if we built busybox without config support */
288 /* use ptr to ptr to avoid checking whether head was initialized */
289 pp_rule = &G.log_rules;
290 /* iterate through lines of config, skipping comments */
291 while (config_read(parser, tok, 3, 2, "# \t", PARSE_NORMAL | PARSE_MIN_DIE)) {
295 /* unexpected trailing token? */
299 cur_rule = *pp_rule = xzalloc(sizeof(*cur_rule));
301 cur_selector = tok[0];
302 /* iterate through selectors: "kern.info;kern.!err;..." */
306 uint8_t negated_prio; /* "kern.!err" */
307 uint8_t single_prio; /* "kern.=err" */
308 uint32_t facmap; /* bitmap of enabled facilities */
309 uint8_t primap; /* bitmap of enabled priorities */
312 next_selector = strchr(cur_selector, ';');
314 *next_selector++ = '\0';
316 t = strchr(cur_selector, '.');
319 *t++ = '\0'; /* separate facility from priority */
334 primap = 0xff; /* all 8 log levels enabled */
337 code = find_by_name(t, prioritynames);
341 priority = code->c_val;
342 if (priority == INTERNAL_NOPRI) {
343 /* ensure we take "enabled_facility_priomap[fac] &= 0" branch below */
346 priority = 1 << priority;
359 if (*cur_selector == '*')
360 facmap = (1<<LOG_NFACILITIES) - 1;
365 /* iterate through facilities: "kern,daemon.<priospec>" */
367 next_facility = strchr(t, ',');
369 *next_facility++ = '\0';
370 code = find_by_name(t, facilitynames);
373 /* "mark" is not a real facility, skip it */
374 if (code->c_val != INTERNAL_MARK)
375 facmap |= 1<<(LOG_FAC(code->c_val));
380 /* merge result with previous selectors */
381 for (i = 0; i < LOG_NFACILITIES; ++i) {
382 if (!(facmap & (1<<i)))
385 cur_rule->enabled_facility_priomap[i] &= primap;
387 cur_rule->enabled_facility_priomap[i] |= primap;
390 cur_selector = next_selector;
391 } while (cur_selector);
393 /* check whether current file name was mentioned in previous rules or
394 * as global logfile (G.logFile).
396 if (strcmp(G.logFile.path, tok[1]) == 0) {
397 cur_rule->file = &G.logFile;
400 /* temporarily use cur_rule as iterator, but *pp_rule still points
401 * to currently processing rule entry.
402 * NOTE: *pp_rule points to the current (and last in the list) rule.
404 for (cur_rule = G.log_rules; cur_rule != *pp_rule; cur_rule = cur_rule->next) {
405 if (strcmp(cur_rule->file->path, tok[1]) == 0) {
406 /* found - reuse the same file structure */
407 (*pp_rule)->file = cur_rule->file;
412 cur_rule->file = xzalloc(sizeof(*cur_rule->file));
413 cur_rule->file->fd = -1;
414 cur_rule->file->path = xstrdup(tok[1]);
416 pp_rule = &cur_rule->next;
418 config_close(parser);
422 bb_error_msg_and_die("error in '%s' at line %d", file, parser->lineno);
426 /* circular buffer variables/structures */
427 #if ENABLE_FEATURE_IPC_SYSLOG
429 #if CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE < 4
430 #error Sorry, you must set the syslogd buffer size to at least 4KB.
431 #error Please check CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE
434 /* our shared key (syslogd.c and logread.c must be in sync) */
435 enum { KEY_ID = 0x414e4547 }; /* "GENA" */
437 static void ipcsyslog_cleanup(void)
443 shmctl(G.shmid, IPC_RMID, NULL);
445 if (G.s_semid != -1) {
446 semctl(G.s_semid, 0, IPC_RMID, 0);
450 static void ipcsyslog_init(void)
453 printf("shmget(%x, %d,...)\n", (int)KEY_ID, G.shm_size);
455 G.shmid = shmget(KEY_ID, G.shm_size, IPC_CREAT | 0644);
457 bb_perror_msg_and_die("shmget");
460 G.shbuf = shmat(G.shmid, NULL, 0);
461 if (G.shbuf == (void*) -1L) { /* shmat has bizarre error return */
462 bb_perror_msg_and_die("shmat");
465 memset(G.shbuf, 0, G.shm_size);
466 G.shbuf->size = G.shm_size - offsetof(struct shbuf_ds, data) - 1;
467 /*G.shbuf->tail = 0;*/
469 /* we'll trust the OS to set initial semval to 0 (let's hope) */
470 G.s_semid = semget(KEY_ID, 2, IPC_CREAT | IPC_EXCL | 1023);
471 if (G.s_semid == -1) {
472 if (errno == EEXIST) {
473 G.s_semid = semget(KEY_ID, 2, 0);
477 bb_perror_msg_and_die("semget");
481 /* Write message to shared mem buffer */
482 static void log_to_shmem(const char *msg)
484 int old_tail, new_tail;
487 if (semop(G.s_semid, G.SMwdn, 3) == -1) {
488 bb_perror_msg_and_die("SMwdn");
491 /* Circular Buffer Algorithm:
492 * --------------------------
493 * tail == position where to store next syslog message.
494 * tail's max value is (shbuf->size - 1)
495 * Last byte of buffer is never used and remains NUL.
497 len = strlen(msg) + 1; /* length with NUL included */
499 old_tail = G.shbuf->tail;
500 new_tail = old_tail + len;
501 if (new_tail < G.shbuf->size) {
502 /* store message, set new tail */
503 memcpy(G.shbuf->data + old_tail, msg, len);
504 G.shbuf->tail = new_tail;
506 /* k == available buffer space ahead of old tail */
507 int k = G.shbuf->size - old_tail;
508 /* copy what fits to the end of buffer, and repeat */
509 memcpy(G.shbuf->data + old_tail, msg, k);
515 if (semop(G.s_semid, G.SMwup, 1) == -1) {
516 bb_perror_msg_and_die("SMwup");
519 printf("tail:%d\n", G.shbuf->tail);
522 void ipcsyslog_cleanup(void);
523 void ipcsyslog_init(void);
524 void log_to_shmem(const char *msg);
525 #endif /* FEATURE_IPC_SYSLOG */
527 /* Print a message to the log file. */
528 static void log_locally(time_t now, char *msg, logFile_t *log_file)
530 #ifdef SYSLOGD_WRLOCK
533 int len = strlen(msg);
535 if (log_file->fd >= 0) {
536 /* Reopen log file every second. This allows admin
537 * to delete the file and not worry about restarting us.
538 * This costs almost nothing since it happens
539 * _at most_ once a second.
543 if (G.last_log_time != now) {
544 G.last_log_time = now;
550 log_file->fd = open(log_file->path, O_WRONLY | O_CREAT
551 | O_NOCTTY | O_APPEND | O_NONBLOCK,
553 if (log_file->fd < 0) {
554 /* cannot open logfile? - print to /dev/console then */
555 int fd = device_open(DEV_CONSOLE, O_WRONLY | O_NOCTTY | O_NONBLOCK);
557 fd = 2; /* then stderr, dammit */
558 full_write(fd, msg, len);
563 #if ENABLE_FEATURE_ROTATE_LOGFILE
566 log_file->isRegular = (fstat(log_file->fd, &statf) == 0 && S_ISREG(statf.st_mode));
567 /* bug (mostly harmless): can wrap around if file > 4gb */
568 log_file->size = statf.st_size;
573 #ifdef SYSLOGD_WRLOCK
574 fl.l_whence = SEEK_SET;
578 fcntl(log_file->fd, F_SETLKW, &fl);
581 #if ENABLE_FEATURE_ROTATE_LOGFILE
582 if (G.logFileSize && log_file->isRegular && log_file->size > G.logFileSize) {
583 if (G.logFileRotate) { /* always 0..99 */
584 int i = strlen(log_file->path) + 3 + 1;
587 i = G.logFileRotate - 1;
588 /* rename: f.8 -> f.9; f.7 -> f.8; ... */
590 sprintf(newFile, "%s.%d", log_file->path, i);
592 sprintf(oldFile, "%s.%d", log_file->path, --i);
593 /* ignore errors - file might be missing */
594 rename(oldFile, newFile);
596 /* newFile == "f.0" now */
597 rename(log_file->path, newFile);
598 #ifdef SYSLOGD_WRLOCK
600 fcntl(log_file->fd, F_SETLKW, &fl);
605 ftruncate(log_file->fd, 0);
609 full_write(log_file->fd, msg, len);
610 #ifdef SYSLOGD_WRLOCK
612 fcntl(log_file->fd, F_SETLKW, &fl);
616 static void parse_fac_prio_20(int pri, char *res20)
618 const CODE *c_pri, *c_fac;
620 c_fac = find_by_val(LOG_FAC(pri) << 3, facilitynames);
622 c_pri = find_by_val(LOG_PRI(pri), prioritynames);
624 snprintf(res20, 20, "%s.%s", c_fac->c_name, c_pri->c_name);
628 snprintf(res20, 20, "<%d>", pri);
631 /* len parameter is used only for "is there a timestamp?" check.
632 * NB: some callers cheat and supply len==0 when they know
633 * that there is no timestamp, short-circuiting the test. */
634 static void timestamp_and_log(int pri, char *msg, int len)
639 /* Jan 18 00:11:22 msg... */
640 /* 01234567890123456 */
641 if (len < 16 || msg[3] != ' ' || msg[6] != ' '
642 || msg[9] != ':' || msg[12] != ':' || msg[15] != ' '
645 timestamp = ctime(&now) + 4; /* skip day of week */
651 timestamp[15] = '\0';
653 if (option_mask32 & OPT_small)
654 sprintf(G.printbuf, "%s %s\n", timestamp, msg);
657 parse_fac_prio_20(pri, res);
658 sprintf(G.printbuf, "%s %.64s %s %s\n", timestamp, G.hostname, res, msg);
661 /* Log message locally (to file or shared mem) */
662 #if ENABLE_FEATURE_SYSLOGD_CFG
666 uint8_t facility = LOG_FAC(pri);
667 uint8_t prio_bit = 1 << LOG_PRI(pri);
669 for (rule = G.log_rules; rule; rule = rule->next) {
670 if (rule->enabled_facility_priomap[facility] & prio_bit) {
671 log_locally(now, G.printbuf, rule->file);
679 if (LOG_PRI(pri) < G.logLevel) {
680 #if ENABLE_FEATURE_IPC_SYSLOG
681 if ((option_mask32 & OPT_circularlog) && G.shbuf) {
686 log_locally(now, G.printbuf, &G.logFile);
690 static void timestamp_and_log_internal(const char *msg)
693 if (ENABLE_FEATURE_REMOTE_LOG && !(option_mask32 & OPT_locallog))
695 timestamp_and_log(LOG_SYSLOG | LOG_INFO, (char*)msg, 0);
698 /* tmpbuf[len] is a NUL byte (set by caller), but there can be other,
699 * embedded NULs. Split messages on each of these NULs, parse prio,
700 * escape control chars and log each locally. */
701 static void split_escape_and_log(char *tmpbuf, int len)
708 char *q = G.parsebuf;
709 int pri = (LOG_USER | LOG_NOTICE);
712 /* Parse the magic priority number */
713 pri = bb_strtou(p + 1, &p, 10);
716 if (pri & ~(LOG_FACMASK | LOG_PRIMASK))
717 pri = (LOG_USER | LOG_NOTICE);
723 if (!(c & ~0x1f) && c != '\t') {
725 c += '@'; /* ^@, ^A, ^B... */
732 timestamp_and_log(pri, G.parsebuf, q - G.parsebuf);
737 static void do_mark(int sig)
739 if (G.markInterval) {
740 timestamp_and_log_internal("-- MARK --");
741 alarm(G.markInterval);
746 /* Don't inline: prevent struct sockaddr_un to take up space on stack
748 static NOINLINE int create_socket(void)
750 struct sockaddr_un sunx;
754 #if ENABLE_FEATURE_SYSTEMD
755 if (sd_listen_fds() == 1)
756 return SD_LISTEN_FDS_START;
759 memset(&sunx, 0, sizeof(sunx));
760 sunx.sun_family = AF_UNIX;
762 /* Unlink old /dev/log or object it points to. */
763 /* (if it exists, bind will fail) */
764 strcpy(sunx.sun_path, "/dev/log");
765 dev_log_name = xmalloc_follow_symlinks("/dev/log");
767 safe_strncpy(sunx.sun_path, dev_log_name, sizeof(sunx.sun_path));
770 unlink(sunx.sun_path);
772 sock_fd = xsocket(AF_UNIX, SOCK_DGRAM, 0);
773 xbind(sock_fd, (struct sockaddr *) &sunx, sizeof(sunx));
774 chmod("/dev/log", 0666);
779 #if ENABLE_FEATURE_REMOTE_LOG
780 static int try_to_resolve_remote(remoteHost_t *rh)
782 if (!rh->remoteAddr) {
783 unsigned now = monotonic_sec();
785 /* Don't resolve name too often - DNS timeouts can be big */
786 if ((now - rh->last_dns_resolve) < DNS_WAIT_SEC)
788 rh->last_dns_resolve = now;
789 rh->remoteAddr = host2sockaddr(rh->remoteHostname, 514);
793 return xsocket(rh->remoteAddr->u.sa.sa_family, SOCK_DGRAM, 0);
797 static void do_syslogd(void) NORETURN;
798 static void do_syslogd(void)
801 #if ENABLE_FEATURE_REMOTE_LOG
804 #if ENABLE_FEATURE_SYSLOGD_DUP
807 char *recvbuf = G.recvbuf;
809 #define recvbuf (G.recvbuf)
812 /* Set up signal handlers (so that they interrupt read()) */
813 signal_no_SA_RESTART_empty_mask(SIGTERM, record_signo);
814 signal_no_SA_RESTART_empty_mask(SIGINT, record_signo);
815 //signal_no_SA_RESTART_empty_mask(SIGQUIT, record_signo);
816 signal(SIGHUP, SIG_IGN);
818 signal(SIGALRM, do_mark);
819 alarm(G.markInterval);
821 sock_fd = create_socket();
823 if (ENABLE_FEATURE_IPC_SYSLOG && (option_mask32 & OPT_circularlog)) {
827 timestamp_and_log_internal("syslogd started: BusyBox v" BB_VER);
829 while (!bb_got_signal) {
832 #if ENABLE_FEATURE_SYSLOGD_DUP
834 if (recvbuf == G.recvbuf)
835 recvbuf = G.recvbuf + MAX_READ;
840 sz = read(sock_fd, recvbuf, MAX_READ - 1);
843 bb_perror_msg("read from /dev/log");
847 /* Drop trailing '\n' and NULs (typically there is one NUL) */
851 /* man 3 syslog says: "A trailing newline is added when needed".
852 * However, neither glibc nor uclibc do this:
853 * syslog(prio, "test") sends "test\0" to /dev/log,
854 * syslog(prio, "test\n") sends "test\n\0".
855 * IOW: newline is passed verbatim!
856 * I take it to mean that it's syslogd's job
857 * to make those look identical in the log files. */
858 if (recvbuf[sz-1] != '\0' && recvbuf[sz-1] != '\n')
862 #if ENABLE_FEATURE_SYSLOGD_DUP
863 if ((option_mask32 & OPT_dup) && (sz == last_sz))
864 if (memcmp(last_buf, recvbuf, sz) == 0)
868 #if ENABLE_FEATURE_REMOTE_LOG
869 /* Stock syslogd sends it '\n'-terminated
870 * over network, mimic that */
873 /* We are not modifying log messages in any way before send */
874 /* Remote site cannot trust _us_ anyway and need to do validation again */
875 for (item = G.remoteHosts; item != NULL; item = item->link) {
876 remoteHost_t *rh = (remoteHost_t *)item->data;
878 if (rh->remoteFD == -1) {
879 rh->remoteFD = try_to_resolve_remote(rh);
880 if (rh->remoteFD == -1)
884 /* Send message to remote logger.
885 * On some errors, close and set remoteFD to -1
886 * so that DNS resolution is retried.
888 if (sendto(rh->remoteFD, recvbuf, sz+1,
889 MSG_DONTWAIT | MSG_NOSIGNAL,
890 &(rh->remoteAddr->u.sa), rh->remoteAddr->len) == -1
894 case ENOTCONN: /* paranoia */
898 free(rh->remoteAddr);
899 rh->remoteAddr = NULL;
904 if (!ENABLE_FEATURE_REMOTE_LOG || (option_mask32 & OPT_locallog)) {
905 recvbuf[sz] = '\0'; /* ensure it *is* NUL terminated */
906 split_escape_and_log(recvbuf, sz);
908 } /* while (!bb_got_signal) */
910 timestamp_and_log_internal("syslogd exiting");
911 puts("syslogd exiting");
912 if (ENABLE_FEATURE_IPC_SYSLOG)
914 kill_myself_with_sig(bb_got_signal);
918 int syslogd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
919 int syslogd_main(int argc UNUSED_PARAM, char **argv)
923 #if ENABLE_FEATURE_REMOTE_LOG
924 llist_t *remoteAddrList = NULL;
929 /* No non-option params, -R can occur multiple times */
930 opt_complementary = "=0" IF_FEATURE_REMOTE_LOG(":R::");
931 opts = getopt32(argv, OPTION_STR, OPTION_PARAM);
932 #if ENABLE_FEATURE_REMOTE_LOG
933 while (remoteAddrList) {
934 remoteHost_t *rh = xzalloc(sizeof(*rh));
935 rh->remoteHostname = llist_pop(&remoteAddrList);
937 rh->last_dns_resolve = monotonic_sec() - DNS_WAIT_SEC - 1;
938 llist_add_to(&G.remoteHosts, rh);
943 if (opts & OPT_mark) // -m
944 G.markInterval = xatou_range(opt_m, 0, INT_MAX/60) * 60;
946 //if (opts & OPT_nofork) // -n
947 //if (opts & OPT_outfile) // -O
948 if (opts & OPT_loglevel) // -l
949 G.logLevel = xatou_range(opt_l, 1, 8);
950 //if (opts & OPT_small) // -S
951 #if ENABLE_FEATURE_ROTATE_LOGFILE
952 if (opts & OPT_filesize) // -s
953 G.logFileSize = xatou_range(opt_s, 0, INT_MAX/1024) * 1024;
954 if (opts & OPT_rotatecnt) // -b
955 G.logFileRotate = xatou_range(opt_b, 0, 99);
957 #if ENABLE_FEATURE_IPC_SYSLOG
959 G.shm_size = xatoul_range(opt_C, 4, INT_MAX/1024) * 1024;
961 /* If they have not specified remote logging, then log locally */
962 if (ENABLE_FEATURE_REMOTE_LOG && !(opts & OPT_remotelog)) // -R
963 option_mask32 |= OPT_locallog;
964 #if ENABLE_FEATURE_SYSLOGD_CFG
965 parse_syslogdcfg(opt_f);
968 /* Store away localhost's name before the fork */
969 G.hostname = safe_gethostname();
970 *strchrnul(G.hostname, '.') = '\0';
972 if (!(opts & OPT_nofork)) {
973 bb_daemonize_or_rexec(DAEMON_CHDIR_ROOT, argv);
976 write_pidfile("/var/run/syslogd.pid");
978 /* return EXIT_SUCCESS; */
981 /* Clean up. Needed because we are included from syslogd_and_logger.c */
984 #undef SYSLOGD_WRLOCK