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 */
295 logFD = device_open(logFilePath, O_WRONLY | O_CREAT
296 | O_NOCTTY | O_APPEND | O_NONBLOCK);
298 /* cannot open logfile? - print to /dev/console then */
299 int fd = device_open(_PATH_CONSOLE, O_WRONLY | O_NOCTTY | O_NONBLOCK);
301 fd = 2; /* then stderr, dammit */
302 full_write(fd, msg, len);
307 #if ENABLE_FEATURE_ROTATE_LOGFILE
308 isRegular = (fstat(logFD, &statf) == 0 && (statf.st_mode & S_IFREG));
309 /* bug (mostly harmless): can wrap around if file > 4gb */
310 curFileSize = statf.st_size;
314 fl.l_whence = SEEK_SET;
318 fcntl(logFD, F_SETLKW, &fl);
320 #if ENABLE_FEATURE_ROTATE_LOGFILE
321 if (logFileSize && isRegular && curFileSize > logFileSize) {
322 if (logFileRotate) { /* always 0..99 */
323 int i = strlen(logFilePath) + 3 + 1;
326 i = logFileRotate - 1;
327 /* rename: f.8 -> f.9; f.7 -> f.8; ... */
329 sprintf(newFile, "%s.%d", logFilePath, i);
331 sprintf(oldFile, "%s.%d", logFilePath, --i);
332 rename(oldFile, newFile);
334 /* newFile == "f.0" now */
335 rename(logFilePath, newFile);
337 fcntl(logFD, F_SETLKW, &fl);
344 curFileSize += full_write(logFD, msg, len);
346 fcntl(logFD, F_SETLKW, &fl);
349 static void parse_fac_prio_20(int pri, char *res20)
354 c_fac = facilitynames;
355 while (c_fac->c_name) {
356 if (c_fac->c_val != (LOG_FAC(pri) << 3)) {
359 /* facility is found, look for prio */
360 c_pri = prioritynames;
361 while (c_pri->c_name) {
362 if (c_pri->c_val != LOG_PRI(pri)) {
365 snprintf(res20, 20, "%s.%s",
366 c_fac->c_name, c_pri->c_name);
369 /* prio not found, bail out */
372 snprintf(res20, 20, "<%d>", pri);
376 /* len parameter is used only for "is there a timestamp?" check.
377 * NB: some callers cheat and supply 0 when they know
378 * that there is no timestamp, short-cutting the test. */
379 static void timestamp_and_log(int pri, char *msg, int len)
384 if (len < 16 || msg[3] != ' ' || msg[6] != ' '
385 || msg[9] != ':' || msg[12] != ':' || msg[15] != ' '
388 timestamp = ctime(&now) + 4;
393 timestamp[15] = '\0';
395 /* Log message locally (to file or shared mem) */
396 if (!ENABLE_FEATURE_REMOTE_LOG || (option_mask32 & OPT_locallog)) {
397 if (LOG_PRI(pri) < logLevel) {
398 if (option_mask32 & OPT_small)
399 sprintf(PRINTBUF, "%s %s\n", timestamp, msg);
402 parse_fac_prio_20(pri, res);
403 sprintf(PRINTBUF, "%s %s %s %s\n", timestamp, localHostName, res, msg);
405 log_locally(PRINTBUF);
410 static void split_escape_and_log(char *tmpbuf, int len)
418 int pri = (LOG_USER | LOG_NOTICE);
421 /* Parse the magic priority number */
422 pri = bb_strtou(p + 1, &p, 10);
424 if (pri & ~(LOG_FACMASK | LOG_PRIMASK)) {
425 pri = (LOG_USER | LOG_NOTICE);
434 c += '@'; /* ^@, ^A, ^B... */
440 timestamp_and_log(pri, PARSEBUF, q - PARSEBUF);
444 static void quit_signal(int sig)
446 timestamp_and_log(LOG_SYSLOG | LOG_INFO, "System log daemon exiting", 0);
447 puts("System log daemon exiting");
448 unlink(dev_log_name);
449 if (ENABLE_FEATURE_IPC_SYSLOG)
454 static void do_mark(int sig)
457 timestamp_and_log(LOG_SYSLOG | LOG_INFO, "-- MARK --", 0);
462 static void do_syslogd(void) ATTRIBUTE_NORETURN;
463 static void do_syslogd(void)
465 struct sockaddr_un sunx;
466 socklen_t addrLength;
470 /* Set up signal handlers */
471 signal(SIGINT, quit_signal);
472 signal(SIGTERM, quit_signal);
473 signal(SIGQUIT, quit_signal);
474 signal(SIGHUP, SIG_IGN);
475 signal(SIGCHLD, SIG_IGN);
477 signal(SIGCLD, SIG_IGN);
479 signal(SIGALRM, do_mark);
482 dev_log_name = xmalloc_realpath(_PATH_LOG);
484 dev_log_name = _PATH_LOG;
486 /* Unlink old /dev/log (or object it points to) */
487 unlink(dev_log_name);
489 memset(&sunx, 0, sizeof(sunx));
490 sunx.sun_family = AF_UNIX;
491 strncpy(sunx.sun_path, dev_log_name, sizeof(sunx.sun_path));
492 sock_fd = xsocket(AF_UNIX, SOCK_DGRAM, 0);
493 addrLength = sizeof(sunx.sun_family) + strlen(sunx.sun_path);
494 if (bind(sock_fd, (struct sockaddr *) &sunx, addrLength) < 0) {
495 bb_perror_msg_and_die("cannot connect to socket %s", dev_log_name);
498 if (chmod(dev_log_name, 0666) < 0) {
499 bb_perror_msg_and_die("cannot set permission on %s", dev_log_name);
501 if (ENABLE_FEATURE_IPC_SYSLOG && (option_mask32 & OPT_circularlog)) {
505 timestamp_and_log(LOG_SYSLOG | LOG_INFO, "syslogd started: BusyBox v" BB_VER, 0);
509 FD_SET(sock_fd, &fds);
511 if (select(sock_fd + 1, &fds, NULL, NULL, NULL) < 0) {
512 if (errno == EINTR) {
513 /* alarm may have happened */
516 bb_perror_msg_and_die("select");
519 if (FD_ISSET(sock_fd, &fds)) {
521 i = recv(sock_fd, RECVBUF, MAX_READ - 1, 0);
523 bb_perror_msg_and_die("UNIX socket error");
524 /* TODO: maybe suppress duplicates? */
525 #if ENABLE_FEATURE_REMOTE_LOG
526 /* We are not modifying log messages in any way before send */
527 /* Remote site cannot trust _us_ anyway and need to do validation again */
528 if (option_mask32 & OPT_remotelog) {
529 if (-1 == remoteFD) {
530 remoteFD = socket(AF_INET, SOCK_DGRAM, 0);
532 if (-1 != remoteFD) {
533 /* send message to remote logger, ignore possible error */
534 sendto(remoteFD, RECVBUF, i, MSG_DONTWAIT,
535 (struct sockaddr *) &remoteAddr,
541 split_escape_and_log(RECVBUF, i);
546 int syslogd_main(int argc, char **argv)
551 /* do normal option parsing */
552 opt_complementary = "=0"; /* no non-option params */
553 getopt32(argc, argv, OPTION_STR, OPTION_PARAM);
554 if (option_mask32 & OPT_mark) // -m
555 markInterval = xatou_range(opt_m, 0, INT_MAX/60) * 60;
556 //if (option_mask32 & OPT_nofork) // -n
557 //if (option_mask32 & OPT_outfile) // -O
558 if (option_mask32 & OPT_loglevel) // -l
559 logLevel = xatou_range(opt_l, 1, 8);
560 //if (option_mask32 & OPT_small) // -S
561 #if ENABLE_FEATURE_ROTATE_LOGFILE
562 if (option_mask32 & OPT_filesize) // -s
563 logFileSize = xatou_range(opt_s, 0, INT_MAX/1024) * 1024;
564 if (option_mask32 & OPT_rotatecnt) // -b
565 logFileRotate = xatou_range(opt_b, 0, 99);
567 #if ENABLE_FEATURE_REMOTE_LOG
568 if (option_mask32 & OPT_remotelog) { // -R
570 p = strchr(opt_R, ':');
575 remoteAddr.sin_family = AF_INET;
576 /* FIXME: looks ip4-specific. need to do better */
577 remoteAddr.sin_addr = *(struct in_addr *) *(xgethostbyname(opt_R)->h_addr_list);
578 remoteAddr.sin_port = htons(port);
580 //if (option_mask32 & OPT_locallog) // -L
582 #if ENABLE_FEATURE_IPC_SYSLOG
583 if ((option_mask32 & OPT_circularlog) && opt_C) // -C
584 shm_size = xatoul_range(opt_C, 4, INT_MAX/1024) * 1024;
587 /* If they have not specified remote logging, then log locally */
588 if (ENABLE_FEATURE_REMOTE_LOG && !(option_mask32 & OPT_remotelog))
589 option_mask32 |= OPT_locallog;
591 /* Store away localhost's name before the fork */
592 gethostname(localHostName, sizeof(localHostName));
593 p = strchr(localHostName, '.');
598 if (!(option_mask32 & OPT_nofork)) {
600 vfork_daemon_rexec(0, 1, argc, argv, "-n");
607 /* return EXIT_SUCCESS; */