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 /* interval between marks in seconds */
32 static int markInterval = 20 * 60;
34 /* level of messages to be locally logged */
35 static int logLevel = 8;
37 /* localhost's name */
38 static char localHostName[64];
40 #if ENABLE_FEATURE_ROTATE_LOGFILE
41 /* max size of message file before being rotated */
42 static unsigned logFileSize = 200 * 1024;
43 /* number of rotated message files */
44 static unsigned logFileRotate = 1;
45 static unsigned curFileSize;
46 static smallint isRegular;
49 #if ENABLE_FEATURE_REMOTE_LOG
50 #include <netinet/in.h>
51 /* udp socket for logging to remote host */
52 static int remoteFD = -1;
53 static len_and_sockaddr* remoteAddr;
56 /* We are using bb_common_bufsiz1 for buffering: */
57 enum { MAX_READ = (BUFSIZ/6) & ~0xf };
58 /* We recv into RECVBUF... (size: MAX_READ ~== BUFSIZ/6) */
59 #define RECVBUF bb_common_bufsiz1
60 /* ...then copy to PARSEBUF, escaping control chars */
61 /* (can grow x2 max ~== BUFSIZ/3) */
62 #define PARSEBUF (bb_common_bufsiz1 + MAX_READ)
63 /* ...then sprintf into PRINTBUF, adding timestamp (15 chars),
64 * host (64), fac.prio (20) to the message */
65 /* (growth by: 15 + 64 + 20 + delims = ~110) */
66 #define PRINTBUF (bb_common_bufsiz1 + 3*MAX_READ)
67 /* totals: BUFSIZ == BUFSIZ/6 + BUFSIZ/3 + (BUFSIZ/3+BUFSIZ/6)
68 * -- we have BUFSIZ/6 extra at the ent of PRINTBUF
69 * which covers needed ~110 extra bytes (and much more) */
74 OPTBIT_mark = 0, // -m
77 OPTBIT_loglevel, // -l
79 USE_FEATURE_ROTATE_LOGFILE(OPTBIT_filesize ,) // -s
80 USE_FEATURE_ROTATE_LOGFILE(OPTBIT_rotatecnt ,) // -b
81 USE_FEATURE_REMOTE_LOG( OPTBIT_remote ,) // -R
82 USE_FEATURE_REMOTE_LOG( OPTBIT_localtoo ,) // -L
83 USE_FEATURE_IPC_SYSLOG( OPTBIT_circularlog,) // -C
85 OPT_mark = 1 << OPTBIT_mark ,
86 OPT_nofork = 1 << OPTBIT_nofork ,
87 OPT_outfile = 1 << OPTBIT_outfile ,
88 OPT_loglevel = 1 << OPTBIT_loglevel,
89 OPT_small = 1 << OPTBIT_small ,
90 OPT_filesize = USE_FEATURE_ROTATE_LOGFILE((1 << OPTBIT_filesize )) + 0,
91 OPT_rotatecnt = USE_FEATURE_ROTATE_LOGFILE((1 << OPTBIT_rotatecnt )) + 0,
92 OPT_remotelog = USE_FEATURE_REMOTE_LOG( (1 << OPTBIT_remote )) + 0,
93 OPT_locallog = USE_FEATURE_REMOTE_LOG( (1 << OPTBIT_localtoo )) + 0,
94 OPT_circularlog = USE_FEATURE_IPC_SYSLOG( (1 << OPTBIT_circularlog)) + 0,
96 #define OPTION_STR "m:nO:l:S" \
97 USE_FEATURE_ROTATE_LOGFILE("s:" ) \
98 USE_FEATURE_ROTATE_LOGFILE("b:" ) \
99 USE_FEATURE_REMOTE_LOG( "R:" ) \
100 USE_FEATURE_REMOTE_LOG( "L" ) \
101 USE_FEATURE_IPC_SYSLOG( "C::")
102 #define OPTION_DECL *opt_m, *opt_l \
103 USE_FEATURE_ROTATE_LOGFILE(,*opt_s) \
104 USE_FEATURE_ROTATE_LOGFILE(,*opt_b) \
105 USE_FEATURE_REMOTE_LOG( ,*opt_R) \
106 USE_FEATURE_IPC_SYSLOG( ,*opt_C = NULL)
107 #define OPTION_PARAM &opt_m, &logFilePath, &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)
114 /* circular buffer variables/structures */
115 #if ENABLE_FEATURE_IPC_SYSLOG
118 #if CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE < 4
119 #error Sorry, you must set the syslogd buffer size to at least 4KB.
120 #error Please check CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE
128 #define KEY_ID ((long)0x414e4547) /* "GENA" */
130 // Semaphore operation structures
131 static struct shbuf_ds {
132 int32_t size; // size of data written
133 int32_t head; // start of message list
134 int32_t tail; // end of message list
135 char data[1]; // data/messages
136 } *shbuf; // shared memory pointer
138 static int shmid = -1; // ipc shared memory id
139 static int s_semid = -1; // ipc semaphore id
140 static int shm_size = ((CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE)*1024); // default shm size
142 static void ipcsyslog_cleanup(void)
148 shmctl(shmid, IPC_RMID, NULL);
151 semctl(s_semid, 0, IPC_RMID, 0);
155 static void ipcsyslog_init(void)
158 printf("shmget(%lx, %d,...)\n", KEY_ID, shm_size);
160 shmid = shmget(KEY_ID, shm_size, IPC_CREAT | 1023);
162 bb_perror_msg_and_die("shmget");
165 shbuf = shmat(shmid, NULL, 0);
167 bb_perror_msg_and_die("shmat");
170 shbuf->size = shm_size - offsetof(struct shbuf_ds, data);
171 shbuf->head = shbuf->tail = 0;
173 // we'll trust the OS to set initial semval to 0 (let's hope)
174 s_semid = semget(KEY_ID, 2, IPC_CREAT | IPC_EXCL | 1023);
176 if (errno == EEXIST) {
177 s_semid = semget(KEY_ID, 2, 0);
181 bb_perror_msg_and_die("semget");
185 /* Write message to shared mem buffer */
186 static void log_to_shmem(const char *msg, int len)
188 /* Why libc insists on these being rw? */
189 static struct sembuf SMwup[1] = { {1, -1, IPC_NOWAIT} };
190 static struct sembuf SMwdn[3] = { {0, 0}, {1, 0}, {1, +1} };
192 int old_tail, new_tail;
195 if (semop(s_semid, SMwdn, 3) == -1) {
196 bb_perror_msg_and_die("SMwdn");
199 /* Circular Buffer Algorithm:
200 * --------------------------
201 * tail == position where to store next syslog message.
202 * head == position of next message to retrieve ("print").
203 * if head == tail, there is no "unprinted" messages left.
204 * head is typically advanced by separate "reader" program,
205 * but if there isn't one, we have to do it ourself.
206 * messages are NUL-separated.
208 len++; /* length with NUL included */
210 old_tail = shbuf->tail;
211 new_tail = old_tail + len;
212 if (new_tail < shbuf->size) {
213 /* No need to move head if shbuf->head <= old_tail,
215 if (old_tail < shbuf->head && shbuf->head <= new_tail) {
216 /* ...need to move head forward */
217 c = memchr(shbuf->data + new_tail, '\0',
218 shbuf->size - new_tail);
219 if (!c) /* no NUL ahead of us, wrap around */
220 c = memchr(shbuf->data, '\0', old_tail);
221 if (!c) { /* still nothing? point to this msg... */
222 shbuf->head = old_tail;
224 /* convert pointer to offset + skip NUL */
225 shbuf->head = c - shbuf->data + 1;
228 /* store message, set new tail */
229 memcpy(shbuf->data + old_tail, msg, len);
230 shbuf->tail = new_tail;
232 /* we need to break up the message and wrap it around */
233 /* k == available buffer space ahead of old tail */
234 int k = shbuf->size - old_tail - 1;
235 if (shbuf->head > old_tail) {
236 /* we are going to overwrite head, need to
237 * move it out of the way */
238 c = memchr(shbuf->data, '\0', old_tail);
239 if (!c) { /* nothing? point to this msg... */
240 shbuf->head = old_tail;
241 } else { /* convert pointer to offset + skip NUL */
242 shbuf->head = c - shbuf->data + 1;
245 /* copy what fits to the end of buffer, and repeat */
246 memcpy(shbuf->data + old_tail, msg, k);
252 if (semop(s_semid, SMwup, 1) == -1) {
253 bb_perror_msg_and_die("SMwup");
256 printf("head:%d tail:%d\n", shbuf->head, shbuf->tail);
259 void ipcsyslog_cleanup(void);
260 void ipcsyslog_init(void);
261 void log_to_shmem(const char *msg);
262 #endif /* FEATURE_IPC_SYSLOG */
265 /* Print a message to the log file. */
266 static void log_locally(char *msg)
270 int len = strlen(msg);
272 #if ENABLE_FEATURE_IPC_SYSLOG
273 if ((option_mask32 & OPT_circularlog) && shbuf) {
274 log_to_shmem(msg, len);
282 last = cur; /* reopen log file every second */
288 logFD = device_open(logFilePath, O_WRONLY | O_CREAT
289 | O_NOCTTY | O_APPEND | O_NONBLOCK);
291 /* cannot open logfile? - print to /dev/console then */
292 int fd = device_open(_PATH_CONSOLE, O_WRONLY | O_NOCTTY | O_NONBLOCK);
294 fd = 2; /* then stderr, dammit */
295 full_write(fd, msg, len);
300 #if ENABLE_FEATURE_ROTATE_LOGFILE
304 isRegular = (fstat(logFD, &statf) == 0 && (statf.st_mode & S_IFREG));
305 /* bug (mostly harmless): can wrap around if file > 4gb */
306 curFileSize = statf.st_size;
311 fl.l_whence = SEEK_SET;
315 fcntl(logFD, F_SETLKW, &fl);
317 #if ENABLE_FEATURE_ROTATE_LOGFILE
318 if (logFileSize && isRegular && curFileSize > logFileSize) {
319 if (logFileRotate) { /* always 0..99 */
320 int i = strlen(logFilePath) + 3 + 1;
323 i = logFileRotate - 1;
324 /* rename: f.8 -> f.9; f.7 -> f.8; ... */
326 sprintf(newFile, "%s.%d", logFilePath, i);
328 sprintf(oldFile, "%s.%d", logFilePath, --i);
329 rename(oldFile, newFile);
331 /* newFile == "f.0" now */
332 rename(logFilePath, newFile);
334 fcntl(logFD, F_SETLKW, &fl);
342 full_write(logFD, msg, len);
344 fcntl(logFD, F_SETLKW, &fl);
347 static void parse_fac_prio_20(int pri, char *res20)
352 c_fac = facilitynames;
353 while (c_fac->c_name) {
354 if (c_fac->c_val != (LOG_FAC(pri) << 3)) {
357 /* facility is found, look for prio */
358 c_pri = prioritynames;
359 while (c_pri->c_name) {
360 if (c_pri->c_val != LOG_PRI(pri)) {
363 snprintf(res20, 20, "%s.%s",
364 c_fac->c_name, c_pri->c_name);
367 /* prio not found, bail out */
370 snprintf(res20, 20, "<%d>", pri);
374 /* len parameter is used only for "is there a timestamp?" check.
375 * NB: some callers cheat and supply 0 when they know
376 * that there is no timestamp, short-cutting the test. */
377 static void timestamp_and_log(int pri, char *msg, int len)
381 if (len < 16 || msg[3] != ' ' || msg[6] != ' '
382 || msg[9] != ':' || msg[12] != ':' || msg[15] != ' '
386 timestamp = ctime(&now) + 4;
391 timestamp[15] = '\0';
393 /* Log message locally (to file or shared mem) */
394 if (!ENABLE_FEATURE_REMOTE_LOG || (option_mask32 & OPT_locallog)) {
395 if (LOG_PRI(pri) < logLevel) {
396 if (option_mask32 & OPT_small)
397 sprintf(PRINTBUF, "%s %s\n", timestamp, msg);
400 parse_fac_prio_20(pri, res);
401 sprintf(PRINTBUF, "%s %s %s %s\n", timestamp, localHostName, res, msg);
403 log_locally(PRINTBUF);
408 static void split_escape_and_log(char *tmpbuf, int len)
416 int pri = (LOG_USER | LOG_NOTICE);
419 /* Parse the magic priority number */
420 pri = bb_strtou(p + 1, &p, 10);
422 if (pri & ~(LOG_FACMASK | LOG_PRIMASK)) {
423 pri = (LOG_USER | LOG_NOTICE);
432 c += '@'; /* ^@, ^A, ^B... */
438 timestamp_and_log(pri, PARSEBUF, q - PARSEBUF);
442 static void quit_signal(int sig)
444 timestamp_and_log(LOG_SYSLOG | LOG_INFO, (char*)"syslogd exiting", 0);
445 puts("syslogd exiting");
446 if (ENABLE_FEATURE_IPC_SYSLOG)
451 static void do_mark(int sig)
454 timestamp_and_log(LOG_SYSLOG | LOG_INFO, (char*)"-- MARK --", 0);
459 static void do_syslogd(void) ATTRIBUTE_NORETURN;
460 static void do_syslogd(void)
462 struct sockaddr_un sunx;
467 /* Set up signal handlers */
468 signal(SIGINT, quit_signal);
469 signal(SIGTERM, quit_signal);
470 signal(SIGQUIT, quit_signal);
471 signal(SIGHUP, SIG_IGN);
472 signal(SIGCHLD, SIG_IGN);
474 signal(SIGCLD, SIG_IGN);
476 signal(SIGALRM, do_mark);
479 memset(&sunx, 0, sizeof(sunx));
480 sunx.sun_family = AF_UNIX;
481 strcpy(sunx.sun_path, "/dev/log");
483 /* Unlink old /dev/log or object it points to. */
484 /* (if it exists, bind will fail) */
485 logmode = LOGMODE_NONE;
486 dev_log_name = xmalloc_readlink_or_warn("/dev/log");
487 logmode = LOGMODE_STDIO;
489 int fd = xopen(".", O_NONBLOCK);
491 /* we do not check whether this is a link also */
492 unlink(dev_log_name);
495 safe_strncpy(sunx.sun_path, dev_log_name, sizeof(sunx.sun_path));
501 sock_fd = xsocket(AF_UNIX, SOCK_DGRAM, 0);
502 xbind(sock_fd, (struct sockaddr *) &sunx, sizeof(sunx));
504 if (chmod("/dev/log", 0666) < 0) {
505 bb_perror_msg_and_die("cannot set permission on /dev/log");
507 if (ENABLE_FEATURE_IPC_SYSLOG && (option_mask32 & OPT_circularlog)) {
511 timestamp_and_log(LOG_SYSLOG | LOG_INFO,
512 (char*)"syslogd started: BusyBox v" BB_VER, 0);
516 FD_SET(sock_fd, &fds);
518 if (select(sock_fd + 1, &fds, NULL, NULL, NULL) < 0) {
519 if (errno == EINTR) {
520 /* alarm may have happened */
523 bb_perror_msg_and_die("select");
526 if (FD_ISSET(sock_fd, &fds)) {
528 i = recv(sock_fd, RECVBUF, MAX_READ - 1, 0);
530 bb_perror_msg_and_die("UNIX socket error");
531 /* TODO: maybe suppress duplicates? */
532 #if ENABLE_FEATURE_REMOTE_LOG
533 /* We are not modifying log messages in any way before send */
534 /* Remote site cannot trust _us_ anyway and need to do validation again */
536 if (-1 == remoteFD) {
537 remoteFD = socket(remoteAddr->sa.sa_family, SOCK_DGRAM, 0);
539 if (-1 != remoteFD) {
540 /* send message to remote logger, ignore possible error */
541 sendto(remoteFD, RECVBUF, i, MSG_DONTWAIT,
542 &remoteAddr->sa, remoteAddr->len);
547 split_escape_and_log(RECVBUF, i);
552 int syslogd_main(int argc, char **argv);
553 int syslogd_main(int argc, char **argv)
558 /* do normal option parsing */
559 opt_complementary = "=0"; /* no non-option params */
560 getopt32(argc, argv, OPTION_STR, OPTION_PARAM);
561 if (option_mask32 & OPT_mark) // -m
562 markInterval = xatou_range(opt_m, 0, INT_MAX/60) * 60;
563 //if (option_mask32 & OPT_nofork) // -n
564 //if (option_mask32 & OPT_outfile) // -O
565 if (option_mask32 & OPT_loglevel) // -l
566 logLevel = xatou_range(opt_l, 1, 8);
567 //if (option_mask32 & OPT_small) // -S
568 #if ENABLE_FEATURE_ROTATE_LOGFILE
569 if (option_mask32 & OPT_filesize) // -s
570 logFileSize = xatou_range(opt_s, 0, INT_MAX/1024) * 1024;
571 if (option_mask32 & OPT_rotatecnt) // -b
572 logFileRotate = xatou_range(opt_b, 0, 99);
574 #if ENABLE_FEATURE_REMOTE_LOG
575 if (option_mask32 & OPT_remotelog) { // -R
576 remoteAddr = xhost2sockaddr(opt_R, 514);
578 //if (option_mask32 & OPT_locallog) // -L
580 #if ENABLE_FEATURE_IPC_SYSLOG
582 shm_size = xatoul_range(opt_C, 4, INT_MAX/1024) * 1024;
585 /* If they have not specified remote logging, then log locally */
586 if (ENABLE_FEATURE_REMOTE_LOG && !(option_mask32 & OPT_remotelog))
587 option_mask32 |= OPT_locallog;
589 /* Store away localhost's name before the fork */
590 gethostname(localHostName, sizeof(localHostName));
591 p = strchr(localHostName, '.');
596 if (!(option_mask32 & OPT_nofork)) {
598 vfork_daemon_rexec(0, 1, argc, argv, "-n");
605 /* return EXIT_SUCCESS; */