9e4bc63c2fd66a940828c2ddf82bbec4025a040d
[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 /* Path to the unix socket */
26 static char dev_log_name[MAXPATHLEN];
27
28 /* Path for the file where all log messages are written */
29 static const char *logFilePath = "/var/log/messages";
30
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;
36 #endif
37
38 /* interval between marks in seconds */
39 static int markInterval = 20 * 60;
40
41 /* level of messages to be locally logged */
42 static int logLevel = 8;
43
44 /* localhost's name */
45 static char localHostName[64];
46
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;
52 #endif
53
54
55 /* NB: we may need 2x this amount on stack... */
56 enum { MAX_READ = 1024 };
57
58
59 /* options */
60 /* Correct regardless of combination of CONFIG_xxx */
61 enum {
62         OPTBIT_mark = 0, // -m
63         OPTBIT_nofork, // -n
64         OPTBIT_outfile, // -O
65         OPTBIT_loglevel, // -l
66         OPTBIT_small, // -S
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
72
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,
83 };
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)
100
101
102 /* circular buffer variables/structures */
103 #if ENABLE_FEATURE_IPC_SYSLOG
104
105
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
109 #endif
110
111 #include <sys/ipc.h>
112 #include <sys/sem.h>
113 #include <sys/shm.h>
114
115 /* our shared key */
116 #define KEY_ID ((long)0x414e4547) /* "GENA" */
117
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
125
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
129
130 static void ipcsyslog_cleanup(void)
131 {
132         if (shmid != -1) {
133                 shmdt(shbuf);
134         }
135         if (shmid != -1) {
136                 shmctl(shmid, IPC_RMID, NULL);
137         }
138         if (s_semid != -1) {
139                 semctl(s_semid, 0, IPC_RMID, 0);
140         }
141 }
142
143 static void ipcsyslog_init(void)
144 {
145         shmid = shmget(KEY_ID, shm_size, IPC_CREAT | 1023);
146         if (shmid == -1) {
147                 bb_perror_msg_and_die("shmget");
148         }
149
150         shbuf = shmat(shmid, NULL, 0);
151         if (!shbuf) {
152                 bb_perror_msg_and_die("shmat");
153         }
154
155         shbuf->size = shm_size - offsetof(struct shbuf_ds, data);
156         shbuf->head = shbuf->tail = 0;
157
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);
160         if (s_semid == -1) {
161                 if (errno == EEXIST) {
162                         s_semid = semget(KEY_ID, 2, 0);
163                         if (s_semid != -1)
164                                 return;
165                 }
166                 bb_perror_msg_and_die("semget");
167         }
168 }
169
170 /* write message to buffer */
171 static void log_to_shmem(const char *msg, int len)
172 {
173         static /*const*/ struct sembuf SMwup[1] = { {1, -1, IPC_NOWAIT} };
174         static /*const*/ struct sembuf SMwdn[3] = { {0, 0}, {1, 0}, {1, +1} };
175
176         int old_tail, new_tail;
177         char *c;
178
179         if (semop(s_semid, SMwdn, 3) == -1) {
180                 bb_perror_msg_and_die("SMwdn");
181         }
182
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.
191          */
192         len++; /* length with NUL included */
193  again:
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,
198                  * else... */
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;
207                         } else {
208                                 /* convert pointer to offset + skip NUL */
209                                 shbuf->head = c - shbuf->data + 1;
210                         }
211                 }
212                 /* store message, set new tail */
213                 memcpy(shbuf->data + old_tail, msg, len);
214                 shbuf->tail = new_tail;
215         } else {
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;
227                         }
228                 }
229                 /* copy what fits to the end of buffer, and repeat */
230                 memcpy(shbuf->data + old_tail, msg, k);
231                 msg += k;
232                 len -= k;
233                 shbuf->tail = 0;
234                 goto again;
235         }
236         if (semop(s_semid, SMwup, 1) == -1) {
237                 bb_perror_msg_and_die("SMwup");
238         }
239 }
240 #else
241 void ipcsyslog_cleanup(void);
242 void ipcsyslog_init(void);
243 void log_to_shmem(const char *msg);
244
245
246 #endif /* FEATURE_IPC_SYSLOG */
247
248
249 /* Print a message to the log file. */
250 static void log_locally(char *msg)
251 {
252         int fd, len = strlen(msg);
253
254 #if ENABLE_FEATURE_IPC_SYSLOG
255         if ((option_mask32 & OPT_circularlog) && shbuf) {
256                 log_to_shmem(msg, len);
257                 return;
258         }
259 #endif
260
261  again:
262         fd = device_open(logFilePath, O_WRONLY | O_CREAT
263                                         | O_NOCTTY | O_APPEND | O_NONBLOCK);
264         if (fd >= 0) {
265                 struct flock fl;
266
267                 fl.l_whence = SEEK_SET;
268                 fl.l_start = 0;
269                 fl.l_len = 1;
270                 fl.l_type = F_WRLCK;
271                 fcntl(fd, F_SETLKW, &fl);
272
273 #if ENABLE_FEATURE_ROTATE_LOGFILE
274                 if (logFileSize) {
275                         struct stat statf;
276                         int r = fstat(fd, &statf);
277                         if (!r && (statf.st_mode & S_IFREG)
278                          && (lseek(fd, 0, SEEK_END) > logFileSize)
279                         ) {
280                                 if (logFileRotate) { /* always 0..99 */
281                                         int i = strlen(logFilePath) + 3 + 1;
282                                         char oldFile[i];
283                                         char newFile[i];
284                                         i = logFileRotate - 1;
285                                         /* rename: f.8 -> f.9; f.7 -> f.8; ... */
286                                         while (1) {
287                                                 sprintf(newFile, "%s.%d", logFilePath, i);
288                                                 if (i == 0) break;
289                                                 sprintf(oldFile, "%s.%d", logFilePath, --i);
290                                                 rename(oldFile, newFile);
291                                         }
292                                         /* newFile == "f.0" now */
293                                         rename(logFilePath, newFile);
294                                         fl.l_type = F_UNLCK;
295                                         fcntl(fd, F_SETLKW, &fl);
296                                         close(fd);
297                                         goto again;
298                                 }
299                                 ftruncate(fd, 0);
300                         }
301                 }
302 #endif
303                 full_write(fd, msg, len);
304                 fl.l_type = F_UNLCK;
305                 fcntl(fd, F_SETLKW, &fl);
306                 close(fd);
307         } else {
308                 /* cannot open logfile? - print to /dev/console then */
309                 fd = device_open(_PATH_CONSOLE, O_WRONLY | O_NOCTTY | O_NONBLOCK);
310                 if (fd < 0)
311                         fd = 2; /* then stderr, dammit */
312                 full_write(fd, msg, len);
313                 if (fd != 2)
314                         close(fd);
315         }
316 }
317
318 static void parse_fac_prio_20(int pri, char *res20)
319 {
320         CODE *c_pri, *c_fac;
321
322         if (pri != 0) {
323                 c_fac = facilitynames;
324                 while (c_fac->c_name) {
325                         if (c_fac->c_val != (LOG_FAC(pri) << 3)) {
326                                 c_fac++; continue;
327                         }
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)) {
332                                         c_pri++; continue;
333                                 }
334                                 snprintf(res20, 20, "%s.%s",
335                                                 c_fac->c_name, c_pri->c_name);
336                                 return;
337                         }
338                         /* prio not found, bail out */
339                         break;
340                 }
341                 snprintf(res20, 20, "<%d>", pri);
342         }
343 }
344
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)
349 {
350         time_t now;
351         char *timestamp;
352
353         if (len < 16 || msg[3] != ' ' || msg[6] != ' '
354          || msg[9] != ':' || msg[12] != ':' || msg[15] != ' '
355         ) {
356                 time(&now);
357                 timestamp = ctime(&now) + 4;
358         } else {
359                 timestamp = msg;
360                 msg += 16;
361         }
362         timestamp[15] = '\0';
363
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);
369                         else {
370                                 char res[20];
371                                 parse_fac_prio_20(pri, res);
372                                 msg = xasprintf("%s %s %s %s\n", timestamp, localHostName, res, msg);
373                         }
374                         log_locally(msg);
375                         free(msg);
376                 }
377         }
378 }
379
380 static void split_escape_and_log(char *tmpbuf, int len)
381 {
382         char line[len * 2 + 1]; /* gcc' cheap alloca */
383         char *p = tmpbuf;
384
385         tmpbuf += len;
386         while (p < tmpbuf) {
387                 char c;
388                 char *q = line;
389                 int pri = (LOG_USER | LOG_NOTICE);
390
391                 if (*p == '<') {
392                         /* Parse the magic priority number. */
393                         pri = bb_strtou(p + 1, &p, 10);
394                         if (*p == '>') p++;
395                         if (pri & ~(LOG_FACMASK | LOG_PRIMASK)) {
396                                 pri = (LOG_USER | LOG_NOTICE);
397                         }
398                 }
399
400                 while ((c = *p++)) {
401                         if (c == '\n')
402                                 c = ' ';
403                         if (!(c & ~0x1f)) {
404                                 *q++ = '^';
405                                 c += '@'; /* ^@, ^A, ^B... */
406                         }
407                         *q++ = c;
408                 }
409                 *q = '\0';
410                 /* now log it */
411                 timestamp_and_log(pri, line, q - line);
412         }
413 }
414
415 static void quit_signal(int sig)
416 {
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)
421                 ipcsyslog_cleanup();
422         exit(1);
423 }
424
425 static void do_mark(int sig)
426 {
427         if (markInterval) {
428                 timestamp_and_log(LOG_SYSLOG | LOG_INFO, "-- MARK --", 0);
429                 alarm(markInterval);
430         }
431 }
432
433 static void do_syslogd(void) ATTRIBUTE_NORETURN;
434 static void do_syslogd(void)
435 {
436         struct sockaddr_un sunx;
437         socklen_t addrLength;
438         int sock_fd;
439         fd_set fds;
440
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);
447 #ifdef SIGCLD
448         signal(SIGCLD, SIG_IGN);
449 #endif
450         signal(SIGALRM, do_mark);
451         alarm(markInterval);
452
453         /* Unlink old /dev/log (or object it points to) */
454         if (realpath(_PATH_LOG, dev_log_name) != NULL) {
455                 unlink(dev_log_name);
456         }
457
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);
465         }
466
467         if (chmod(dev_log_name, 0666) < 0) {
468                 bb_perror_msg_and_die("cannot set permission on %s", dev_log_name);
469         }
470         if (ENABLE_FEATURE_IPC_SYSLOG && (option_mask32 & OPT_circularlog)) {
471                 ipcsyslog_init();
472         }
473
474         timestamp_and_log(LOG_SYSLOG | LOG_INFO, "syslogd started: BusyBox v" BB_VER, 0);
475
476         for (;;) {
477                 FD_ZERO(&fds);
478                 FD_SET(sock_fd, &fds);
479
480                 if (select(sock_fd + 1, &fds, NULL, NULL, NULL) < 0) {
481                         if (errno == EINTR) {
482                                 /* alarm may have happened. */
483                                 continue;
484                         }
485                         bb_perror_msg_and_die("select");
486                 }
487
488                 if (FD_ISSET(sock_fd, &fds)) {
489                         int i;
490 #define tmpbuf bb_common_bufsiz1
491                         i = recv(sock_fd, tmpbuf, MAX_READ, 0);
492                         if (i <= 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);
501                                 }
502                                 if (-1 != remoteFD) {
503                                         /* send message to remote logger, ignore possible error */
504                                         sendto(remoteFD, tmpbuf, i, MSG_DONTWAIT,
505                                                 (struct sockaddr *) &remoteAddr,
506                                                 sizeof(remoteAddr));
507                                 }
508                         }
509 #endif
510                         tmpbuf[i] = '\0';
511                         split_escape_and_log(tmpbuf, i);
512 #undef tmpbuf
513                 } /* FD_ISSET() */
514         } /* for */
515 }
516
517 int syslogd_main(int argc, char **argv)
518 {
519         char OPTION_DECL;
520         char *p;
521
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);
536 #endif
537 #if ENABLE_FEATURE_REMOTE_LOG
538         if (option_mask32 & OPT_remotelog) { // -R
539                 int port = 514;
540                 p = strchr(opt_R, ':');
541                 if (p) {
542                         *p++ = '\0';
543                         port = xatou16(p);
544                 }
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);
549         }
550         //if (option_mask32 & OPT_locallog) // -L
551 #endif
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;
555 #endif
556
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;
560
561         /* Store away localhost's name before the fork */
562         gethostname(localHostName, sizeof(localHostName));
563         p = strchr(localHostName, '.');
564         if (p) {
565                 *p = '\0';
566         }
567
568         if (!(option_mask32 & OPT_nofork)) {
569 #ifdef BB_NOMMU
570                 vfork_daemon_rexec(0, 1, argc, argv, "-n");
571 #else
572                 xdaemon(0, 1);
573 #endif
574         }
575         umask(0);
576         do_syslogd();
577
578         return EXIT_SUCCESS;
579 }