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