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 */
49 MAX_READ = CONFIG_FEATURE_SYSLOGD_READ_BUFFER_SIZE,
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 #if ENABLE_FEATURE_REMOTE_LOG
63 unsigned last_dns_resolve;
64 len_and_sockaddr *remoteAddr;
65 const char *remoteHostname;
69 /* Allows us to have smaller initializer. Ugly. */
71 const char *logFilePath; \
73 /* interval between marks in seconds */ \
74 /*int markInterval;*/ \
75 /* level of messages to be logged */ \
77 IF_FEATURE_ROTATE_LOGFILE( \
78 /* max size of file before rotation */ \
79 unsigned logFileSize; \
80 /* number of rotated message files */ \
81 unsigned logFileRotate; \
82 unsigned curFileSize; \
85 IF_FEATURE_IPC_SYSLOG( \
86 int shmid; /* ipc shared memory id */ \
87 int s_semid; /* ipc semaphore id */ \
89 struct sembuf SMwup[1]; \
90 struct sembuf SMwdn[3]; \
100 #if ENABLE_FEATURE_REMOTE_LOG
101 llist_t *remoteHosts;
103 #if ENABLE_FEATURE_IPC_SYSLOG
104 struct shbuf_ds *shbuf;
106 time_t last_log_time;
107 /* localhost's name. We print only first 64 chars */
110 /* We recv into recvbuf... */
111 char recvbuf[MAX_READ * (1 + ENABLE_FEATURE_SYSLOGD_DUP)];
112 /* ...then copy to parsebuf, escaping control chars */
113 /* (can grow x2 max) */
114 char parsebuf[MAX_READ*2];
115 /* ...then sprintf into printbuf, adding timestamp (15 chars),
116 * host (64), fac.prio (20) to the message */
117 /* (growth by: 15 + 64 + 20 + delims = ~110) */
118 char printbuf[MAX_READ*2 + 128];
121 static const struct init_globals init_data = {
122 .logFilePath = "/var/log/messages",
125 .markInterval = 20 * 60,
128 #if ENABLE_FEATURE_ROTATE_LOGFILE
129 .logFileSize = 200 * 1024,
132 #if ENABLE_FEATURE_IPC_SYSLOG
135 .shm_size = ((CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE)*1024), // default shm size
136 .SMwup = { {1, -1, IPC_NOWAIT} },
137 .SMwdn = { {0, 0}, {1, 0}, {1, +1} },
141 #define G (*ptr_to_globals)
142 #define INIT_G() do { \
143 SET_PTR_TO_GLOBALS(memcpy(xzalloc(sizeof(G)), &init_data, sizeof(init_data))); \
149 OPTBIT_mark = 0, // -m
151 OPTBIT_outfile, // -O
152 OPTBIT_loglevel, // -l
154 IF_FEATURE_ROTATE_LOGFILE(OPTBIT_filesize ,) // -s
155 IF_FEATURE_ROTATE_LOGFILE(OPTBIT_rotatecnt ,) // -b
156 IF_FEATURE_REMOTE_LOG( OPTBIT_remotelog ,) // -R
157 IF_FEATURE_REMOTE_LOG( OPTBIT_locallog ,) // -L
158 IF_FEATURE_IPC_SYSLOG( OPTBIT_circularlog,) // -C
159 IF_FEATURE_SYSLOGD_DUP( OPTBIT_dup ,) // -D
161 OPT_mark = 1 << OPTBIT_mark ,
162 OPT_nofork = 1 << OPTBIT_nofork ,
163 OPT_outfile = 1 << OPTBIT_outfile ,
164 OPT_loglevel = 1 << OPTBIT_loglevel,
165 OPT_small = 1 << OPTBIT_small ,
166 OPT_filesize = IF_FEATURE_ROTATE_LOGFILE((1 << OPTBIT_filesize )) + 0,
167 OPT_rotatecnt = IF_FEATURE_ROTATE_LOGFILE((1 << OPTBIT_rotatecnt )) + 0,
168 OPT_remotelog = IF_FEATURE_REMOTE_LOG( (1 << OPTBIT_remotelog )) + 0,
169 OPT_locallog = IF_FEATURE_REMOTE_LOG( (1 << OPTBIT_locallog )) + 0,
170 OPT_circularlog = IF_FEATURE_IPC_SYSLOG( (1 << OPTBIT_circularlog)) + 0,
171 OPT_dup = IF_FEATURE_SYSLOGD_DUP( (1 << OPTBIT_dup )) + 0,
173 #define OPTION_STR "m:nO:l:S" \
174 IF_FEATURE_ROTATE_LOGFILE("s:" ) \
175 IF_FEATURE_ROTATE_LOGFILE("b:" ) \
176 IF_FEATURE_REMOTE_LOG( "R:" ) \
177 IF_FEATURE_REMOTE_LOG( "L" ) \
178 IF_FEATURE_IPC_SYSLOG( "C::") \
179 IF_FEATURE_SYSLOGD_DUP( "D" )
180 #define OPTION_DECL *opt_m, *opt_l \
181 IF_FEATURE_ROTATE_LOGFILE(,*opt_s) \
182 IF_FEATURE_ROTATE_LOGFILE(,*opt_b) \
183 IF_FEATURE_IPC_SYSLOG( ,*opt_C = NULL)
184 #define OPTION_PARAM &opt_m, &G.logFilePath, &opt_l \
185 IF_FEATURE_ROTATE_LOGFILE(,&opt_s) \
186 IF_FEATURE_ROTATE_LOGFILE(,&opt_b) \
187 IF_FEATURE_REMOTE_LOG( ,&remoteAddrList) \
188 IF_FEATURE_IPC_SYSLOG( ,&opt_C)
191 /* circular buffer variables/structures */
192 #if ENABLE_FEATURE_IPC_SYSLOG
194 #if CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE < 4
195 #error Sorry, you must set the syslogd buffer size to at least 4KB.
196 #error Please check CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE
199 /* our shared key (syslogd.c and logread.c must be in sync) */
200 enum { KEY_ID = 0x414e4547 }; /* "GENA" */
202 static void ipcsyslog_cleanup(void)
208 shmctl(G.shmid, IPC_RMID, NULL);
210 if (G.s_semid != -1) {
211 semctl(G.s_semid, 0, IPC_RMID, 0);
215 static void ipcsyslog_init(void)
218 printf("shmget(%x, %d,...)\n", (int)KEY_ID, G.shm_size);
220 G.shmid = shmget(KEY_ID, G.shm_size, IPC_CREAT | 0644);
222 bb_perror_msg_and_die("shmget");
225 G.shbuf = shmat(G.shmid, NULL, 0);
226 if (G.shbuf == (void*) -1L) { /* shmat has bizarre error return */
227 bb_perror_msg_and_die("shmat");
230 memset(G.shbuf, 0, G.shm_size);
231 G.shbuf->size = G.shm_size - offsetof(struct shbuf_ds, data) - 1;
232 /*G.shbuf->tail = 0;*/
234 // we'll trust the OS to set initial semval to 0 (let's hope)
235 G.s_semid = semget(KEY_ID, 2, IPC_CREAT | IPC_EXCL | 1023);
236 if (G.s_semid == -1) {
237 if (errno == EEXIST) {
238 G.s_semid = semget(KEY_ID, 2, 0);
242 bb_perror_msg_and_die("semget");
246 /* Write message to shared mem buffer */
247 static void log_to_shmem(const char *msg, int len)
249 int old_tail, new_tail;
251 if (semop(G.s_semid, G.SMwdn, 3) == -1) {
252 bb_perror_msg_and_die("SMwdn");
255 /* Circular Buffer Algorithm:
256 * --------------------------
257 * tail == position where to store next syslog message.
258 * tail's max value is (shbuf->size - 1)
259 * Last byte of buffer is never used and remains NUL.
261 len++; /* length with NUL included */
263 old_tail = G.shbuf->tail;
264 new_tail = old_tail + len;
265 if (new_tail < G.shbuf->size) {
266 /* store message, set new tail */
267 memcpy(G.shbuf->data + old_tail, msg, len);
268 G.shbuf->tail = new_tail;
270 /* k == available buffer space ahead of old tail */
271 int k = G.shbuf->size - old_tail;
272 /* copy what fits to the end of buffer, and repeat */
273 memcpy(G.shbuf->data + old_tail, msg, k);
279 if (semop(G.s_semid, G.SMwup, 1) == -1) {
280 bb_perror_msg_and_die("SMwup");
283 printf("tail:%d\n", G.shbuf->tail);
286 void ipcsyslog_cleanup(void);
287 void ipcsyslog_init(void);
288 void log_to_shmem(const char *msg);
289 #endif /* FEATURE_IPC_SYSLOG */
292 /* Print a message to the log file. */
293 static void log_locally(time_t now, char *msg)
295 #ifdef SYSLOGD_WRLOCK
298 int len = strlen(msg);
300 #if ENABLE_FEATURE_IPC_SYSLOG
301 if ((option_mask32 & OPT_circularlog) && G.shbuf) {
302 log_to_shmem(msg, len);
307 /* Reopen log file every second. This allows admin
308 * to delete the file and not worry about restarting us.
309 * This costs almost nothing since it happens
310 * _at most_ once a second.
314 if (G.last_log_time != now) {
315 G.last_log_time = now;
321 G.logFD = open(G.logFilePath, O_WRONLY | O_CREAT
322 | O_NOCTTY | O_APPEND | O_NONBLOCK,
325 /* cannot open logfile? - print to /dev/console then */
326 int fd = device_open(DEV_CONSOLE, O_WRONLY | O_NOCTTY | O_NONBLOCK);
328 fd = 2; /* then stderr, dammit */
329 full_write(fd, msg, len);
334 #if ENABLE_FEATURE_ROTATE_LOGFILE
337 G.isRegular = (fstat(G.logFD, &statf) == 0 && S_ISREG(statf.st_mode));
338 /* bug (mostly harmless): can wrap around if file > 4gb */
339 G.curFileSize = statf.st_size;
344 #ifdef SYSLOGD_WRLOCK
345 fl.l_whence = SEEK_SET;
349 fcntl(G.logFD, F_SETLKW, &fl);
352 #if ENABLE_FEATURE_ROTATE_LOGFILE
353 if (G.logFileSize && G.isRegular && G.curFileSize > G.logFileSize) {
354 if (G.logFileRotate) { /* always 0..99 */
355 int i = strlen(G.logFilePath) + 3 + 1;
358 i = G.logFileRotate - 1;
359 /* rename: f.8 -> f.9; f.7 -> f.8; ... */
361 sprintf(newFile, "%s.%d", G.logFilePath, i);
363 sprintf(oldFile, "%s.%d", G.logFilePath, --i);
364 /* ignore errors - file might be missing */
365 rename(oldFile, newFile);
367 /* newFile == "f.0" now */
368 rename(G.logFilePath, newFile);
369 #ifdef SYSLOGD_WRLOCK
371 fcntl(G.logFD, F_SETLKW, &fl);
376 ftruncate(G.logFD, 0);
380 full_write(G.logFD, msg, len);
381 #ifdef SYSLOGD_WRLOCK
383 fcntl(G.logFD, F_SETLKW, &fl);
387 static void parse_fac_prio_20(int pri, char *res20)
389 const CODE *c_pri, *c_fac;
392 c_fac = facilitynames;
393 while (c_fac->c_name) {
394 if (c_fac->c_val != (LOG_FAC(pri) << 3)) {
398 /* facility is found, look for prio */
399 c_pri = prioritynames;
400 while (c_pri->c_name) {
401 if (c_pri->c_val != LOG_PRI(pri)) {
405 snprintf(res20, 20, "%s.%s",
406 c_fac->c_name, c_pri->c_name);
409 /* prio not found, bail out */
412 snprintf(res20, 20, "<%d>", pri);
416 /* len parameter is used only for "is there a timestamp?" check.
417 * NB: some callers cheat and supply len==0 when they know
418 * that there is no timestamp, short-circuiting the test. */
419 static void timestamp_and_log(int pri, char *msg, int len)
424 /* Jan 18 00:11:22 msg... */
425 /* 01234567890123456 */
426 if (len < 16 || msg[3] != ' ' || msg[6] != ' '
427 || msg[9] != ':' || msg[12] != ':' || msg[15] != ' '
430 timestamp = ctime(&now) + 4; /* skip day of week */
436 timestamp[15] = '\0';
438 if (option_mask32 & OPT_small)
439 sprintf(G.printbuf, "%s %s\n", timestamp, msg);
442 parse_fac_prio_20(pri, res);
443 sprintf(G.printbuf, "%s %.64s %s %s\n", timestamp, G.hostname, res, msg);
446 /* Log message locally (to file or shared mem) */
447 log_locally(now, G.printbuf);
450 static void timestamp_and_log_internal(const char *msg)
453 if (ENABLE_FEATURE_REMOTE_LOG && !(option_mask32 & OPT_locallog))
455 timestamp_and_log(LOG_SYSLOG | LOG_INFO, (char*)msg, 0);
458 /* tmpbuf[len] is a NUL byte (set by caller), but there can be other,
459 * embedded NULs. Split messages on each of these NULs, parse prio,
460 * escape control chars and log each locally. */
461 static void split_escape_and_log(char *tmpbuf, int len)
468 char *q = G.parsebuf;
469 int pri = (LOG_USER | LOG_NOTICE);
472 /* Parse the magic priority number */
473 pri = bb_strtou(p + 1, &p, 10);
476 if (pri & ~(LOG_FACMASK | LOG_PRIMASK))
477 pri = (LOG_USER | LOG_NOTICE);
483 if (!(c & ~0x1f) && c != '\t') {
485 c += '@'; /* ^@, ^A, ^B... */
492 if (LOG_PRI(pri) < G.logLevel)
493 timestamp_and_log(pri, G.parsebuf, q - G.parsebuf);
498 static void do_mark(int sig)
500 if (G.markInterval) {
501 timestamp_and_log_internal("-- MARK --");
502 alarm(G.markInterval);
507 /* Don't inline: prevent struct sockaddr_un to take up space on stack
509 static NOINLINE int create_socket(void)
511 struct sockaddr_un sunx;
515 memset(&sunx, 0, sizeof(sunx));
516 sunx.sun_family = AF_UNIX;
518 /* Unlink old /dev/log or object it points to. */
519 /* (if it exists, bind will fail) */
520 strcpy(sunx.sun_path, "/dev/log");
521 dev_log_name = xmalloc_follow_symlinks("/dev/log");
523 safe_strncpy(sunx.sun_path, dev_log_name, sizeof(sunx.sun_path));
526 unlink(sunx.sun_path);
528 sock_fd = xsocket(AF_UNIX, SOCK_DGRAM, 0);
529 xbind(sock_fd, (struct sockaddr *) &sunx, sizeof(sunx));
530 chmod("/dev/log", 0666);
535 #if ENABLE_FEATURE_REMOTE_LOG
536 static int try_to_resolve_remote(remoteHost_t *rh)
538 if (!rh->remoteAddr) {
539 unsigned now = monotonic_sec();
541 /* Don't resolve name too often - DNS timeouts can be big */
542 if ((now - rh->last_dns_resolve) < DNS_WAIT_SEC)
544 rh->last_dns_resolve = now;
545 rh->remoteAddr = host2sockaddr(rh->remoteHostname, 514);
549 return socket(rh->remoteAddr->u.sa.sa_family, SOCK_DGRAM, 0);
553 static void do_syslogd(void) NORETURN;
554 static void do_syslogd(void)
557 #if ENABLE_FEATURE_REMOTE_LOG
560 #if ENABLE_FEATURE_SYSLOGD_DUP
563 char *recvbuf = G.recvbuf;
565 #define recvbuf (G.recvbuf)
568 /* Set up signal handlers (so that they interrupt read()) */
569 signal_no_SA_RESTART_empty_mask(SIGTERM, record_signo);
570 signal_no_SA_RESTART_empty_mask(SIGINT, record_signo);
571 //signal_no_SA_RESTART_empty_mask(SIGQUIT, record_signo);
572 signal(SIGHUP, SIG_IGN);
574 signal(SIGALRM, do_mark);
575 alarm(G.markInterval);
577 sock_fd = create_socket();
579 if (ENABLE_FEATURE_IPC_SYSLOG && (option_mask32 & OPT_circularlog)) {
583 timestamp_and_log_internal("syslogd started: BusyBox v" BB_VER);
585 while (!bb_got_signal) {
588 #if ENABLE_FEATURE_SYSLOGD_DUP
590 if (recvbuf == G.recvbuf)
591 recvbuf = G.recvbuf + MAX_READ;
596 sz = read(sock_fd, recvbuf, MAX_READ - 1);
599 bb_perror_msg("read from /dev/log");
603 /* Drop trailing '\n' and NULs (typically there is one NUL) */
607 /* man 3 syslog says: "A trailing newline is added when needed".
608 * However, neither glibc nor uclibc do this:
609 * syslog(prio, "test") sends "test\0" to /dev/log,
610 * syslog(prio, "test\n") sends "test\n\0".
611 * IOW: newline is passed verbatim!
612 * I take it to mean that it's syslogd's job
613 * to make those look identical in the log files. */
614 if (recvbuf[sz-1] != '\0' && recvbuf[sz-1] != '\n')
618 #if ENABLE_FEATURE_SYSLOGD_DUP
619 if ((option_mask32 & OPT_dup) && (sz == last_sz))
620 if (memcmp(last_buf, recvbuf, sz) == 0)
624 #if ENABLE_FEATURE_REMOTE_LOG
625 /* Stock syslogd sends it '\n'-terminated
626 * over network, mimic that */
629 /* We are not modifying log messages in any way before send */
630 /* Remote site cannot trust _us_ anyway and need to do validation again */
631 for (item = G.remoteHosts; item != NULL; item = item->link) {
632 remoteHost_t *rh = (remoteHost_t *)item->data;
634 if (rh->remoteFD == -1) {
635 rh->remoteFD = try_to_resolve_remote(rh);
636 if (rh->remoteFD == -1)
639 /* Send message to remote logger, ignore possible error */
640 /* TODO: on some errors, close and set G.remoteFD to -1
641 * so that DNS resolution and connect is retried? */
642 sendto(rh->remoteFD, recvbuf, sz+1, MSG_DONTWAIT,
643 &(rh->remoteAddr->u.sa), rh->remoteAddr->len);
646 if (!ENABLE_FEATURE_REMOTE_LOG || (option_mask32 & OPT_locallog)) {
647 recvbuf[sz] = '\0'; /* ensure it *is* NUL terminated */
648 split_escape_and_log(recvbuf, sz);
650 } /* while (!bb_got_signal) */
652 timestamp_and_log_internal("syslogd exiting");
653 puts("syslogd exiting");
654 if (ENABLE_FEATURE_IPC_SYSLOG)
656 kill_myself_with_sig(bb_got_signal);
660 int syslogd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
661 int syslogd_main(int argc UNUSED_PARAM, char **argv)
665 #if ENABLE_FEATURE_REMOTE_LOG
666 llist_t *remoteAddrList = NULL;
671 /* No non-option params, -R can occur multiple times */
672 opt_complementary = "=0" IF_FEATURE_REMOTE_LOG(":R::");
673 opts = getopt32(argv, OPTION_STR, OPTION_PARAM);
674 #if ENABLE_FEATURE_REMOTE_LOG
675 while (remoteAddrList) {
676 remoteHost_t *rh = xzalloc(sizeof(*rh));
677 rh->remoteHostname = llist_pop(&remoteAddrList);
679 rh->last_dns_resolve = monotonic_sec() - DNS_WAIT_SEC - 1;
680 llist_add_to(&G.remoteHosts, rh);
685 if (opts & OPT_mark) // -m
686 G.markInterval = xatou_range(opt_m, 0, INT_MAX/60) * 60;
688 //if (opts & OPT_nofork) // -n
689 //if (opts & OPT_outfile) // -O
690 if (opts & OPT_loglevel) // -l
691 G.logLevel = xatou_range(opt_l, 1, 8);
692 //if (opts & OPT_small) // -S
693 #if ENABLE_FEATURE_ROTATE_LOGFILE
694 if (opts & OPT_filesize) // -s
695 G.logFileSize = xatou_range(opt_s, 0, INT_MAX/1024) * 1024;
696 if (opts & OPT_rotatecnt) // -b
697 G.logFileRotate = xatou_range(opt_b, 0, 99);
699 #if ENABLE_FEATURE_IPC_SYSLOG
701 G.shm_size = xatoul_range(opt_C, 4, INT_MAX/1024) * 1024;
704 /* If they have not specified remote logging, then log locally */
705 if (ENABLE_FEATURE_REMOTE_LOG && !(opts & OPT_remotelog)) // -R
706 option_mask32 |= OPT_locallog;
708 /* Store away localhost's name before the fork */
709 G.hostname = safe_gethostname();
710 *strchrnul(G.hostname, '.') = '\0';
712 if (!(opts & OPT_nofork)) {
713 bb_daemonize_or_rexec(DAEMON_CHDIR_ROOT, argv);
716 write_pidfile("/var/run/syslogd.pid");
718 /* return EXIT_SUCCESS; */
721 /* Clean up. Needed because we are included from syslogd_and_logger.c */
724 #undef SYSLOGD_WRLOCK