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 some extra junk from syslog.h */
22 #include <sys/syslog.h>
27 /* Path for the file where all log messages are written */
28 static const char *logFilePath = "/var/log/messages";
29 static int logFD = -1;
31 /* This is not very useful, is bloat, and broken:
32 * can deadlock if alarmed to make MARK while writing to IPC buffer
33 * (semaphores are down but do_mark routine tries to down them again) */
35 /* interval between marks in seconds */
36 static int markInterval = 20 * 60;
39 /* level of messages to be locally logged */
40 static int logLevel = 8;
42 /* localhost's name */
43 static char localHostName[64];
45 #if ENABLE_FEATURE_ROTATE_LOGFILE
46 /* max size of message file before being rotated */
47 static unsigned logFileSize = 200 * 1024;
48 /* number of rotated message files */
49 static unsigned logFileRotate = 1;
50 static unsigned curFileSize;
51 static smallint isRegular;
54 #if ENABLE_FEATURE_REMOTE_LOG
55 #include <netinet/in.h>
56 /* udp socket for logging to remote host */
57 static int remoteFD = -1;
58 static len_and_sockaddr* remoteAddr;
61 /* We are using bb_common_bufsiz1 for buffering: */
62 enum { MAX_READ = (BUFSIZ/6) & ~0xf };
63 /* We recv into RECVBUF... (size: MAX_READ ~== BUFSIZ/6) */
64 #define RECVBUF bb_common_bufsiz1
65 /* ...then copy to PARSEBUF, escaping control chars */
66 /* (can grow x2 max ~== BUFSIZ/3) */
67 #define PARSEBUF (bb_common_bufsiz1 + MAX_READ)
68 /* ...then sprintf into PRINTBUF, adding timestamp (15 chars),
69 * host (64), fac.prio (20) to the message */
70 /* (growth by: 15 + 64 + 20 + delims = ~110) */
71 #define PRINTBUF (bb_common_bufsiz1 + 3*MAX_READ)
72 /* totals: BUFSIZ == BUFSIZ/6 + BUFSIZ/3 + (BUFSIZ/3+BUFSIZ/6)
73 * -- we have BUFSIZ/6 extra at the ent of PRINTBUF
74 * which covers needed ~110 extra bytes (and much more) */
79 OPTBIT_mark = 0, // -m
82 OPTBIT_loglevel, // -l
84 USE_FEATURE_ROTATE_LOGFILE(OPTBIT_filesize ,) // -s
85 USE_FEATURE_ROTATE_LOGFILE(OPTBIT_rotatecnt ,) // -b
86 USE_FEATURE_REMOTE_LOG( OPTBIT_remote ,) // -R
87 USE_FEATURE_REMOTE_LOG( OPTBIT_localtoo ,) // -L
88 USE_FEATURE_IPC_SYSLOG( OPTBIT_circularlog,) // -C
90 OPT_mark = 1 << OPTBIT_mark ,
91 OPT_nofork = 1 << OPTBIT_nofork ,
92 OPT_outfile = 1 << OPTBIT_outfile ,
93 OPT_loglevel = 1 << OPTBIT_loglevel,
94 OPT_small = 1 << OPTBIT_small ,
95 OPT_filesize = USE_FEATURE_ROTATE_LOGFILE((1 << OPTBIT_filesize )) + 0,
96 OPT_rotatecnt = USE_FEATURE_ROTATE_LOGFILE((1 << OPTBIT_rotatecnt )) + 0,
97 OPT_remotelog = USE_FEATURE_REMOTE_LOG( (1 << OPTBIT_remote )) + 0,
98 OPT_locallog = USE_FEATURE_REMOTE_LOG( (1 << OPTBIT_localtoo )) + 0,
99 OPT_circularlog = USE_FEATURE_IPC_SYSLOG( (1 << OPTBIT_circularlog)) + 0,
101 #define OPTION_STR "m:nO:l:S" \
102 USE_FEATURE_ROTATE_LOGFILE("s:" ) \
103 USE_FEATURE_ROTATE_LOGFILE("b:" ) \
104 USE_FEATURE_REMOTE_LOG( "R:" ) \
105 USE_FEATURE_REMOTE_LOG( "L" ) \
106 USE_FEATURE_IPC_SYSLOG( "C::")
107 #define OPTION_DECL *opt_m, *opt_l \
108 USE_FEATURE_ROTATE_LOGFILE(,*opt_s) \
109 USE_FEATURE_ROTATE_LOGFILE(,*opt_b) \
110 USE_FEATURE_REMOTE_LOG( ,*opt_R) \
111 USE_FEATURE_IPC_SYSLOG( ,*opt_C = NULL)
112 #define OPTION_PARAM &opt_m, &logFilePath, &opt_l \
113 USE_FEATURE_ROTATE_LOGFILE(,&opt_s) \
114 USE_FEATURE_ROTATE_LOGFILE(,&opt_b) \
115 USE_FEATURE_REMOTE_LOG( ,&opt_R) \
116 USE_FEATURE_IPC_SYSLOG( ,&opt_C)
119 /* circular buffer variables/structures */
120 #if ENABLE_FEATURE_IPC_SYSLOG
123 #if CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE < 4
124 #error Sorry, you must set the syslogd buffer size to at least 4KB.
125 #error Please check CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE
133 #define KEY_ID ((long)0x414e4547) /* "GENA" */
135 // Semaphore operation structures
136 static struct shbuf_ds {
137 int32_t size; // size of data written
138 int32_t head; // start of message list
139 int32_t tail; // end of message list
140 char data[1]; // data/messages
141 } *shbuf; // shared memory pointer
143 static int shmid = -1; // ipc shared memory id
144 static int s_semid = -1; // ipc semaphore id
145 static int shm_size = ((CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE)*1024); // default shm size
147 static void ipcsyslog_cleanup(void)
153 shmctl(shmid, IPC_RMID, NULL);
156 semctl(s_semid, 0, IPC_RMID, 0);
160 static void ipcsyslog_init(void)
163 printf("shmget(%lx, %d,...)\n", KEY_ID, shm_size);
165 shmid = shmget(KEY_ID, shm_size, IPC_CREAT | 1023);
167 bb_perror_msg_and_die("shmget");
170 shbuf = shmat(shmid, NULL, 0);
172 bb_perror_msg_and_die("shmat");
175 shbuf->size = shm_size - offsetof(struct shbuf_ds, data);
176 shbuf->head = shbuf->tail = 0;
178 // we'll trust the OS to set initial semval to 0 (let's hope)
179 s_semid = semget(KEY_ID, 2, IPC_CREAT | IPC_EXCL | 1023);
181 if (errno == EEXIST) {
182 s_semid = semget(KEY_ID, 2, 0);
186 bb_perror_msg_and_die("semget");
190 /* Write message to shared mem buffer */
191 static void log_to_shmem(const char *msg, int len)
193 /* Why libc insists on these being rw? */
194 static struct sembuf SMwup[1] = { {1, -1, IPC_NOWAIT} };
195 static struct sembuf SMwdn[3] = { {0, 0}, {1, 0}, {1, +1} };
197 int old_tail, new_tail;
200 if (semop(s_semid, SMwdn, 3) == -1) {
201 bb_perror_msg_and_die("SMwdn");
204 /* Circular Buffer Algorithm:
205 * --------------------------
206 * tail == position where to store next syslog message.
207 * head == position of next message to retrieve ("print").
208 * if head == tail, there is no "unprinted" messages left.
209 * head is typically advanced by separate "reader" program,
210 * but if there isn't one, we have to do it ourself.
211 * messages are NUL-separated.
213 len++; /* length with NUL included */
215 old_tail = shbuf->tail;
216 new_tail = old_tail + len;
217 if (new_tail < shbuf->size) {
218 /* No need to move head if shbuf->head <= old_tail,
220 if (old_tail < shbuf->head && shbuf->head <= new_tail) {
221 /* ...need to move head forward */
222 c = memchr(shbuf->data + new_tail, '\0',
223 shbuf->size - new_tail);
224 if (!c) /* no NUL ahead of us, wrap around */
225 c = memchr(shbuf->data, '\0', old_tail);
226 if (!c) { /* still nothing? point to this msg... */
227 shbuf->head = old_tail;
229 /* convert pointer to offset + skip NUL */
230 shbuf->head = c - shbuf->data + 1;
233 /* store message, set new tail */
234 memcpy(shbuf->data + old_tail, msg, len);
235 shbuf->tail = new_tail;
237 /* we need to break up the message and wrap it around */
238 /* k == available buffer space ahead of old tail */
239 int k = shbuf->size - old_tail - 1;
240 if (shbuf->head > old_tail) {
241 /* we are going to overwrite head, need to
242 * move it out of the way */
243 c = memchr(shbuf->data, '\0', old_tail);
244 if (!c) { /* nothing? point to this msg... */
245 shbuf->head = old_tail;
246 } else { /* convert pointer to offset + skip NUL */
247 shbuf->head = c - shbuf->data + 1;
250 /* copy what fits to the end of buffer, and repeat */
251 memcpy(shbuf->data + old_tail, msg, k);
257 if (semop(s_semid, SMwup, 1) == -1) {
258 bb_perror_msg_and_die("SMwup");
261 printf("head:%d tail:%d\n", shbuf->head, shbuf->tail);
264 void ipcsyslog_cleanup(void);
265 void ipcsyslog_init(void);
266 void log_to_shmem(const char *msg);
267 #endif /* FEATURE_IPC_SYSLOG */
270 /* Print a message to the log file. */
271 static void log_locally(char *msg)
275 int len = strlen(msg);
277 #if ENABLE_FEATURE_IPC_SYSLOG
278 if ((option_mask32 & OPT_circularlog) && shbuf) {
279 log_to_shmem(msg, len);
287 last = cur; /* reopen log file every second */
293 logFD = device_open(logFilePath, O_WRONLY | O_CREAT
294 | O_NOCTTY | O_APPEND | O_NONBLOCK);
296 /* cannot open logfile? - print to /dev/console then */
297 int fd = device_open(_PATH_CONSOLE, O_WRONLY | O_NOCTTY | O_NONBLOCK);
299 fd = 2; /* then stderr, dammit */
300 full_write(fd, msg, len);
305 #if ENABLE_FEATURE_ROTATE_LOGFILE
309 isRegular = (fstat(logFD, &statf) == 0 && (statf.st_mode & S_IFREG));
310 /* bug (mostly harmless): can wrap around if file > 4gb */
311 curFileSize = statf.st_size;
316 fl.l_whence = SEEK_SET;
320 fcntl(logFD, F_SETLKW, &fl);
322 #if ENABLE_FEATURE_ROTATE_LOGFILE
323 if (logFileSize && isRegular && curFileSize > logFileSize) {
324 if (logFileRotate) { /* always 0..99 */
325 int i = strlen(logFilePath) + 3 + 1;
328 i = logFileRotate - 1;
329 /* rename: f.8 -> f.9; f.7 -> f.8; ... */
331 sprintf(newFile, "%s.%d", logFilePath, i);
333 sprintf(oldFile, "%s.%d", logFilePath, --i);
334 rename(oldFile, newFile);
336 /* newFile == "f.0" now */
337 rename(logFilePath, newFile);
339 fcntl(logFD, F_SETLKW, &fl);
347 full_write(logFD, msg, len);
349 fcntl(logFD, F_SETLKW, &fl);
352 static void parse_fac_prio_20(int pri, char *res20)
357 c_fac = facilitynames;
358 while (c_fac->c_name) {
359 if (c_fac->c_val != (LOG_FAC(pri) << 3)) {
362 /* facility is found, look for prio */
363 c_pri = prioritynames;
364 while (c_pri->c_name) {
365 if (c_pri->c_val != LOG_PRI(pri)) {
368 snprintf(res20, 20, "%s.%s",
369 c_fac->c_name, c_pri->c_name);
372 /* prio not found, bail out */
375 snprintf(res20, 20, "<%d>", pri);
379 /* len parameter is used only for "is there a timestamp?" check.
380 * NB: some callers cheat and supply 0 when they know
381 * that there is no timestamp, short-cutting the test. */
382 static void timestamp_and_log(int pri, char *msg, int len)
386 if (len < 16 || msg[3] != ' ' || msg[6] != ' '
387 || msg[9] != ':' || msg[12] != ':' || msg[15] != ' '
391 timestamp = ctime(&now) + 4;
396 timestamp[15] = '\0';
398 /* Log message locally (to file or shared mem) */
399 if (!ENABLE_FEATURE_REMOTE_LOG || (option_mask32 & OPT_locallog)) {
400 if (LOG_PRI(pri) < logLevel) {
401 if (option_mask32 & OPT_small)
402 sprintf(PRINTBUF, "%s %s\n", timestamp, msg);
405 parse_fac_prio_20(pri, res);
406 sprintf(PRINTBUF, "%s %s %s %s\n", timestamp, localHostName, res, msg);
408 log_locally(PRINTBUF);
413 static void split_escape_and_log(char *tmpbuf, int len)
421 int pri = (LOG_USER | LOG_NOTICE);
424 /* Parse the magic priority number */
425 pri = bb_strtou(p + 1, &p, 10);
427 if (pri & ~(LOG_FACMASK | LOG_PRIMASK)) {
428 pri = (LOG_USER | LOG_NOTICE);
437 c += '@'; /* ^@, ^A, ^B... */
443 timestamp_and_log(pri, PARSEBUF, q - PARSEBUF);
447 static void quit_signal(int sig)
449 timestamp_and_log(LOG_SYSLOG | LOG_INFO, (char*)"syslogd exiting", 0);
450 puts("syslogd exiting");
451 if (ENABLE_FEATURE_IPC_SYSLOG)
457 static void do_mark(int sig)
460 timestamp_and_log(LOG_SYSLOG | LOG_INFO, (char*)"-- MARK --", 0);
466 static void do_syslogd(void) ATTRIBUTE_NORETURN;
467 static void do_syslogd(void)
469 struct sockaddr_un sunx;
474 /* Set up signal handlers */
475 signal(SIGINT, quit_signal);
476 signal(SIGTERM, quit_signal);
477 signal(SIGQUIT, quit_signal);
478 signal(SIGHUP, SIG_IGN);
479 signal(SIGCHLD, SIG_IGN);
481 signal(SIGCLD, SIG_IGN);
484 signal(SIGALRM, do_mark);
488 memset(&sunx, 0, sizeof(sunx));
489 sunx.sun_family = AF_UNIX;
490 strcpy(sunx.sun_path, "/dev/log");
492 /* Unlink old /dev/log or object it points to. */
493 /* (if it exists, bind will fail) */
494 logmode = LOGMODE_NONE;
495 dev_log_name = xmalloc_readlink_or_warn("/dev/log");
496 logmode = LOGMODE_STDIO;
498 int fd = xopen(".", O_NONBLOCK);
500 /* we do not check whether this is a link also */
501 unlink(dev_log_name);
504 safe_strncpy(sunx.sun_path, dev_log_name, sizeof(sunx.sun_path));
510 sock_fd = xsocket(AF_UNIX, SOCK_DGRAM, 0);
511 xbind(sock_fd, (struct sockaddr *) &sunx, sizeof(sunx));
513 if (chmod("/dev/log", 0666) < 0) {
514 bb_perror_msg_and_die("cannot set permission on /dev/log");
516 if (ENABLE_FEATURE_IPC_SYSLOG && (option_mask32 & OPT_circularlog)) {
520 timestamp_and_log(LOG_SYSLOG | LOG_INFO,
521 (char*)"syslogd started: BusyBox v" BB_VER, 0);
525 FD_SET(sock_fd, &fds);
527 if (select(sock_fd + 1, &fds, NULL, NULL, NULL) < 0) {
528 if (errno == EINTR) {
529 /* alarm may have happened */
532 bb_perror_msg_and_die("select");
535 if (FD_ISSET(sock_fd, &fds)) {
537 i = recv(sock_fd, RECVBUF, MAX_READ - 1, 0);
539 bb_perror_msg_and_die("UNIX socket error");
540 /* TODO: maybe suppress duplicates? */
541 #if ENABLE_FEATURE_REMOTE_LOG
542 /* We are not modifying log messages in any way before send */
543 /* Remote site cannot trust _us_ anyway and need to do validation again */
545 if (-1 == remoteFD) {
546 remoteFD = socket(remoteAddr->sa.sa_family, SOCK_DGRAM, 0);
548 if (-1 != remoteFD) {
549 /* send message to remote logger, ignore possible error */
550 sendto(remoteFD, RECVBUF, i, MSG_DONTWAIT,
551 &remoteAddr->sa, remoteAddr->len);
556 split_escape_and_log(RECVBUF, i);
561 int syslogd_main(int argc, char **argv);
562 int syslogd_main(int argc, char **argv)
567 /* do normal option parsing */
568 opt_complementary = "=0"; /* no non-option params */
569 getopt32(argc, argv, OPTION_STR, OPTION_PARAM);
571 if (option_mask32 & OPT_mark) // -m
572 markInterval = xatou_range(opt_m, 0, INT_MAX/60) * 60;
574 //if (option_mask32 & OPT_nofork) // -n
575 //if (option_mask32 & OPT_outfile) // -O
576 if (option_mask32 & OPT_loglevel) // -l
577 logLevel = xatou_range(opt_l, 1, 8);
578 //if (option_mask32 & OPT_small) // -S
579 #if ENABLE_FEATURE_ROTATE_LOGFILE
580 if (option_mask32 & OPT_filesize) // -s
581 logFileSize = xatou_range(opt_s, 0, INT_MAX/1024) * 1024;
582 if (option_mask32 & OPT_rotatecnt) // -b
583 logFileRotate = xatou_range(opt_b, 0, 99);
585 #if ENABLE_FEATURE_REMOTE_LOG
586 if (option_mask32 & OPT_remotelog) { // -R
587 remoteAddr = xhost2sockaddr(opt_R, 514);
589 //if (option_mask32 & OPT_locallog) // -L
591 #if ENABLE_FEATURE_IPC_SYSLOG
593 shm_size = xatoul_range(opt_C, 4, INT_MAX/1024) * 1024;
596 /* If they have not specified remote logging, then log locally */
597 if (ENABLE_FEATURE_REMOTE_LOG && !(option_mask32 & OPT_remotelog))
598 option_mask32 |= OPT_locallog;
600 /* Store away localhost's name before the fork */
601 gethostname(localHostName, sizeof(localHostName));
602 p = strchr(localHostName, '.');
607 if (!(option_mask32 & OPT_nofork)) {
609 vfork_daemon_rexec(0, 1, argc, argv, "-n");
616 /* return EXIT_SUCCESS; */