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.
31 #include <sys/socket.h>
32 #include <sys/types.h>
34 #include <sys/param.h>
36 /* SYSLOG_NAMES defined to pull some extra junk from syslog.h */
38 #include <sys/syslog.h>
41 /* Path for the file where all log messages are written */
42 #define __LOG_FILE "/var/log/messages"
44 /* Path to the unix socket */
45 static char lfile[MAXPATHLEN];
47 static const char *logFilePath = __LOG_FILE;
49 #ifdef CONFIG_FEATURE_ROTATE_LOGFILE
50 /* max size of message file before being rotated */
51 static int logFileSize = 200 * 1024;
53 /* number of rotated message files */
54 static int logFileRotate = 1;
57 /* interval between marks in seconds */
58 static int MarkInterval = 20 * 60;
60 /* localhost's name */
61 static char LocalHostName[64];
63 #ifdef CONFIG_FEATURE_REMOTE_LOG
64 #include <netinet/in.h>
65 /* udp socket for logging to remote host */
66 static int remotefd = -1;
67 static struct sockaddr_in remoteaddr;
69 /* where do we log? */
70 static char *RemoteHost;
72 /* what port to log to? */
73 static int RemotePort = 514;
75 /* To remote log or not to remote log, that is the question. */
76 static int doRemoteLog = FALSE;
77 static int local_logging = FALSE;
80 /* Make loging output smaller. */
81 static bool small = false;
84 #define MAXLINE 1024 /* maximum line length */
87 /* circular buffer variables/structures */
88 #ifdef CONFIG_FEATURE_IPC_SYSLOG
90 #if CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE < 4
91 #error Sorry, you must set the syslogd buffer size to at least 4KB.
92 #error Please check CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE
100 static const long KEY_ID = 0x414e4547; /*"GENA" */
102 // Semaphore operation structures
103 static struct shbuf_ds {
104 int size; // size of data written
105 int head; // start of message list
106 int tail; // end of message list
107 char data[1]; // data/messages
108 } *buf = NULL; // shared memory pointer
110 static struct sembuf SMwup[1] = { {1, -1, IPC_NOWAIT} }; // set SMwup
111 static struct sembuf SMwdn[3] = { {0, 0}, {1, 0}, {1, +1} }; // set SMwdn
113 static int shmid = -1; // ipc shared memory id
114 static int s_semid = -1; // ipc semaphore id
115 static int shm_size = ((CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE)*1024); // default shm size
116 static int circular_logging = FALSE;
119 * sem_up - up()'s a semaphore.
121 static inline void sem_up(int semid)
123 if (semop(semid, SMwup, 1) == -1) {
124 bb_perror_msg_and_die("semop[SMwup]");
129 * sem_down - down()'s a semaphore
131 static inline void sem_down(int semid)
133 if (semop(semid, SMwdn, 3) == -1) {
134 bb_perror_msg_and_die("semop[SMwdn]");
139 static void ipcsyslog_cleanup(void)
141 printf("Exiting Syslogd!\n");
147 shmctl(shmid, IPC_RMID, NULL);
150 semctl(s_semid, 0, IPC_RMID, 0);
154 static void ipcsyslog_init(void)
157 if ((shmid = shmget(KEY_ID, shm_size, IPC_CREAT | 1023)) == -1) {
158 bb_perror_msg_and_die("shmget");
161 if ((buf = shmat(shmid, NULL, 0)) == NULL) {
162 bb_perror_msg_and_die("shmat");
165 buf->size = shm_size - sizeof(*buf);
166 buf->head = buf->tail = 0;
168 // we'll trust the OS to set initial semval to 0 (let's hope)
169 if ((s_semid = semget(KEY_ID, 2, IPC_CREAT | IPC_EXCL | 1023)) == -1) {
170 if (errno == EEXIST) {
171 if ((s_semid = semget(KEY_ID, 2, 0)) == -1) {
172 bb_perror_msg_and_die("semget");
175 bb_perror_msg_and_die("semget");
179 printf("Buffer already allocated just grab the semaphore?");
183 /* write message to buffer */
184 static void circ_message(const char *msg)
186 int l = strlen(msg) + 1; /* count the whole message w/ '\0' included */
191 * Circular Buffer Algorithm:
192 * --------------------------
194 * Start-off w/ empty buffer of specific size SHM_SIZ
195 * Start filling it up w/ messages. I use '\0' as separator to break up messages.
196 * This is also very handy since we can do printf on message.
198 * Once the buffer is full we need to get rid of the first message in buffer and
199 * insert the new message. (Note: if the message being added is >1 message then
200 * we will need to "remove" >1 old message from the buffer). The way this is done
202 * When we reach the end of the buffer we set a mark and start from the beginning.
203 * Now what about the beginning and end of the buffer? Well we have the "head"
204 * index/pointer which is the starting point for the messages and we have "tail"
205 * index/pointer which is the ending point for the messages. When we "display" the
206 * messages we start from the beginning and continue until we reach "tail". If we
207 * reach end of buffer, then we just start from the beginning (offset 0). "head" and
208 * "tail" are actually offsets from the beginning of the buffer.
210 * Note: This algorithm uses Linux IPC mechanism w/ shared memory and semaphores to provide
211 * a threadsafe way of handling shared memory operations.
213 if ((buf->tail + l) < buf->size) {
214 /* before we append the message we need to check the HEAD so that we won't
215 overwrite any of the message that we still need and adjust HEAD to point
216 to the next message! */
217 if (buf->tail < buf->head) {
218 if ((buf->tail + l) >= buf->head) {
219 /* we need to move the HEAD to point to the next message
220 * Theoretically we have enough room to add the whole message to the
221 * buffer, because of the first outer IF statement, so we don't have
222 * to worry about overflows here!
224 int k = buf->tail + l - buf->head; /* we need to know how many bytes
225 we are overwriting to make
228 memchr(buf->data + buf->head + k, '\0',
229 buf->size - (buf->head + k));
230 if (c != NULL) { /* do a sanity check just in case! */
231 buf->head = c - buf->data + 1; /* we need to convert pointer to
232 offset + skip the '\0' since
233 we need to point to the beginning
234 of the next message */
235 /* Note: HEAD is only used to "retrieve" messages, it's not used
236 when writing messages into our buffer */
237 } else { /* show an error message to know we messed up? */
238 printf("Weird! Can't find the terminator token?\n");
244 /* in other cases no overflows have been done yet, so we don't care! */
245 /* we should be ok to append the message now */
246 strncpy(buf->data + buf->tail, msg, l); /* append our message */
247 buf->tail += l; /* count full message w/ '\0' terminating char */
249 /* we need to break up the message and "circle" it around */
251 int k = buf->tail + l - buf->size; /* count # of bytes we don't fit */
253 /* We need to move HEAD! This is always the case since we are going
254 * to "circle" the message.
256 c = memchr(buf->data + k, '\0', buf->size - k);
258 if (c != NULL) { /* if we don't have '\0'??? weird!!! */
259 /* move head pointer */
260 buf->head = c - buf->data + 1;
262 /* now write the first part of the message */
263 strncpy(buf->data + buf->tail, msg, l - k - 1);
265 /* ALWAYS terminate end of buffer w/ '\0' */
266 buf->data[buf->size - 1] = '\0';
268 /* now write out the rest of the string to the beginning of the buffer */
269 strcpy(buf->data, &msg[l - k - 1]);
271 /* we need to place the TAIL at the end of the message */
275 ("Weird! Can't find the terminator token from the beginning?\n");
276 buf->head = buf->tail = 0; /* reset buffer, since it's probably corrupted */
282 #endif /* CONFIG_FEATURE_IPC_SYSLOG */
284 /* Note: There is also a function called "message()" in init.c */
285 /* Print a message to the log file. */
286 static void message(char *fmt, ...) __attribute__ ((format(printf, 1, 2)));
287 static void message(char *fmt, ...)
293 fl.l_whence = SEEK_SET;
297 #ifdef CONFIG_FEATURE_IPC_SYSLOG
298 if ((circular_logging == TRUE) && (buf != NULL)) {
301 va_start(arguments, fmt);
302 vsnprintf(b, sizeof(b) - 1, fmt, arguments);
308 if ((fd = device_open(logFilePath,
309 O_WRONLY | O_CREAT | O_NOCTTY | O_APPEND |
312 fcntl(fd, F_SETLKW, &fl);
313 #ifdef CONFIG_FEATURE_ROTATE_LOGFILE
314 if ( logFileSize > 0 ) {
316 int r = fstat(fd, &statf);
317 if( !r && (statf.st_mode & S_IFREG)
318 && (lseek(fd,0,SEEK_END) > logFileSize) ) {
319 if(logFileRotate > 0) {
321 char oldFile[(strlen(logFilePath)+4)], newFile[(strlen(logFilePath)+4)];
322 for(i=logFileRotate-1;i>0;i--) {
323 sprintf(oldFile, "%s.%d", logFilePath, i-1);
324 sprintf(newFile, "%s.%d", logFilePath, i);
325 rename(oldFile, newFile);
327 sprintf(newFile, "%s.%d", logFilePath, 0);
329 fcntl (fd, F_SETLKW, &fl);
331 rename(logFilePath, newFile);
332 fd = device_open (logFilePath,
333 O_WRONLY | O_CREAT | O_NOCTTY | O_APPEND |
336 fcntl (fd, F_SETLKW, &fl);
343 va_start(arguments, fmt);
344 vdprintf(fd, fmt, arguments);
347 fcntl(fd, F_SETLKW, &fl);
350 /* Always send console messages to /dev/console so people will see them. */
351 if ((fd = device_open(_PATH_CONSOLE,
352 O_WRONLY | O_NOCTTY | O_NONBLOCK)) >= 0) {
353 va_start(arguments, fmt);
354 vdprintf(fd, fmt, arguments);
358 fprintf(stderr, "Bummer, can't print: ");
359 va_start(arguments, fmt);
360 vfprintf(stderr, fmt, arguments);
367 #ifdef CONFIG_FEATURE_REMOTE_LOG
368 static void init_RemoteLog(void)
370 memset(&remoteaddr, 0, sizeof(remoteaddr));
371 remotefd = bb_xsocket(AF_INET, SOCK_DGRAM, 0);
372 remoteaddr.sin_family = AF_INET;
373 remoteaddr.sin_addr = *(struct in_addr *) *(xgethostbyname(RemoteHost))->h_addr_list;
374 remoteaddr.sin_port = htons(RemotePort);
378 static void logMessage(int pri, char *msg)
383 #ifdef CONFIG_FEATURE_REMOTE_LOG
384 static char line[MAXLINE + 1];
389 for (c_fac = facilitynames;
390 c_fac->c_name && !(c_fac->c_val == LOG_FAC(pri) << 3); c_fac++);
391 for (c_pri = prioritynames;
392 c_pri->c_name && !(c_pri->c_val == LOG_PRI(pri)); c_pri++);
393 if (c_fac->c_name == NULL || c_pri->c_name == NULL) {
394 snprintf(res, sizeof(res), "<%d>", pri);
396 snprintf(res, sizeof(res), "%s.%s", c_fac->c_name, c_pri->c_name);
400 if (strlen(msg) < 16 || msg[3] != ' ' || msg[6] != ' ' ||
401 msg[9] != ':' || msg[12] != ':' || msg[15] != ' ') {
403 timestamp = ctime(&now) + 4;
404 timestamp[15] = '\0';
407 timestamp[15] = '\0';
411 /* todo: supress duplicates */
413 #ifdef CONFIG_FEATURE_REMOTE_LOG
414 if (doRemoteLog == TRUE) {
415 /* trying connect the socket */
416 if (-1 == remotefd) {
420 /* if we have a valid socket, send the message */
421 if (-1 != remotefd) {
423 snprintf(line, sizeof(line), "<%d>%s", pri, msg);
426 /* send message to remote logger */
427 if(( -1 == sendto(remotefd, line, strlen(line), 0,
428 (struct sockaddr *) &remoteaddr,
429 sizeof(remoteaddr))) && (errno == EINTR)) {
430 /* sleep now seconds and retry (with now * 2) */
438 if (local_logging == TRUE)
441 /* now spew out the message to wherever it is supposed to go */
443 message("%s %s\n", timestamp, msg);
445 message("%s %s %s %s\n", timestamp, LocalHostName, res, msg);
449 static void quit_signal(int sig)
451 logMessage(LOG_SYSLOG | LOG_INFO, "System log daemon exiting.");
453 #ifdef CONFIG_FEATURE_IPC_SYSLOG
460 static void domark(int sig)
462 if (MarkInterval > 0) {
463 logMessage(LOG_SYSLOG | LOG_INFO, "-- MARK --");
468 /* This must be a #define, since when CONFIG_DEBUG and BUFFERS_GO_IN_BSS are
469 * enabled, we otherwise get a "storage size isn't constant error. */
470 static int serveConnection(char *tmpbuf, int n_read)
474 while (p < tmpbuf + n_read) {
476 int pri = (LOG_USER | LOG_NOTICE);
478 char line[MAXLINE + 1];
482 while ((c = *p) && q < &line[sizeof(line) - 1]) {
483 if (c == '<' && num_lt == 0) {
484 /* Parse the magic priority number. */
487 while (isdigit(*(++p))) {
488 pri = 10 * pri + (*p - '0');
490 if (pri & ~(LOG_FACMASK | LOG_PRIMASK)) {
491 pri = (LOG_USER | LOG_NOTICE);
493 } else if (c == '\n') {
495 } else if (iscntrl(c) && (c < 0177)) {
506 logMessage(pri, line);
511 static void doSyslogd(void) ATTRIBUTE_NORETURN;
512 static void doSyslogd(void)
514 struct sockaddr_un sunx;
515 socklen_t addrLength;
520 /* Set up signal handlers. */
521 signal(SIGINT, quit_signal);
522 signal(SIGTERM, quit_signal);
523 signal(SIGQUIT, quit_signal);
524 signal(SIGHUP, SIG_IGN);
525 signal(SIGCHLD, SIG_IGN);
527 signal(SIGCLD, SIG_IGN);
529 signal(SIGALRM, domark);
532 /* Create the syslog file so realpath() can work. */
533 if (realpath(_PATH_LOG, lfile) != NULL) {
537 memset(&sunx, 0, sizeof(sunx));
538 sunx.sun_family = AF_UNIX;
539 strncpy(sunx.sun_path, lfile, sizeof(sunx.sun_path));
540 sock_fd = bb_xsocket(AF_UNIX, SOCK_DGRAM, 0);
541 addrLength = sizeof(sunx.sun_family) + strlen(sunx.sun_path);
542 if (bind(sock_fd, (struct sockaddr *) &sunx, addrLength) < 0) {
543 bb_perror_msg_and_die("Could not connect to socket " _PATH_LOG);
546 if (chmod(lfile, 0666) < 0) {
547 bb_perror_msg_and_die("Could not set permission on " _PATH_LOG);
549 #ifdef CONFIG_FEATURE_IPC_SYSLOG
550 if (circular_logging == TRUE) {
555 #ifdef CONFIG_FEATURE_REMOTE_LOG
556 if (doRemoteLog == TRUE) {
561 logMessage(LOG_SYSLOG | LOG_INFO, "syslogd started: " "BusyBox v" BB_VER );
566 FD_SET(sock_fd, &fds);
568 if (select(sock_fd + 1, &fds, NULL, NULL, NULL) < 0) {
569 if (errno == EINTR) {
570 /* alarm may have happened. */
573 bb_perror_msg_and_die("select error");
576 if (FD_ISSET(sock_fd, &fds)) {
579 # define TMP_BUF_SZ BUFSIZ
581 # define TMP_BUF_SZ MAXLINE
583 #define tmpbuf bb_common_bufsiz1
585 if ((i = recv(sock_fd, tmpbuf, TMP_BUF_SZ, 0)) > 0) {
587 serveConnection(tmpbuf, i);
589 bb_perror_msg_and_die("UNIX socket error");
592 } /* for main loop */
595 int syslogd_main(int argc, char **argv)
603 /* do normal option parsing */
604 while ((opt = getopt(argc, argv, "m:nO:s:Sb:R:LC::")) > 0) {
607 MarkInterval = atoi(optarg) * 60;
613 logFilePath = optarg;
615 #ifdef CONFIG_FEATURE_ROTATE_LOGFILE
617 logFileSize = atoi(optarg) * 1024;
620 logFileRotate = atoi(optarg);
621 if( logFileRotate > 99 ) logFileRotate = 99;
624 #ifdef CONFIG_FEATURE_REMOTE_LOG
626 RemoteHost = bb_xstrdup(optarg);
627 if ((p = strchr(RemoteHost, ':'))) {
628 RemotePort = atoi(p + 1);
634 local_logging = TRUE;
637 #ifdef CONFIG_FEATURE_IPC_SYSLOG
640 int buf_size = atoi(optarg);
642 shm_size = buf_size * 1024;
645 circular_logging = TRUE;
656 #ifdef CONFIG_FEATURE_REMOTE_LOG
657 /* If they have not specified remote logging, then log locally */
658 if (doRemoteLog == FALSE)
659 local_logging = TRUE;
663 /* Store away localhost's name before the fork */
664 gethostname(LocalHostName, sizeof(LocalHostName));
665 if ((p = strchr(LocalHostName, '.'))) {
671 if (doFork == TRUE) {
673 vfork_daemon_rexec(0, 1, argc, argv, "-n");