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(time_t now, 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 != now) {
303 G.last_log_time = now; /* 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)
402 if (len < 16 || msg[3] != ' ' || msg[6] != ' '
403 || msg[9] != ':' || msg[12] != ':' || msg[15] != ' '
406 timestamp = ctime(&now) + 4; /* skip day of week */
412 timestamp[15] = '\0';
414 if (option_mask32 & OPT_small)
415 sprintf(G.printbuf, "%s %s\n", timestamp, msg);
418 parse_fac_prio_20(pri, res);
419 sprintf(G.printbuf, "%s %s %s %s\n", timestamp, G.localHostName, res, msg);
422 /* Log message locally (to file or shared mem) */
423 log_locally(now, G.printbuf);
426 static void timestamp_and_log_internal(const char *msg)
428 if (ENABLE_FEATURE_REMOTE_LOG && !(option_mask32 & OPT_locallog))
430 timestamp_and_log(LOG_SYSLOG | LOG_INFO, (char*)msg, 0);
433 static void split_escape_and_log(char *tmpbuf, int len)
440 char *q = G.parsebuf;
441 int pri = (LOG_USER | LOG_NOTICE);
444 /* Parse the magic priority number */
445 pri = bb_strtou(p + 1, &p, 10);
448 if (pri & ~(LOG_FACMASK | LOG_PRIMASK))
449 pri = (LOG_USER | LOG_NOTICE);
455 if (!(c & ~0x1f) && c != '\t') {
457 c += '@'; /* ^@, ^A, ^B... */
464 if (LOG_PRI(pri) < G.logLevel)
465 timestamp_and_log(pri, G.parsebuf, q - G.parsebuf);
469 static void quit_signal(int sig)
471 timestamp_and_log_internal("syslogd exiting");
472 puts("syslogd exiting");
473 if (ENABLE_FEATURE_IPC_SYSLOG)
479 static void do_mark(int sig)
481 if (G.markInterval) {
482 timestamp_and_log_internal("-- MARK --");
483 alarm(G.markInterval);
488 /* Don't inline: prevent struct sockaddr_un to take up space on stack
490 static NOINLINE int create_socket(void)
492 struct sockaddr_un sunx;
496 memset(&sunx, 0, sizeof(sunx));
497 sunx.sun_family = AF_UNIX;
499 /* Unlink old /dev/log or object it points to. */
500 /* (if it exists, bind will fail) */
501 strcpy(sunx.sun_path, "/dev/log");
502 dev_log_name = xmalloc_follow_symlinks("/dev/log");
504 safe_strncpy(sunx.sun_path, dev_log_name, sizeof(sunx.sun_path));
507 unlink(sunx.sun_path);
509 sock_fd = xsocket(AF_UNIX, SOCK_DGRAM, 0);
510 xbind(sock_fd, (struct sockaddr *) &sunx, sizeof(sunx));
511 chmod("/dev/log", 0666);
516 #if ENABLE_FEATURE_REMOTE_LOG
517 static int try_to_resolve_remote(void)
520 unsigned now = monotonic_sec();
522 /* Don't resolve name too often - DNS timeouts can be big */
523 if ((now - G.last_dns_resolve) < DNS_WAIT_SEC)
525 G.last_dns_resolve = now;
526 G.remoteAddr = host2sockaddr(G.remoteAddrStr, 514);
530 return socket(G.remoteAddr->sa.sa_family, SOCK_DGRAM, 0);
534 static void do_syslogd(void) ATTRIBUTE_NORETURN;
535 static void do_syslogd(void)
539 /* Set up signal handlers */
540 signal(SIGINT, quit_signal);
541 signal(SIGTERM, quit_signal);
542 signal(SIGQUIT, quit_signal);
543 signal(SIGHUP, SIG_IGN);
544 /* signal(SIGCHLD, SIG_IGN); - why? */
546 signal(SIGALRM, do_mark);
547 alarm(G.markInterval);
549 sock_fd = create_socket();
551 if (ENABLE_FEATURE_IPC_SYSLOG && (option_mask32 & OPT_circularlog)) {
555 timestamp_and_log_internal("syslogd started: BusyBox v" BB_VER);
560 sz = safe_read(sock_fd, G.recvbuf, MAX_READ - 1);
562 bb_perror_msg_and_die("read from /dev/log");
565 /* Drop trailing NULs (typically there is one NUL) */
569 /* man 3 syslog says: "A trailing newline is added when needed".
570 * However, neither glibc nor uclibc do this:
571 * syslog(prio, "test") sends "test\0" to /dev/log,
572 * syslog(prio, "test\n") sends "test\n\0",
573 * IOW: newline is passed verbatim!
574 * I take it to mean that it's syslogd's job
575 * to make those look identical in the log files */
576 if (G.recvbuf[sz-1] && G.recvbuf[sz-1] != '\n')
580 /* Maybe we need to add '\n' here, not later?
581 * It looks like stock syslogd does send '\n' over network,
582 * but we do not (see sendto below) */
583 G.recvbuf[sz] = '\0'; /* make sure it *is* NUL terminated */
585 /* TODO: maybe suppress duplicates? */
586 #if ENABLE_FEATURE_REMOTE_LOG
587 /* We are not modifying log messages in any way before send */
588 /* Remote site cannot trust _us_ anyway and need to do validation again */
589 if (G.remoteAddrStr) {
590 if (-1 == G.remoteFD) {
591 G.remoteFD = try_to_resolve_remote();
592 if (-1 == G.remoteFD)
595 /* send message to remote logger, ignore possible error */
596 sendto(G.remoteFD, G.recvbuf, sz, MSG_DONTWAIT,
597 &G.remoteAddr->sa, G.remoteAddr->len);
601 if (!ENABLE_FEATURE_REMOTE_LOG || (option_mask32 & OPT_locallog))
602 split_escape_and_log(G.recvbuf, sz);
606 int syslogd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
607 int syslogd_main(int argc, char **argv)
613 #if ENABLE_FEATURE_REMOTE_LOG
614 G.last_dns_resolve = monotonic_sec() - DNS_WAIT_SEC - 1;
617 /* do normal option parsing */
618 opt_complementary = "=0"; /* no non-option params */
619 getopt32(argv, OPTION_STR, OPTION_PARAM);
621 if (option_mask32 & OPT_mark) // -m
622 G.markInterval = xatou_range(opt_m, 0, INT_MAX/60) * 60;
624 //if (option_mask32 & OPT_nofork) // -n
625 //if (option_mask32 & OPT_outfile) // -O
626 if (option_mask32 & OPT_loglevel) // -l
627 G.logLevel = xatou_range(opt_l, 1, 8);
628 //if (option_mask32 & OPT_small) // -S
629 #if ENABLE_FEATURE_ROTATE_LOGFILE
630 if (option_mask32 & OPT_filesize) // -s
631 G.logFileSize = xatou_range(opt_s, 0, INT_MAX/1024) * 1024;
632 if (option_mask32 & OPT_rotatecnt) // -b
633 G.logFileRotate = xatou_range(opt_b, 0, 99);
635 #if ENABLE_FEATURE_IPC_SYSLOG
637 G.shm_size = xatoul_range(opt_C, 4, INT_MAX/1024) * 1024;
640 /* If they have not specified remote logging, then log locally */
641 if (ENABLE_FEATURE_REMOTE_LOG && !(option_mask32 & OPT_remotelog))
642 option_mask32 |= OPT_locallog;
644 /* Store away localhost's name before the fork */
645 gethostname(G.localHostName, sizeof(G.localHostName));
646 p = strchr(G.localHostName, '.');
651 if (!(option_mask32 & OPT_nofork)) {
652 bb_daemonize_or_rexec(DAEMON_CHDIR_ROOT, argv);
655 write_pidfile("/var/run/syslogd.pid");
657 /* return EXIT_SUCCESS; */