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.
20 /* SYSLOG_NAMES defined to pull prioritynames[] and facilitynames[]
21 * from syslog.h. Grrrr - glibc puts those in _rwdata_! :( */
23 #define SYSLOG_NAMES_CONST /* uclibc is saner :) */
24 #include <sys/syslog.h>
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) */
47 DNS_WAIT_SEC = 2 * 60,
50 /* Semaphore operation structures */
52 int32_t size; /* size of data - 1 */
53 int32_t tail; /* end of message list */
54 char data[1]; /* data/messages */
57 /* Allows us to have smaller initializer. Ugly. */
59 const char *logFilePath; \
61 /* interval between marks in seconds */ \
62 /*int markInterval;*/ \
63 /* level of messages to be logged */ \
65 USE_FEATURE_ROTATE_LOGFILE( \
66 /* max size of file before rotation */ \
67 unsigned logFileSize; \
68 /* number of rotated message files */ \
69 unsigned logFileRotate; \
70 unsigned curFileSize; \
73 USE_FEATURE_REMOTE_LOG( \
74 /* udp socket for remote logging */ \
76 len_and_sockaddr* remoteAddr; \
78 USE_FEATURE_IPC_SYSLOG( \
79 int shmid; /* ipc shared memory id */ \
80 int s_semid; /* ipc semaphore id */ \
82 struct sembuf SMwup[1]; \
83 struct sembuf SMwdn[3]; \
93 #if ENABLE_FEATURE_REMOTE_LOG
94 unsigned last_dns_resolve;
98 #if ENABLE_FEATURE_IPC_SYSLOG
99 struct shbuf_ds *shbuf;
101 time_t last_log_time;
102 /* localhost's name */
103 char localHostName[64];
105 /* We recv into recvbuf... */
106 char recvbuf[MAX_READ];
107 /* ...then copy to parsebuf, escaping control chars */
108 /* (can grow x2 max) */
109 char parsebuf[MAX_READ*2];
110 /* ...then sprintf into printbuf, adding timestamp (15 chars),
111 * host (64), fac.prio (20) to the message */
112 /* (growth by: 15 + 64 + 20 + delims = ~110) */
113 char printbuf[MAX_READ*2 + 128];
116 static const struct init_globals init_data = {
117 .logFilePath = "/var/log/messages",
120 .markInterval = 20 * 60,
123 #if ENABLE_FEATURE_ROTATE_LOGFILE
124 .logFileSize = 200 * 1024,
127 #if ENABLE_FEATURE_REMOTE_LOG
130 #if ENABLE_FEATURE_IPC_SYSLOG
133 .shm_size = ((CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE)*1024), // default shm size
134 .SMwup = { {1, -1, IPC_NOWAIT} },
135 .SMwdn = { {0, 0}, {1, 0}, {1, +1} },
139 #define G (*ptr_to_globals)
140 #define INIT_G() do { \
141 PTR_TO_GLOBALS = memcpy(xzalloc(sizeof(G)), &init_data, sizeof(init_data)); \
147 OPTBIT_mark = 0, // -m
149 OPTBIT_outfile, // -O
150 OPTBIT_loglevel, // -l
152 USE_FEATURE_ROTATE_LOGFILE(OPTBIT_filesize ,) // -s
153 USE_FEATURE_ROTATE_LOGFILE(OPTBIT_rotatecnt ,) // -b
154 USE_FEATURE_REMOTE_LOG( OPTBIT_remote ,) // -R
155 USE_FEATURE_REMOTE_LOG( OPTBIT_locallog ,) // -L
156 USE_FEATURE_IPC_SYSLOG( OPTBIT_circularlog,) // -C
158 OPT_mark = 1 << OPTBIT_mark ,
159 OPT_nofork = 1 << OPTBIT_nofork ,
160 OPT_outfile = 1 << OPTBIT_outfile ,
161 OPT_loglevel = 1 << OPTBIT_loglevel,
162 OPT_small = 1 << OPTBIT_small ,
163 OPT_filesize = USE_FEATURE_ROTATE_LOGFILE((1 << OPTBIT_filesize )) + 0,
164 OPT_rotatecnt = USE_FEATURE_ROTATE_LOGFILE((1 << OPTBIT_rotatecnt )) + 0,
165 OPT_remotelog = USE_FEATURE_REMOTE_LOG( (1 << OPTBIT_remote )) + 0,
166 OPT_locallog = USE_FEATURE_REMOTE_LOG( (1 << OPTBIT_locallog )) + 0,
167 OPT_circularlog = USE_FEATURE_IPC_SYSLOG( (1 << OPTBIT_circularlog)) + 0,
169 #define OPTION_STR "m:nO:l:S" \
170 USE_FEATURE_ROTATE_LOGFILE("s:" ) \
171 USE_FEATURE_ROTATE_LOGFILE("b:" ) \
172 USE_FEATURE_REMOTE_LOG( "R:" ) \
173 USE_FEATURE_REMOTE_LOG( "L" ) \
174 USE_FEATURE_IPC_SYSLOG( "C::")
175 #define OPTION_DECL *opt_m, *opt_l \
176 USE_FEATURE_ROTATE_LOGFILE(,*opt_s) \
177 USE_FEATURE_ROTATE_LOGFILE(,*opt_b) \
178 USE_FEATURE_IPC_SYSLOG( ,*opt_C = NULL)
179 #define OPTION_PARAM &opt_m, &G.logFilePath, &opt_l \
180 USE_FEATURE_ROTATE_LOGFILE(,&opt_s) \
181 USE_FEATURE_ROTATE_LOGFILE(,&opt_b) \
182 USE_FEATURE_REMOTE_LOG( ,&G.remoteAddrStr) \
183 USE_FEATURE_IPC_SYSLOG( ,&opt_C)
186 /* circular buffer variables/structures */
187 #if ENABLE_FEATURE_IPC_SYSLOG
189 #if CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE < 4
190 #error Sorry, you must set the syslogd buffer size to at least 4KB.
191 #error Please check CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE
195 #define KEY_ID ((long)0x414e4547) /* "GENA" */
197 static void ipcsyslog_cleanup(void)
203 shmctl(G.shmid, IPC_RMID, NULL);
205 if (G.s_semid != -1) {
206 semctl(G.s_semid, 0, IPC_RMID, 0);
210 static void ipcsyslog_init(void)
213 printf("shmget(%lx, %d,...)\n", KEY_ID, G.shm_size);
215 G.shmid = shmget(KEY_ID, G.shm_size, IPC_CREAT | 0644);
217 bb_perror_msg_and_die("shmget");
220 G.shbuf = shmat(G.shmid, NULL, 0);
222 bb_perror_msg_and_die("shmat");
225 memset(G.shbuf, 0, G.shm_size);
226 G.shbuf->size = G.shm_size - offsetof(struct shbuf_ds, data) - 1;
227 /*G.shbuf->tail = 0;*/
229 // we'll trust the OS to set initial semval to 0 (let's hope)
230 G.s_semid = semget(KEY_ID, 2, IPC_CREAT | IPC_EXCL | 1023);
231 if (G.s_semid == -1) {
232 if (errno == EEXIST) {
233 G.s_semid = semget(KEY_ID, 2, 0);
237 bb_perror_msg_and_die("semget");
241 /* Write message to shared mem buffer */
242 static void log_to_shmem(const char *msg, int len)
244 int old_tail, new_tail;
246 if (semop(G.s_semid, G.SMwdn, 3) == -1) {
247 bb_perror_msg_and_die("SMwdn");
250 /* Circular Buffer Algorithm:
251 * --------------------------
252 * tail == position where to store next syslog message.
253 * tail's max value is (shbuf->size - 1)
254 * Last byte of buffer is never used and remains NUL.
256 len++; /* length with NUL included */
258 old_tail = G.shbuf->tail;
259 new_tail = old_tail + len;
260 if (new_tail < G.shbuf->size) {
261 /* store message, set new tail */
262 memcpy(G.shbuf->data + old_tail, msg, len);
263 G.shbuf->tail = new_tail;
265 /* k == available buffer space ahead of old tail */
266 int k = G.shbuf->size - old_tail;
267 /* copy what fits to the end of buffer, and repeat */
268 memcpy(G.shbuf->data + old_tail, msg, k);
274 if (semop(G.s_semid, G.SMwup, 1) == -1) {
275 bb_perror_msg_and_die("SMwup");
278 printf("tail:%d\n", G.shbuf->tail);
281 void ipcsyslog_cleanup(void);
282 void ipcsyslog_init(void);
283 void log_to_shmem(const char *msg);
284 #endif /* FEATURE_IPC_SYSLOG */
287 /* Print a message to the log file. */
288 static void log_locally(char *msg)
291 int len = strlen(msg);
293 #if ENABLE_FEATURE_IPC_SYSLOG
294 if ((option_mask32 & OPT_circularlog) && G.shbuf) {
295 log_to_shmem(msg, len);
302 if (G.last_log_time != cur) {
303 G.last_log_time = cur; /* reopen log file every second */
309 G.logFD = device_open(G.logFilePath, O_WRONLY | O_CREAT
310 | O_NOCTTY | O_APPEND | O_NONBLOCK);
312 /* cannot open logfile? - print to /dev/console then */
313 int fd = device_open(DEV_CONSOLE, O_WRONLY | O_NOCTTY | O_NONBLOCK);
315 fd = 2; /* then stderr, dammit */
316 full_write(fd, msg, len);
321 #if ENABLE_FEATURE_ROTATE_LOGFILE
324 G.isRegular = (fstat(G.logFD, &statf) == 0 && S_ISREG(statf.st_mode));
325 /* bug (mostly harmless): can wrap around if file > 4gb */
326 G.curFileSize = statf.st_size;
331 fl.l_whence = SEEK_SET;
335 fcntl(G.logFD, F_SETLKW, &fl);
337 #if ENABLE_FEATURE_ROTATE_LOGFILE
338 if (G.logFileSize && G.isRegular && G.curFileSize > G.logFileSize) {
339 if (G.logFileRotate) { /* always 0..99 */
340 int i = strlen(G.logFilePath) + 3 + 1;
343 i = G.logFileRotate - 1;
344 /* rename: f.8 -> f.9; f.7 -> f.8; ... */
346 sprintf(newFile, "%s.%d", G.logFilePath, i);
348 sprintf(oldFile, "%s.%d", G.logFilePath, --i);
349 rename(oldFile, newFile);
351 /* newFile == "f.0" now */
352 rename(G.logFilePath, newFile);
354 fcntl(G.logFD, F_SETLKW, &fl);
358 ftruncate(G.logFD, 0);
362 full_write(G.logFD, msg, len);
364 fcntl(G.logFD, F_SETLKW, &fl);
367 static void parse_fac_prio_20(int pri, char *res20)
369 const CODE *c_pri, *c_fac;
372 c_fac = facilitynames;
373 while (c_fac->c_name) {
374 if (c_fac->c_val != (LOG_FAC(pri) << 3)) {
377 /* facility is found, look for prio */
378 c_pri = prioritynames;
379 while (c_pri->c_name) {
380 if (c_pri->c_val != LOG_PRI(pri)) {
383 snprintf(res20, 20, "%s.%s",
384 c_fac->c_name, c_pri->c_name);
387 /* prio not found, bail out */
390 snprintf(res20, 20, "<%d>", pri);
394 /* len parameter is used only for "is there a timestamp?" check.
395 * NB: some callers cheat and supply len==0 when they know
396 * that there is no timestamp, short-circuiting the test. */
397 static void timestamp_and_log(int pri, char *msg, int len)
401 if (ENABLE_FEATURE_REMOTE_LOG && !(option_mask32 & OPT_locallog))
404 if (len < 16 || msg[3] != ' ' || msg[6] != ' '
405 || msg[9] != ':' || msg[12] != ':' || msg[15] != ' '
409 timestamp = ctime(&now) + 4;
414 timestamp[15] = '\0';
416 /* Log message locally (to file or shared mem) */
417 if (option_mask32 & OPT_small)
418 sprintf(G.printbuf, "%s %s\n", timestamp, msg);
421 parse_fac_prio_20(pri, res);
422 sprintf(G.printbuf, "%s %s %s %s\n", timestamp, G.localHostName, res, msg);
424 log_locally(G.printbuf);
427 static void split_escape_and_log(char *tmpbuf, int len)
434 char *q = G.parsebuf;
435 int pri = (LOG_USER | LOG_NOTICE);
438 /* Parse the magic priority number */
439 pri = bb_strtou(p + 1, &p, 10);
442 if (pri & ~(LOG_FACMASK | LOG_PRIMASK))
443 pri = (LOG_USER | LOG_NOTICE);
449 if (!(c & ~0x1f) && c != '\t') {
451 c += '@'; /* ^@, ^A, ^B... */
458 if (LOG_PRI(pri) < G.logLevel)
459 timestamp_and_log(pri, G.parsebuf, q - G.parsebuf);
463 static void quit_signal(int sig)
465 timestamp_and_log(LOG_SYSLOG | LOG_INFO, (char*)"syslogd exiting", 0);
466 puts("syslogd exiting");
467 if (ENABLE_FEATURE_IPC_SYSLOG)
473 static void do_mark(int sig)
475 if (G.markInterval) {
476 timestamp_and_log(LOG_SYSLOG | LOG_INFO, (char*)"-- MARK --", 0);
477 alarm(G.markInterval);
482 /* Don't inline: prevent struct sockaddr_un to take up space on stack
484 static NOINLINE int create_socket(void)
486 struct sockaddr_un sunx;
490 memset(&sunx, 0, sizeof(sunx));
491 sunx.sun_family = AF_UNIX;
493 /* Unlink old /dev/log or object it points to. */
494 /* (if it exists, bind will fail) */
495 strcpy(sunx.sun_path, "/dev/log");
496 dev_log_name = xmalloc_follow_symlinks("/dev/log");
498 safe_strncpy(sunx.sun_path, dev_log_name, sizeof(sunx.sun_path));
501 unlink(sunx.sun_path);
503 sock_fd = xsocket(AF_UNIX, SOCK_DGRAM, 0);
504 xbind(sock_fd, (struct sockaddr *) &sunx, sizeof(sunx));
505 chmod("/dev/log", 0666);
510 #if ENABLE_FEATURE_REMOTE_LOG
511 static int try_to_resolve_remote(void)
514 unsigned now = monotonic_sec();
516 /* Don't resolve name too often - DNS timeouts can be big */
517 if ((now - G.last_dns_resolve) < DNS_WAIT_SEC)
519 G.last_dns_resolve = now;
520 G.remoteAddr = host2sockaddr(G.remoteAddrStr, 514);
524 return socket(G.remoteAddr->sa.sa_family, SOCK_DGRAM, 0);
528 static void do_syslogd(void) ATTRIBUTE_NORETURN;
529 static void do_syslogd(void)
533 /* Set up signal handlers */
534 signal(SIGINT, quit_signal);
535 signal(SIGTERM, quit_signal);
536 signal(SIGQUIT, quit_signal);
537 signal(SIGHUP, SIG_IGN);
538 /* signal(SIGCHLD, SIG_IGN); - why? */
540 signal(SIGALRM, do_mark);
541 alarm(G.markInterval);
543 sock_fd = create_socket();
545 if (ENABLE_FEATURE_IPC_SYSLOG && (option_mask32 & OPT_circularlog)) {
549 timestamp_and_log(LOG_SYSLOG | LOG_INFO,
550 (char*)"syslogd started: BusyBox v" BB_VER, 0);
555 sz = safe_read(sock_fd, G.recvbuf, MAX_READ - 1);
557 bb_perror_msg_and_die("read from /dev/log");
560 /* Drop trailing NULs (typically there is one NUL) */
564 /* man 3 syslog says: "A trailing newline is added when needed".
565 * However, neither glibc nor uclibc do this:
566 * syslog(prio, "test") sends "test\0" to /dev/log,
567 * syslog(prio, "test\n") sends "test\n\0",
568 * IOW: newline is passed verbatim!
569 * I take it to mean that it's syslogd's job
570 * to make those look identical in the log files */
571 if (G.recvbuf[sz-1] && G.recvbuf[sz-1] != '\n')
575 /* Maybe we need to add '\n' here, not later?
576 * It looks like stock syslogd does send '\n' over network,
577 * but we do not (see sendto below) */
578 G.recvbuf[sz] = '\0'; /* make sure it *is* NUL terminated */
580 /* TODO: maybe suppress duplicates? */
581 #if ENABLE_FEATURE_REMOTE_LOG
582 /* We are not modifying log messages in any way before send */
583 /* Remote site cannot trust _us_ anyway and need to do validation again */
584 if (G.remoteAddrStr) {
585 if (-1 == G.remoteFD) {
586 G.remoteFD = try_to_resolve_remote();
587 if (-1 == G.remoteFD)
590 /* send message to remote logger, ignore possible error */
591 sendto(G.remoteFD, G.recvbuf, sz, MSG_DONTWAIT,
592 &G.remoteAddr->sa, G.remoteAddr->len);
596 if (!ENABLE_FEATURE_REMOTE_LOG || (option_mask32 & OPT_locallog))
597 split_escape_and_log(G.recvbuf, sz);
601 int syslogd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
602 int syslogd_main(int argc, char **argv)
608 #if ENABLE_FEATURE_REMOTE_LOG
609 G.last_dns_resolve = monotonic_sec() - DNS_WAIT_SEC - 1;
612 /* do normal option parsing */
613 opt_complementary = "=0"; /* no non-option params */
614 getopt32(argv, OPTION_STR, OPTION_PARAM);
616 if (option_mask32 & OPT_mark) // -m
617 G.markInterval = xatou_range(opt_m, 0, INT_MAX/60) * 60;
619 //if (option_mask32 & OPT_nofork) // -n
620 //if (option_mask32 & OPT_outfile) // -O
621 if (option_mask32 & OPT_loglevel) // -l
622 G.logLevel = xatou_range(opt_l, 1, 8);
623 //if (option_mask32 & OPT_small) // -S
624 #if ENABLE_FEATURE_ROTATE_LOGFILE
625 if (option_mask32 & OPT_filesize) // -s
626 G.logFileSize = xatou_range(opt_s, 0, INT_MAX/1024) * 1024;
627 if (option_mask32 & OPT_rotatecnt) // -b
628 G.logFileRotate = xatou_range(opt_b, 0, 99);
630 #if ENABLE_FEATURE_IPC_SYSLOG
632 G.shm_size = xatoul_range(opt_C, 4, INT_MAX/1024) * 1024;
635 /* If they have not specified remote logging, then log locally */
636 if (ENABLE_FEATURE_REMOTE_LOG && !(option_mask32 & OPT_remotelog))
637 option_mask32 |= OPT_locallog;
639 /* Store away localhost's name before the fork */
640 gethostname(G.localHostName, sizeof(G.localHostName));
641 p = strchr(G.localHostName, '.');
646 if (!(option_mask32 & OPT_nofork)) {
647 bb_daemonize_or_rexec(DAEMON_CHDIR_ROOT, argv);
650 write_pidfile("/var/run/syslogd.pid");
652 /* return EXIT_SUCCESS; */