3b511490f21ec223368fc7bd4edaa20c12c0dcbc
[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 to the unix socket */
28 static char *dev_log_name;
29
30 /* Path for the file where all log messages are written */
31 static const char *logFilePath = "/var/log/messages";
32 static int logFD = -1;
33
34 /* interval between marks in seconds */
35 static int markInterval = 20 * 60;
36
37 /* level of messages to be locally logged */
38 static int logLevel = 8;
39
40 /* localhost's name */
41 static char localHostName[64];
42
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;
50 #endif
51
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;
57 #endif
58
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) */
73
74
75 /* Options */
76 enum {
77         OPTBIT_mark = 0, // -m
78         OPTBIT_nofork, // -n
79         OPTBIT_outfile, // -O
80         OPTBIT_loglevel, // -l
81         OPTBIT_small, // -S
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
87
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,
98 };
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)
115
116
117 /* circular buffer variables/structures */
118 #if ENABLE_FEATURE_IPC_SYSLOG
119
120
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
124 #endif
125
126 #include <sys/ipc.h>
127 #include <sys/sem.h>
128 #include <sys/shm.h>
129
130 /* our shared key */
131 #define KEY_ID ((long)0x414e4547) /* "GENA" */
132
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
140
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
144
145 static void ipcsyslog_cleanup(void)
146 {
147         if (shmid != -1) {
148                 shmdt(shbuf);
149         }
150         if (shmid != -1) {
151                 shmctl(shmid, IPC_RMID, NULL);
152         }
153         if (s_semid != -1) {
154                 semctl(s_semid, 0, IPC_RMID, 0);
155         }
156 }
157
158 static void ipcsyslog_init(void)
159 {
160         if (DEBUG)
161                 printf("shmget(%lx, %d,...)\n", KEY_ID, shm_size);
162
163         shmid = shmget(KEY_ID, shm_size, IPC_CREAT | 1023);
164         if (shmid == -1) {
165                 bb_perror_msg_and_die("shmget");
166         }
167
168         shbuf = shmat(shmid, NULL, 0);
169         if (!shbuf) {
170                 bb_perror_msg_and_die("shmat");
171         }
172
173         shbuf->size = shm_size - offsetof(struct shbuf_ds, data);
174         shbuf->head = shbuf->tail = 0;
175
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);
178         if (s_semid == -1) {
179                 if (errno == EEXIST) {
180                         s_semid = semget(KEY_ID, 2, 0);
181                         if (s_semid != -1)
182                                 return;
183                 }
184                 bb_perror_msg_and_die("semget");
185         }
186 }
187
188 /* Write message to shared mem buffer */
189 static void log_to_shmem(const char *msg, int len)
190 {
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} };
194
195         int old_tail, new_tail;
196         char *c;
197
198         if (semop(s_semid, SMwdn, 3) == -1) {
199                 bb_perror_msg_and_die("SMwdn");
200         }
201
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.
210          */
211         len++; /* length with NUL included */
212  again:
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,
217                  * else... */
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;
226                         } else {
227                                 /* convert pointer to offset + skip NUL */
228                                 shbuf->head = c - shbuf->data + 1;
229                         }
230                 }
231                 /* store message, set new tail */
232                 memcpy(shbuf->data + old_tail, msg, len);
233                 shbuf->tail = new_tail;
234         } else {
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;
246                         }
247                 }
248                 /* copy what fits to the end of buffer, and repeat */
249                 memcpy(shbuf->data + old_tail, msg, k);
250                 msg += k;
251                 len -= k;
252                 shbuf->tail = 0;
253                 goto again;
254         }
255         if (semop(s_semid, SMwup, 1) == -1) {
256                 bb_perror_msg_and_die("SMwup");
257         }
258         if (DEBUG)
259                 printf("head:%d tail:%d\n", shbuf->head, shbuf->tail);
260 }
261 #else
262 void ipcsyslog_cleanup(void);
263 void ipcsyslog_init(void);
264 void log_to_shmem(const char *msg);
265
266
267 #endif /* FEATURE_IPC_SYSLOG */
268
269
270 /* Print a message to the log file. */
271 static void log_locally(char *msg)
272 {
273         static time_t last;
274
275         struct flock fl;
276         int len = strlen(msg);
277
278 #if ENABLE_FEATURE_IPC_SYSLOG
279         if ((option_mask32 & OPT_circularlog) && shbuf) {
280                 log_to_shmem(msg, len);
281                 return;
282         }
283 #endif
284         if (logFD >= 0) {
285                 time_t cur;
286                 time(&cur);
287                 if (last != cur) {
288                         last = cur; /* reopen log file every second */
289                         close(logFD);
290                         goto reopen;
291                 }
292         } else {
293  reopen:
294                 logFD = device_open(logFilePath, O_WRONLY | O_CREAT
295                                         | O_NOCTTY | O_APPEND | O_NONBLOCK);
296                 if (logFD < 0) {
297                         /* cannot open logfile? - print to /dev/console then */
298                         int fd = device_open(_PATH_CONSOLE, O_WRONLY | O_NOCTTY | O_NONBLOCK);
299                         if (fd < 0)
300                                 fd = 2; /* then stderr, dammit */
301                         full_write(fd, msg, len);
302                         if (fd != 2)
303                                 close(fd);
304                         return;
305                 }
306 #if ENABLE_FEATURE_ROTATE_LOGFILE
307                 {
308                 struct stat statf;
309
310                 isRegular = (fstat(logFD, &statf) == 0 && (statf.st_mode & S_IFREG));
311                 /* bug (mostly harmless): can wrap around if file > 4gb */
312                 curFileSize = statf.st_size;
313                 }
314 #endif
315         }
316
317         fl.l_whence = SEEK_SET;
318         fl.l_start = 0;
319         fl.l_len = 1;
320         fl.l_type = F_WRLCK;
321         fcntl(logFD, F_SETLKW, &fl);
322
323 #if ENABLE_FEATURE_ROTATE_LOGFILE
324         if (logFileSize && isRegular && curFileSize > logFileSize) {
325                 if (logFileRotate) { /* always 0..99 */
326                         int i = strlen(logFilePath) + 3 + 1;
327                         char oldFile[i];
328                         char newFile[i];
329                         i = logFileRotate - 1;
330                         /* rename: f.8 -> f.9; f.7 -> f.8; ... */
331                         while (1) {
332                                 sprintf(newFile, "%s.%d", logFilePath, i);
333                                 if (i == 0) break;
334                                 sprintf(oldFile, "%s.%d", logFilePath, --i);
335                                 rename(oldFile, newFile);
336                         }
337                         /* newFile == "f.0" now */
338                         rename(logFilePath, newFile);
339                         fl.l_type = F_UNLCK;
340                         fcntl(logFD, F_SETLKW, &fl);
341                         close(logFD);
342                         goto reopen;
343                 }
344                 ftruncate(logFD, 0);
345         }
346         curFileSize +=
347 #endif
348                         full_write(logFD, msg, len);
349         fl.l_type = F_UNLCK;
350         fcntl(logFD, F_SETLKW, &fl);
351 }
352
353 static void parse_fac_prio_20(int pri, char *res20)
354 {
355         CODE *c_pri, *c_fac;
356
357         if (pri != 0) {
358                 c_fac = facilitynames;
359                 while (c_fac->c_name) {
360                         if (c_fac->c_val != (LOG_FAC(pri) << 3)) {
361                                 c_fac++; continue;
362                         }
363                         /* facility is found, look for prio */
364                         c_pri = prioritynames;
365                         while (c_pri->c_name) {
366                                 if (c_pri->c_val != LOG_PRI(pri)) {
367                                         c_pri++; continue;
368                                 }
369                                 snprintf(res20, 20, "%s.%s",
370                                                 c_fac->c_name, c_pri->c_name);
371                                 return;
372                         }
373                         /* prio not found, bail out */
374                         break;
375                 }
376                 snprintf(res20, 20, "<%d>", pri);
377         }
378 }
379
380 /* len parameter is used only for "is there a timestamp?" check.
381  * NB: some callers cheat and supply 0 when they know
382  * that there is no timestamp, short-cutting the test. */
383 static void timestamp_and_log(int pri, char *msg, int len)
384 {
385         char *timestamp;
386
387         if (len < 16 || msg[3] != ' ' || msg[6] != ' '
388          || msg[9] != ':' || msg[12] != ':' || msg[15] != ' '
389         ) {
390                 time_t now;
391                 time(&now);
392                 timestamp = ctime(&now) + 4;
393         } else {
394                 timestamp = msg;
395                 msg += 16;
396         }
397         timestamp[15] = '\0';
398
399         /* Log message locally (to file or shared mem) */
400         if (!ENABLE_FEATURE_REMOTE_LOG || (option_mask32 & OPT_locallog)) {
401                 if (LOG_PRI(pri) < logLevel) {
402                         if (option_mask32 & OPT_small)
403                                 sprintf(PRINTBUF, "%s %s\n", timestamp, msg);
404                         else {
405                                 char res[20];
406                                 parse_fac_prio_20(pri, res);
407                                 sprintf(PRINTBUF, "%s %s %s %s\n", timestamp, localHostName, res, msg);
408                         }
409                         log_locally(PRINTBUF);
410                 }
411         }
412 }
413
414 static void split_escape_and_log(char *tmpbuf, int len)
415 {
416         char *p = tmpbuf;
417
418         tmpbuf += len;
419         while (p < tmpbuf) {
420                 char c;
421                 char *q = PARSEBUF;
422                 int pri = (LOG_USER | LOG_NOTICE);
423
424                 if (*p == '<') {
425                         /* Parse the magic priority number */
426                         pri = bb_strtou(p + 1, &p, 10);
427                         if (*p == '>') p++;
428                         if (pri & ~(LOG_FACMASK | LOG_PRIMASK)) {
429                                 pri = (LOG_USER | LOG_NOTICE);
430                         }
431                 }
432
433                 while ((c = *p++)) {
434                         if (c == '\n')
435                                 c = ' ';
436                         if (!(c & ~0x1f)) {
437                                 *q++ = '^';
438                                 c += '@'; /* ^@, ^A, ^B... */
439                         }
440                         *q++ = c;
441                 }
442                 *q = '\0';
443                 /* Now log it */
444                 timestamp_and_log(pri, PARSEBUF, q - PARSEBUF);
445         }
446 }
447
448 static void quit_signal(int sig)
449 {
450         timestamp_and_log(LOG_SYSLOG | LOG_INFO, "System log daemon exiting", 0);
451         puts("System log daemon exiting");
452         unlink(dev_log_name);
453         if (ENABLE_FEATURE_IPC_SYSLOG)
454                 ipcsyslog_cleanup();
455         exit(1);
456 }
457
458 static void do_mark(int sig)
459 {
460         if (markInterval) {
461                 timestamp_and_log(LOG_SYSLOG | LOG_INFO, "-- MARK --", 0);
462                 alarm(markInterval);
463         }
464 }
465
466 static void do_syslogd(void) ATTRIBUTE_NORETURN;
467 static void do_syslogd(void)
468 {
469         struct sockaddr_un sunx;
470         socklen_t addrLength;
471         int sock_fd;
472         fd_set fds;
473
474         /* Set up signal handlers */
475         signal(SIGINT, quit_signal);
476         signal(SIGTERM, quit_signal);
477         signal(SIGQUIT, quit_signal);
478         signal(SIGHUP, SIG_IGN);
479         signal(SIGCHLD, SIG_IGN);
480 #ifdef SIGCLD
481         signal(SIGCLD, SIG_IGN);
482 #endif
483         signal(SIGALRM, do_mark);
484         alarm(markInterval);
485
486         dev_log_name = xmalloc_realpath(_PATH_LOG);
487         if (!dev_log_name)
488                 dev_log_name = _PATH_LOG;
489
490         /* Unlink old /dev/log (or object it points to) */
491         unlink(dev_log_name);
492
493         memset(&sunx, 0, sizeof(sunx));
494         sunx.sun_family = AF_UNIX;
495         strncpy(sunx.sun_path, dev_log_name, sizeof(sunx.sun_path));
496         sock_fd = xsocket(AF_UNIX, SOCK_DGRAM, 0);
497         addrLength = sizeof(sunx.sun_family) + strlen(sunx.sun_path);
498         xbind(sock_fd, (struct sockaddr *) &sunx, addrLength);
499
500         if (chmod(dev_log_name, 0666) < 0) {
501                 bb_perror_msg_and_die("cannot set permission on %s", dev_log_name);
502         }
503         if (ENABLE_FEATURE_IPC_SYSLOG && (option_mask32 & OPT_circularlog)) {
504                 ipcsyslog_init();
505         }
506
507         timestamp_and_log(LOG_SYSLOG | LOG_INFO, "syslogd started: BusyBox v" BB_VER, 0);
508
509         for (;;) {
510                 FD_ZERO(&fds);
511                 FD_SET(sock_fd, &fds);
512
513                 if (select(sock_fd + 1, &fds, NULL, NULL, NULL) < 0) {
514                         if (errno == EINTR) {
515                                 /* alarm may have happened */
516                                 continue;
517                         }
518                         bb_perror_msg_and_die("select");
519                 }
520
521                 if (FD_ISSET(sock_fd, &fds)) {
522                         int i;
523                         i = recv(sock_fd, RECVBUF, MAX_READ - 1, 0);
524                         if (i <= 0)
525                                 bb_perror_msg_and_die("UNIX socket error");
526                         /* TODO: maybe suppress duplicates? */
527 #if ENABLE_FEATURE_REMOTE_LOG
528                         /* We are not modifying log messages in any way before send */
529                         /* Remote site cannot trust _us_ anyway and need to do validation again */
530                         if (option_mask32 & OPT_remotelog) {
531                                 if (-1 == remoteFD) {
532                                         remoteFD = socket(AF_INET, SOCK_DGRAM, 0);
533                                 }
534                                 if (-1 != remoteFD) {
535                                         /* send message to remote logger, ignore possible error */
536                                         sendto(remoteFD, RECVBUF, i, MSG_DONTWAIT,
537                                                 (struct sockaddr *) &remoteAddr,
538                                                 sizeof(remoteAddr));
539                                 }
540                         }
541 #endif
542                         RECVBUF[i] = '\0';
543                         split_escape_and_log(RECVBUF, i);
544                 } /* FD_ISSET() */
545         } /* for */
546 }
547
548 int syslogd_main(int argc, char **argv)
549 {
550         char OPTION_DECL;
551         char *p;
552
553         /* do normal option parsing */
554         opt_complementary = "=0"; /* no non-option params */
555         getopt32(argc, argv, OPTION_STR, OPTION_PARAM);
556         if (option_mask32 & OPT_mark) // -m
557                 markInterval = xatou_range(opt_m, 0, INT_MAX/60) * 60;
558         //if (option_mask32 & OPT_nofork) // -n
559         //if (option_mask32 & OPT_outfile) // -O
560         if (option_mask32 & OPT_loglevel) // -l
561                 logLevel = xatou_range(opt_l, 1, 8);
562         //if (option_mask32 & OPT_small) // -S
563 #if ENABLE_FEATURE_ROTATE_LOGFILE
564         if (option_mask32 & OPT_filesize) // -s
565                 logFileSize = xatou_range(opt_s, 0, INT_MAX/1024) * 1024;
566         if (option_mask32 & OPT_rotatecnt) // -b
567                 logFileRotate = xatou_range(opt_b, 0, 99);
568 #endif
569 #if ENABLE_FEATURE_REMOTE_LOG
570         if (option_mask32 & OPT_remotelog) { // -R
571                 int port = 514;
572                 p = strchr(opt_R, ':');
573                 if (p) {
574                         *p++ = '\0';
575                         port = xatou16(p);
576                 }
577                 remoteAddr.sin_family = AF_INET;
578                 /* FIXME: looks ip4-specific. need to do better */
579                 remoteAddr.sin_addr = *(struct in_addr *) *(xgethostbyname(opt_R)->h_addr_list);
580                 remoteAddr.sin_port = htons(port);
581         }
582         //if (option_mask32 & OPT_locallog) // -L
583 #endif
584 #if ENABLE_FEATURE_IPC_SYSLOG
585         if ((option_mask32 & OPT_circularlog) && opt_C) // -C
586                 shm_size = xatoul_range(opt_C, 4, INT_MAX/1024) * 1024;
587 #endif
588
589         /* If they have not specified remote logging, then log locally */
590         if (ENABLE_FEATURE_REMOTE_LOG && !(option_mask32 & OPT_remotelog))
591                 option_mask32 |= OPT_locallog;
592
593         /* Store away localhost's name before the fork */
594         gethostname(localHostName, sizeof(localHostName));
595         p = strchr(localHostName, '.');
596         if (p) {
597                 *p = '\0';
598         }
599
600         if (!(option_mask32 & OPT_nofork)) {
601 #ifdef BB_NOMMU
602                 vfork_daemon_rexec(0, 1, argc, argv, "-n");
603 #else
604                 xdaemon(0, 1);
605 #endif
606         }
607         umask(0);
608         do_syslogd();
609         /* return EXIT_SUCCESS; */
610 }