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;
60 /* NB: we may need 2x this amount on stack... */
61 enum { MAX_READ = 1024 };
65 /* Correct regardless of combination of CONFIG_xxx */
67 OPTBIT_mark = 0, // -m
70 OPTBIT_loglevel, // -l
72 USE_FEATURE_ROTATE_LOGFILE(OPTBIT_filesize ,) // -s
73 USE_FEATURE_ROTATE_LOGFILE(OPTBIT_rotatecnt ,) // -b
74 USE_FEATURE_REMOTE_LOG( OPTBIT_remote ,) // -R
75 USE_FEATURE_REMOTE_LOG( OPTBIT_localtoo ,) // -L
76 USE_FEATURE_IPC_SYSLOG( OPTBIT_circularlog,) // -C
78 OPT_mark = 1 << OPTBIT_mark ,
79 OPT_nofork = 1 << OPTBIT_nofork ,
80 OPT_outfile = 1 << OPTBIT_outfile ,
81 OPT_loglevel = 1 << OPTBIT_loglevel,
82 OPT_small = 1 << OPTBIT_small ,
83 OPT_filesize = USE_FEATURE_ROTATE_LOGFILE((1 << OPTBIT_filesize )) + 0,
84 OPT_rotatecnt = USE_FEATURE_ROTATE_LOGFILE((1 << OPTBIT_rotatecnt )) + 0,
85 OPT_remotelog = USE_FEATURE_REMOTE_LOG( (1 << OPTBIT_remote )) + 0,
86 OPT_locallog = USE_FEATURE_REMOTE_LOG( (1 << OPTBIT_localtoo )) + 0,
87 OPT_circularlog = USE_FEATURE_IPC_SYSLOG( (1 << OPTBIT_circularlog)) + 0,
89 #define OPTION_STR "m:nO:l:S" \
90 USE_FEATURE_ROTATE_LOGFILE("s:" ) \
91 USE_FEATURE_ROTATE_LOGFILE("b:" ) \
92 USE_FEATURE_REMOTE_LOG( "R:" ) \
93 USE_FEATURE_REMOTE_LOG( "L" ) \
94 USE_FEATURE_IPC_SYSLOG( "C::")
95 #define OPTION_DECL *opt_m, *opt_l \
96 USE_FEATURE_ROTATE_LOGFILE(,*opt_s) \
97 USE_FEATURE_ROTATE_LOGFILE(,*opt_b) \
98 USE_FEATURE_REMOTE_LOG( ,*opt_R) \
99 USE_FEATURE_IPC_SYSLOG( ,*opt_C = NULL)
100 #define OPTION_PARAM &opt_m, &logFilePath, &opt_l \
101 USE_FEATURE_ROTATE_LOGFILE(,&opt_s) \
102 USE_FEATURE_ROTATE_LOGFILE(,&opt_b) \
103 USE_FEATURE_REMOTE_LOG( ,&opt_R) \
104 USE_FEATURE_IPC_SYSLOG( ,&opt_C)
107 /* circular buffer variables/structures */
108 #if ENABLE_FEATURE_IPC_SYSLOG
111 #if CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE < 4
112 #error Sorry, you must set the syslogd buffer size to at least 4KB.
113 #error Please check CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE
121 #define KEY_ID ((long)0x414e4547) /* "GENA" */
123 // Semaphore operation structures
124 static struct shbuf_ds {
125 int32_t size; // size of data written
126 int32_t head; // start of message list
127 int32_t tail; // end of message list
128 char data[1]; // data/messages
129 } *shbuf; // shared memory pointer
131 static int shmid = -1; // ipc shared memory id
132 static int s_semid = -1; // ipc semaphore id
133 static int shm_size = ((CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE)*1024); // default shm size
135 static void ipcsyslog_cleanup(void)
141 shmctl(shmid, IPC_RMID, NULL);
144 semctl(s_semid, 0, IPC_RMID, 0);
148 static void ipcsyslog_init(void)
151 printf("shmget(%lx, %d,...)\n", KEY_ID, shm_size);
153 shmid = shmget(KEY_ID, shm_size, IPC_CREAT | 1023);
155 bb_perror_msg_and_die("shmget");
158 shbuf = shmat(shmid, NULL, 0);
160 bb_perror_msg_and_die("shmat");
163 shbuf->size = shm_size - offsetof(struct shbuf_ds, data);
164 shbuf->head = shbuf->tail = 0;
166 // we'll trust the OS to set initial semval to 0 (let's hope)
167 s_semid = semget(KEY_ID, 2, IPC_CREAT | IPC_EXCL | 1023);
169 if (errno == EEXIST) {
170 s_semid = semget(KEY_ID, 2, 0);
174 bb_perror_msg_and_die("semget");
178 /* write message to buffer */
179 static void log_to_shmem(const char *msg, int len)
181 static /*const*/ struct sembuf SMwup[1] = { {1, -1, IPC_NOWAIT} };
182 static /*const*/ struct sembuf SMwdn[3] = { {0, 0}, {1, 0}, {1, +1} };
184 int old_tail, new_tail;
187 if (semop(s_semid, SMwdn, 3) == -1) {
188 bb_perror_msg_and_die("SMwdn");
191 /* Circular Buffer Algorithm:
192 * --------------------------
193 * tail == position where to store next syslog message.
194 * head == position of next message to retrieve ("print").
195 * if head == tail, there is no "unprinted" messages left.
196 * head is typically advanced by separate "reader" program,
197 * but if there isn't one, we have to do it ourself.
198 * messages are NUL-separated.
200 len++; /* length with NUL included */
202 old_tail = shbuf->tail;
203 new_tail = old_tail + len;
204 if (new_tail < shbuf->size) {
205 /* No need to move head if shbuf->head <= old_tail,
207 if (old_tail < shbuf->head && shbuf->head <= new_tail) {
208 /* ...need to move head forward */
209 c = memchr(shbuf->data + new_tail, '\0',
210 shbuf->size - new_tail);
211 if (!c) /* no NUL ahead of us, wrap around */
212 c = memchr(shbuf->data, '\0', old_tail);
213 if (!c) { /* still nothing? point to this msg... */
214 shbuf->head = old_tail;
216 /* convert pointer to offset + skip NUL */
217 shbuf->head = c - shbuf->data + 1;
220 /* store message, set new tail */
221 memcpy(shbuf->data + old_tail, msg, len);
222 shbuf->tail = new_tail;
224 /* we need to break up the message and wrap it around */
225 /* k == available buffer space ahead of old tail */
226 int k = shbuf->size - old_tail - 1;
227 if (shbuf->head > old_tail) {
228 /* we are going to overwrite head, need to
229 * move it out of the way */
230 c = memchr(shbuf->data, '\0', old_tail);
231 if (!c) { /* nothing? point to this msg... */
232 shbuf->head = old_tail;
233 } else { /* convert pointer to offset + skip NUL */
234 shbuf->head = c - shbuf->data + 1;
237 /* copy what fits to the end of buffer, and repeat */
238 memcpy(shbuf->data + old_tail, msg, k);
244 if (semop(s_semid, SMwup, 1) == -1) {
245 bb_perror_msg_and_die("SMwup");
248 printf("head:%d tail:%d\n", shbuf->head, shbuf->tail);
251 void ipcsyslog_cleanup(void);
252 void ipcsyslog_init(void);
253 void log_to_shmem(const char *msg);
256 #endif /* FEATURE_IPC_SYSLOG */
259 /* Print a message to the log file. */
260 static void log_locally(char *msg)
265 int len = strlen(msg);
267 #if ENABLE_FEATURE_IPC_SYSLOG
268 if ((option_mask32 & OPT_circularlog) && shbuf) {
269 log_to_shmem(msg, len);
277 last = cur; /* reopen log file every second */
284 logFD = device_open(logFilePath, O_WRONLY | O_CREAT
285 | O_NOCTTY | O_APPEND | O_NONBLOCK);
287 /* cannot open logfile? - print to /dev/console then */
288 int fd = device_open(_PATH_CONSOLE, O_WRONLY | O_NOCTTY | O_NONBLOCK);
290 fd = 2; /* then stderr, dammit */
291 full_write(fd, msg, len);
296 #if ENABLE_FEATURE_ROTATE_LOGFILE
297 isRegular = (fstat(logFD, &statf) == 0 && (statf.st_mode & S_IFREG));
298 /* bug (mostly harmless): can wrap around if file > 4gb */
299 curFileSize = statf.st_size;
303 fl.l_whence = SEEK_SET;
307 fcntl(logFD, F_SETLKW, &fl);
309 #if ENABLE_FEATURE_ROTATE_LOGFILE
310 if (logFileSize && isRegular && curFileSize > logFileSize) {
311 if (logFileRotate) { /* always 0..99 */
312 int i = strlen(logFilePath) + 3 + 1;
315 i = logFileRotate - 1;
316 /* rename: f.8 -> f.9; f.7 -> f.8; ... */
318 sprintf(newFile, "%s.%d", logFilePath, i);
320 sprintf(oldFile, "%s.%d", logFilePath, --i);
321 rename(oldFile, newFile);
323 /* newFile == "f.0" now */
324 rename(logFilePath, newFile);
326 fcntl(logFD, F_SETLKW, &fl);
333 curFileSize += full_write(logFD, msg, len);
335 fcntl(logFD, F_SETLKW, &fl);
338 static void parse_fac_prio_20(int pri, char *res20)
343 c_fac = facilitynames;
344 while (c_fac->c_name) {
345 if (c_fac->c_val != (LOG_FAC(pri) << 3)) {
348 /* facility is found, look for prio */
349 c_pri = prioritynames;
350 while (c_pri->c_name) {
351 if (c_pri->c_val != LOG_PRI(pri)) {
354 snprintf(res20, 20, "%s.%s",
355 c_fac->c_name, c_pri->c_name);
358 /* prio not found, bail out */
361 snprintf(res20, 20, "<%d>", pri);
365 /* len parameter is used only for "is there a timestamp?" check
366 * NB: some callers cheat and supply 0 when they know
367 * that there is no timestamp, short-cutting the test */
368 static void timestamp_and_log(int pri, char *msg, int len)
373 if (len < 16 || msg[3] != ' ' || msg[6] != ' '
374 || msg[9] != ':' || msg[12] != ':' || msg[15] != ' '
377 timestamp = ctime(&now) + 4;
382 timestamp[15] = '\0';
384 /* Log message locally (to file or shared mem) */
385 if (!ENABLE_FEATURE_REMOTE_LOG || (option_mask32 & OPT_locallog)) {
386 if (LOG_PRI(pri) < logLevel) {
387 if (option_mask32 & OPT_small)
388 msg = xasprintf("%s %s\n", timestamp, msg);
391 parse_fac_prio_20(pri, res);
392 msg = xasprintf("%s %s %s %s\n", timestamp, localHostName, res, msg);
400 static void split_escape_and_log(char *tmpbuf, int len)
402 char line[len * 2 + 1]; /* gcc' cheap alloca */
409 int pri = (LOG_USER | LOG_NOTICE);
412 /* Parse the magic priority number. */
413 pri = bb_strtou(p + 1, &p, 10);
415 if (pri & ~(LOG_FACMASK | LOG_PRIMASK)) {
416 pri = (LOG_USER | LOG_NOTICE);
425 c += '@'; /* ^@, ^A, ^B... */
431 timestamp_and_log(pri, line, q - line);
435 static void quit_signal(int sig)
437 timestamp_and_log(LOG_SYSLOG | LOG_INFO, "System log daemon exiting", 0);
438 puts("System log daemon exiting");
439 unlink(dev_log_name);
440 if (ENABLE_FEATURE_IPC_SYSLOG)
445 static void do_mark(int sig)
448 timestamp_and_log(LOG_SYSLOG | LOG_INFO, "-- MARK --", 0);
453 static void do_syslogd(void) ATTRIBUTE_NORETURN;
454 static void do_syslogd(void)
456 struct sockaddr_un sunx;
457 socklen_t addrLength;
461 /* Set up signal handlers. */
462 signal(SIGINT, quit_signal);
463 signal(SIGTERM, quit_signal);
464 signal(SIGQUIT, quit_signal);
465 signal(SIGHUP, SIG_IGN);
466 signal(SIGCHLD, SIG_IGN);
468 signal(SIGCLD, SIG_IGN);
470 signal(SIGALRM, do_mark);
473 dev_log_name = xmalloc_realpath(_PATH_LOG);
475 dev_log_name = _PATH_LOG;
477 /* Unlink old /dev/log (or object it points to) */
478 unlink(dev_log_name);
480 memset(&sunx, 0, sizeof(sunx));
481 sunx.sun_family = AF_UNIX;
482 strncpy(sunx.sun_path, dev_log_name, sizeof(sunx.sun_path));
483 sock_fd = xsocket(AF_UNIX, SOCK_DGRAM, 0);
484 addrLength = sizeof(sunx.sun_family) + strlen(sunx.sun_path);
485 if (bind(sock_fd, (struct sockaddr *) &sunx, addrLength) < 0) {
486 bb_perror_msg_and_die("cannot connect to socket %s", dev_log_name);
489 if (chmod(dev_log_name, 0666) < 0) {
490 bb_perror_msg_and_die("cannot set permission on %s", dev_log_name);
492 if (ENABLE_FEATURE_IPC_SYSLOG && (option_mask32 & OPT_circularlog)) {
496 timestamp_and_log(LOG_SYSLOG | LOG_INFO, "syslogd started: BusyBox v" BB_VER, 0);
500 FD_SET(sock_fd, &fds);
502 if (select(sock_fd + 1, &fds, NULL, NULL, NULL) < 0) {
503 if (errno == EINTR) {
504 /* alarm may have happened. */
507 bb_perror_msg_and_die("select");
510 if (FD_ISSET(sock_fd, &fds)) {
512 #define tmpbuf bb_common_bufsiz1
513 i = recv(sock_fd, tmpbuf, MAX_READ, 0);
515 bb_perror_msg_and_die("UNIX socket error");
516 /* TODO: maybe supress duplicates? */
517 #if ENABLE_FEATURE_REMOTE_LOG
518 /* We are not modifying log messages in any way before send */
519 /* Remote site cannot trust _us_ anyway and need to do validation again */
520 if (option_mask32 & OPT_remotelog) {
521 if (-1 == remoteFD) {
522 remoteFD = socket(AF_INET, SOCK_DGRAM, 0);
524 if (-1 != remoteFD) {
525 /* send message to remote logger, ignore possible error */
526 sendto(remoteFD, tmpbuf, i, MSG_DONTWAIT,
527 (struct sockaddr *) &remoteAddr,
533 split_escape_and_log(tmpbuf, i);
539 int syslogd_main(int argc, char **argv)
544 /* do normal option parsing */
545 opt_complementary = "=0"; /* no non-option params */
546 getopt32(argc, argv, OPTION_STR, OPTION_PARAM);
547 if (option_mask32 & OPT_mark) // -m
548 markInterval = xatou_range(opt_m, 0, INT_MAX/60) * 60;
549 //if (option_mask32 & OPT_nofork) // -n
550 //if (option_mask32 & OPT_outfile) // -O
551 if (option_mask32 & OPT_loglevel) // -l
552 logLevel = xatou_range(opt_l, 1, 8);
553 //if (option_mask32 & OPT_small) // -S
554 #if ENABLE_FEATURE_ROTATE_LOGFILE
555 if (option_mask32 & OPT_filesize) // -s
556 logFileSize = xatou_range(opt_s, 0, INT_MAX/1024) * 1024;
557 if (option_mask32 & OPT_rotatecnt) // -b
558 logFileRotate = xatou_range(opt_b, 0, 99);
560 #if ENABLE_FEATURE_REMOTE_LOG
561 if (option_mask32 & OPT_remotelog) { // -R
563 p = strchr(opt_R, ':');
568 remoteAddr.sin_family = AF_INET;
569 /* FIXME: looks ip4-specific. need to do better */
570 remoteAddr.sin_addr = *(struct in_addr *) *(xgethostbyname(opt_R)->h_addr_list);
571 remoteAddr.sin_port = htons(port);
573 //if (option_mask32 & OPT_locallog) // -L
575 #if ENABLE_FEATURE_IPC_SYSLOG
576 if ((option_mask32 & OPT_circularlog) && opt_C) // -C
577 shm_size = xatoul_range(opt_C, 4, INT_MAX/1024) * 1024;
580 /* If they have not specified remote logging, then log locally */
581 if (ENABLE_FEATURE_REMOTE_LOG && !(option_mask32 & OPT_remotelog))
582 option_mask32 |= OPT_locallog;
584 /* Store away localhost's name before the fork */
585 gethostname(localHostName, sizeof(localHostName));
586 p = strchr(localHostName, '.');
591 if (!(option_mask32 & OPT_nofork)) {
593 vfork_daemon_rexec(0, 1, argc, argv, "-n");