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) */
48 DNS_WAIT_SEC = 2 * 60,
51 /* Semaphore operation structures */
53 int32_t size; /* size of data - 1 */
54 int32_t tail; /* end of message list */
55 char data[1]; /* data/messages */
58 /* Allows us to have smaller initializer. Ugly. */
60 const char *logFilePath; \
62 /* interval between marks in seconds */ \
63 /*int markInterval;*/ \
64 /* level of messages to be logged */ \
66 USE_FEATURE_ROTATE_LOGFILE( \
67 /* max size of file before rotation */ \
68 unsigned logFileSize; \
69 /* number of rotated message files */ \
70 unsigned logFileRotate; \
71 unsigned curFileSize; \
74 USE_FEATURE_REMOTE_LOG( \
75 /* udp socket for remote logging */ \
77 len_and_sockaddr* remoteAddr; \
79 USE_FEATURE_IPC_SYSLOG( \
80 int shmid; /* ipc shared memory id */ \
81 int s_semid; /* ipc semaphore id */ \
83 struct sembuf SMwup[1]; \
84 struct sembuf SMwdn[3]; \
94 #if ENABLE_FEATURE_REMOTE_LOG
95 unsigned last_dns_resolve;
99 #if ENABLE_FEATURE_IPC_SYSLOG
100 struct shbuf_ds *shbuf;
102 time_t last_log_time;
103 /* localhost's name. We print only first 64 chars */
106 /* We recv into recvbuf... */
107 char recvbuf[MAX_READ * (1 + ENABLE_FEATURE_SYSLOGD_DUP)];
108 /* ...then copy to parsebuf, escaping control chars */
109 /* (can grow x2 max) */
110 char parsebuf[MAX_READ*2];
111 /* ...then sprintf into printbuf, adding timestamp (15 chars),
112 * host (64), fac.prio (20) to the message */
113 /* (growth by: 15 + 64 + 20 + delims = ~110) */
114 char printbuf[MAX_READ*2 + 128];
117 static const struct init_globals init_data = {
118 .logFilePath = "/var/log/messages",
121 .markInterval = 20 * 60,
124 #if ENABLE_FEATURE_ROTATE_LOGFILE
125 .logFileSize = 200 * 1024,
128 #if ENABLE_FEATURE_REMOTE_LOG
131 #if ENABLE_FEATURE_IPC_SYSLOG
134 .shm_size = ((CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE)*1024), // default shm size
135 .SMwup = { {1, -1, IPC_NOWAIT} },
136 .SMwdn = { {0, 0}, {1, 0}, {1, +1} },
140 #define G (*ptr_to_globals)
141 #define INIT_G() do { \
142 SET_PTR_TO_GLOBALS(memcpy(xzalloc(sizeof(G)), &init_data, sizeof(init_data))); \
148 OPTBIT_mark = 0, // -m
150 OPTBIT_outfile, // -O
151 OPTBIT_loglevel, // -l
153 USE_FEATURE_ROTATE_LOGFILE(OPTBIT_filesize ,) // -s
154 USE_FEATURE_ROTATE_LOGFILE(OPTBIT_rotatecnt ,) // -b
155 USE_FEATURE_REMOTE_LOG( OPTBIT_remote ,) // -R
156 USE_FEATURE_REMOTE_LOG( OPTBIT_locallog ,) // -L
157 USE_FEATURE_IPC_SYSLOG( OPTBIT_circularlog,) // -C
158 USE_FEATURE_SYSLOGD_DUP( OPTBIT_dup ,) // -D
160 OPT_mark = 1 << OPTBIT_mark ,
161 OPT_nofork = 1 << OPTBIT_nofork ,
162 OPT_outfile = 1 << OPTBIT_outfile ,
163 OPT_loglevel = 1 << OPTBIT_loglevel,
164 OPT_small = 1 << OPTBIT_small ,
165 OPT_filesize = USE_FEATURE_ROTATE_LOGFILE((1 << OPTBIT_filesize )) + 0,
166 OPT_rotatecnt = USE_FEATURE_ROTATE_LOGFILE((1 << OPTBIT_rotatecnt )) + 0,
167 OPT_remotelog = USE_FEATURE_REMOTE_LOG( (1 << OPTBIT_remote )) + 0,
168 OPT_locallog = USE_FEATURE_REMOTE_LOG( (1 << OPTBIT_locallog )) + 0,
169 OPT_circularlog = USE_FEATURE_IPC_SYSLOG( (1 << OPTBIT_circularlog)) + 0,
170 OPT_dup = USE_FEATURE_SYSLOGD_DUP( (1 << OPTBIT_dup )) + 0,
172 #define OPTION_STR "m:nO:l:S" \
173 USE_FEATURE_ROTATE_LOGFILE("s:" ) \
174 USE_FEATURE_ROTATE_LOGFILE("b:" ) \
175 USE_FEATURE_REMOTE_LOG( "R:" ) \
176 USE_FEATURE_REMOTE_LOG( "L" ) \
177 USE_FEATURE_IPC_SYSLOG( "C::") \
178 USE_FEATURE_SYSLOGD_DUP( "D" )
179 #define OPTION_DECL *opt_m, *opt_l \
180 USE_FEATURE_ROTATE_LOGFILE(,*opt_s) \
181 USE_FEATURE_ROTATE_LOGFILE(,*opt_b) \
182 USE_FEATURE_IPC_SYSLOG( ,*opt_C = NULL)
183 #define OPTION_PARAM &opt_m, &G.logFilePath, &opt_l \
184 USE_FEATURE_ROTATE_LOGFILE(,&opt_s) \
185 USE_FEATURE_ROTATE_LOGFILE(,&opt_b) \
186 USE_FEATURE_REMOTE_LOG( ,&G.remoteAddrStr) \
187 USE_FEATURE_IPC_SYSLOG( ,&opt_C)
190 /* circular buffer variables/structures */
191 #if ENABLE_FEATURE_IPC_SYSLOG
193 #if CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE < 4
194 #error Sorry, you must set the syslogd buffer size to at least 4KB.
195 #error Please check CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE
198 /* our shared key (syslogd.c and logread.c must be in sync) */
199 enum { KEY_ID = 0x414e4547 }; /* "GENA" */
201 static void ipcsyslog_cleanup(void)
207 shmctl(G.shmid, IPC_RMID, NULL);
209 if (G.s_semid != -1) {
210 semctl(G.s_semid, 0, IPC_RMID, 0);
214 static void ipcsyslog_init(void)
217 printf("shmget(%x, %d,...)\n", (int)KEY_ID, G.shm_size);
219 G.shmid = shmget(KEY_ID, G.shm_size, IPC_CREAT | 0644);
221 bb_perror_msg_and_die("shmget");
224 G.shbuf = shmat(G.shmid, NULL, 0);
225 if (G.shbuf == (void*) -1L) { /* shmat has bizarre error return */
226 bb_perror_msg_and_die("shmat");
229 memset(G.shbuf, 0, G.shm_size);
230 G.shbuf->size = G.shm_size - offsetof(struct shbuf_ds, data) - 1;
231 /*G.shbuf->tail = 0;*/
233 // we'll trust the OS to set initial semval to 0 (let's hope)
234 G.s_semid = semget(KEY_ID, 2, IPC_CREAT | IPC_EXCL | 1023);
235 if (G.s_semid == -1) {
236 if (errno == EEXIST) {
237 G.s_semid = semget(KEY_ID, 2, 0);
241 bb_perror_msg_and_die("semget");
245 /* Write message to shared mem buffer */
246 static void log_to_shmem(const char *msg, int len)
248 int old_tail, new_tail;
250 if (semop(G.s_semid, G.SMwdn, 3) == -1) {
251 bb_perror_msg_and_die("SMwdn");
254 /* Circular Buffer Algorithm:
255 * --------------------------
256 * tail == position where to store next syslog message.
257 * tail's max value is (shbuf->size - 1)
258 * Last byte of buffer is never used and remains NUL.
260 len++; /* length with NUL included */
262 old_tail = G.shbuf->tail;
263 new_tail = old_tail + len;
264 if (new_tail < G.shbuf->size) {
265 /* store message, set new tail */
266 memcpy(G.shbuf->data + old_tail, msg, len);
267 G.shbuf->tail = new_tail;
269 /* k == available buffer space ahead of old tail */
270 int k = G.shbuf->size - old_tail;
271 /* copy what fits to the end of buffer, and repeat */
272 memcpy(G.shbuf->data + old_tail, msg, k);
278 if (semop(G.s_semid, G.SMwup, 1) == -1) {
279 bb_perror_msg_and_die("SMwup");
282 printf("tail:%d\n", G.shbuf->tail);
285 void ipcsyslog_cleanup(void);
286 void ipcsyslog_init(void);
287 void log_to_shmem(const char *msg);
288 #endif /* FEATURE_IPC_SYSLOG */
291 /* Print a message to the log file. */
292 static void log_locally(time_t now, char *msg)
295 int len = strlen(msg);
297 #if ENABLE_FEATURE_IPC_SYSLOG
298 if ((option_mask32 & OPT_circularlog) && G.shbuf) {
299 log_to_shmem(msg, len);
306 if (G.last_log_time != now) {
307 G.last_log_time = now; /* reopen log file every second */
313 G.logFD = device_open(G.logFilePath, O_WRONLY | O_CREAT
314 | O_NOCTTY | O_APPEND | O_NONBLOCK);
316 /* cannot open logfile? - print to /dev/console then */
317 int fd = device_open(DEV_CONSOLE, O_WRONLY | O_NOCTTY | O_NONBLOCK);
319 fd = 2; /* then stderr, dammit */
320 full_write(fd, msg, len);
325 #if ENABLE_FEATURE_ROTATE_LOGFILE
328 G.isRegular = (fstat(G.logFD, &statf) == 0 && S_ISREG(statf.st_mode));
329 /* bug (mostly harmless): can wrap around if file > 4gb */
330 G.curFileSize = statf.st_size;
335 fl.l_whence = SEEK_SET;
339 fcntl(G.logFD, F_SETLKW, &fl);
341 #if ENABLE_FEATURE_ROTATE_LOGFILE
342 if (G.logFileSize && G.isRegular && G.curFileSize > G.logFileSize) {
343 if (G.logFileRotate) { /* always 0..99 */
344 int i = strlen(G.logFilePath) + 3 + 1;
347 i = G.logFileRotate - 1;
348 /* rename: f.8 -> f.9; f.7 -> f.8; ... */
350 sprintf(newFile, "%s.%d", G.logFilePath, i);
352 sprintf(oldFile, "%s.%d", G.logFilePath, --i);
353 /* ignore errors - file might be missing */
354 rename(oldFile, newFile);
356 /* newFile == "f.0" now */
357 rename(G.logFilePath, newFile);
359 fcntl(G.logFD, F_SETLKW, &fl);
363 ftruncate(G.logFD, 0);
367 full_write(G.logFD, msg, len);
369 fcntl(G.logFD, F_SETLKW, &fl);
372 static void parse_fac_prio_20(int pri, char *res20)
374 const CODE *c_pri, *c_fac;
377 c_fac = facilitynames;
378 while (c_fac->c_name) {
379 if (c_fac->c_val != (LOG_FAC(pri) << 3)) {
383 /* facility is found, look for prio */
384 c_pri = prioritynames;
385 while (c_pri->c_name) {
386 if (c_pri->c_val != LOG_PRI(pri)) {
390 snprintf(res20, 20, "%s.%s",
391 c_fac->c_name, c_pri->c_name);
394 /* prio not found, bail out */
397 snprintf(res20, 20, "<%d>", pri);
401 /* len parameter is used only for "is there a timestamp?" check.
402 * NB: some callers cheat and supply len==0 when they know
403 * that there is no timestamp, short-circuiting the test. */
404 static void timestamp_and_log(int pri, char *msg, int len)
409 if (len < 16 || msg[3] != ' ' || msg[6] != ' '
410 || msg[9] != ':' || msg[12] != ':' || msg[15] != ' '
413 timestamp = ctime(&now) + 4; /* skip day of week */
419 timestamp[15] = '\0';
421 if (option_mask32 & OPT_small)
422 sprintf(G.printbuf, "%s %s\n", timestamp, msg);
425 parse_fac_prio_20(pri, res);
426 sprintf(G.printbuf, "%s %.64s %s %s\n", timestamp, G.hostname, res, msg);
429 /* Log message locally (to file or shared mem) */
430 log_locally(now, G.printbuf);
433 static void timestamp_and_log_internal(const char *msg)
435 if (ENABLE_FEATURE_REMOTE_LOG && !(option_mask32 & OPT_locallog))
437 timestamp_and_log(LOG_SYSLOG | LOG_INFO, (char*)msg, 0);
440 /* tmpbuf[len] is a NUL byte (set by caller), but there can be other,
441 * embedded NULs. Split messages on each of these NULs, parse prio,
442 * escape control chars and log each locally. */
443 static void split_escape_and_log(char *tmpbuf, int len)
450 char *q = G.parsebuf;
451 int pri = (LOG_USER | LOG_NOTICE);
454 /* Parse the magic priority number */
455 pri = bb_strtou(p + 1, &p, 10);
458 if (pri & ~(LOG_FACMASK | LOG_PRIMASK))
459 pri = (LOG_USER | LOG_NOTICE);
465 if (!(c & ~0x1f) && c != '\t') {
467 c += '@'; /* ^@, ^A, ^B... */
474 if (LOG_PRI(pri) < G.logLevel)
475 timestamp_and_log(pri, G.parsebuf, q - G.parsebuf);
479 static void quit_signal(int sig)
481 timestamp_and_log_internal("syslogd exiting");
482 puts("syslogd exiting");
483 if (ENABLE_FEATURE_IPC_SYSLOG)
485 kill_myself_with_sig(sig);
489 static void do_mark(int sig)
491 if (G.markInterval) {
492 timestamp_and_log_internal("-- MARK --");
493 alarm(G.markInterval);
498 /* Don't inline: prevent struct sockaddr_un to take up space on stack
500 static NOINLINE int create_socket(void)
502 struct sockaddr_un sunx;
506 memset(&sunx, 0, sizeof(sunx));
507 sunx.sun_family = AF_UNIX;
509 /* Unlink old /dev/log or object it points to. */
510 /* (if it exists, bind will fail) */
511 strcpy(sunx.sun_path, "/dev/log");
512 dev_log_name = xmalloc_follow_symlinks("/dev/log");
514 safe_strncpy(sunx.sun_path, dev_log_name, sizeof(sunx.sun_path));
517 unlink(sunx.sun_path);
519 sock_fd = xsocket(AF_UNIX, SOCK_DGRAM, 0);
520 xbind(sock_fd, (struct sockaddr *) &sunx, sizeof(sunx));
521 chmod("/dev/log", 0666);
526 #if ENABLE_FEATURE_REMOTE_LOG
527 static int try_to_resolve_remote(void)
530 unsigned now = monotonic_sec();
532 /* Don't resolve name too often - DNS timeouts can be big */
533 if ((now - G.last_dns_resolve) < DNS_WAIT_SEC)
535 G.last_dns_resolve = now;
536 G.remoteAddr = host2sockaddr(G.remoteAddrStr, 514);
540 return socket(G.remoteAddr->u.sa.sa_family, SOCK_DGRAM, 0);
544 static void do_syslogd(void) NORETURN;
545 static void do_syslogd(void)
548 #if ENABLE_FEATURE_SYSLOGD_DUP
551 char *recvbuf = G.recvbuf;
553 #define recvbuf (G.recvbuf)
556 /* Set up signal handlers */
562 signal(SIGHUP, SIG_IGN);
563 /* signal(SIGCHLD, SIG_IGN); - why? */
565 signal(SIGALRM, do_mark);
566 alarm(G.markInterval);
568 sock_fd = create_socket();
570 if (ENABLE_FEATURE_IPC_SYSLOG && (option_mask32 & OPT_circularlog)) {
574 timestamp_and_log_internal("syslogd started: BusyBox v" BB_VER);
579 #if ENABLE_FEATURE_SYSLOGD_DUP
581 if (recvbuf == G.recvbuf)
582 recvbuf = G.recvbuf + MAX_READ;
587 sz = safe_read(sock_fd, recvbuf, MAX_READ - 1);
589 bb_perror_msg_and_die("read from /dev/log");
591 /* Drop trailing '\n' and NULs (typically there is one NUL) */
595 /* man 3 syslog says: "A trailing newline is added when needed".
596 * However, neither glibc nor uclibc do this:
597 * syslog(prio, "test") sends "test\0" to /dev/log,
598 * syslog(prio, "test\n") sends "test\n\0".
599 * IOW: newline is passed verbatim!
600 * I take it to mean that it's syslogd's job
601 * to make those look identical in the log files. */
602 if (recvbuf[sz-1] != '\0' && recvbuf[sz-1] != '\n')
606 #if ENABLE_FEATURE_SYSLOGD_DUP
607 if ((option_mask32 & OPT_dup) && (sz == last_sz))
608 if (memcmp(last_buf, recvbuf, sz) == 0)
612 #if ENABLE_FEATURE_REMOTE_LOG
613 /* We are not modifying log messages in any way before send */
614 /* Remote site cannot trust _us_ anyway and need to do validation again */
615 if (G.remoteAddrStr) {
616 if (-1 == G.remoteFD) {
617 G.remoteFD = try_to_resolve_remote();
618 if (-1 == G.remoteFD)
621 /* Stock syslogd sends it '\n'-terminated
622 * over network, mimic that */
624 /* send message to remote logger, ignore possible error */
625 /* TODO: on some errors, close and set G.remoteFD to -1
626 * so that DNS resolution and connect is retried? */
627 sendto(G.remoteFD, recvbuf, sz+1, MSG_DONTWAIT,
628 &G.remoteAddr->u.sa, G.remoteAddr->len);
632 if (!ENABLE_FEATURE_REMOTE_LOG || (option_mask32 & OPT_locallog)) {
633 recvbuf[sz] = '\0'; /* ensure it *is* NUL terminated */
634 split_escape_and_log(recvbuf, sz);
640 int syslogd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
641 int syslogd_main(int argc UNUSED_PARAM, char **argv)
646 #if ENABLE_FEATURE_REMOTE_LOG
647 G.last_dns_resolve = monotonic_sec() - DNS_WAIT_SEC - 1;
650 /* do normal option parsing */
651 opt_complementary = "=0"; /* no non-option params */
652 getopt32(argv, OPTION_STR, OPTION_PARAM);
654 if (option_mask32 & OPT_mark) // -m
655 G.markInterval = xatou_range(opt_m, 0, INT_MAX/60) * 60;
657 //if (option_mask32 & OPT_nofork) // -n
658 //if (option_mask32 & OPT_outfile) // -O
659 if (option_mask32 & OPT_loglevel) // -l
660 G.logLevel = xatou_range(opt_l, 1, 8);
661 //if (option_mask32 & OPT_small) // -S
662 #if ENABLE_FEATURE_ROTATE_LOGFILE
663 if (option_mask32 & OPT_filesize) // -s
664 G.logFileSize = xatou_range(opt_s, 0, INT_MAX/1024) * 1024;
665 if (option_mask32 & OPT_rotatecnt) // -b
666 G.logFileRotate = xatou_range(opt_b, 0, 99);
668 #if ENABLE_FEATURE_IPC_SYSLOG
670 G.shm_size = xatoul_range(opt_C, 4, INT_MAX/1024) * 1024;
673 /* If they have not specified remote logging, then log locally */
674 if (ENABLE_FEATURE_REMOTE_LOG && !(option_mask32 & OPT_remotelog))
675 option_mask32 |= OPT_locallog;
677 /* Store away localhost's name before the fork */
678 G.hostname = safe_gethostname();
679 *strchrnul(G.hostname, '.') = '\0';
681 if (!(option_mask32 & OPT_nofork)) {
682 bb_daemonize_or_rexec(DAEMON_CHDIR_ROOT, argv);
685 write_pidfile("/var/run/syslogd.pid");
687 /* return EXIT_SUCCESS; */
690 /* Clean up. Needed because we are included from syslogd_and_logger.c */