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
28 #if ENABLE_FEATURE_REMOTE_LOG
29 #include <netinet/in.h>
32 #if ENABLE_FEATURE_IPC_SYSLOG
41 /* MARK code is not very useful, is bloat, and broken:
42 * can deadlock if alarmed to make MARK while writing to IPC buffer
43 * (semaphores are down but do_mark routine tries to down them again) */
46 /* Write locking does not seem to be useful either */
51 DNS_WAIT_SEC = 2 * 60,
54 /* Semaphore operation structures */
56 int32_t size; /* size of data - 1 */
57 int32_t tail; /* end of message list */
58 char data[1]; /* data/messages */
61 /* Allows us to have smaller initializer. Ugly. */
63 const char *logFilePath; \
65 /* interval between marks in seconds */ \
66 /*int markInterval;*/ \
67 /* level of messages to be logged */ \
69 IF_FEATURE_ROTATE_LOGFILE( \
70 /* max size of file before rotation */ \
71 unsigned logFileSize; \
72 /* number of rotated message files */ \
73 unsigned logFileRotate; \
74 unsigned curFileSize; \
77 IF_FEATURE_REMOTE_LOG( \
78 /* udp socket for remote logging */ \
80 len_and_sockaddr* remoteAddr; \
82 IF_FEATURE_IPC_SYSLOG( \
83 int shmid; /* ipc shared memory id */ \
84 int s_semid; /* ipc semaphore id */ \
86 struct sembuf SMwup[1]; \
87 struct sembuf SMwdn[3]; \
97 #if ENABLE_FEATURE_REMOTE_LOG
98 unsigned last_dns_resolve;
102 #if ENABLE_FEATURE_IPC_SYSLOG
103 struct shbuf_ds *shbuf;
105 time_t last_log_time;
106 /* localhost's name. We print only first 64 chars */
109 /* We recv into recvbuf... */
110 char recvbuf[MAX_READ * (1 + ENABLE_FEATURE_SYSLOGD_DUP)];
111 /* ...then copy to parsebuf, escaping control chars */
112 /* (can grow x2 max) */
113 char parsebuf[MAX_READ*2];
114 /* ...then sprintf into printbuf, adding timestamp (15 chars),
115 * host (64), fac.prio (20) to the message */
116 /* (growth by: 15 + 64 + 20 + delims = ~110) */
117 char printbuf[MAX_READ*2 + 128];
120 static const struct init_globals init_data = {
121 .logFilePath = "/var/log/messages",
124 .markInterval = 20 * 60,
127 #if ENABLE_FEATURE_ROTATE_LOGFILE
128 .logFileSize = 200 * 1024,
131 #if ENABLE_FEATURE_REMOTE_LOG
134 #if ENABLE_FEATURE_IPC_SYSLOG
137 .shm_size = ((CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE)*1024), // default shm size
138 .SMwup = { {1, -1, IPC_NOWAIT} },
139 .SMwdn = { {0, 0}, {1, 0}, {1, +1} },
143 #define G (*ptr_to_globals)
144 #define INIT_G() do { \
145 SET_PTR_TO_GLOBALS(memcpy(xzalloc(sizeof(G)), &init_data, sizeof(init_data))); \
151 OPTBIT_mark = 0, // -m
153 OPTBIT_outfile, // -O
154 OPTBIT_loglevel, // -l
156 IF_FEATURE_ROTATE_LOGFILE(OPTBIT_filesize ,) // -s
157 IF_FEATURE_ROTATE_LOGFILE(OPTBIT_rotatecnt ,) // -b
158 IF_FEATURE_REMOTE_LOG( OPTBIT_remotelog ,) // -R
159 IF_FEATURE_REMOTE_LOG( OPTBIT_locallog ,) // -L
160 IF_FEATURE_IPC_SYSLOG( OPTBIT_circularlog,) // -C
161 IF_FEATURE_SYSLOGD_DUP( OPTBIT_dup ,) // -D
163 OPT_mark = 1 << OPTBIT_mark ,
164 OPT_nofork = 1 << OPTBIT_nofork ,
165 OPT_outfile = 1 << OPTBIT_outfile ,
166 OPT_loglevel = 1 << OPTBIT_loglevel,
167 OPT_small = 1 << OPTBIT_small ,
168 OPT_filesize = IF_FEATURE_ROTATE_LOGFILE((1 << OPTBIT_filesize )) + 0,
169 OPT_rotatecnt = IF_FEATURE_ROTATE_LOGFILE((1 << OPTBIT_rotatecnt )) + 0,
170 OPT_remotelog = IF_FEATURE_REMOTE_LOG( (1 << OPTBIT_remotelog )) + 0,
171 OPT_locallog = IF_FEATURE_REMOTE_LOG( (1 << OPTBIT_locallog )) + 0,
172 OPT_circularlog = IF_FEATURE_IPC_SYSLOG( (1 << OPTBIT_circularlog)) + 0,
173 OPT_dup = IF_FEATURE_SYSLOGD_DUP( (1 << OPTBIT_dup )) + 0,
175 #define OPTION_STR "m:nO:l:S" \
176 IF_FEATURE_ROTATE_LOGFILE("s:" ) \
177 IF_FEATURE_ROTATE_LOGFILE("b:" ) \
178 IF_FEATURE_REMOTE_LOG( "R:" ) \
179 IF_FEATURE_REMOTE_LOG( "L" ) \
180 IF_FEATURE_IPC_SYSLOG( "C::") \
181 IF_FEATURE_SYSLOGD_DUP( "D" )
182 #define OPTION_DECL *opt_m, *opt_l \
183 IF_FEATURE_ROTATE_LOGFILE(,*opt_s) \
184 IF_FEATURE_ROTATE_LOGFILE(,*opt_b) \
185 IF_FEATURE_IPC_SYSLOG( ,*opt_C = NULL)
186 #define OPTION_PARAM &opt_m, &G.logFilePath, &opt_l \
187 IF_FEATURE_ROTATE_LOGFILE(,&opt_s) \
188 IF_FEATURE_ROTATE_LOGFILE(,&opt_b) \
189 IF_FEATURE_REMOTE_LOG( ,&G.remoteAddrStr) \
190 IF_FEATURE_IPC_SYSLOG( ,&opt_C)
193 /* circular buffer variables/structures */
194 #if ENABLE_FEATURE_IPC_SYSLOG
196 #if CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE < 4
197 #error Sorry, you must set the syslogd buffer size to at least 4KB.
198 #error Please check CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE
201 /* our shared key (syslogd.c and logread.c must be in sync) */
202 enum { KEY_ID = 0x414e4547 }; /* "GENA" */
204 static void ipcsyslog_cleanup(void)
210 shmctl(G.shmid, IPC_RMID, NULL);
212 if (G.s_semid != -1) {
213 semctl(G.s_semid, 0, IPC_RMID, 0);
217 static void ipcsyslog_init(void)
220 printf("shmget(%x, %d,...)\n", (int)KEY_ID, G.shm_size);
222 G.shmid = shmget(KEY_ID, G.shm_size, IPC_CREAT | 0644);
224 bb_perror_msg_and_die("shmget");
227 G.shbuf = shmat(G.shmid, NULL, 0);
228 if (G.shbuf == (void*) -1L) { /* shmat has bizarre error return */
229 bb_perror_msg_and_die("shmat");
232 memset(G.shbuf, 0, G.shm_size);
233 G.shbuf->size = G.shm_size - offsetof(struct shbuf_ds, data) - 1;
234 /*G.shbuf->tail = 0;*/
236 // we'll trust the OS to set initial semval to 0 (let's hope)
237 G.s_semid = semget(KEY_ID, 2, IPC_CREAT | IPC_EXCL | 1023);
238 if (G.s_semid == -1) {
239 if (errno == EEXIST) {
240 G.s_semid = semget(KEY_ID, 2, 0);
244 bb_perror_msg_and_die("semget");
248 /* Write message to shared mem buffer */
249 static void log_to_shmem(const char *msg, int len)
251 int old_tail, new_tail;
253 if (semop(G.s_semid, G.SMwdn, 3) == -1) {
254 bb_perror_msg_and_die("SMwdn");
257 /* Circular Buffer Algorithm:
258 * --------------------------
259 * tail == position where to store next syslog message.
260 * tail's max value is (shbuf->size - 1)
261 * Last byte of buffer is never used and remains NUL.
263 len++; /* length with NUL included */
265 old_tail = G.shbuf->tail;
266 new_tail = old_tail + len;
267 if (new_tail < G.shbuf->size) {
268 /* store message, set new tail */
269 memcpy(G.shbuf->data + old_tail, msg, len);
270 G.shbuf->tail = new_tail;
272 /* k == available buffer space ahead of old tail */
273 int k = G.shbuf->size - old_tail;
274 /* copy what fits to the end of buffer, and repeat */
275 memcpy(G.shbuf->data + old_tail, msg, k);
281 if (semop(G.s_semid, G.SMwup, 1) == -1) {
282 bb_perror_msg_and_die("SMwup");
285 printf("tail:%d\n", G.shbuf->tail);
288 void ipcsyslog_cleanup(void);
289 void ipcsyslog_init(void);
290 void log_to_shmem(const char *msg);
291 #endif /* FEATURE_IPC_SYSLOG */
294 /* Print a message to the log file. */
295 static void log_locally(time_t now, char *msg)
297 #ifdef SYSLOGD_WRLOCK
300 int len = strlen(msg);
302 #if ENABLE_FEATURE_IPC_SYSLOG
303 if ((option_mask32 & OPT_circularlog) && G.shbuf) {
304 log_to_shmem(msg, len);
309 /* Reopen log file every second. This allows admin
310 * to delete the file and not worry about restarting us.
311 * This costs almost nothing since it happens
312 * _at most_ once a second.
316 if (G.last_log_time != now) {
317 G.last_log_time = now;
323 G.logFD = open(G.logFilePath, O_WRONLY | O_CREAT
324 | O_NOCTTY | O_APPEND | O_NONBLOCK,
327 /* cannot open logfile? - print to /dev/console then */
328 int fd = device_open(DEV_CONSOLE, O_WRONLY | O_NOCTTY | O_NONBLOCK);
330 fd = 2; /* then stderr, dammit */
331 full_write(fd, msg, len);
336 #if ENABLE_FEATURE_ROTATE_LOGFILE
339 G.isRegular = (fstat(G.logFD, &statf) == 0 && S_ISREG(statf.st_mode));
340 /* bug (mostly harmless): can wrap around if file > 4gb */
341 G.curFileSize = statf.st_size;
346 #ifdef SYSLOGD_WRLOCK
347 fl.l_whence = SEEK_SET;
351 fcntl(G.logFD, F_SETLKW, &fl);
354 #if ENABLE_FEATURE_ROTATE_LOGFILE
355 if (G.logFileSize && G.isRegular && G.curFileSize > G.logFileSize) {
356 if (G.logFileRotate) { /* always 0..99 */
357 int i = strlen(G.logFilePath) + 3 + 1;
360 i = G.logFileRotate - 1;
361 /* rename: f.8 -> f.9; f.7 -> f.8; ... */
363 sprintf(newFile, "%s.%d", G.logFilePath, i);
365 sprintf(oldFile, "%s.%d", G.logFilePath, --i);
366 /* ignore errors - file might be missing */
367 rename(oldFile, newFile);
369 /* newFile == "f.0" now */
370 rename(G.logFilePath, newFile);
371 #ifdef SYSLOGD_WRLOCK
373 fcntl(G.logFD, F_SETLKW, &fl);
378 ftruncate(G.logFD, 0);
382 full_write(G.logFD, msg, len);
383 #ifdef SYSLOGD_WRLOCK
385 fcntl(G.logFD, F_SETLKW, &fl);
389 static void parse_fac_prio_20(int pri, char *res20)
391 const CODE *c_pri, *c_fac;
394 c_fac = facilitynames;
395 while (c_fac->c_name) {
396 if (c_fac->c_val != (LOG_FAC(pri) << 3)) {
400 /* facility is found, look for prio */
401 c_pri = prioritynames;
402 while (c_pri->c_name) {
403 if (c_pri->c_val != LOG_PRI(pri)) {
407 snprintf(res20, 20, "%s.%s",
408 c_fac->c_name, c_pri->c_name);
411 /* prio not found, bail out */
414 snprintf(res20, 20, "<%d>", pri);
418 /* len parameter is used only for "is there a timestamp?" check.
419 * NB: some callers cheat and supply len==0 when they know
420 * that there is no timestamp, short-circuiting the test. */
421 static void timestamp_and_log(int pri, char *msg, int len)
426 /* Jan 18 00:11:22 msg... */
427 /* 01234567890123456 */
428 if (len < 16 || msg[3] != ' ' || msg[6] != ' '
429 || msg[9] != ':' || msg[12] != ':' || msg[15] != ' '
432 timestamp = ctime(&now) + 4; /* skip day of week */
438 timestamp[15] = '\0';
440 if (option_mask32 & OPT_small)
441 sprintf(G.printbuf, "%s %s\n", timestamp, msg);
444 parse_fac_prio_20(pri, res);
445 sprintf(G.printbuf, "%s %.64s %s %s\n", timestamp, G.hostname, res, msg);
448 /* Log message locally (to file or shared mem) */
449 log_locally(now, G.printbuf);
452 static void timestamp_and_log_internal(const char *msg)
455 if (ENABLE_FEATURE_REMOTE_LOG && !(option_mask32 & OPT_locallog))
457 timestamp_and_log(LOG_SYSLOG | LOG_INFO, (char*)msg, 0);
460 /* tmpbuf[len] is a NUL byte (set by caller), but there can be other,
461 * embedded NULs. Split messages on each of these NULs, parse prio,
462 * escape control chars and log each locally. */
463 static void split_escape_and_log(char *tmpbuf, int len)
470 char *q = G.parsebuf;
471 int pri = (LOG_USER | LOG_NOTICE);
474 /* Parse the magic priority number */
475 pri = bb_strtou(p + 1, &p, 10);
478 if (pri & ~(LOG_FACMASK | LOG_PRIMASK))
479 pri = (LOG_USER | LOG_NOTICE);
485 if (!(c & ~0x1f) && c != '\t') {
487 c += '@'; /* ^@, ^A, ^B... */
494 if (LOG_PRI(pri) < G.logLevel)
495 timestamp_and_log(pri, G.parsebuf, q - G.parsebuf);
500 static void do_mark(int sig)
502 if (G.markInterval) {
503 timestamp_and_log_internal("-- MARK --");
504 alarm(G.markInterval);
509 /* Don't inline: prevent struct sockaddr_un to take up space on stack
511 static NOINLINE int create_socket(void)
513 struct sockaddr_un sunx;
517 memset(&sunx, 0, sizeof(sunx));
518 sunx.sun_family = AF_UNIX;
520 /* Unlink old /dev/log or object it points to. */
521 /* (if it exists, bind will fail) */
522 strcpy(sunx.sun_path, "/dev/log");
523 dev_log_name = xmalloc_follow_symlinks("/dev/log");
525 safe_strncpy(sunx.sun_path, dev_log_name, sizeof(sunx.sun_path));
528 unlink(sunx.sun_path);
530 sock_fd = xsocket(AF_UNIX, SOCK_DGRAM, 0);
531 xbind(sock_fd, (struct sockaddr *) &sunx, sizeof(sunx));
532 chmod("/dev/log", 0666);
537 #if ENABLE_FEATURE_REMOTE_LOG
538 static int try_to_resolve_remote(void)
541 unsigned now = monotonic_sec();
543 /* Don't resolve name too often - DNS timeouts can be big */
544 if ((now - G.last_dns_resolve) < DNS_WAIT_SEC)
546 G.last_dns_resolve = now;
547 G.remoteAddr = host2sockaddr(G.remoteAddrStr, 514);
551 return socket(G.remoteAddr->u.sa.sa_family, SOCK_DGRAM, 0);
555 static void do_syslogd(void) NORETURN;
556 static void do_syslogd(void)
559 #if ENABLE_FEATURE_SYSLOGD_DUP
562 char *recvbuf = G.recvbuf;
564 #define recvbuf (G.recvbuf)
567 /* Set up signal handlers (so that they interrupt read()) */
568 signal_no_SA_RESTART_empty_mask(SIGTERM, record_signo);
569 signal_no_SA_RESTART_empty_mask(SIGINT, record_signo);
570 //signal_no_SA_RESTART_empty_mask(SIGQUIT, record_signo);
571 signal(SIGHUP, SIG_IGN);
573 signal(SIGALRM, do_mark);
574 alarm(G.markInterval);
576 sock_fd = create_socket();
578 if (ENABLE_FEATURE_IPC_SYSLOG && (option_mask32 & OPT_circularlog)) {
582 timestamp_and_log_internal("syslogd started: BusyBox v" BB_VER);
584 while (!bb_got_signal) {
587 #if ENABLE_FEATURE_SYSLOGD_DUP
589 if (recvbuf == G.recvbuf)
590 recvbuf = G.recvbuf + MAX_READ;
595 sz = read(sock_fd, recvbuf, MAX_READ - 1);
598 bb_perror_msg("read from /dev/log");
602 /* Drop trailing '\n' and NULs (typically there is one NUL) */
606 /* man 3 syslog says: "A trailing newline is added when needed".
607 * However, neither glibc nor uclibc do this:
608 * syslog(prio, "test") sends "test\0" to /dev/log,
609 * syslog(prio, "test\n") sends "test\n\0".
610 * IOW: newline is passed verbatim!
611 * I take it to mean that it's syslogd's job
612 * to make those look identical in the log files. */
613 if (recvbuf[sz-1] != '\0' && recvbuf[sz-1] != '\n')
617 #if ENABLE_FEATURE_SYSLOGD_DUP
618 if ((option_mask32 & OPT_dup) && (sz == last_sz))
619 if (memcmp(last_buf, recvbuf, sz) == 0)
623 #if ENABLE_FEATURE_REMOTE_LOG
624 /* We are not modifying log messages in any way before send */
625 /* Remote site cannot trust _us_ anyway and need to do validation again */
626 if (G.remoteAddrStr) {
627 if (-1 == G.remoteFD) {
628 G.remoteFD = try_to_resolve_remote();
629 if (-1 == G.remoteFD)
632 /* Stock syslogd sends it '\n'-terminated
633 * over network, mimic that */
635 /* send message to remote logger, ignore possible error */
636 /* TODO: on some errors, close and set G.remoteFD to -1
637 * so that DNS resolution and connect is retried? */
638 sendto(G.remoteFD, recvbuf, sz+1, MSG_DONTWAIT,
639 &G.remoteAddr->u.sa, G.remoteAddr->len);
643 if (!ENABLE_FEATURE_REMOTE_LOG || (option_mask32 & OPT_locallog)) {
644 recvbuf[sz] = '\0'; /* ensure it *is* NUL terminated */
645 split_escape_and_log(recvbuf, sz);
647 } /* while (!bb_got_signal) */
649 timestamp_and_log_internal("syslogd exiting");
650 puts("syslogd exiting");
651 if (ENABLE_FEATURE_IPC_SYSLOG)
653 kill_myself_with_sig(bb_got_signal);
657 int syslogd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
658 int syslogd_main(int argc UNUSED_PARAM, char **argv)
664 #if ENABLE_FEATURE_REMOTE_LOG
665 G.last_dns_resolve = monotonic_sec() - DNS_WAIT_SEC - 1;
668 /* do normal option parsing */
669 opt_complementary = "=0"; /* no non-option params */
670 opts = getopt32(argv, OPTION_STR, OPTION_PARAM);
672 if (opts & OPT_mark) // -m
673 G.markInterval = xatou_range(opt_m, 0, INT_MAX/60) * 60;
675 //if (opts & OPT_nofork) // -n
676 //if (opts & OPT_outfile) // -O
677 if (opts & OPT_loglevel) // -l
678 G.logLevel = xatou_range(opt_l, 1, 8);
679 //if (opts & OPT_small) // -S
680 #if ENABLE_FEATURE_ROTATE_LOGFILE
681 if (opts & OPT_filesize) // -s
682 G.logFileSize = xatou_range(opt_s, 0, INT_MAX/1024) * 1024;
683 if (opts & OPT_rotatecnt) // -b
684 G.logFileRotate = xatou_range(opt_b, 0, 99);
686 #if ENABLE_FEATURE_IPC_SYSLOG
688 G.shm_size = xatoul_range(opt_C, 4, INT_MAX/1024) * 1024;
691 /* If they have not specified remote logging, then log locally */
692 if (ENABLE_FEATURE_REMOTE_LOG && !(opts & OPT_remotelog)) // -R
693 option_mask32 |= OPT_locallog;
695 /* Store away localhost's name before the fork */
696 G.hostname = safe_gethostname();
697 *strchrnul(G.hostname, '.') = '\0';
699 if (!(opts & OPT_nofork)) {
700 bb_daemonize_or_rexec(DAEMON_CHDIR_ROOT, argv);
703 write_pidfile("/var/run/syslogd.pid");
705 /* return EXIT_SUCCESS; */
708 /* Clean up. Needed because we are included from syslogd_and_logger.c */
711 #undef SYSLOGD_WRLOCK