53290f1ccfcbbb7d46141dd1446ec3391ce7f9fd
[oweals/busybox.git] / sysklogd / syslogd.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini syslogd implementation for busybox
4  *
5  * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
6  *
7  * Copyright (C) 2000 by Karl M. Hegbloom <karlheg@debian.org>
8  *
9  * "circular buffer" Copyright (C) 2001 by Gennady Feldman <gfeldman@gena01.com>
10  *
11  * Maintainer: Gennady Feldman <gfeldman@gena01.com> as of Mar 12, 2001
12  *
13  * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
14  */
15
16 #include "busybox.h"
17 #include <paths.h>
18 #include <sys/un.h>
19
20 /* SYSLOG_NAMES defined to pull some extra junk from syslog.h */
21 #define SYSLOG_NAMES
22 #include <sys/syslog.h>
23 #include <sys/uio.h>
24
25 #define DEBUG 0
26
27 /* Path for the file where all log messages are written */
28 static const char *logFilePath = "/var/log/messages";
29 static int logFD = -1;
30
31 /* interval between marks in seconds */
32 static int markInterval = 20 * 60;
33
34 /* level of messages to be locally logged */
35 static int logLevel = 8;
36
37 /* localhost's name */
38 static char localHostName[64];
39
40 #if ENABLE_FEATURE_ROTATE_LOGFILE
41 /* max size of message file before being rotated */
42 static unsigned logFileSize = 200 * 1024;
43 /* number of rotated message files */
44 static unsigned logFileRotate = 1;
45 static unsigned curFileSize;
46 static smallint isRegular;
47 #endif
48
49 #if ENABLE_FEATURE_REMOTE_LOG
50 #include <netinet/in.h>
51 /* udp socket for logging to remote host */
52 static int remoteFD = -1;
53 static len_and_sockaddr* remoteAddr;
54 #endif
55
56 /* We are using bb_common_bufsiz1 for buffering: */
57 enum { MAX_READ = (BUFSIZ/6) & ~0xf };
58 /* We recv into RECVBUF... (size: MAX_READ ~== BUFSIZ/6) */
59 #define RECVBUF  bb_common_bufsiz1
60 /* ...then copy to PARSEBUF, escaping control chars */
61 /* (can grow x2 max ~== BUFSIZ/3) */
62 #define PARSEBUF (bb_common_bufsiz1 + MAX_READ)
63 /* ...then sprintf into PRINTBUF, adding timestamp (15 chars),
64  * host (64), fac.prio (20) to the message */
65 /* (growth by: 15 + 64 + 20 + delims = ~110) */
66 #define PRINTBUF (bb_common_bufsiz1 + 3*MAX_READ)
67 /* totals: BUFSIZ == BUFSIZ/6 + BUFSIZ/3 + (BUFSIZ/3+BUFSIZ/6)
68  * -- we have BUFSIZ/6 extra at the ent of PRINTBUF
69  * which covers needed ~110 extra bytes (and much more) */
70
71
72 /* Options */
73 enum {
74         OPTBIT_mark = 0, // -m
75         OPTBIT_nofork, // -n
76         OPTBIT_outfile, // -O
77         OPTBIT_loglevel, // -l
78         OPTBIT_small, // -S
79         USE_FEATURE_ROTATE_LOGFILE(OPTBIT_filesize   ,) // -s
80         USE_FEATURE_ROTATE_LOGFILE(OPTBIT_rotatecnt  ,) // -b
81         USE_FEATURE_REMOTE_LOG(    OPTBIT_remote     ,) // -R
82         USE_FEATURE_REMOTE_LOG(    OPTBIT_localtoo   ,) // -L
83         USE_FEATURE_IPC_SYSLOG(    OPTBIT_circularlog,) // -C
84
85         OPT_mark        = 1 << OPTBIT_mark    ,
86         OPT_nofork      = 1 << OPTBIT_nofork  ,
87         OPT_outfile     = 1 << OPTBIT_outfile ,
88         OPT_loglevel    = 1 << OPTBIT_loglevel,
89         OPT_small       = 1 << OPTBIT_small   ,
90         OPT_filesize    = USE_FEATURE_ROTATE_LOGFILE((1 << OPTBIT_filesize   )) + 0,
91         OPT_rotatecnt   = USE_FEATURE_ROTATE_LOGFILE((1 << OPTBIT_rotatecnt  )) + 0,
92         OPT_remotelog   = USE_FEATURE_REMOTE_LOG(    (1 << OPTBIT_remote     )) + 0,
93         OPT_locallog    = USE_FEATURE_REMOTE_LOG(    (1 << OPTBIT_localtoo   )) + 0,
94         OPT_circularlog = USE_FEATURE_IPC_SYSLOG(    (1 << OPTBIT_circularlog)) + 0,
95 };
96 #define OPTION_STR "m:nO:l:S" \
97         USE_FEATURE_ROTATE_LOGFILE("s:" ) \
98         USE_FEATURE_ROTATE_LOGFILE("b:" ) \
99         USE_FEATURE_REMOTE_LOG(    "R:" ) \
100         USE_FEATURE_REMOTE_LOG(    "L"  ) \
101         USE_FEATURE_IPC_SYSLOG(    "C::")
102 #define OPTION_DECL *opt_m, *opt_l \
103         USE_FEATURE_ROTATE_LOGFILE(,*opt_s) \
104         USE_FEATURE_ROTATE_LOGFILE(,*opt_b) \
105         USE_FEATURE_REMOTE_LOG(    ,*opt_R) \
106         USE_FEATURE_IPC_SYSLOG(    ,*opt_C = NULL)
107 #define OPTION_PARAM &opt_m, &logFilePath, &opt_l \
108         USE_FEATURE_ROTATE_LOGFILE(,&opt_s) \
109         USE_FEATURE_ROTATE_LOGFILE(,&opt_b) \
110         USE_FEATURE_REMOTE_LOG(    ,&opt_R) \
111         USE_FEATURE_IPC_SYSLOG(    ,&opt_C)
112
113
114 /* circular buffer variables/structures */
115 #if ENABLE_FEATURE_IPC_SYSLOG
116
117
118 #if CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE < 4
119 #error Sorry, you must set the syslogd buffer size to at least 4KB.
120 #error Please check CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE
121 #endif
122
123 #include <sys/ipc.h>
124 #include <sys/sem.h>
125 #include <sys/shm.h>
126
127 /* our shared key */
128 #define KEY_ID ((long)0x414e4547) /* "GENA" */
129
130 // Semaphore operation structures
131 static struct shbuf_ds {
132         int32_t size;   // size of data written
133         int32_t head;   // start of message list
134         int32_t tail;   // end of message list
135         char data[1];   // data/messages
136 } *shbuf;               // shared memory pointer
137
138 static int shmid = -1;   // ipc shared memory id
139 static int s_semid = -1; // ipc semaphore id
140 static int shm_size = ((CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE)*1024);   // default shm size
141
142 static void ipcsyslog_cleanup(void)
143 {
144         if (shmid != -1) {
145                 shmdt(shbuf);
146         }
147         if (shmid != -1) {
148                 shmctl(shmid, IPC_RMID, NULL);
149         }
150         if (s_semid != -1) {
151                 semctl(s_semid, 0, IPC_RMID, 0);
152         }
153 }
154
155 static void ipcsyslog_init(void)
156 {
157         if (DEBUG)
158                 printf("shmget(%lx, %d,...)\n", KEY_ID, shm_size);
159
160         shmid = shmget(KEY_ID, shm_size, IPC_CREAT | 1023);
161         if (shmid == -1) {
162                 bb_perror_msg_and_die("shmget");
163         }
164
165         shbuf = shmat(shmid, NULL, 0);
166         if (!shbuf) {
167                 bb_perror_msg_and_die("shmat");
168         }
169
170         shbuf->size = shm_size - offsetof(struct shbuf_ds, data);
171         shbuf->head = shbuf->tail = 0;
172
173         // we'll trust the OS to set initial semval to 0 (let's hope)
174         s_semid = semget(KEY_ID, 2, IPC_CREAT | IPC_EXCL | 1023);
175         if (s_semid == -1) {
176                 if (errno == EEXIST) {
177                         s_semid = semget(KEY_ID, 2, 0);
178                         if (s_semid != -1)
179                                 return;
180                 }
181                 bb_perror_msg_and_die("semget");
182         }
183 }
184
185 /* Write message to shared mem buffer */
186 static void log_to_shmem(const char *msg, int len)
187 {
188         /* Why libc insists on these being rw? */
189         static struct sembuf SMwup[1] = { {1, -1, IPC_NOWAIT} };
190         static struct sembuf SMwdn[3] = { {0, 0}, {1, 0}, {1, +1} };
191
192         int old_tail, new_tail;
193         char *c;
194
195         if (semop(s_semid, SMwdn, 3) == -1) {
196                 bb_perror_msg_and_die("SMwdn");
197         }
198
199         /* Circular Buffer Algorithm:
200          * --------------------------
201          * tail == position where to store next syslog message.
202          * head == position of next message to retrieve ("print").
203          * if head == tail, there is no "unprinted" messages left.
204          * head is typically advanced by separate "reader" program,
205          * but if there isn't one, we have to do it ourself.
206          * messages are NUL-separated.
207          */
208         len++; /* length with NUL included */
209  again:
210         old_tail = shbuf->tail;
211         new_tail = old_tail + len;
212         if (new_tail < shbuf->size) {
213                 /* No need to move head if shbuf->head <= old_tail,
214                  * else... */
215                 if (old_tail < shbuf->head && shbuf->head <= new_tail) {
216                         /* ...need to move head forward */
217                         c = memchr(shbuf->data + new_tail, '\0',
218                                            shbuf->size - new_tail);
219                         if (!c) /* no NUL ahead of us, wrap around */
220                                 c = memchr(shbuf->data, '\0', old_tail);
221                         if (!c) { /* still nothing? point to this msg... */
222                                 shbuf->head = old_tail;
223                         } else {
224                                 /* convert pointer to offset + skip NUL */
225                                 shbuf->head = c - shbuf->data + 1;
226                         }
227                 }
228                 /* store message, set new tail */
229                 memcpy(shbuf->data + old_tail, msg, len);
230                 shbuf->tail = new_tail;
231         } else {
232                 /* we need to break up the message and wrap it around */
233                 /* k == available buffer space ahead of old tail */
234                 int k = shbuf->size - old_tail - 1;
235                 if (shbuf->head > old_tail) {
236                         /* we are going to overwrite head, need to
237                          * move it out of the way */
238                         c = memchr(shbuf->data, '\0', old_tail);
239                         if (!c) { /* nothing? point to this msg... */
240                                 shbuf->head = old_tail;
241                         } else { /* convert pointer to offset + skip NUL */
242                                 shbuf->head = c - shbuf->data + 1;
243                         }
244                 }
245                 /* copy what fits to the end of buffer, and repeat */
246                 memcpy(shbuf->data + old_tail, msg, k);
247                 msg += k;
248                 len -= k;
249                 shbuf->tail = 0;
250                 goto again;
251         }
252         if (semop(s_semid, SMwup, 1) == -1) {
253                 bb_perror_msg_and_die("SMwup");
254         }
255         if (DEBUG)
256                 printf("head:%d tail:%d\n", shbuf->head, shbuf->tail);
257 }
258 #else
259 void ipcsyslog_cleanup(void);
260 void ipcsyslog_init(void);
261 void log_to_shmem(const char *msg);
262 #endif /* FEATURE_IPC_SYSLOG */
263
264
265 /* Print a message to the log file. */
266 static void log_locally(char *msg)
267 {
268         static time_t last;
269         struct flock fl;
270         int len = strlen(msg);
271
272 #if ENABLE_FEATURE_IPC_SYSLOG
273         if ((option_mask32 & OPT_circularlog) && shbuf) {
274                 log_to_shmem(msg, len);
275                 return;
276         }
277 #endif
278         if (logFD >= 0) {
279                 time_t cur;
280                 time(&cur);
281                 if (last != cur) {
282                         last = cur; /* reopen log file every second */
283                         close(logFD);
284                         goto reopen;
285                 }
286         } else {
287  reopen:
288                 logFD = device_open(logFilePath, O_WRONLY | O_CREAT
289                                         | O_NOCTTY | O_APPEND | O_NONBLOCK);
290                 if (logFD < 0) {
291                         /* cannot open logfile? - print to /dev/console then */
292                         int fd = device_open(_PATH_CONSOLE, O_WRONLY | O_NOCTTY | O_NONBLOCK);
293                         if (fd < 0)
294                                 fd = 2; /* then stderr, dammit */
295                         full_write(fd, msg, len);
296                         if (fd != 2)
297                                 close(fd);
298                         return;
299                 }
300 #if ENABLE_FEATURE_ROTATE_LOGFILE
301                 {
302                 struct stat statf;
303
304                 isRegular = (fstat(logFD, &statf) == 0 && (statf.st_mode & S_IFREG));
305                 /* bug (mostly harmless): can wrap around if file > 4gb */
306                 curFileSize = statf.st_size;
307                 }
308 #endif
309         }
310
311         fl.l_whence = SEEK_SET;
312         fl.l_start = 0;
313         fl.l_len = 1;
314         fl.l_type = F_WRLCK;
315         fcntl(logFD, F_SETLKW, &fl);
316
317 #if ENABLE_FEATURE_ROTATE_LOGFILE
318         if (logFileSize && isRegular && curFileSize > logFileSize) {
319                 if (logFileRotate) { /* always 0..99 */
320                         int i = strlen(logFilePath) + 3 + 1;
321                         char oldFile[i];
322                         char newFile[i];
323                         i = logFileRotate - 1;
324                         /* rename: f.8 -> f.9; f.7 -> f.8; ... */
325                         while (1) {
326                                 sprintf(newFile, "%s.%d", logFilePath, i);
327                                 if (i == 0) break;
328                                 sprintf(oldFile, "%s.%d", logFilePath, --i);
329                                 rename(oldFile, newFile);
330                         }
331                         /* newFile == "f.0" now */
332                         rename(logFilePath, newFile);
333                         fl.l_type = F_UNLCK;
334                         fcntl(logFD, F_SETLKW, &fl);
335                         close(logFD);
336                         goto reopen;
337                 }
338                 ftruncate(logFD, 0);
339         }
340         curFileSize +=
341 #endif
342                         full_write(logFD, msg, len);
343         fl.l_type = F_UNLCK;
344         fcntl(logFD, F_SETLKW, &fl);
345 }
346
347 static void parse_fac_prio_20(int pri, char *res20)
348 {
349         CODE *c_pri, *c_fac;
350
351         if (pri != 0) {
352                 c_fac = facilitynames;
353                 while (c_fac->c_name) {
354                         if (c_fac->c_val != (LOG_FAC(pri) << 3)) {
355                                 c_fac++; continue;
356                         }
357                         /* facility is found, look for prio */
358                         c_pri = prioritynames;
359                         while (c_pri->c_name) {
360                                 if (c_pri->c_val != LOG_PRI(pri)) {
361                                         c_pri++; continue;
362                                 }
363                                 snprintf(res20, 20, "%s.%s",
364                                                 c_fac->c_name, c_pri->c_name);
365                                 return;
366                         }
367                         /* prio not found, bail out */
368                         break;
369                 }
370                 snprintf(res20, 20, "<%d>", pri);
371         }
372 }
373
374 /* len parameter is used only for "is there a timestamp?" check.
375  * NB: some callers cheat and supply 0 when they know
376  * that there is no timestamp, short-cutting the test. */
377 static void timestamp_and_log(int pri, char *msg, int len)
378 {
379         char *timestamp;
380
381         if (len < 16 || msg[3] != ' ' || msg[6] != ' '
382          || msg[9] != ':' || msg[12] != ':' || msg[15] != ' '
383         ) {
384                 time_t now;
385                 time(&now);
386                 timestamp = ctime(&now) + 4;
387         } else {
388                 timestamp = msg;
389                 msg += 16;
390         }
391         timestamp[15] = '\0';
392
393         /* Log message locally (to file or shared mem) */
394         if (!ENABLE_FEATURE_REMOTE_LOG || (option_mask32 & OPT_locallog)) {
395                 if (LOG_PRI(pri) < logLevel) {
396                         if (option_mask32 & OPT_small)
397                                 sprintf(PRINTBUF, "%s %s\n", timestamp, msg);
398                         else {
399                                 char res[20];
400                                 parse_fac_prio_20(pri, res);
401                                 sprintf(PRINTBUF, "%s %s %s %s\n", timestamp, localHostName, res, msg);
402                         }
403                         log_locally(PRINTBUF);
404                 }
405         }
406 }
407
408 static void split_escape_and_log(char *tmpbuf, int len)
409 {
410         char *p = tmpbuf;
411
412         tmpbuf += len;
413         while (p < tmpbuf) {
414                 char c;
415                 char *q = PARSEBUF;
416                 int pri = (LOG_USER | LOG_NOTICE);
417
418                 if (*p == '<') {
419                         /* Parse the magic priority number */
420                         pri = bb_strtou(p + 1, &p, 10);
421                         if (*p == '>') p++;
422                         if (pri & ~(LOG_FACMASK | LOG_PRIMASK)) {
423                                 pri = (LOG_USER | LOG_NOTICE);
424                         }
425                 }
426
427                 while ((c = *p++)) {
428                         if (c == '\n')
429                                 c = ' ';
430                         if (!(c & ~0x1f)) {
431                                 *q++ = '^';
432                                 c += '@'; /* ^@, ^A, ^B... */
433                         }
434                         *q++ = c;
435                 }
436                 *q = '\0';
437                 /* Now log it */
438                 timestamp_and_log(pri, PARSEBUF, q - PARSEBUF);
439         }
440 }
441
442 static void quit_signal(int sig)
443 {
444         timestamp_and_log(LOG_SYSLOG | LOG_INFO, (char*)"syslogd exiting", 0);
445         puts("syslogd exiting");
446         if (ENABLE_FEATURE_IPC_SYSLOG)
447                 ipcsyslog_cleanup();
448         exit(1);
449 }
450
451 static void do_mark(int sig)
452 {
453         if (markInterval) {
454                 timestamp_and_log(LOG_SYSLOG | LOG_INFO, (char*)"-- MARK --", 0);
455                 alarm(markInterval);
456         }
457 }
458
459 static void do_syslogd(void) ATTRIBUTE_NORETURN;
460 static void do_syslogd(void)
461 {
462         struct sockaddr_un sunx;
463         int sock_fd;
464         fd_set fds;
465         char *dev_log_name;
466
467         /* Set up signal handlers */
468         signal(SIGINT, quit_signal);
469         signal(SIGTERM, quit_signal);
470         signal(SIGQUIT, quit_signal);
471         signal(SIGHUP, SIG_IGN);
472         signal(SIGCHLD, SIG_IGN);
473 #ifdef SIGCLD
474         signal(SIGCLD, SIG_IGN);
475 #endif
476         signal(SIGALRM, do_mark);
477         alarm(markInterval);
478
479         memset(&sunx, 0, sizeof(sunx));
480         sunx.sun_family = AF_UNIX;
481         strcpy(sunx.sun_path, "/dev/log");
482
483         /* Unlink old /dev/log or object it points to. */
484         /* (if it exists, bind will fail) */
485         logmode = LOGMODE_NONE;
486         dev_log_name = xmalloc_readlink_or_warn("/dev/log");
487         logmode = LOGMODE_STDIO;
488         if (dev_log_name) {
489                 int fd = xopen(".", O_NONBLOCK);
490                 xchdir("/dev");
491                 /* we do not check whether this is a link also */
492                 unlink(dev_log_name);
493                 fchdir(fd);
494                 close(fd);
495                 safe_strncpy(sunx.sun_path, dev_log_name, sizeof(sunx.sun_path));
496                 free(dev_log_name);
497         } else {
498                 unlink("/dev/log");
499         }
500
501         sock_fd = xsocket(AF_UNIX, SOCK_DGRAM, 0);
502         xbind(sock_fd, (struct sockaddr *) &sunx, sizeof(sunx));
503
504         if (chmod("/dev/log", 0666) < 0) {
505                 bb_perror_msg_and_die("cannot set permission on /dev/log");
506         }
507         if (ENABLE_FEATURE_IPC_SYSLOG && (option_mask32 & OPT_circularlog)) {
508                 ipcsyslog_init();
509         }
510
511         timestamp_and_log(LOG_SYSLOG | LOG_INFO,
512                         (char*)"syslogd started: BusyBox v" BB_VER, 0);
513
514         for (;;) {
515                 FD_ZERO(&fds);
516                 FD_SET(sock_fd, &fds);
517
518                 if (select(sock_fd + 1, &fds, NULL, NULL, NULL) < 0) {
519                         if (errno == EINTR) {
520                                 /* alarm may have happened */
521                                 continue;
522                         }
523                         bb_perror_msg_and_die("select");
524                 }
525
526                 if (FD_ISSET(sock_fd, &fds)) {
527                         int i;
528                         i = recv(sock_fd, RECVBUF, MAX_READ - 1, 0);
529                         if (i <= 0)
530                                 bb_perror_msg_and_die("UNIX socket error");
531                         /* TODO: maybe suppress duplicates? */
532 #if ENABLE_FEATURE_REMOTE_LOG
533                         /* We are not modifying log messages in any way before send */
534                         /* Remote site cannot trust _us_ anyway and need to do validation again */
535                         if (remoteAddr) {
536                                 if (-1 == remoteFD) {
537                                         remoteFD = socket(remoteAddr->sa.sa_family, SOCK_DGRAM, 0);
538                                 }
539                                 if (-1 != remoteFD) {
540                                         /* send message to remote logger, ignore possible error */
541                                         sendto(remoteFD, RECVBUF, i, MSG_DONTWAIT,
542                                                 &remoteAddr->sa, remoteAddr->len);
543                                 }
544                         }
545 #endif
546                         RECVBUF[i] = '\0';
547                         split_escape_and_log(RECVBUF, i);
548                 } /* FD_ISSET() */
549         } /* for */
550 }
551
552 int syslogd_main(int argc, char **argv);
553 int syslogd_main(int argc, char **argv)
554 {
555         char OPTION_DECL;
556         char *p;
557
558         /* do normal option parsing */
559         opt_complementary = "=0"; /* no non-option params */
560         getopt32(argc, argv, OPTION_STR, OPTION_PARAM);
561         if (option_mask32 & OPT_mark) // -m
562                 markInterval = xatou_range(opt_m, 0, INT_MAX/60) * 60;
563         //if (option_mask32 & OPT_nofork) // -n
564         //if (option_mask32 & OPT_outfile) // -O
565         if (option_mask32 & OPT_loglevel) // -l
566                 logLevel = xatou_range(opt_l, 1, 8);
567         //if (option_mask32 & OPT_small) // -S
568 #if ENABLE_FEATURE_ROTATE_LOGFILE
569         if (option_mask32 & OPT_filesize) // -s
570                 logFileSize = xatou_range(opt_s, 0, INT_MAX/1024) * 1024;
571         if (option_mask32 & OPT_rotatecnt) // -b
572                 logFileRotate = xatou_range(opt_b, 0, 99);
573 #endif
574 #if ENABLE_FEATURE_REMOTE_LOG
575         if (option_mask32 & OPT_remotelog) { // -R
576                 remoteAddr = xhost2sockaddr(opt_R, 514);
577         }
578         //if (option_mask32 & OPT_locallog) // -L
579 #endif
580 #if ENABLE_FEATURE_IPC_SYSLOG
581         if (opt_C) // -Cn
582                 shm_size = xatoul_range(opt_C, 4, INT_MAX/1024) * 1024;
583 #endif
584
585         /* If they have not specified remote logging, then log locally */
586         if (ENABLE_FEATURE_REMOTE_LOG && !(option_mask32 & OPT_remotelog))
587                 option_mask32 |= OPT_locallog;
588
589         /* Store away localhost's name before the fork */
590         gethostname(localHostName, sizeof(localHostName));
591         p = strchr(localHostName, '.');
592         if (p) {
593                 *p = '\0';
594         }
595
596         if (!(option_mask32 & OPT_nofork)) {
597 #ifdef BB_NOMMU
598                 vfork_daemon_rexec(0, 1, argc, argv, "-n");
599 #else
600                 bb_daemonize();
601 #endif
602         }
603         umask(0);
604         do_syslogd();
605         /* return EXIT_SUCCESS; */
606 }