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 to the unix socket */
28 static char *dev_log_name;
30 /* Path for the file where all log messages are written */
31 static const char *logFilePath = "/var/log/messages";
32 static int logFD = -1;
34 /* interval between marks in seconds */
35 static int markInterval = 20 * 60;
37 /* level of messages to be locally logged */
38 static int logLevel = 8;
40 /* localhost's name */
41 static char localHostName[64];
43 #if ENABLE_FEATURE_ROTATE_LOGFILE
44 /* max size of message file before being rotated */
45 static unsigned logFileSize = 200 * 1024;
46 /* number of rotated message files */
47 static unsigned logFileRotate = 1;
48 static unsigned curFileSize;
49 static smallint isRegular;
52 #if ENABLE_FEATURE_REMOTE_LOG
53 #include <netinet/in.h>
54 /* udp socket for logging to remote host */
55 static int remoteFD = -1;
56 static struct sockaddr_in remoteAddr;
59 /* We are using bb_common_bufsiz1 for buffering: */
60 enum { MAX_READ = (BUFSIZ/6) & ~0xf };
61 /* We recv into RECVBUF... (size: MAX_READ ~== BUFSIZ/6) */
62 #define RECVBUF bb_common_bufsiz1
63 /* ...then copy to PARSEBUF, escaping control chars */
64 /* (can grow x2 max ~== BUFSIZ/3) */
65 #define PARSEBUF (bb_common_bufsiz1 + MAX_READ)
66 /* ...then sprintf into PRINTBUF, adding timestamp (15 chars),
67 * host (64), fac.prio (20) to the message */
68 /* (growth by: 15 + 64 + 20 + delims = ~110) */
69 #define PRINTBUF (bb_common_bufsiz1 + 3*MAX_READ)
70 /* totals: BUFSIZ == BUFSIZ/6 + BUFSIZ/3 + (BUFSIZ/3+BUFSIZ/6)
71 * -- we have BUFSIZ/6 extra at the ent of PRINTBUF
72 * which covers needed ~110 extra bytes (and much more) */
77 OPTBIT_mark = 0, // -m
80 OPTBIT_loglevel, // -l
82 USE_FEATURE_ROTATE_LOGFILE(OPTBIT_filesize ,) // -s
83 USE_FEATURE_ROTATE_LOGFILE(OPTBIT_rotatecnt ,) // -b
84 USE_FEATURE_REMOTE_LOG( OPTBIT_remote ,) // -R
85 USE_FEATURE_REMOTE_LOG( OPTBIT_localtoo ,) // -L
86 USE_FEATURE_IPC_SYSLOG( OPTBIT_circularlog,) // -C
88 OPT_mark = 1 << OPTBIT_mark ,
89 OPT_nofork = 1 << OPTBIT_nofork ,
90 OPT_outfile = 1 << OPTBIT_outfile ,
91 OPT_loglevel = 1 << OPTBIT_loglevel,
92 OPT_small = 1 << OPTBIT_small ,
93 OPT_filesize = USE_FEATURE_ROTATE_LOGFILE((1 << OPTBIT_filesize )) + 0,
94 OPT_rotatecnt = USE_FEATURE_ROTATE_LOGFILE((1 << OPTBIT_rotatecnt )) + 0,
95 OPT_remotelog = USE_FEATURE_REMOTE_LOG( (1 << OPTBIT_remote )) + 0,
96 OPT_locallog = USE_FEATURE_REMOTE_LOG( (1 << OPTBIT_localtoo )) + 0,
97 OPT_circularlog = USE_FEATURE_IPC_SYSLOG( (1 << OPTBIT_circularlog)) + 0,
99 #define OPTION_STR "m:nO:l:S" \
100 USE_FEATURE_ROTATE_LOGFILE("s:" ) \
101 USE_FEATURE_ROTATE_LOGFILE("b:" ) \
102 USE_FEATURE_REMOTE_LOG( "R:" ) \
103 USE_FEATURE_REMOTE_LOG( "L" ) \
104 USE_FEATURE_IPC_SYSLOG( "C::")
105 #define OPTION_DECL *opt_m, *opt_l \
106 USE_FEATURE_ROTATE_LOGFILE(,*opt_s) \
107 USE_FEATURE_ROTATE_LOGFILE(,*opt_b) \
108 USE_FEATURE_REMOTE_LOG( ,*opt_R) \
109 USE_FEATURE_IPC_SYSLOG( ,*opt_C = NULL)
110 #define OPTION_PARAM &opt_m, &logFilePath, &opt_l \
111 USE_FEATURE_ROTATE_LOGFILE(,&opt_s) \
112 USE_FEATURE_ROTATE_LOGFILE(,&opt_b) \
113 USE_FEATURE_REMOTE_LOG( ,&opt_R) \
114 USE_FEATURE_IPC_SYSLOG( ,&opt_C)
117 /* circular buffer variables/structures */
118 #if ENABLE_FEATURE_IPC_SYSLOG
121 #if CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE < 4
122 #error Sorry, you must set the syslogd buffer size to at least 4KB.
123 #error Please check CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE
131 #define KEY_ID ((long)0x414e4547) /* "GENA" */
133 // Semaphore operation structures
134 static struct shbuf_ds {
135 int32_t size; // size of data written
136 int32_t head; // start of message list
137 int32_t tail; // end of message list
138 char data[1]; // data/messages
139 } *shbuf; // shared memory pointer
141 static int shmid = -1; // ipc shared memory id
142 static int s_semid = -1; // ipc semaphore id
143 static int shm_size = ((CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE)*1024); // default shm size
145 static void ipcsyslog_cleanup(void)
151 shmctl(shmid, IPC_RMID, NULL);
154 semctl(s_semid, 0, IPC_RMID, 0);
158 static void ipcsyslog_init(void)
161 printf("shmget(%lx, %d,...)\n", KEY_ID, shm_size);
163 shmid = shmget(KEY_ID, shm_size, IPC_CREAT | 1023);
165 bb_perror_msg_and_die("shmget");
168 shbuf = shmat(shmid, NULL, 0);
170 bb_perror_msg_and_die("shmat");
173 shbuf->size = shm_size - offsetof(struct shbuf_ds, data);
174 shbuf->head = shbuf->tail = 0;
176 // we'll trust the OS to set initial semval to 0 (let's hope)
177 s_semid = semget(KEY_ID, 2, IPC_CREAT | IPC_EXCL | 1023);
179 if (errno == EEXIST) {
180 s_semid = semget(KEY_ID, 2, 0);
184 bb_perror_msg_and_die("semget");
188 /* Write message to shared mem buffer */
189 static void log_to_shmem(const char *msg, int len)
191 /* Why libc insists on these being rw? */
192 static struct sembuf SMwup[1] = { {1, -1, IPC_NOWAIT} };
193 static struct sembuf SMwdn[3] = { {0, 0}, {1, 0}, {1, +1} };
195 int old_tail, new_tail;
198 if (semop(s_semid, SMwdn, 3) == -1) {
199 bb_perror_msg_and_die("SMwdn");
202 /* Circular Buffer Algorithm:
203 * --------------------------
204 * tail == position where to store next syslog message.
205 * head == position of next message to retrieve ("print").
206 * if head == tail, there is no "unprinted" messages left.
207 * head is typically advanced by separate "reader" program,
208 * but if there isn't one, we have to do it ourself.
209 * messages are NUL-separated.
211 len++; /* length with NUL included */
213 old_tail = shbuf->tail;
214 new_tail = old_tail + len;
215 if (new_tail < shbuf->size) {
216 /* No need to move head if shbuf->head <= old_tail,
218 if (old_tail < shbuf->head && shbuf->head <= new_tail) {
219 /* ...need to move head forward */
220 c = memchr(shbuf->data + new_tail, '\0',
221 shbuf->size - new_tail);
222 if (!c) /* no NUL ahead of us, wrap around */
223 c = memchr(shbuf->data, '\0', old_tail);
224 if (!c) { /* still nothing? point to this msg... */
225 shbuf->head = old_tail;
227 /* convert pointer to offset + skip NUL */
228 shbuf->head = c - shbuf->data + 1;
231 /* store message, set new tail */
232 memcpy(shbuf->data + old_tail, msg, len);
233 shbuf->tail = new_tail;
235 /* we need to break up the message and wrap it around */
236 /* k == available buffer space ahead of old tail */
237 int k = shbuf->size - old_tail - 1;
238 if (shbuf->head > old_tail) {
239 /* we are going to overwrite head, need to
240 * move it out of the way */
241 c = memchr(shbuf->data, '\0', old_tail);
242 if (!c) { /* nothing? point to this msg... */
243 shbuf->head = old_tail;
244 } else { /* convert pointer to offset + skip NUL */
245 shbuf->head = c - shbuf->data + 1;
248 /* copy what fits to the end of buffer, and repeat */
249 memcpy(shbuf->data + old_tail, msg, k);
255 if (semop(s_semid, SMwup, 1) == -1) {
256 bb_perror_msg_and_die("SMwup");
259 printf("head:%d tail:%d\n", shbuf->head, shbuf->tail);
262 void ipcsyslog_cleanup(void);
263 void ipcsyslog_init(void);
264 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)
276 int len = strlen(msg);
278 #if ENABLE_FEATURE_IPC_SYSLOG
279 if ((option_mask32 & OPT_circularlog) && shbuf) {
280 log_to_shmem(msg, len);
288 last = cur; /* reopen log file every second */
294 logFD = device_open(logFilePath, O_WRONLY | O_CREAT
295 | O_NOCTTY | O_APPEND | O_NONBLOCK);
297 /* cannot open logfile? - print to /dev/console then */
298 int fd = device_open(_PATH_CONSOLE, O_WRONLY | O_NOCTTY | O_NONBLOCK);
300 fd = 2; /* then stderr, dammit */
301 full_write(fd, msg, len);
306 #if ENABLE_FEATURE_ROTATE_LOGFILE
310 isRegular = (fstat(logFD, &statf) == 0 && (statf.st_mode & S_IFREG));
311 /* bug (mostly harmless): can wrap around if file > 4gb */
312 curFileSize = statf.st_size;
317 fl.l_whence = SEEK_SET;
321 fcntl(logFD, F_SETLKW, &fl);
323 #if ENABLE_FEATURE_ROTATE_LOGFILE
324 if (logFileSize && isRegular && curFileSize > logFileSize) {
325 if (logFileRotate) { /* always 0..99 */
326 int i = strlen(logFilePath) + 3 + 1;
329 i = logFileRotate - 1;
330 /* rename: f.8 -> f.9; f.7 -> f.8; ... */
332 sprintf(newFile, "%s.%d", logFilePath, i);
334 sprintf(oldFile, "%s.%d", logFilePath, --i);
335 rename(oldFile, newFile);
337 /* newFile == "f.0" now */
338 rename(logFilePath, newFile);
340 fcntl(logFD, F_SETLKW, &fl);
348 full_write(logFD, msg, len);
350 fcntl(logFD, F_SETLKW, &fl);
353 static void parse_fac_prio_20(int pri, char *res20)
358 c_fac = facilitynames;
359 while (c_fac->c_name) {
360 if (c_fac->c_val != (LOG_FAC(pri) << 3)) {
363 /* facility is found, look for prio */
364 c_pri = prioritynames;
365 while (c_pri->c_name) {
366 if (c_pri->c_val != LOG_PRI(pri)) {
369 snprintf(res20, 20, "%s.%s",
370 c_fac->c_name, c_pri->c_name);
373 /* prio not found, bail out */
376 snprintf(res20, 20, "<%d>", pri);
380 /* len parameter is used only for "is there a timestamp?" check.
381 * NB: some callers cheat and supply 0 when they know
382 * that there is no timestamp, short-cutting the test. */
383 static void timestamp_and_log(int pri, char *msg, int len)
387 if (len < 16 || msg[3] != ' ' || msg[6] != ' '
388 || msg[9] != ':' || msg[12] != ':' || msg[15] != ' '
392 timestamp = ctime(&now) + 4;
397 timestamp[15] = '\0';
399 /* Log message locally (to file or shared mem) */
400 if (!ENABLE_FEATURE_REMOTE_LOG || (option_mask32 & OPT_locallog)) {
401 if (LOG_PRI(pri) < logLevel) {
402 if (option_mask32 & OPT_small)
403 sprintf(PRINTBUF, "%s %s\n", timestamp, msg);
406 parse_fac_prio_20(pri, res);
407 sprintf(PRINTBUF, "%s %s %s %s\n", timestamp, localHostName, res, msg);
409 log_locally(PRINTBUF);
414 static void split_escape_and_log(char *tmpbuf, int len)
422 int pri = (LOG_USER | LOG_NOTICE);
425 /* Parse the magic priority number */
426 pri = bb_strtou(p + 1, &p, 10);
428 if (pri & ~(LOG_FACMASK | LOG_PRIMASK)) {
429 pri = (LOG_USER | LOG_NOTICE);
438 c += '@'; /* ^@, ^A, ^B... */
444 timestamp_and_log(pri, PARSEBUF, q - PARSEBUF);
448 static void quit_signal(int sig)
450 timestamp_and_log(LOG_SYSLOG | LOG_INFO, "System log daemon exiting", 0);
451 puts("System log daemon exiting");
452 unlink(dev_log_name);
453 if (ENABLE_FEATURE_IPC_SYSLOG)
458 static void do_mark(int sig)
461 timestamp_and_log(LOG_SYSLOG | LOG_INFO, "-- MARK --", 0);
466 static void do_syslogd(void) ATTRIBUTE_NORETURN;
467 static void do_syslogd(void)
469 struct sockaddr_un sunx;
470 socklen_t addrLength;
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);
483 signal(SIGALRM, do_mark);
486 dev_log_name = xmalloc_realpath(_PATH_LOG);
488 dev_log_name = _PATH_LOG;
490 /* Unlink old /dev/log (or object it points to) */
491 unlink(dev_log_name);
493 memset(&sunx, 0, sizeof(sunx));
494 sunx.sun_family = AF_UNIX;
495 strncpy(sunx.sun_path, dev_log_name, sizeof(sunx.sun_path));
496 sock_fd = xsocket(AF_UNIX, SOCK_DGRAM, 0);
497 addrLength = sizeof(sunx.sun_family) + strlen(sunx.sun_path);
498 xbind(sock_fd, (struct sockaddr *) &sunx, addrLength);
500 if (chmod(dev_log_name, 0666) < 0) {
501 bb_perror_msg_and_die("cannot set permission on %s", dev_log_name);
503 if (ENABLE_FEATURE_IPC_SYSLOG && (option_mask32 & OPT_circularlog)) {
507 timestamp_and_log(LOG_SYSLOG | LOG_INFO, "syslogd started: BusyBox v" BB_VER, 0);
511 FD_SET(sock_fd, &fds);
513 if (select(sock_fd + 1, &fds, NULL, NULL, NULL) < 0) {
514 if (errno == EINTR) {
515 /* alarm may have happened */
518 bb_perror_msg_and_die("select");
521 if (FD_ISSET(sock_fd, &fds)) {
523 i = recv(sock_fd, RECVBUF, MAX_READ - 1, 0);
525 bb_perror_msg_and_die("UNIX socket error");
526 /* TODO: maybe suppress duplicates? */
527 #if ENABLE_FEATURE_REMOTE_LOG
528 /* We are not modifying log messages in any way before send */
529 /* Remote site cannot trust _us_ anyway and need to do validation again */
530 if (option_mask32 & OPT_remotelog) {
531 if (-1 == remoteFD) {
532 remoteFD = socket(AF_INET, SOCK_DGRAM, 0);
534 if (-1 != remoteFD) {
535 /* send message to remote logger, ignore possible error */
536 sendto(remoteFD, RECVBUF, i, MSG_DONTWAIT,
537 (struct sockaddr *) &remoteAddr,
543 split_escape_and_log(RECVBUF, i);
548 int syslogd_main(int argc, char **argv)
553 /* do normal option parsing */
554 opt_complementary = "=0"; /* no non-option params */
555 getopt32(argc, argv, OPTION_STR, OPTION_PARAM);
556 if (option_mask32 & OPT_mark) // -m
557 markInterval = xatou_range(opt_m, 0, INT_MAX/60) * 60;
558 //if (option_mask32 & OPT_nofork) // -n
559 //if (option_mask32 & OPT_outfile) // -O
560 if (option_mask32 & OPT_loglevel) // -l
561 logLevel = xatou_range(opt_l, 1, 8);
562 //if (option_mask32 & OPT_small) // -S
563 #if ENABLE_FEATURE_ROTATE_LOGFILE
564 if (option_mask32 & OPT_filesize) // -s
565 logFileSize = xatou_range(opt_s, 0, INT_MAX/1024) * 1024;
566 if (option_mask32 & OPT_rotatecnt) // -b
567 logFileRotate = xatou_range(opt_b, 0, 99);
569 #if ENABLE_FEATURE_REMOTE_LOG
570 if (option_mask32 & OPT_remotelog) { // -R
572 p = strchr(opt_R, ':');
577 /* FIXME: looks ip4-specific. need to do better */
578 bb_lookup_host(&remoteAddr, opt_R);
579 remoteAddr.sin_port = bb_lookup_port(port, "udp", port);
581 //if (option_mask32 & OPT_locallog) // -L
583 #if ENABLE_FEATURE_IPC_SYSLOG
584 if ((option_mask32 & OPT_circularlog) && opt_C) // -C
585 shm_size = xatoul_range(opt_C, 4, INT_MAX/1024) * 1024;
588 /* If they have not specified remote logging, then log locally */
589 if (ENABLE_FEATURE_REMOTE_LOG && !(option_mask32 & OPT_remotelog))
590 option_mask32 |= OPT_locallog;
592 /* Store away localhost's name before the fork */
593 gethostname(localHostName, sizeof(localHostName));
594 p = strchr(localHostName, '.');
599 if (!(option_mask32 & OPT_nofork)) {
601 vfork_daemon_rexec(0, 1, argc, argv, "-n");
608 /* return EXIT_SUCCESS; */