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) */
45 enum { MAX_READ = 256 };
47 /* Semaphore operation structures */
49 int32_t size; /* size of data written */
50 int32_t head; /* start of message list */
51 int32_t tail; /* end of message list */
52 char data[1]; /* data/messages */
55 /* Allows us to have smaller initializer. Ugly. */
57 const char *logFilePath; \
59 /* interval between marks in seconds */ \
60 /*int markInterval;*/ \
61 /* level of messages to be logged */ \
63 USE_FEATURE_ROTATE_LOGFILE( \
64 /* max size of file before rotation */ \
65 unsigned logFileSize; \
66 /* number of rotated message files */ \
67 unsigned logFileRotate; \
68 unsigned curFileSize; \
71 USE_FEATURE_REMOTE_LOG( \
72 /* udp socket for remote logging */ \
74 len_and_sockaddr* remoteAddr; \
76 USE_FEATURE_IPC_SYSLOG( \
77 int shmid; /* ipc shared memory id */ \
78 int s_semid; /* ipc semaphore id */ \
80 struct sembuf SMwup[1]; \
81 struct sembuf SMwdn[3]; \
90 #if ENABLE_FEATURE_IPC_SYSLOG
91 struct shbuf_ds *shbuf;
94 /* localhost's name */
95 char localHostName[64];
97 /* We recv into recvbuf... */
98 char recvbuf[MAX_READ];
99 /* ...then copy to parsebuf, escaping control chars */
100 /* (can grow x2 max) */
101 char parsebuf[MAX_READ*2];
102 /* ...then sprintf into printbuf, adding timestamp (15 chars),
103 * host (64), fac.prio (20) to the message */
104 /* (growth by: 15 + 64 + 20 + delims = ~110) */
105 char printbuf[MAX_READ*2 + 128];
108 static const struct init_globals init_data = {
109 .logFilePath = "/var/log/messages",
112 .markInterval = 20 * 60,
115 #if ENABLE_FEATURE_ROTATE_LOGFILE
116 .logFileSize = 200 * 1024,
119 #if ENABLE_FEATURE_REMOTE_LOG
122 #if ENABLE_FEATURE_IPC_SYSLOG
125 .shm_size = ((CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE)*1024), // default shm size
126 .SMwup = { {1, -1, IPC_NOWAIT} },
127 .SMwdn = { {0, 0}, {1, 0}, {1, +1} },
131 #define G (*ptr_to_globals)
136 OPTBIT_mark = 0, // -m
138 OPTBIT_outfile, // -O
139 OPTBIT_loglevel, // -l
141 USE_FEATURE_ROTATE_LOGFILE(OPTBIT_filesize ,) // -s
142 USE_FEATURE_ROTATE_LOGFILE(OPTBIT_rotatecnt ,) // -b
143 USE_FEATURE_REMOTE_LOG( OPTBIT_remote ,) // -R
144 USE_FEATURE_REMOTE_LOG( OPTBIT_localtoo ,) // -L
145 USE_FEATURE_IPC_SYSLOG( OPTBIT_circularlog,) // -C
147 OPT_mark = 1 << OPTBIT_mark ,
148 OPT_nofork = 1 << OPTBIT_nofork ,
149 OPT_outfile = 1 << OPTBIT_outfile ,
150 OPT_loglevel = 1 << OPTBIT_loglevel,
151 OPT_small = 1 << OPTBIT_small ,
152 OPT_filesize = USE_FEATURE_ROTATE_LOGFILE((1 << OPTBIT_filesize )) + 0,
153 OPT_rotatecnt = USE_FEATURE_ROTATE_LOGFILE((1 << OPTBIT_rotatecnt )) + 0,
154 OPT_remotelog = USE_FEATURE_REMOTE_LOG( (1 << OPTBIT_remote )) + 0,
155 OPT_locallog = USE_FEATURE_REMOTE_LOG( (1 << OPTBIT_localtoo )) + 0,
156 OPT_circularlog = USE_FEATURE_IPC_SYSLOG( (1 << OPTBIT_circularlog)) + 0,
158 #define OPTION_STR "m:nO:l:S" \
159 USE_FEATURE_ROTATE_LOGFILE("s:" ) \
160 USE_FEATURE_ROTATE_LOGFILE("b:" ) \
161 USE_FEATURE_REMOTE_LOG( "R:" ) \
162 USE_FEATURE_REMOTE_LOG( "L" ) \
163 USE_FEATURE_IPC_SYSLOG( "C::")
164 #define OPTION_DECL *opt_m, *opt_l \
165 USE_FEATURE_ROTATE_LOGFILE(,*opt_s) \
166 USE_FEATURE_ROTATE_LOGFILE(,*opt_b) \
167 USE_FEATURE_REMOTE_LOG( ,*opt_R) \
168 USE_FEATURE_IPC_SYSLOG( ,*opt_C = NULL)
169 #define OPTION_PARAM &opt_m, &G.logFilePath, &opt_l \
170 USE_FEATURE_ROTATE_LOGFILE(,&opt_s) \
171 USE_FEATURE_ROTATE_LOGFILE(,&opt_b) \
172 USE_FEATURE_REMOTE_LOG( ,&opt_R) \
173 USE_FEATURE_IPC_SYSLOG( ,&opt_C)
176 /* circular buffer variables/structures */
177 #if ENABLE_FEATURE_IPC_SYSLOG
179 #if CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE < 4
180 #error Sorry, you must set the syslogd buffer size to at least 4KB.
181 #error Please check CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE
185 #define KEY_ID ((long)0x414e4547) /* "GENA" */
187 static void ipcsyslog_cleanup(void)
193 shmctl(G.shmid, IPC_RMID, NULL);
195 if (G.s_semid != -1) {
196 semctl(G.s_semid, 0, IPC_RMID, 0);
200 static void ipcsyslog_init(void)
203 printf("shmget(%lx, %d,...)\n", KEY_ID, G.shm_size);
205 G.shmid = shmget(KEY_ID, G.shm_size, IPC_CREAT | 1023);
207 bb_perror_msg_and_die("shmget");
210 G.shbuf = shmat(G.shmid, NULL, 0);
212 bb_perror_msg_and_die("shmat");
215 G.shbuf->size = G.shm_size - offsetof(struct shbuf_ds, data);
216 G.shbuf->head = G.shbuf->tail = 0;
218 // we'll trust the OS to set initial semval to 0 (let's hope)
219 G.s_semid = semget(KEY_ID, 2, IPC_CREAT | IPC_EXCL | 1023);
220 if (G.s_semid == -1) {
221 if (errno == EEXIST) {
222 G.s_semid = semget(KEY_ID, 2, 0);
226 bb_perror_msg_and_die("semget");
230 /* Write message to shared mem buffer */
231 static void log_to_shmem(const char *msg, int len)
233 int old_tail, new_tail;
236 if (semop(G.s_semid, G.SMwdn, 3) == -1) {
237 bb_perror_msg_and_die("SMwdn");
240 /* Circular Buffer Algorithm:
241 * --------------------------
242 * tail == position where to store next syslog message.
243 * head == position of next message to retrieve ("print").
244 * if head == tail, there is no "unprinted" messages left.
245 * head is typically advanced by separate "reader" program,
246 * but if there isn't one, we have to do it ourself.
247 * messages are NUL-separated.
249 len++; /* length with NUL included */
251 old_tail = G.shbuf->tail;
252 new_tail = old_tail + len;
253 if (new_tail < G.shbuf->size) {
254 /* No need to move head if shbuf->head <= old_tail,
256 if (old_tail < G.shbuf->head && G.shbuf->head <= new_tail) {
257 /* ...need to move head forward */
258 c = memchr(G.shbuf->data + new_tail, '\0',
259 G.shbuf->size - new_tail);
260 if (!c) /* no NUL ahead of us, wrap around */
261 c = memchr(G.shbuf->data, '\0', old_tail);
262 if (!c) { /* still nothing? point to this msg... */
263 G.shbuf->head = old_tail;
265 /* convert pointer to offset + skip NUL */
266 G.shbuf->head = c - G.shbuf->data + 1;
269 /* store message, set new tail */
270 memcpy(G.shbuf->data + old_tail, msg, len);
271 G.shbuf->tail = new_tail;
273 /* we need to break up the message and wrap it around */
274 /* k == available buffer space ahead of old tail */
275 int k = G.shbuf->size - old_tail - 1;
276 if (G.shbuf->head > old_tail) {
277 /* we are going to overwrite head, need to
278 * move it out of the way */
279 c = memchr(G.shbuf->data, '\0', old_tail);
280 if (!c) { /* nothing? point to this msg... */
281 G.shbuf->head = old_tail;
282 } else { /* convert pointer to offset + skip NUL */
283 G.shbuf->head = c - G.shbuf->data + 1;
286 /* copy what fits to the end of buffer, and repeat */
287 memcpy(G.shbuf->data + old_tail, msg, k);
293 if (semop(G.s_semid, G.SMwup, 1) == -1) {
294 bb_perror_msg_and_die("SMwup");
297 printf("head:%d tail:%d\n", G.shbuf->head, G.shbuf->tail);
300 void ipcsyslog_cleanup(void);
301 void ipcsyslog_init(void);
302 void log_to_shmem(const char *msg);
303 #endif /* FEATURE_IPC_SYSLOG */
306 /* Print a message to the log file. */
307 static void log_locally(char *msg)
310 int len = strlen(msg);
312 #if ENABLE_FEATURE_IPC_SYSLOG
313 if ((option_mask32 & OPT_circularlog) && G.shbuf) {
314 log_to_shmem(msg, len);
321 if (G.last_log_time != cur) {
322 G.last_log_time = cur; /* reopen log file every second */
328 G.logFD = device_open(G.logFilePath, O_WRONLY | O_CREAT
329 | O_NOCTTY | O_APPEND | O_NONBLOCK);
331 /* cannot open logfile? - print to /dev/console then */
332 int fd = device_open(_PATH_CONSOLE, O_WRONLY | O_NOCTTY | O_NONBLOCK);
334 fd = 2; /* then stderr, dammit */
335 full_write(fd, msg, len);
340 #if ENABLE_FEATURE_ROTATE_LOGFILE
344 G.isRegular = (fstat(G.logFD, &statf) == 0 && (statf.st_mode & S_IFREG));
345 /* bug (mostly harmless): can wrap around if file > 4gb */
346 G.curFileSize = statf.st_size;
351 fl.l_whence = SEEK_SET;
355 fcntl(G.logFD, F_SETLKW, &fl);
357 #if ENABLE_FEATURE_ROTATE_LOGFILE
358 if (G.logFileSize && G.isRegular && G.curFileSize > G.logFileSize) {
359 if (G.logFileRotate) { /* always 0..99 */
360 int i = strlen(G.logFilePath) + 3 + 1;
363 i = G.logFileRotate - 1;
364 /* rename: f.8 -> f.9; f.7 -> f.8; ... */
366 sprintf(newFile, "%s.%d", G.logFilePath, i);
368 sprintf(oldFile, "%s.%d", G.logFilePath, --i);
369 rename(oldFile, newFile);
371 /* newFile == "f.0" now */
372 rename(G.logFilePath, newFile);
374 fcntl(G.logFD, F_SETLKW, &fl);
378 ftruncate(G.logFD, 0);
382 full_write(G.logFD, msg, len);
384 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)) {
397 /* facility is found, look for prio */
398 c_pri = prioritynames;
399 while (c_pri->c_name) {
400 if (c_pri->c_val != LOG_PRI(pri)) {
403 snprintf(res20, 20, "%s.%s",
404 c_fac->c_name, c_pri->c_name);
407 /* prio not found, bail out */
410 snprintf(res20, 20, "<%d>", pri);
414 /* len parameter is used only for "is there a timestamp?" check.
415 * NB: some callers cheat and supply 0 when they know
416 * that there is no timestamp, short-cutting the test. */
417 static void timestamp_and_log(int pri, char *msg, int len)
421 if (len < 16 || msg[3] != ' ' || msg[6] != ' '
422 || msg[9] != ':' || msg[12] != ':' || msg[15] != ' '
426 timestamp = ctime(&now) + 4;
431 timestamp[15] = '\0';
433 /* Log message locally (to file or shared mem) */
434 if (!ENABLE_FEATURE_REMOTE_LOG || (option_mask32 & OPT_locallog)) {
435 if (LOG_PRI(pri) < G.logLevel) {
436 if (option_mask32 & OPT_small)
437 sprintf(G.printbuf, "%s %s\n", timestamp, msg);
440 parse_fac_prio_20(pri, res);
441 sprintf(G.printbuf, "%s %s %s %s\n", timestamp, G.localHostName, res, msg);
443 log_locally(G.printbuf);
448 static void split_escape_and_log(char *tmpbuf, int len)
455 char *q = G.parsebuf;
456 int pri = (LOG_USER | LOG_NOTICE);
459 /* Parse the magic priority number */
460 pri = bb_strtou(p + 1, &p, 10);
462 if (pri & ~(LOG_FACMASK | LOG_PRIMASK)) {
463 pri = (LOG_USER | LOG_NOTICE);
472 c += '@'; /* ^@, ^A, ^B... */
478 timestamp_and_log(pri, G.parsebuf, q - G.parsebuf);
482 static void quit_signal(int sig)
484 timestamp_and_log(LOG_SYSLOG | LOG_INFO, (char*)"syslogd exiting", 0);
485 puts("syslogd exiting");
486 if (ENABLE_FEATURE_IPC_SYSLOG)
492 static void do_mark(int sig)
494 if (G.markInterval) {
495 timestamp_and_log(LOG_SYSLOG | LOG_INFO, (char*)"-- MARK --", 0);
496 alarm(G.markInterval);
501 static void do_syslogd(void) ATTRIBUTE_NORETURN;
502 static void do_syslogd(void)
504 struct sockaddr_un sunx;
509 /* Set up signal handlers */
510 signal(SIGINT, quit_signal);
511 signal(SIGTERM, quit_signal);
512 signal(SIGQUIT, quit_signal);
513 signal(SIGHUP, SIG_IGN);
514 signal(SIGCHLD, SIG_IGN);
516 signal(SIGCLD, SIG_IGN);
519 signal(SIGALRM, do_mark);
520 alarm(G.markInterval);
522 remove_pidfile("/var/run/syslogd.pid");
524 memset(&sunx, 0, sizeof(sunx));
525 sunx.sun_family = AF_UNIX;
526 strcpy(sunx.sun_path, "/dev/log");
528 /* Unlink old /dev/log or object it points to. */
529 /* (if it exists, bind will fail) */
530 logmode = LOGMODE_NONE;
531 dev_log_name = xmalloc_readlink_or_warn("/dev/log");
532 logmode = LOGMODE_STDIO;
534 int fd = xopen(".", O_NONBLOCK);
536 /* we do not check whether this is a link also */
537 unlink(dev_log_name);
540 safe_strncpy(sunx.sun_path, dev_log_name, sizeof(sunx.sun_path));
546 sock_fd = xsocket(AF_UNIX, SOCK_DGRAM, 0);
547 xbind(sock_fd, (struct sockaddr *) &sunx, sizeof(sunx));
549 if (chmod("/dev/log", 0666) < 0) {
550 bb_perror_msg_and_die("cannot set permission on /dev/log");
552 if (ENABLE_FEATURE_IPC_SYSLOG && (option_mask32 & OPT_circularlog)) {
556 timestamp_and_log(LOG_SYSLOG | LOG_INFO,
557 (char*)"syslogd started: BusyBox v" BB_VER, 0);
561 FD_SET(sock_fd, &fds);
563 if (select(sock_fd + 1, &fds, NULL, NULL, NULL) < 0) {
564 if (errno == EINTR) {
565 /* alarm may have happened */
568 bb_perror_msg_and_die("select");
571 if (FD_ISSET(sock_fd, &fds)) {
573 i = recv(sock_fd, G.recvbuf, MAX_READ - 1, 0);
575 bb_perror_msg_and_die("UNIX socket error");
576 /* TODO: maybe suppress duplicates? */
577 #if ENABLE_FEATURE_REMOTE_LOG
578 /* We are not modifying log messages in any way before send */
579 /* Remote site cannot trust _us_ anyway and need to do validation again */
581 if (-1 == G.remoteFD) {
582 G.remoteFD = socket(G.remoteAddr->sa.sa_family, SOCK_DGRAM, 0);
584 if (-1 != G.remoteFD) {
585 /* send message to remote logger, ignore possible error */
586 sendto(G.remoteFD, G.recvbuf, i, MSG_DONTWAIT,
587 &G.remoteAddr->sa, G.remoteAddr->len);
592 split_escape_and_log(G.recvbuf, i);
597 int syslogd_main(int argc, char **argv);
598 int syslogd_main(int argc, char **argv)
603 PTR_TO_GLOBALS = memcpy(xzalloc(sizeof(G)), &init_data, sizeof(init_data));
605 /* do normal option parsing */
606 opt_complementary = "=0"; /* no non-option params */
607 getopt32(argc, argv, OPTION_STR, OPTION_PARAM);
609 if (option_mask32 & OPT_mark) // -m
610 G.markInterval = xatou_range(opt_m, 0, INT_MAX/60) * 60;
612 //if (option_mask32 & OPT_nofork) // -n
613 //if (option_mask32 & OPT_outfile) // -O
614 if (option_mask32 & OPT_loglevel) // -l
615 G.logLevel = xatou_range(opt_l, 1, 8);
616 //if (option_mask32 & OPT_small) // -S
617 #if ENABLE_FEATURE_ROTATE_LOGFILE
618 if (option_mask32 & OPT_filesize) // -s
619 G.logFileSize = xatou_range(opt_s, 0, INT_MAX/1024) * 1024;
620 if (option_mask32 & OPT_rotatecnt) // -b
621 G.logFileRotate = xatou_range(opt_b, 0, 99);
623 #if ENABLE_FEATURE_REMOTE_LOG
624 if (option_mask32 & OPT_remotelog) { // -R
625 G.remoteAddr = xhost2sockaddr(opt_R, 514);
627 //if (option_mask32 & OPT_locallog) // -L
629 #if ENABLE_FEATURE_IPC_SYSLOG
631 G.shm_size = xatoul_range(opt_C, 4, INT_MAX/1024) * 1024;
634 /* If they have not specified remote logging, then log locally */
635 if (ENABLE_FEATURE_REMOTE_LOG && !(option_mask32 & OPT_remotelog))
636 option_mask32 |= OPT_locallog;
638 /* Store away localhost's name before the fork */
639 gethostname(G.localHostName, sizeof(G.localHostName));
640 p = strchr(G.localHostName, '.');
645 if (!(option_mask32 & OPT_nofork)) {
646 bb_daemonize_or_rexec(DAEMON_CHDIR_ROOT, argv);
649 write_pidfile("/var/run/syslogd.pid");
651 /* return EXIT_SUCCESS; */