accumulated post-1.4.0 fixes
[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 len_and_sockaddr* 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 #endif /* FEATURE_IPC_SYSLOG */
266
267
268 /* Print a message to the log file. */
269 static void log_locally(char *msg)
270 {
271         static time_t last;
272         struct flock fl;
273         int len = strlen(msg);
274
275 #if ENABLE_FEATURE_IPC_SYSLOG
276         if ((option_mask32 & OPT_circularlog) && shbuf) {
277                 log_to_shmem(msg, len);
278                 return;
279         }
280 #endif
281         if (logFD >= 0) {
282                 time_t cur;
283                 time(&cur);
284                 if (last != cur) {
285                         last = cur; /* reopen log file every second */
286                         close(logFD);
287                         goto reopen;
288                 }
289         } else {
290  reopen:
291                 logFD = device_open(logFilePath, O_WRONLY | O_CREAT
292                                         | O_NOCTTY | O_APPEND | O_NONBLOCK);
293                 if (logFD < 0) {
294                         /* cannot open logfile? - print to /dev/console then */
295                         int fd = device_open(_PATH_CONSOLE, O_WRONLY | O_NOCTTY | O_NONBLOCK);
296                         if (fd < 0)
297                                 fd = 2; /* then stderr, dammit */
298                         full_write(fd, msg, len);
299                         if (fd != 2)
300                                 close(fd);
301                         return;
302                 }
303 #if ENABLE_FEATURE_ROTATE_LOGFILE
304                 {
305                 struct stat statf;
306
307                 isRegular = (fstat(logFD, &statf) == 0 && (statf.st_mode & S_IFREG));
308                 /* bug (mostly harmless): can wrap around if file > 4gb */
309                 curFileSize = statf.st_size;
310                 }
311 #endif
312         }
313
314         fl.l_whence = SEEK_SET;
315         fl.l_start = 0;
316         fl.l_len = 1;
317         fl.l_type = F_WRLCK;
318         fcntl(logFD, F_SETLKW, &fl);
319
320 #if ENABLE_FEATURE_ROTATE_LOGFILE
321         if (logFileSize && isRegular && curFileSize > logFileSize) {
322                 if (logFileRotate) { /* always 0..99 */
323                         int i = strlen(logFilePath) + 3 + 1;
324                         char oldFile[i];
325                         char newFile[i];
326                         i = logFileRotate - 1;
327                         /* rename: f.8 -> f.9; f.7 -> f.8; ... */
328                         while (1) {
329                                 sprintf(newFile, "%s.%d", logFilePath, i);
330                                 if (i == 0) break;
331                                 sprintf(oldFile, "%s.%d", logFilePath, --i);
332                                 rename(oldFile, newFile);
333                         }
334                         /* newFile == "f.0" now */
335                         rename(logFilePath, newFile);
336                         fl.l_type = F_UNLCK;
337                         fcntl(logFD, F_SETLKW, &fl);
338                         close(logFD);
339                         goto reopen;
340                 }
341                 ftruncate(logFD, 0);
342         }
343         curFileSize +=
344 #endif
345                         full_write(logFD, msg, len);
346         fl.l_type = F_UNLCK;
347         fcntl(logFD, F_SETLKW, &fl);
348 }
349
350 static void parse_fac_prio_20(int pri, char *res20)
351 {
352         CODE *c_pri, *c_fac;
353
354         if (pri != 0) {
355                 c_fac = facilitynames;
356                 while (c_fac->c_name) {
357                         if (c_fac->c_val != (LOG_FAC(pri) << 3)) {
358                                 c_fac++; continue;
359                         }
360                         /* facility is found, look for prio */
361                         c_pri = prioritynames;
362                         while (c_pri->c_name) {
363                                 if (c_pri->c_val != LOG_PRI(pri)) {
364                                         c_pri++; continue;
365                                 }
366                                 snprintf(res20, 20, "%s.%s",
367                                                 c_fac->c_name, c_pri->c_name);
368                                 return;
369                         }
370                         /* prio not found, bail out */
371                         break;
372                 }
373                 snprintf(res20, 20, "<%d>", pri);
374         }
375 }
376
377 /* len parameter is used only for "is there a timestamp?" check.
378  * NB: some callers cheat and supply 0 when they know
379  * that there is no timestamp, short-cutting the test. */
380 static void timestamp_and_log(int pri, char *msg, int len)
381 {
382         char *timestamp;
383
384         if (len < 16 || msg[3] != ' ' || msg[6] != ' '
385          || msg[9] != ':' || msg[12] != ':' || msg[15] != ' '
386         ) {
387                 time_t now;
388                 time(&now);
389                 timestamp = ctime(&now) + 4;
390         } else {
391                 timestamp = msg;
392                 msg += 16;
393         }
394         timestamp[15] = '\0';
395
396         /* Log message locally (to file or shared mem) */
397         if (!ENABLE_FEATURE_REMOTE_LOG || (option_mask32 & OPT_locallog)) {
398                 if (LOG_PRI(pri) < logLevel) {
399                         if (option_mask32 & OPT_small)
400                                 sprintf(PRINTBUF, "%s %s\n", timestamp, msg);
401                         else {
402                                 char res[20];
403                                 parse_fac_prio_20(pri, res);
404                                 sprintf(PRINTBUF, "%s %s %s %s\n", timestamp, localHostName, res, msg);
405                         }
406                         log_locally(PRINTBUF);
407                 }
408         }
409 }
410
411 static void split_escape_and_log(char *tmpbuf, int len)
412 {
413         char *p = tmpbuf;
414
415         tmpbuf += len;
416         while (p < tmpbuf) {
417                 char c;
418                 char *q = PARSEBUF;
419                 int pri = (LOG_USER | LOG_NOTICE);
420
421                 if (*p == '<') {
422                         /* Parse the magic priority number */
423                         pri = bb_strtou(p + 1, &p, 10);
424                         if (*p == '>') p++;
425                         if (pri & ~(LOG_FACMASK | LOG_PRIMASK)) {
426                                 pri = (LOG_USER | LOG_NOTICE);
427                         }
428                 }
429
430                 while ((c = *p++)) {
431                         if (c == '\n')
432                                 c = ' ';
433                         if (!(c & ~0x1f)) {
434                                 *q++ = '^';
435                                 c += '@'; /* ^@, ^A, ^B... */
436                         }
437                         *q++ = c;
438                 }
439                 *q = '\0';
440                 /* Now log it */
441                 timestamp_and_log(pri, PARSEBUF, q - PARSEBUF);
442         }
443 }
444
445 static void quit_signal(int sig)
446 {
447         timestamp_and_log(LOG_SYSLOG | LOG_INFO, "syslogd exiting", 0);
448         puts("syslogd exiting");
449         unlink(dev_log_name);
450         if (ENABLE_FEATURE_IPC_SYSLOG)
451                 ipcsyslog_cleanup();
452         exit(1);
453 }
454
455 static void do_mark(int sig)
456 {
457         if (markInterval) {
458                 timestamp_and_log(LOG_SYSLOG | LOG_INFO, "-- MARK --", 0);
459                 alarm(markInterval);
460         }
461 }
462
463 static void do_syslogd(void) ATTRIBUTE_NORETURN;
464 static void do_syslogd(void)
465 {
466         struct sockaddr_un sunx;
467         socklen_t addr_len;
468         int sock_fd;
469         fd_set fds;
470
471         /* Set up signal handlers */
472         signal(SIGINT, quit_signal);
473         signal(SIGTERM, quit_signal);
474         signal(SIGQUIT, quit_signal);
475         signal(SIGHUP, SIG_IGN);
476         signal(SIGCHLD, SIG_IGN);
477 #ifdef SIGCLD
478         signal(SIGCLD, SIG_IGN);
479 #endif
480         signal(SIGALRM, do_mark);
481         alarm(markInterval);
482
483         dev_log_name = xmalloc_realpath(_PATH_LOG);
484         if (!dev_log_name)
485                 dev_log_name = _PATH_LOG;
486
487         /* Unlink old /dev/log (or object it points to) */
488         unlink(dev_log_name);
489
490         memset(&sunx, 0, sizeof(sunx));
491         sunx.sun_family = AF_UNIX;
492         strncpy(sunx.sun_path, dev_log_name, sizeof(sunx.sun_path));
493         sock_fd = xsocket(AF_UNIX, SOCK_DGRAM, 0);
494         addr_len = sizeof(sunx.sun_family) + strlen(sunx.sun_path);
495         xbind(sock_fd, (struct sockaddr *) &sunx, addr_len);
496
497         if (chmod(dev_log_name, 0666) < 0) {
498                 bb_perror_msg_and_die("cannot set permission on %s", dev_log_name);
499         }
500         if (ENABLE_FEATURE_IPC_SYSLOG && (option_mask32 & OPT_circularlog)) {
501                 ipcsyslog_init();
502         }
503
504         timestamp_and_log(LOG_SYSLOG | LOG_INFO, "syslogd started: BusyBox v" BB_VER, 0);
505
506         for (;;) {
507                 FD_ZERO(&fds);
508                 FD_SET(sock_fd, &fds);
509
510                 if (select(sock_fd + 1, &fds, NULL, NULL, NULL) < 0) {
511                         if (errno == EINTR) {
512                                 /* alarm may have happened */
513                                 continue;
514                         }
515                         bb_perror_msg_and_die("select");
516                 }
517
518                 if (FD_ISSET(sock_fd, &fds)) {
519                         int i;
520                         i = recv(sock_fd, RECVBUF, MAX_READ - 1, 0);
521                         if (i <= 0)
522                                 bb_perror_msg_and_die("UNIX socket error");
523                         /* TODO: maybe suppress duplicates? */
524 #if ENABLE_FEATURE_REMOTE_LOG
525                         /* We are not modifying log messages in any way before send */
526                         /* Remote site cannot trust _us_ anyway and need to do validation again */
527                         if (remoteAddr) {
528                                 if (-1 == remoteFD) {
529                                         remoteFD = socket(remoteAddr->sa.sa_family, SOCK_DGRAM, 0);
530                                 }
531                                 if (-1 != remoteFD) {
532                                         /* send message to remote logger, ignore possible error */
533                                         sendto(remoteFD, RECVBUF, i, MSG_DONTWAIT,
534                                                 &remoteAddr->sa, remoteAddr->len);
535                                 }
536                         }
537 #endif
538                         RECVBUF[i] = '\0';
539                         split_escape_and_log(RECVBUF, i);
540                 } /* FD_ISSET() */
541         } /* for */
542 }
543
544 int syslogd_main(int argc, char **argv)
545 {
546         char OPTION_DECL;
547         char *p;
548
549         /* do normal option parsing */
550         opt_complementary = "=0"; /* no non-option params */
551         getopt32(argc, argv, OPTION_STR, OPTION_PARAM);
552         if (option_mask32 & OPT_mark) // -m
553                 markInterval = xatou_range(opt_m, 0, INT_MAX/60) * 60;
554         //if (option_mask32 & OPT_nofork) // -n
555         //if (option_mask32 & OPT_outfile) // -O
556         if (option_mask32 & OPT_loglevel) // -l
557                 logLevel = xatou_range(opt_l, 1, 8);
558         //if (option_mask32 & OPT_small) // -S
559 #if ENABLE_FEATURE_ROTATE_LOGFILE
560         if (option_mask32 & OPT_filesize) // -s
561                 logFileSize = xatou_range(opt_s, 0, INT_MAX/1024) * 1024;
562         if (option_mask32 & OPT_rotatecnt) // -b
563                 logFileRotate = xatou_range(opt_b, 0, 99);
564 #endif
565 #if ENABLE_FEATURE_REMOTE_LOG
566         if (option_mask32 & OPT_remotelog) { // -R
567                 remoteAddr = host2sockaddr(opt_R, 514);
568         }
569         //if (option_mask32 & OPT_locallog) // -L
570 #endif
571 #if ENABLE_FEATURE_IPC_SYSLOG
572         if (opt_C) // -Cn
573                 shm_size = xatoul_range(opt_C, 4, INT_MAX/1024) * 1024;
574 #endif
575
576         /* If they have not specified remote logging, then log locally */
577         if (ENABLE_FEATURE_REMOTE_LOG && !(option_mask32 & OPT_remotelog))
578                 option_mask32 |= OPT_locallog;
579
580         /* Store away localhost's name before the fork */
581         gethostname(localHostName, sizeof(localHostName));
582         p = strchr(localHostName, '.');
583         if (p) {
584                 *p = '\0';
585         }
586
587         if (!(option_mask32 & OPT_nofork)) {
588 #ifdef BB_NOMMU
589                 vfork_daemon_rexec(0, 1, argc, argv, "-n");
590 #else
591                 bb_daemonize();
592 #endif
593         }
594         umask(0);
595         do_syslogd();
596         /* return EXIT_SUCCESS; */
597 }