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>
25 /* Path to the unix socket */
26 static char dev_log_name[MAXPATHLEN];
28 /* Path for the file where all log messages are written */
29 static const char *logFilePath = "/var/log/messages";
31 #if ENABLE_FEATURE_ROTATE_LOGFILE
32 /* max size of message file before being rotated */
33 static int logFileSize = 200 * 1024;
34 /* number of rotated message files */
35 static int logFileRotate = 1;
38 /* interval between marks in seconds */
39 static int markInterval = 20 * 60;
41 /* level of messages to be locally logged */
42 static int logLevel = 8;
44 /* localhost's name */
45 static char localHostName[64];
47 #if ENABLE_FEATURE_REMOTE_LOG
48 #include <netinet/in.h>
49 /* udp socket for logging to remote host */
50 static int remoteFD = -1;
51 static struct sockaddr_in remoteAddr;
55 /* NB: we may need 2x this amount on stack... */
56 enum { MAX_READ = 1024 };
60 /* Correct regardless of combination of CONFIG_xxx */
62 OPTBIT_mark = 0, // -m
65 OPTBIT_loglevel, // -l
67 USE_FEATURE_ROTATE_LOGFILE(OPTBIT_filesize ,) // -s
68 USE_FEATURE_ROTATE_LOGFILE(OPTBIT_rotatecnt ,) // -b
69 USE_FEATURE_REMOTE_LOG( OPTBIT_remote ,) // -R
70 USE_FEATURE_REMOTE_LOG( OPTBIT_localtoo ,) // -L
71 USE_FEATURE_IPC_SYSLOG( OPTBIT_circularlog,) // -C
73 OPT_mark = 1 << OPTBIT_mark ,
74 OPT_nofork = 1 << OPTBIT_nofork ,
75 OPT_outfile = 1 << OPTBIT_outfile ,
76 OPT_loglevel = 1 << OPTBIT_loglevel,
77 OPT_small = 1 << OPTBIT_small ,
78 OPT_filesize = USE_FEATURE_ROTATE_LOGFILE((1 << OPTBIT_filesize )) + 0,
79 OPT_rotatecnt = USE_FEATURE_ROTATE_LOGFILE((1 << OPTBIT_rotatecnt )) + 0,
80 OPT_remotelog = USE_FEATURE_REMOTE_LOG( (1 << OPTBIT_remote )) + 0,
81 OPT_locallog = USE_FEATURE_REMOTE_LOG( (1 << OPTBIT_localtoo )) + 0,
82 OPT_circularlog = USE_FEATURE_IPC_SYSLOG( (1 << OPTBIT_circularlog)) + 0,
84 #define OPTION_STR "m:nO:l:S" \
85 USE_FEATURE_ROTATE_LOGFILE("s:" ) \
86 USE_FEATURE_ROTATE_LOGFILE("b:" ) \
87 USE_FEATURE_REMOTE_LOG( "R:" ) \
88 USE_FEATURE_REMOTE_LOG( "L" ) \
89 USE_FEATURE_IPC_SYSLOG( "C::")
90 #define OPTION_DECL *opt_m, *opt_l \
91 USE_FEATURE_ROTATE_LOGFILE(,*opt_s) \
92 USE_FEATURE_ROTATE_LOGFILE(,*opt_b) \
93 USE_FEATURE_REMOTE_LOG( ,*opt_R) \
94 USE_FEATURE_IPC_SYSLOG( ,*opt_C = NULL)
95 #define OPTION_PARAM &opt_m, &logFilePath, &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)
102 /* circular buffer variables/structures */
103 #if ENABLE_FEATURE_IPC_SYSLOG
106 #if CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE < 4
107 #error Sorry, you must set the syslogd buffer size to at least 4KB.
108 #error Please check CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE
116 #define KEY_ID ((long)0x414e4547) /* "GENA" */
118 // Semaphore operation structures
119 static struct shbuf_ds {
120 int32_t size; // size of data written
121 int32_t head; // start of message list
122 int32_t tail; // end of message list
123 char data[1]; // data/messages
124 } *shbuf; // shared memory pointer
126 static int shmid = -1; // ipc shared memory id
127 static int s_semid = -1; // ipc semaphore id
128 static int shm_size = ((CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE)*1024); // default shm size
130 static void ipcsyslog_cleanup(void)
136 shmctl(shmid, IPC_RMID, NULL);
139 semctl(s_semid, 0, IPC_RMID, 0);
143 static void ipcsyslog_init(void)
145 shmid = shmget(KEY_ID, shm_size, IPC_CREAT | 1023);
147 bb_perror_msg_and_die("shmget");
150 shbuf = shmat(shmid, NULL, 0);
152 bb_perror_msg_and_die("shmat");
155 shbuf->size = shm_size - offsetof(struct shbuf_ds, data);
156 shbuf->head = shbuf->tail = 0;
158 // we'll trust the OS to set initial semval to 0 (let's hope)
159 s_semid = semget(KEY_ID, 2, IPC_CREAT | IPC_EXCL | 1023);
161 if (errno == EEXIST) {
162 s_semid = semget(KEY_ID, 2, 0);
166 bb_perror_msg_and_die("semget");
170 /* write message to buffer */
171 static void log_to_shmem(const char *msg, int len)
173 static /*const*/ struct sembuf SMwup[1] = { {1, -1, IPC_NOWAIT} };
174 static /*const*/ struct sembuf SMwdn[3] = { {0, 0}, {1, 0}, {1, +1} };
176 int old_tail, new_tail;
179 if (semop(s_semid, SMwdn, 3) == -1) {
180 bb_perror_msg_and_die("SMwdn");
183 /* Circular Buffer Algorithm:
184 * --------------------------
185 * tail == position where to store next syslog message.
186 * head == position of next message to retrieve ("print").
187 * if head == tail, there is no "unprinted" messages left.
188 * head is typically advanced by separate "reader" program,
189 * but if there isn't one, we have to do it ourself.
190 * messages are NUL-separated.
192 len++; /* length with NUL included */
194 old_tail = shbuf->tail;
195 new_tail = old_tail + len;
196 if (new_tail < shbuf->size) {
197 /* No need to move head if shbuf->head <= old_tail,
199 if (old_tail < shbuf->head && shbuf->head <= new_tail) {
200 /* ...need to move head forward */
201 c = memchr(shbuf->data + new_tail, '\0',
202 shbuf->size - new_tail);
203 if (!c) /* no NUL ahead of us, wrap around */
204 c = memchr(shbuf->data, '\0', old_tail);
205 if (!c) { /* still nothing? point to this msg... */
206 shbuf->head = old_tail;
208 /* convert pointer to offset + skip NUL */
209 shbuf->head = c - shbuf->data + 1;
212 /* store message, set new tail */
213 memcpy(shbuf->data + old_tail, msg, len);
214 shbuf->tail = new_tail;
216 /* we need to break up the message and wrap it around */
217 /* k == available buffer space ahead of old tail */
218 int k = shbuf->size - old_tail - 1;
219 if (shbuf->head > old_tail) {
220 /* we are going to overwrite head, need to
221 * move it out of the way */
222 c = memchr(shbuf->data, '\0', old_tail);
223 if (!c) { /* nothing? point to this msg... */
224 shbuf->head = old_tail;
225 } else { /* convert pointer to offset + skip NUL */
226 shbuf->head = c - shbuf->data + 1;
229 /* copy what fits to the end of buffer, and repeat */
230 memcpy(shbuf->data + old_tail, msg, k);
236 if (semop(s_semid, SMwup, 1) == -1) {
237 bb_perror_msg_and_die("SMwup");
241 void ipcsyslog_cleanup(void);
242 void ipcsyslog_init(void);
243 void log_to_shmem(const char *msg);
246 #endif /* FEATURE_IPC_SYSLOG */
249 /* Print a message to the log file. */
250 static void log_locally(char *msg)
252 int fd, len = strlen(msg);
254 #if ENABLE_FEATURE_IPC_SYSLOG
255 if ((option_mask32 & OPT_circularlog) && shbuf) {
256 log_to_shmem(msg, len);
262 fd = device_open(logFilePath, O_WRONLY | O_CREAT
263 | O_NOCTTY | O_APPEND | O_NONBLOCK);
267 fl.l_whence = SEEK_SET;
271 fcntl(fd, F_SETLKW, &fl);
273 #if ENABLE_FEATURE_ROTATE_LOGFILE
276 int r = fstat(fd, &statf);
277 if (!r && (statf.st_mode & S_IFREG)
278 && (lseek(fd, 0, SEEK_END) > logFileSize)
280 if (logFileRotate) { /* always 0..99 */
281 int i = strlen(logFilePath) + 3 + 1;
284 i = logFileRotate - 1;
285 /* rename: f.8 -> f.9; f.7 -> f.8; ... */
287 sprintf(newFile, "%s.%d", logFilePath, i);
289 sprintf(oldFile, "%s.%d", logFilePath, --i);
290 rename(oldFile, newFile);
292 /* newFile == "f.0" now */
293 rename(logFilePath, newFile);
295 fcntl(fd, F_SETLKW, &fl);
303 full_write(fd, msg, len);
305 fcntl(fd, F_SETLKW, &fl);
308 /* cannot open logfile? - print to /dev/console then */
309 fd = device_open(_PATH_CONSOLE, O_WRONLY | O_NOCTTY | O_NONBLOCK);
311 fd = 2; /* then stderr, dammit */
312 full_write(fd, msg, len);
318 static void parse_fac_prio_20(int pri, char *res20)
323 c_fac = facilitynames;
324 while (c_fac->c_name) {
325 if (c_fac->c_val != (LOG_FAC(pri) << 3)) {
328 /* facility is found, look for prio */
329 c_pri = prioritynames;
330 while (c_pri->c_name) {
331 if (c_pri->c_val != LOG_PRI(pri)) {
334 snprintf(res20, 20, "%s.%s",
335 c_fac->c_name, c_pri->c_name);
338 /* prio not found, bail out */
341 snprintf(res20, 20, "<%d>", pri);
345 /* len parameter is used only for "is there a timestamp?" check
346 * NB: some callers cheat and supply 0 when they know
347 * that there is no timestamp, short-cutting the test */
348 static void timestamp_and_log(int pri, char *msg, int len)
353 if (len < 16 || msg[3] != ' ' || msg[6] != ' '
354 || msg[9] != ':' || msg[12] != ':' || msg[15] != ' '
357 timestamp = ctime(&now) + 4;
362 timestamp[15] = '\0';
364 /* Log message locally (to file or shared mem) */
365 if (!ENABLE_FEATURE_REMOTE_LOG || (option_mask32 & OPT_locallog)) {
366 if (LOG_PRI(pri) < logLevel) {
367 if (option_mask32 & OPT_small)
368 msg = xasprintf("%s %s\n", timestamp, msg);
371 parse_fac_prio_20(pri, res);
372 msg = xasprintf("%s %s %s %s\n", timestamp, localHostName, res, msg);
380 static void split_escape_and_log(char *tmpbuf, int len)
382 char line[len * 2 + 1]; /* gcc' cheap alloca */
389 int pri = (LOG_USER | LOG_NOTICE);
392 /* Parse the magic priority number. */
393 pri = bb_strtou(p + 1, &p, 10);
395 if (pri & ~(LOG_FACMASK | LOG_PRIMASK)) {
396 pri = (LOG_USER | LOG_NOTICE);
405 c += '@'; /* ^@, ^A, ^B... */
411 timestamp_and_log(pri, line, q - line);
415 static void quit_signal(int sig)
417 timestamp_and_log(LOG_SYSLOG | LOG_INFO, "System log daemon exiting", 0);
418 puts("System log daemon exiting");
419 unlink(dev_log_name);
420 if (ENABLE_FEATURE_IPC_SYSLOG)
425 static void do_mark(int sig)
428 timestamp_and_log(LOG_SYSLOG | LOG_INFO, "-- MARK --", 0);
433 static void do_syslogd(void) ATTRIBUTE_NORETURN;
434 static void do_syslogd(void)
436 struct sockaddr_un sunx;
437 socklen_t addrLength;
441 /* Set up signal handlers. */
442 signal(SIGINT, quit_signal);
443 signal(SIGTERM, quit_signal);
444 signal(SIGQUIT, quit_signal);
445 signal(SIGHUP, SIG_IGN);
446 signal(SIGCHLD, SIG_IGN);
448 signal(SIGCLD, SIG_IGN);
450 signal(SIGALRM, do_mark);
453 /* Unlink old /dev/log (or object it points to) */
454 if (realpath(_PATH_LOG, dev_log_name) != NULL) {
455 unlink(dev_log_name);
458 memset(&sunx, 0, sizeof(sunx));
459 sunx.sun_family = AF_UNIX;
460 strncpy(sunx.sun_path, dev_log_name, sizeof(sunx.sun_path));
461 sock_fd = xsocket(AF_UNIX, SOCK_DGRAM, 0);
462 addrLength = sizeof(sunx.sun_family) + strlen(sunx.sun_path);
463 if (bind(sock_fd, (struct sockaddr *) &sunx, addrLength) < 0) {
464 bb_perror_msg_and_die("cannot connect to socket %s", dev_log_name);
467 if (chmod(dev_log_name, 0666) < 0) {
468 bb_perror_msg_and_die("cannot set permission on %s", dev_log_name);
470 if (ENABLE_FEATURE_IPC_SYSLOG && (option_mask32 & OPT_circularlog)) {
474 timestamp_and_log(LOG_SYSLOG | LOG_INFO, "syslogd started: BusyBox v" BB_VER, 0);
478 FD_SET(sock_fd, &fds);
480 if (select(sock_fd + 1, &fds, NULL, NULL, NULL) < 0) {
481 if (errno == EINTR) {
482 /* alarm may have happened. */
485 bb_perror_msg_and_die("select");
488 if (FD_ISSET(sock_fd, &fds)) {
490 #define tmpbuf bb_common_bufsiz1
491 i = recv(sock_fd, tmpbuf, MAX_READ, 0);
493 bb_perror_msg_and_die("UNIX socket error");
494 /* TODO: maybe supress duplicates? */
495 #if ENABLE_FEATURE_REMOTE_LOG
496 /* We are not modifying log messages in any way before send */
497 /* Remote site cannot trust _us_ anyway and need to do validation again */
498 if (option_mask32 & OPT_remotelog) {
499 if (-1 == remoteFD) {
500 remoteFD = socket(AF_INET, SOCK_DGRAM, 0);
502 if (-1 != remoteFD) {
503 /* send message to remote logger, ignore possible error */
504 sendto(remoteFD, tmpbuf, i, MSG_DONTWAIT,
505 (struct sockaddr *) &remoteAddr,
511 split_escape_and_log(tmpbuf, i);
517 int syslogd_main(int argc, char **argv)
522 /* do normal option parsing */
523 getopt32(argc, argv, OPTION_STR, OPTION_PARAM);
524 if (option_mask32 & OPT_mark) // -m
525 markInterval = xatou_range(opt_m, 0, INT_MAX/60) * 60;
526 //if (option_mask32 & OPT_nofork) // -n
527 //if (option_mask32 & OPT_outfile) // -O
528 if (option_mask32 & OPT_loglevel) // -l
529 logLevel = xatou_range(opt_l, 1, 8);
530 //if (option_mask32 & OPT_small) // -S
531 #if ENABLE_FEATURE_ROTATE_LOGFILE
532 if (option_mask32 & OPT_filesize) // -s
533 logFileSize = xatou_range(opt_s, 0, INT_MAX/1024) * 1024;
534 if (option_mask32 & OPT_rotatecnt) // -b
535 logFileRotate = xatou_range(opt_b, 0, 99);
537 #if ENABLE_FEATURE_REMOTE_LOG
538 if (option_mask32 & OPT_remotelog) { // -R
540 p = strchr(opt_R, ':');
545 remoteAddr.sin_family = AF_INET;
546 /* FIXME: looks ip4-specific. need to do better */
547 remoteAddr.sin_addr = *(struct in_addr *) *(xgethostbyname(opt_R)->h_addr_list);
548 remoteAddr.sin_port = htons(port);
550 //if (option_mask32 & OPT_locallog) // -L
552 #if ENABLE_FEATURE_IPC_SYSLOG
553 if ((option_mask32 & OPT_circularlog) && opt_C) // -C
554 shm_size = xatoul_range(opt_C, 4, INT_MAX/1024) * 1024;
557 /* If they have not specified remote logging, then log locally */
558 if (ENABLE_FEATURE_REMOTE_LOG && !(option_mask32 & OPT_remotelog))
559 option_mask32 |= OPT_locallog;
561 /* Store away localhost's name before the fork */
562 gethostname(localHostName, sizeof(localHostName));
563 p = strchr(localHostName, '.');
568 if (!(option_mask32 & OPT_nofork)) {
570 vfork_daemon_rexec(0, 1, argc, argv, "-n");