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 the GPL v2 or later, see the file LICENSE in this tarball.
17 * Done in syslogd_and_logger.c:
20 #define SYSLOG_NAMES_CONST
27 #if ENABLE_FEATURE_REMOTE_LOG
28 #include <netinet/in.h>
31 #if ENABLE_FEATURE_IPC_SYSLOG
40 /* MARK code is not very useful, is bloat, and broken:
41 * can deadlock if alarmed to make MARK while writing to IPC buffer
42 * (semaphores are down but do_mark routine tries to down them again) */
45 /* Write locking does not seem to be useful either */
50 DNS_WAIT_SEC = 2 * 60,
53 /* Semaphore operation structures */
55 int32_t size; /* size of data - 1 */
56 int32_t tail; /* end of message list */
57 char data[1]; /* data/messages */
60 /* Allows us to have smaller initializer. Ugly. */
62 const char *logFilePath; \
64 /* interval between marks in seconds */ \
65 /*int markInterval;*/ \
66 /* level of messages to be logged */ \
68 IF_FEATURE_ROTATE_LOGFILE( \
69 /* max size of file before rotation */ \
70 unsigned logFileSize; \
71 /* number of rotated message files */ \
72 unsigned logFileRotate; \
73 unsigned curFileSize; \
76 IF_FEATURE_REMOTE_LOG( \
77 /* udp socket for remote logging */ \
79 len_and_sockaddr* remoteAddr; \
81 IF_FEATURE_IPC_SYSLOG( \
82 int shmid; /* ipc shared memory id */ \
83 int s_semid; /* ipc semaphore id */ \
85 struct sembuf SMwup[1]; \
86 struct sembuf SMwdn[3]; \
96 #if ENABLE_FEATURE_REMOTE_LOG
97 unsigned last_dns_resolve;
101 #if ENABLE_FEATURE_IPC_SYSLOG
102 struct shbuf_ds *shbuf;
104 time_t last_log_time;
105 /* localhost's name. We print only first 64 chars */
108 /* We recv into recvbuf... */
109 char recvbuf[MAX_READ * (1 + ENABLE_FEATURE_SYSLOGD_DUP)];
110 /* ...then copy to parsebuf, escaping control chars */
111 /* (can grow x2 max) */
112 char parsebuf[MAX_READ*2];
113 /* ...then sprintf into printbuf, adding timestamp (15 chars),
114 * host (64), fac.prio (20) to the message */
115 /* (growth by: 15 + 64 + 20 + delims = ~110) */
116 char printbuf[MAX_READ*2 + 128];
119 static const struct init_globals init_data = {
120 .logFilePath = "/var/log/messages",
123 .markInterval = 20 * 60,
126 #if ENABLE_FEATURE_ROTATE_LOGFILE
127 .logFileSize = 200 * 1024,
130 #if ENABLE_FEATURE_REMOTE_LOG
133 #if ENABLE_FEATURE_IPC_SYSLOG
136 .shm_size = ((CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE)*1024), // default shm size
137 .SMwup = { {1, -1, IPC_NOWAIT} },
138 .SMwdn = { {0, 0}, {1, 0}, {1, +1} },
142 #define G (*ptr_to_globals)
143 #define INIT_G() do { \
144 SET_PTR_TO_GLOBALS(memcpy(xzalloc(sizeof(G)), &init_data, sizeof(init_data))); \
150 OPTBIT_mark = 0, // -m
152 OPTBIT_outfile, // -O
153 OPTBIT_loglevel, // -l
155 IF_FEATURE_ROTATE_LOGFILE(OPTBIT_filesize ,) // -s
156 IF_FEATURE_ROTATE_LOGFILE(OPTBIT_rotatecnt ,) // -b
157 IF_FEATURE_REMOTE_LOG( OPTBIT_remotelog ,) // -R
158 IF_FEATURE_REMOTE_LOG( OPTBIT_locallog ,) // -L
159 IF_FEATURE_IPC_SYSLOG( OPTBIT_circularlog,) // -C
160 IF_FEATURE_SYSLOGD_DUP( OPTBIT_dup ,) // -D
162 OPT_mark = 1 << OPTBIT_mark ,
163 OPT_nofork = 1 << OPTBIT_nofork ,
164 OPT_outfile = 1 << OPTBIT_outfile ,
165 OPT_loglevel = 1 << OPTBIT_loglevel,
166 OPT_small = 1 << OPTBIT_small ,
167 OPT_filesize = IF_FEATURE_ROTATE_LOGFILE((1 << OPTBIT_filesize )) + 0,
168 OPT_rotatecnt = IF_FEATURE_ROTATE_LOGFILE((1 << OPTBIT_rotatecnt )) + 0,
169 OPT_remotelog = IF_FEATURE_REMOTE_LOG( (1 << OPTBIT_remotelog )) + 0,
170 OPT_locallog = IF_FEATURE_REMOTE_LOG( (1 << OPTBIT_locallog )) + 0,
171 OPT_circularlog = IF_FEATURE_IPC_SYSLOG( (1 << OPTBIT_circularlog)) + 0,
172 OPT_dup = IF_FEATURE_SYSLOGD_DUP( (1 << OPTBIT_dup )) + 0,
174 #define OPTION_STR "m:nO:l:S" \
175 IF_FEATURE_ROTATE_LOGFILE("s:" ) \
176 IF_FEATURE_ROTATE_LOGFILE("b:" ) \
177 IF_FEATURE_REMOTE_LOG( "R:" ) \
178 IF_FEATURE_REMOTE_LOG( "L" ) \
179 IF_FEATURE_IPC_SYSLOG( "C::") \
180 IF_FEATURE_SYSLOGD_DUP( "D" )
181 #define OPTION_DECL *opt_m, *opt_l \
182 IF_FEATURE_ROTATE_LOGFILE(,*opt_s) \
183 IF_FEATURE_ROTATE_LOGFILE(,*opt_b) \
184 IF_FEATURE_IPC_SYSLOG( ,*opt_C = NULL)
185 #define OPTION_PARAM &opt_m, &G.logFilePath, &opt_l \
186 IF_FEATURE_ROTATE_LOGFILE(,&opt_s) \
187 IF_FEATURE_ROTATE_LOGFILE(,&opt_b) \
188 IF_FEATURE_REMOTE_LOG( ,&G.remoteAddrStr) \
189 IF_FEATURE_IPC_SYSLOG( ,&opt_C)
192 /* circular buffer variables/structures */
193 #if ENABLE_FEATURE_IPC_SYSLOG
195 #if CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE < 4
196 #error Sorry, you must set the syslogd buffer size to at least 4KB.
197 #error Please check CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE
200 /* our shared key (syslogd.c and logread.c must be in sync) */
201 enum { KEY_ID = 0x414e4547 }; /* "GENA" */
203 static void ipcsyslog_cleanup(void)
209 shmctl(G.shmid, IPC_RMID, NULL);
211 if (G.s_semid != -1) {
212 semctl(G.s_semid, 0, IPC_RMID, 0);
216 static void ipcsyslog_init(void)
219 printf("shmget(%x, %d,...)\n", (int)KEY_ID, G.shm_size);
221 G.shmid = shmget(KEY_ID, G.shm_size, IPC_CREAT | 0644);
223 bb_perror_msg_and_die("shmget");
226 G.shbuf = shmat(G.shmid, NULL, 0);
227 if (G.shbuf == (void*) -1L) { /* shmat has bizarre error return */
228 bb_perror_msg_and_die("shmat");
231 memset(G.shbuf, 0, G.shm_size);
232 G.shbuf->size = G.shm_size - offsetof(struct shbuf_ds, data) - 1;
233 /*G.shbuf->tail = 0;*/
235 // we'll trust the OS to set initial semval to 0 (let's hope)
236 G.s_semid = semget(KEY_ID, 2, IPC_CREAT | IPC_EXCL | 1023);
237 if (G.s_semid == -1) {
238 if (errno == EEXIST) {
239 G.s_semid = semget(KEY_ID, 2, 0);
243 bb_perror_msg_and_die("semget");
247 /* Write message to shared mem buffer */
248 static void log_to_shmem(const char *msg, int len)
250 int old_tail, new_tail;
252 if (semop(G.s_semid, G.SMwdn, 3) == -1) {
253 bb_perror_msg_and_die("SMwdn");
256 /* Circular Buffer Algorithm:
257 * --------------------------
258 * tail == position where to store next syslog message.
259 * tail's max value is (shbuf->size - 1)
260 * Last byte of buffer is never used and remains NUL.
262 len++; /* length with NUL included */
264 old_tail = G.shbuf->tail;
265 new_tail = old_tail + len;
266 if (new_tail < G.shbuf->size) {
267 /* store message, set new tail */
268 memcpy(G.shbuf->data + old_tail, msg, len);
269 G.shbuf->tail = new_tail;
271 /* k == available buffer space ahead of old tail */
272 int k = G.shbuf->size - old_tail;
273 /* copy what fits to the end of buffer, and repeat */
274 memcpy(G.shbuf->data + old_tail, msg, k);
280 if (semop(G.s_semid, G.SMwup, 1) == -1) {
281 bb_perror_msg_and_die("SMwup");
284 printf("tail:%d\n", G.shbuf->tail);
287 void ipcsyslog_cleanup(void);
288 void ipcsyslog_init(void);
289 void log_to_shmem(const char *msg);
290 #endif /* FEATURE_IPC_SYSLOG */
293 /* Print a message to the log file. */
294 static void log_locally(time_t now, char *msg)
296 #ifdef SYSLOGD_WRLOCK
299 int len = strlen(msg);
301 #if ENABLE_FEATURE_IPC_SYSLOG
302 if ((option_mask32 & OPT_circularlog) && G.shbuf) {
303 log_to_shmem(msg, len);
308 /* Reopen log file every second. This allows admin
309 * to delete the file and not worry about restarting us.
310 * This costs almost nothing since it happens
311 * _at most_ once a second.
315 if (G.last_log_time != now) {
316 G.last_log_time = now;
322 G.logFD = open(G.logFilePath, O_WRONLY | O_CREAT
323 | O_NOCTTY | O_APPEND | O_NONBLOCK,
326 /* cannot open logfile? - print to /dev/console then */
327 int fd = device_open(DEV_CONSOLE, O_WRONLY | O_NOCTTY | O_NONBLOCK);
329 fd = 2; /* then stderr, dammit */
330 full_write(fd, msg, len);
335 #if ENABLE_FEATURE_ROTATE_LOGFILE
338 G.isRegular = (fstat(G.logFD, &statf) == 0 && S_ISREG(statf.st_mode));
339 /* bug (mostly harmless): can wrap around if file > 4gb */
340 G.curFileSize = statf.st_size;
345 #ifdef SYSLOGD_WRLOCK
346 fl.l_whence = SEEK_SET;
350 fcntl(G.logFD, F_SETLKW, &fl);
353 #if ENABLE_FEATURE_ROTATE_LOGFILE
354 if (G.logFileSize && G.isRegular && G.curFileSize > G.logFileSize) {
355 if (G.logFileRotate) { /* always 0..99 */
356 int i = strlen(G.logFilePath) + 3 + 1;
359 i = G.logFileRotate - 1;
360 /* rename: f.8 -> f.9; f.7 -> f.8; ... */
362 sprintf(newFile, "%s.%d", G.logFilePath, i);
364 sprintf(oldFile, "%s.%d", G.logFilePath, --i);
365 /* ignore errors - file might be missing */
366 rename(oldFile, newFile);
368 /* newFile == "f.0" now */
369 rename(G.logFilePath, newFile);
370 #ifdef SYSLOGD_WRLOCK
372 fcntl(G.logFD, F_SETLKW, &fl);
377 ftruncate(G.logFD, 0);
381 full_write(G.logFD, msg, len);
382 #ifdef SYSLOGD_WRLOCK
384 fcntl(G.logFD, F_SETLKW, &fl);
388 static void parse_fac_prio_20(int pri, char *res20)
390 const CODE *c_pri, *c_fac;
393 c_fac = facilitynames;
394 while (c_fac->c_name) {
395 if (c_fac->c_val != (LOG_FAC(pri) << 3)) {
399 /* facility is found, look for prio */
400 c_pri = prioritynames;
401 while (c_pri->c_name) {
402 if (c_pri->c_val != LOG_PRI(pri)) {
406 snprintf(res20, 20, "%s.%s",
407 c_fac->c_name, c_pri->c_name);
410 /* prio not found, bail out */
413 snprintf(res20, 20, "<%d>", pri);
417 /* len parameter is used only for "is there a timestamp?" check.
418 * NB: some callers cheat and supply len==0 when they know
419 * that there is no timestamp, short-circuiting the test. */
420 static void timestamp_and_log(int pri, char *msg, int len)
425 /* Jan 18 00:11:22 msg... */
426 /* 01234567890123456 */
427 if (len < 16 || msg[3] != ' ' || msg[6] != ' '
428 || msg[9] != ':' || msg[12] != ':' || msg[15] != ' '
431 timestamp = ctime(&now) + 4; /* skip day of week */
437 timestamp[15] = '\0';
439 if (option_mask32 & OPT_small)
440 sprintf(G.printbuf, "%s %s\n", timestamp, msg);
443 parse_fac_prio_20(pri, res);
444 sprintf(G.printbuf, "%s %.64s %s %s\n", timestamp, G.hostname, res, msg);
447 /* Log message locally (to file or shared mem) */
448 log_locally(now, G.printbuf);
451 static void timestamp_and_log_internal(const char *msg)
454 if (ENABLE_FEATURE_REMOTE_LOG && !(option_mask32 & OPT_locallog))
456 timestamp_and_log(LOG_SYSLOG | LOG_INFO, (char*)msg, 0);
459 /* tmpbuf[len] is a NUL byte (set by caller), but there can be other,
460 * embedded NULs. Split messages on each of these NULs, parse prio,
461 * escape control chars and log each locally. */
462 static void split_escape_and_log(char *tmpbuf, int len)
469 char *q = G.parsebuf;
470 int pri = (LOG_USER | LOG_NOTICE);
473 /* Parse the magic priority number */
474 pri = bb_strtou(p + 1, &p, 10);
477 if (pri & ~(LOG_FACMASK | LOG_PRIMASK))
478 pri = (LOG_USER | LOG_NOTICE);
484 if (!(c & ~0x1f) && c != '\t') {
486 c += '@'; /* ^@, ^A, ^B... */
493 if (LOG_PRI(pri) < G.logLevel)
494 timestamp_and_log(pri, G.parsebuf, q - G.parsebuf);
499 static void do_mark(int sig)
501 if (G.markInterval) {
502 timestamp_and_log_internal("-- MARK --");
503 alarm(G.markInterval);
508 /* Don't inline: prevent struct sockaddr_un to take up space on stack
510 static NOINLINE int create_socket(void)
512 struct sockaddr_un sunx;
516 memset(&sunx, 0, sizeof(sunx));
517 sunx.sun_family = AF_UNIX;
519 /* Unlink old /dev/log or object it points to. */
520 /* (if it exists, bind will fail) */
521 strcpy(sunx.sun_path, "/dev/log");
522 dev_log_name = xmalloc_follow_symlinks("/dev/log");
524 safe_strncpy(sunx.sun_path, dev_log_name, sizeof(sunx.sun_path));
527 unlink(sunx.sun_path);
529 sock_fd = xsocket(AF_UNIX, SOCK_DGRAM, 0);
530 xbind(sock_fd, (struct sockaddr *) &sunx, sizeof(sunx));
531 chmod("/dev/log", 0666);
536 #if ENABLE_FEATURE_REMOTE_LOG
537 static int try_to_resolve_remote(void)
540 unsigned now = monotonic_sec();
542 /* Don't resolve name too often - DNS timeouts can be big */
543 if ((now - G.last_dns_resolve) < DNS_WAIT_SEC)
545 G.last_dns_resolve = now;
546 G.remoteAddr = host2sockaddr(G.remoteAddrStr, 514);
550 return socket(G.remoteAddr->u.sa.sa_family, SOCK_DGRAM, 0);
554 static void do_syslogd(void) NORETURN;
555 static void do_syslogd(void)
558 #if ENABLE_FEATURE_SYSLOGD_DUP
561 char *recvbuf = G.recvbuf;
563 #define recvbuf (G.recvbuf)
566 /* Set up signal handlers (so that they interrupt read()) */
567 signal_no_SA_RESTART_empty_mask(SIGTERM, record_signo);
568 signal_no_SA_RESTART_empty_mask(SIGINT, record_signo);
569 //signal_no_SA_RESTART_empty_mask(SIGQUIT, record_signo);
570 signal(SIGHUP, SIG_IGN);
572 signal(SIGALRM, do_mark);
573 alarm(G.markInterval);
575 sock_fd = create_socket();
577 if (ENABLE_FEATURE_IPC_SYSLOG && (option_mask32 & OPT_circularlog)) {
581 timestamp_and_log_internal("syslogd started: BusyBox v" BB_VER);
583 while (!bb_got_signal) {
586 #if ENABLE_FEATURE_SYSLOGD_DUP
588 if (recvbuf == G.recvbuf)
589 recvbuf = G.recvbuf + MAX_READ;
594 sz = read(sock_fd, recvbuf, MAX_READ - 1);
597 bb_perror_msg("read from /dev/log");
601 /* Drop trailing '\n' and NULs (typically there is one NUL) */
605 /* man 3 syslog says: "A trailing newline is added when needed".
606 * However, neither glibc nor uclibc do this:
607 * syslog(prio, "test") sends "test\0" to /dev/log,
608 * syslog(prio, "test\n") sends "test\n\0".
609 * IOW: newline is passed verbatim!
610 * I take it to mean that it's syslogd's job
611 * to make those look identical in the log files. */
612 if (recvbuf[sz-1] != '\0' && recvbuf[sz-1] != '\n')
616 #if ENABLE_FEATURE_SYSLOGD_DUP
617 if ((option_mask32 & OPT_dup) && (sz == last_sz))
618 if (memcmp(last_buf, recvbuf, sz) == 0)
622 #if ENABLE_FEATURE_REMOTE_LOG
623 /* We are not modifying log messages in any way before send */
624 /* Remote site cannot trust _us_ anyway and need to do validation again */
625 if (G.remoteAddrStr) {
626 if (-1 == G.remoteFD) {
627 G.remoteFD = try_to_resolve_remote();
628 if (-1 == G.remoteFD)
631 /* Stock syslogd sends it '\n'-terminated
632 * over network, mimic that */
634 /* send message to remote logger, ignore possible error */
635 /* TODO: on some errors, close and set G.remoteFD to -1
636 * so that DNS resolution and connect is retried? */
637 sendto(G.remoteFD, recvbuf, sz+1, MSG_DONTWAIT,
638 &G.remoteAddr->u.sa, G.remoteAddr->len);
642 if (!ENABLE_FEATURE_REMOTE_LOG || (option_mask32 & OPT_locallog)) {
643 recvbuf[sz] = '\0'; /* ensure it *is* NUL terminated */
644 split_escape_and_log(recvbuf, sz);
646 } /* while (!bb_got_signal) */
648 timestamp_and_log_internal("syslogd exiting");
649 puts("syslogd exiting");
650 if (ENABLE_FEATURE_IPC_SYSLOG)
652 kill_myself_with_sig(bb_got_signal);
656 int syslogd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
657 int syslogd_main(int argc UNUSED_PARAM, char **argv)
663 #if ENABLE_FEATURE_REMOTE_LOG
664 G.last_dns_resolve = monotonic_sec() - DNS_WAIT_SEC - 1;
667 /* do normal option parsing */
668 opt_complementary = "=0"; /* no non-option params */
669 opts = getopt32(argv, OPTION_STR, OPTION_PARAM);
671 if (opts & OPT_mark) // -m
672 G.markInterval = xatou_range(opt_m, 0, INT_MAX/60) * 60;
674 //if (opts & OPT_nofork) // -n
675 //if (opts & OPT_outfile) // -O
676 if (opts & OPT_loglevel) // -l
677 G.logLevel = xatou_range(opt_l, 1, 8);
678 //if (opts & OPT_small) // -S
679 #if ENABLE_FEATURE_ROTATE_LOGFILE
680 if (opts & OPT_filesize) // -s
681 G.logFileSize = xatou_range(opt_s, 0, INT_MAX/1024) * 1024;
682 if (opts & OPT_rotatecnt) // -b
683 G.logFileRotate = xatou_range(opt_b, 0, 99);
685 #if ENABLE_FEATURE_IPC_SYSLOG
687 G.shm_size = xatoul_range(opt_C, 4, INT_MAX/1024) * 1024;
690 /* If they have not specified remote logging, then log locally */
691 if (ENABLE_FEATURE_REMOTE_LOG && !(opts & OPT_remotelog)) // -R
692 option_mask32 |= OPT_locallog;
694 /* Store away localhost's name before the fork */
695 G.hostname = safe_gethostname();
696 *strchrnul(G.hostname, '.') = '\0';
698 if (!(opts & OPT_nofork)) {
699 bb_daemonize_or_rexec(DAEMON_CHDIR_ROOT, argv);
702 write_pidfile("/var/run/syslogd.pid");
704 /* return EXIT_SUCCESS; */
707 /* Clean up. Needed because we are included from syslogd_and_logger.c */
710 #undef SYSLOGD_WRLOCK