syslogd: small fix to config patch
[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 GPLv2 or later, see file LICENSE in this source tree.
14  */
15
16 //usage:#define syslogd_trivial_usage
17 //usage:       "[OPTIONS]"
18 //usage:#define syslogd_full_usage "\n\n"
19 //usage:       "System logging utility.\n"
20 //usage:       "This version of syslogd ignores /etc/syslog.conf\n"
21 //usage:     "\nOptions:"
22 //usage:     "\n        -n              Run in foreground"
23 //usage:     "\n        -O FILE         Log to given file (default:/var/log/messages)"
24 //usage:     "\n        -l N            Set local log level"
25 //usage:     "\n        -S              Smaller logging output"
26 //usage:        IF_FEATURE_ROTATE_LOGFILE(
27 //usage:     "\n        -s SIZE         Max size (KB) before rotate (default:200KB, 0=off)"
28 //usage:     "\n        -b N            N rotated logs to keep (default:1, max=99, 0=purge)")
29 //usage:        IF_FEATURE_REMOTE_LOG(
30 //usage:     "\n        -R HOST[:PORT]  Log to IP or hostname on PORT (default PORT=514/UDP)"
31 //usage:     "\n        -L              Log locally and via network (default is network only if -R)")
32 //usage:        IF_FEATURE_SYSLOGD_DUP(
33 //usage:     "\n        -D              Drop duplicates")
34 //usage:        IF_FEATURE_IPC_SYSLOG(
35 //usage:     "\n        -C[size(KiB)]   Log to shared mem buffer (read it using logread)")
36 /* NB: -Csize shouldn't have space (because size is optional) */
37 /* //usage:  "\n        -m MIN          Minutes between MARK lines (default:20, 0=off)" */
38 //usage:
39 //usage:#define syslogd_example_usage
40 //usage:       "$ syslogd -R masterlog:514\n"
41 //usage:       "$ syslogd -R 192.168.1.1:601\n"
42
43 /*
44  * Done in syslogd_and_logger.c:
45 #include "libbb.h"
46 #define SYSLOG_NAMES
47 #define SYSLOG_NAMES_CONST
48 #include <syslog.h>
49 */
50
51 #include <sys/un.h>
52 #include <sys/uio.h>
53
54 #if ENABLE_FEATURE_REMOTE_LOG
55 #include <netinet/in.h>
56 #endif
57
58 #if ENABLE_FEATURE_IPC_SYSLOG
59 #include <sys/ipc.h>
60 #include <sys/sem.h>
61 #include <sys/shm.h>
62 #endif
63
64
65 #define DEBUG 0
66
67 /* MARK code is not very useful, is bloat, and broken:
68  * can deadlock if alarmed to make MARK while writing to IPC buffer
69  * (semaphores are down but do_mark routine tries to down them again) */
70 #undef SYSLOGD_MARK
71
72 /* Write locking does not seem to be useful either */
73 #undef SYSLOGD_WRLOCK
74
75 enum {
76         MAX_READ = CONFIG_FEATURE_SYSLOGD_READ_BUFFER_SIZE,
77         DNS_WAIT_SEC = 2 * 60,
78 };
79
80 /* Semaphore operation structures */
81 struct shbuf_ds {
82         int32_t size;   /* size of data - 1 */
83         int32_t tail;   /* end of message list */
84         char data[1];   /* data/messages */
85 };
86
87 #if ENABLE_FEATURE_REMOTE_LOG
88 typedef struct {
89         int remoteFD;
90         unsigned last_dns_resolve;
91         len_and_sockaddr *remoteAddr;
92         const char *remoteHostname;
93 } remoteHost_t;
94 #endif
95
96 typedef struct logFile_t {
97         const char *path;
98         int fd;
99 #if ENABLE_FEATURE_ROTATE_LOGFILE
100         unsigned size;
101         uint8_t isRegular;
102 #endif
103 } logFile_t;
104
105 #if ENABLE_FEATURE_SYSLOGD_CFG
106 typedef struct logRule_t {
107         uint8_t enabled_facility_priomap[LOG_NFACILITIES];
108         struct logFile_t *file;
109         struct logRule_t *next;
110 } logRule_t;
111 #endif
112
113 /* Allows us to have smaller initializer. Ugly. */
114 #define GLOBALS \
115         logFile_t logFile;                      \
116         /* interval between marks in seconds */ \
117         /*int markInterval;*/                   \
118         /* level of messages to be logged */    \
119         int logLevel;                           \
120 IF_FEATURE_ROTATE_LOGFILE( \
121         /* max size of file before rotation */  \
122         unsigned logFileSize;                   \
123         /* number of rotated message files */   \
124         unsigned logFileRotate;                 \
125 ) \
126 IF_FEATURE_IPC_SYSLOG( \
127         int shmid; /* ipc shared memory id */   \
128         int s_semid; /* ipc semaphore id */     \
129         int shm_size;                           \
130         struct sembuf SMwup[1];                 \
131         struct sembuf SMwdn[3];                 \
132 ) \
133 IF_FEATURE_SYSLOGD_CFG( \
134         logRule_t *log_rules; \
135 )
136
137 struct init_globals {
138         GLOBALS
139 };
140
141 struct globals {
142         GLOBALS
143
144 #if ENABLE_FEATURE_REMOTE_LOG
145         llist_t *remoteHosts;
146 #endif
147 #if ENABLE_FEATURE_IPC_SYSLOG
148         struct shbuf_ds *shbuf;
149 #endif
150         time_t last_log_time;
151         /* localhost's name. We print only first 64 chars */
152         char *hostname;
153
154         /* We recv into recvbuf... */
155         char recvbuf[MAX_READ * (1 + ENABLE_FEATURE_SYSLOGD_DUP)];
156         /* ...then copy to parsebuf, escaping control chars */
157         /* (can grow x2 max) */
158         char parsebuf[MAX_READ*2];
159         /* ...then sprintf into printbuf, adding timestamp (15 chars),
160          * host (64), fac.prio (20) to the message */
161         /* (growth by: 15 + 64 + 20 + delims = ~110) */
162         char printbuf[MAX_READ*2 + 128];
163 };
164
165 static const struct init_globals init_data = {
166         .logFile = {
167                 .path = "/var/log/messages",
168                 .fd = -1,
169         },
170 #ifdef SYSLOGD_MARK
171         .markInterval = 20 * 60,
172 #endif
173         .logLevel = 8,
174 #if ENABLE_FEATURE_ROTATE_LOGFILE
175         .logFileSize = 200 * 1024,
176         .logFileRotate = 1,
177 #endif
178 #if ENABLE_FEATURE_IPC_SYSLOG
179         .shmid = -1,
180         .s_semid = -1,
181         .shm_size = ((CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE)*1024), /* default shm size */
182         .SMwup = { {1, -1, IPC_NOWAIT} },
183         .SMwdn = { {0, 0}, {1, 0}, {1, +1} },
184 #endif
185 };
186
187 #define G (*ptr_to_globals)
188 #define INIT_G() do { \
189         SET_PTR_TO_GLOBALS(memcpy(xzalloc(sizeof(G)), &init_data, sizeof(init_data))); \
190 } while (0)
191
192
193 /* Options */
194 enum {
195         OPTBIT_mark = 0, // -m
196         OPTBIT_nofork, // -n
197         OPTBIT_outfile, // -O
198         OPTBIT_loglevel, // -l
199         OPTBIT_small, // -S
200         IF_FEATURE_ROTATE_LOGFILE(OPTBIT_filesize   ,)  // -s
201         IF_FEATURE_ROTATE_LOGFILE(OPTBIT_rotatecnt  ,)  // -b
202         IF_FEATURE_REMOTE_LOG(    OPTBIT_remotelog  ,)  // -R
203         IF_FEATURE_REMOTE_LOG(    OPTBIT_locallog   ,)  // -L
204         IF_FEATURE_IPC_SYSLOG(    OPTBIT_circularlog,)  // -C
205         IF_FEATURE_SYSLOGD_DUP(   OPTBIT_dup        ,)  // -D
206         IF_FEATURE_SYSLOGD_CFG(   OPTBIT_cfg        ,)  // -f
207
208         OPT_mark        = 1 << OPTBIT_mark    ,
209         OPT_nofork      = 1 << OPTBIT_nofork  ,
210         OPT_outfile     = 1 << OPTBIT_outfile ,
211         OPT_loglevel    = 1 << OPTBIT_loglevel,
212         OPT_small       = 1 << OPTBIT_small   ,
213         OPT_filesize    = IF_FEATURE_ROTATE_LOGFILE((1 << OPTBIT_filesize   )) + 0,
214         OPT_rotatecnt   = IF_FEATURE_ROTATE_LOGFILE((1 << OPTBIT_rotatecnt  )) + 0,
215         OPT_remotelog   = IF_FEATURE_REMOTE_LOG(    (1 << OPTBIT_remotelog  )) + 0,
216         OPT_locallog    = IF_FEATURE_REMOTE_LOG(    (1 << OPTBIT_locallog   )) + 0,
217         OPT_circularlog = IF_FEATURE_IPC_SYSLOG(    (1 << OPTBIT_circularlog)) + 0,
218         OPT_dup         = IF_FEATURE_SYSLOGD_DUP(   (1 << OPTBIT_dup        )) + 0,
219         OPT_cfg         = IF_FEATURE_SYSLOGD_CFG(   (1 << OPTBIT_cfg        )) + 0,
220 };
221 #define OPTION_STR "m:nO:l:S" \
222         IF_FEATURE_ROTATE_LOGFILE("s:" ) \
223         IF_FEATURE_ROTATE_LOGFILE("b:" ) \
224         IF_FEATURE_REMOTE_LOG(    "R:" ) \
225         IF_FEATURE_REMOTE_LOG(    "L"  ) \
226         IF_FEATURE_IPC_SYSLOG(    "C::") \
227         IF_FEATURE_SYSLOGD_DUP(   "D"  ) \
228         IF_FEATURE_SYSLOGD_CFG(   "f:"  )
229 #define OPTION_DECL *opt_m, *opt_l \
230         IF_FEATURE_ROTATE_LOGFILE(,*opt_s) \
231         IF_FEATURE_ROTATE_LOGFILE(,*opt_b) \
232         IF_FEATURE_IPC_SYSLOG(    ,*opt_C = NULL) \
233         IF_FEATURE_SYSLOGD_CFG(   ,*opt_f = NULL)
234 #define OPTION_PARAM &opt_m, &(G.logFile.path), &opt_l \
235         IF_FEATURE_ROTATE_LOGFILE(,&opt_s) \
236         IF_FEATURE_ROTATE_LOGFILE(,&opt_b) \
237         IF_FEATURE_REMOTE_LOG(    ,&remoteAddrList) \
238         IF_FEATURE_IPC_SYSLOG(    ,&opt_C) \
239         IF_FEATURE_SYSLOGD_CFG(   ,&opt_f)
240
241
242 #if ENABLE_FEATURE_SYSLOGD_CFG
243 static const CODE* find_by_name(char *name, const CODE* c_set)
244 {
245         for (; c_set->c_name; c_set++) {
246                 if (strcmp(name, c_set->c_name) == 0)
247                         return c_set;
248         }
249         return NULL;
250 }
251 #endif
252 static const CODE* find_by_val(int val, const CODE* c_set)
253 {
254         for (; c_set->c_name; c_set++) {
255                 if (c_set->c_val == val)
256                         return c_set;
257         }
258         return NULL;
259 }
260
261 #if ENABLE_FEATURE_SYSLOGD_CFG
262 static void parse_syslogdcfg(const char *file)
263 {
264         char *t;
265         logRule_t **pp_rule;
266         /* tok[0] set of selectors */
267         /* tok[1] file name */
268         /* tok[2] has to be NULL */
269         char *tok[3];
270         parser_t *parser;
271
272         parser = config_open2(file ? file : "/etc/syslog.conf",
273                                 file ? xfopen_for_read : fopen_or_warn_stdin);
274         if (!parser)
275                 /* didn't find default /etc/syslog.conf */
276                 /* proceed as if we built busybox without config support */
277                 return;
278
279         /* use ptr to ptr to avoid checking whether head was initialized */
280         pp_rule = &G.log_rules;
281         /* iterate through lines of config, skipping comments */
282         while (config_read(parser, tok, 3, 2, "# \t", PARSE_NORMAL | PARSE_MIN_DIE)) {
283                 char *cur_selector;
284                 logRule_t *cur_rule;
285
286                 /* unexpected trailing token? */
287                 if (tok[2]) {
288                         t = tok[2];
289                         goto cfgerr;
290                 }
291
292                 cur_rule = *pp_rule = xzalloc(sizeof(*cur_rule));
293
294                 cur_selector = tok[0];
295                 /* iterate through selectors: "kern.info;kern.!err;..." */
296                 do {
297                         const CODE *code;
298                         char *next_selector;
299                         uint8_t negated_prio; /* "kern.!err" */
300                         uint8_t single_prio;  /* "kern.=err" */
301                         uint32_t facmap; /* bitmap of enabled facilities */
302                         uint8_t primap;  /* bitmap of enabled priorities */
303                         unsigned i;
304
305                         next_selector = strchr(cur_selector, ';');
306                         if (next_selector)
307                                 *next_selector++ = '\0';
308
309                         t = strchr(cur_selector, '.');
310                         if (!t) {
311                                 t = cur_selector;
312                                 goto cfgerr;
313                         }
314                         *t++ = '\0'; /* separate facility from priority */
315
316                         negated_prio = 0;
317                         single_prio = 0;
318                         if (*t == '!') {
319                                 negated_prio = 1;
320                                 ++t;
321                         }
322                         if (*t == '=') {
323                                 single_prio = 1;
324                                 ++t;
325                         }
326
327                         /* parse priority */
328                         if (*t == '*')
329                                 primap = 0xff; /* all 8 log levels enabled */
330                         else {
331                                 uint8_t priority;
332                                 code = find_by_name(t, prioritynames);
333                                 if (!code)
334                                         goto cfgerr;
335                                 primap = 0;
336                                 priority = code->c_val;
337                                 if (priority == INTERNAL_NOPRI) {
338                                         /* ensure we take "enabled_facility_priomap[fac] &= 0" branch below */
339                                         negated_prio = 1;
340                                 } else {
341                                         priority = 1 << priority;
342                                         do {
343                                                 primap |= priority;
344                                                 if (single_prio)
345                                                         break;
346                                                 priority >>= 1;
347                                         } while (priority);
348                                         if (negated_prio)
349                                                 primap = ~primap;
350                                 }
351                         }
352
353                         /* parse facility */
354                         if (*cur_selector == '*')
355                                 facmap = (1<<LOG_NFACILITIES) - 1;
356                         else {
357                                 char *next_facility;
358                                 facmap = 0;
359                                 t = cur_selector;
360                                 /* iterate through facilities: "kern,daemon.<priospec>" */
361                                 do {
362                                         next_facility = strchr(t, ',');
363                                         if (next_facility)
364                                                 *next_facility++ = '\0';
365                                         code = find_by_name(t, facilitynames);
366                                         if (!code)
367                                                 goto cfgerr;
368                                         /* "mark" is not a real facility, skip it */
369                                         if (code->c_val != INTERNAL_MARK)
370                                                 facmap |= 1<<(LOG_FAC(code->c_val));
371                                         t = next_facility;
372                                 } while (t);
373                         }
374
375                         /* merge result with previous selectors */
376                         for (i = 0; i < LOG_NFACILITIES; ++i) {
377                                 if (!(facmap & (1<<i)))
378                                         continue;
379                                 if (negated_prio)
380                                         cur_rule->enabled_facility_priomap[i] &= primap;
381                                 else
382                                         cur_rule->enabled_facility_priomap[i] |= primap;
383                         }
384
385                         cur_selector = next_selector;
386                 } while (cur_selector);
387
388                 /* check whether current file name was mentioned in previous rules or
389                  * as global logfile (G.logFile).
390                  */
391                 if (strcmp(G.logFile.path, tok[1]) == 0) {
392                         cur_rule->file = &G.logFile;
393                         goto found;
394                 }
395                 /* temporarily use cur_rule as iterator, but *pp_rule still points
396                  * to currently processing rule entry.
397                  * NOTE: *pp_rule points to the current (and last in the list) rule.
398                  */
399                 for (cur_rule = G.log_rules; cur_rule != *pp_rule; cur_rule = cur_rule->next) {
400                         if (strcmp(cur_rule->file->path, tok[1]) == 0) {
401                                 /* found - reuse the same file structure */
402                                 (*pp_rule)->file = cur_rule->file;
403                                 cur_rule = *pp_rule;
404                                 goto found;
405                         }
406                 }
407                 cur_rule->file = xzalloc(sizeof(*cur_rule->file));
408                 cur_rule->file->fd = -1;
409                 cur_rule->file->path = xstrdup(tok[1]);
410  found:
411                 pp_rule = &cur_rule->next;
412         }
413         config_close(parser);
414         return;
415
416  cfgerr:
417         bb_error_msg_and_die("bad line %d: wrong token '%s'", parser->lineno, t);
418 }
419 #endif
420
421 /* circular buffer variables/structures */
422 #if ENABLE_FEATURE_IPC_SYSLOG
423
424 #if CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE < 4
425 #error Sorry, you must set the syslogd buffer size to at least 4KB.
426 #error Please check CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE
427 #endif
428
429 /* our shared key (syslogd.c and logread.c must be in sync) */
430 enum { KEY_ID = 0x414e4547 }; /* "GENA" */
431
432 static void ipcsyslog_cleanup(void)
433 {
434         if (G.shmid != -1) {
435                 shmdt(G.shbuf);
436         }
437         if (G.shmid != -1) {
438                 shmctl(G.shmid, IPC_RMID, NULL);
439         }
440         if (G.s_semid != -1) {
441                 semctl(G.s_semid, 0, IPC_RMID, 0);
442         }
443 }
444
445 static void ipcsyslog_init(void)
446 {
447         if (DEBUG)
448                 printf("shmget(%x, %d,...)\n", (int)KEY_ID, G.shm_size);
449
450         G.shmid = shmget(KEY_ID, G.shm_size, IPC_CREAT | 0644);
451         if (G.shmid == -1) {
452                 bb_perror_msg_and_die("shmget");
453         }
454
455         G.shbuf = shmat(G.shmid, NULL, 0);
456         if (G.shbuf == (void*) -1L) { /* shmat has bizarre error return */
457                 bb_perror_msg_and_die("shmat");
458         }
459
460         memset(G.shbuf, 0, G.shm_size);
461         G.shbuf->size = G.shm_size - offsetof(struct shbuf_ds, data) - 1;
462         /*G.shbuf->tail = 0;*/
463
464         /* we'll trust the OS to set initial semval to 0 (let's hope) */
465         G.s_semid = semget(KEY_ID, 2, IPC_CREAT | IPC_EXCL | 1023);
466         if (G.s_semid == -1) {
467                 if (errno == EEXIST) {
468                         G.s_semid = semget(KEY_ID, 2, 0);
469                         if (G.s_semid != -1)
470                                 return;
471                 }
472                 bb_perror_msg_and_die("semget");
473         }
474 }
475
476 /* Write message to shared mem buffer */
477 static void log_to_shmem(const char *msg)
478 {
479         int old_tail, new_tail;
480         int len;
481
482         if (semop(G.s_semid, G.SMwdn, 3) == -1) {
483                 bb_perror_msg_and_die("SMwdn");
484         }
485
486         /* Circular Buffer Algorithm:
487          * --------------------------
488          * tail == position where to store next syslog message.
489          * tail's max value is (shbuf->size - 1)
490          * Last byte of buffer is never used and remains NUL.
491          */
492         len = strlen(msg) + 1; /* length with NUL included */
493  again:
494         old_tail = G.shbuf->tail;
495         new_tail = old_tail + len;
496         if (new_tail < G.shbuf->size) {
497                 /* store message, set new tail */
498                 memcpy(G.shbuf->data + old_tail, msg, len);
499                 G.shbuf->tail = new_tail;
500         } else {
501                 /* k == available buffer space ahead of old tail */
502                 int k = G.shbuf->size - old_tail;
503                 /* copy what fits to the end of buffer, and repeat */
504                 memcpy(G.shbuf->data + old_tail, msg, k);
505                 msg += k;
506                 len -= k;
507                 G.shbuf->tail = 0;
508                 goto again;
509         }
510         if (semop(G.s_semid, G.SMwup, 1) == -1) {
511                 bb_perror_msg_and_die("SMwup");
512         }
513         if (DEBUG)
514                 printf("tail:%d\n", G.shbuf->tail);
515 }
516 #else
517 void ipcsyslog_cleanup(void);
518 void ipcsyslog_init(void);
519 void log_to_shmem(const char *msg);
520 #endif /* FEATURE_IPC_SYSLOG */
521
522 /* Print a message to the log file. */
523 static void log_locally(time_t now, char *msg, logFile_t *log_file)
524 {
525 #ifdef SYSLOGD_WRLOCK
526         struct flock fl;
527 #endif
528         int len = strlen(msg);
529
530         if (log_file->fd >= 0) {
531                 /* Reopen log file every second. This allows admin
532                  * to delete the file and not worry about restarting us.
533                  * This costs almost nothing since it happens
534                  * _at most_ once a second.
535                  */
536                 if (!now)
537                         now = time(NULL);
538                 if (G.last_log_time != now) {
539                         G.last_log_time = now;
540                         close(log_file->fd);
541                         goto reopen;
542                 }
543         } else {
544  reopen:
545                 log_file->fd = open(log_file->path, O_WRONLY | O_CREAT
546                                         | O_NOCTTY | O_APPEND | O_NONBLOCK,
547                                         0666);
548                 if (log_file->fd < 0) {
549                         /* cannot open logfile? - print to /dev/console then */
550                         int fd = device_open(DEV_CONSOLE, O_WRONLY | O_NOCTTY | O_NONBLOCK);
551                         if (fd < 0)
552                                 fd = 2; /* then stderr, dammit */
553                         full_write(fd, msg, len);
554                         if (fd != 2)
555                                 close(fd);
556                         return;
557                 }
558 #if ENABLE_FEATURE_ROTATE_LOGFILE
559                 {
560                         struct stat statf;
561                         log_file->isRegular = (fstat(log_file->fd, &statf) == 0 && S_ISREG(statf.st_mode));
562                         /* bug (mostly harmless): can wrap around if file > 4gb */
563                         log_file->size = statf.st_size;
564                 }
565 #endif
566         }
567
568 #ifdef SYSLOGD_WRLOCK
569         fl.l_whence = SEEK_SET;
570         fl.l_start = 0;
571         fl.l_len = 1;
572         fl.l_type = F_WRLCK;
573         fcntl(log_file->fd, F_SETLKW, &fl);
574 #endif
575
576 #if ENABLE_FEATURE_ROTATE_LOGFILE
577         if (G.logFileSize && log_file->isRegular && log_file->size > G.logFileSize) {
578                 if (G.logFileRotate) { /* always 0..99 */
579                         int i = strlen(log_file->path) + 3 + 1;
580                         char oldFile[i];
581                         char newFile[i];
582                         i = G.logFileRotate - 1;
583                         /* rename: f.8 -> f.9; f.7 -> f.8; ... */
584                         while (1) {
585                                 sprintf(newFile, "%s.%d", log_file->path, i);
586                                 if (i == 0) break;
587                                 sprintf(oldFile, "%s.%d", log_file->path, --i);
588                                 /* ignore errors - file might be missing */
589                                 rename(oldFile, newFile);
590                         }
591                         /* newFile == "f.0" now */
592                         rename(log_file->path, newFile);
593 #ifdef SYSLOGD_WRLOCK
594                         fl.l_type = F_UNLCK;
595                         fcntl(log_file->fd, F_SETLKW, &fl);
596 #endif
597                         close(log_file->fd);
598                         goto reopen;
599                 }
600                 ftruncate(log_file->fd, 0);
601         }
602         log_file->size +=
603 #endif
604                         full_write(log_file->fd, msg, len);
605 #ifdef SYSLOGD_WRLOCK
606         fl.l_type = F_UNLCK;
607         fcntl(log_file->fd, F_SETLKW, &fl);
608 #endif
609 }
610
611 static void parse_fac_prio_20(int pri, char *res20)
612 {
613         const CODE *c_pri, *c_fac;
614
615         c_fac = find_by_val(LOG_FAC(pri) << 3, facilitynames);
616         if (c_fac) {
617                 c_pri = find_by_val(LOG_PRI(pri), prioritynames);
618                 if (c_pri) {
619                         snprintf(res20, 20, "%s.%s", c_fac->c_name, c_pri->c_name);
620                         return;
621                 }
622         }
623         snprintf(res20, 20, "<%d>", pri);
624 }
625
626 /* len parameter is used only for "is there a timestamp?" check.
627  * NB: some callers cheat and supply len==0 when they know
628  * that there is no timestamp, short-circuiting the test. */
629 static void timestamp_and_log(int pri, char *msg, int len)
630 {
631         char *timestamp;
632         time_t now;
633
634         /* Jan 18 00:11:22 msg... */
635         /* 01234567890123456 */
636         if (len < 16 || msg[3] != ' ' || msg[6] != ' '
637          || msg[9] != ':' || msg[12] != ':' || msg[15] != ' '
638         ) {
639                 time(&now);
640                 timestamp = ctime(&now) + 4; /* skip day of week */
641         } else {
642                 now = 0;
643                 timestamp = msg;
644                 msg += 16;
645         }
646         timestamp[15] = '\0';
647
648         if (option_mask32 & OPT_small)
649                 sprintf(G.printbuf, "%s %s\n", timestamp, msg);
650         else {
651                 char res[20];
652                 parse_fac_prio_20(pri, res);
653                 sprintf(G.printbuf, "%s %.64s %s %s\n", timestamp, G.hostname, res, msg);
654         }
655
656         /* Log message locally (to file or shared mem) */
657 #if ENABLE_FEATURE_SYSLOGD_CFG
658         {
659                 bool match = 0;
660                 logRule_t *rule;
661                 uint8_t facility = LOG_FAC(pri);
662                 uint8_t prio_bit = 1 << LOG_PRI(pri);
663
664                 for (rule = G.log_rules; rule; rule = rule->next) {
665                         if (rule->enabled_facility_priomap[facility] & prio_bit) {
666                                 log_locally(now, G.printbuf, rule->file);
667                                 match = 1;
668                         }
669                 }
670                 if (match)
671                         return;
672         }
673 #endif
674         if (LOG_PRI(pri) < G.logLevel) {
675 #if ENABLE_FEATURE_IPC_SYSLOG
676                 if ((option_mask32 & OPT_circularlog) && G.shbuf) {
677                         log_to_shmem(msg);
678                         return;
679                 }
680 #endif
681                 log_locally(now, G.printbuf, &G.logFile);
682         }
683 }
684
685 static void timestamp_and_log_internal(const char *msg)
686 {
687         /* -L, or no -R */
688         if (ENABLE_FEATURE_REMOTE_LOG && !(option_mask32 & OPT_locallog))
689                 return;
690         timestamp_and_log(LOG_SYSLOG | LOG_INFO, (char*)msg, 0);
691 }
692
693 /* tmpbuf[len] is a NUL byte (set by caller), but there can be other,
694  * embedded NULs. Split messages on each of these NULs, parse prio,
695  * escape control chars and log each locally. */
696 static void split_escape_and_log(char *tmpbuf, int len)
697 {
698         char *p = tmpbuf;
699
700         tmpbuf += len;
701         while (p < tmpbuf) {
702                 char c;
703                 char *q = G.parsebuf;
704                 int pri = (LOG_USER | LOG_NOTICE);
705
706                 if (*p == '<') {
707                         /* Parse the magic priority number */
708                         pri = bb_strtou(p + 1, &p, 10);
709                         if (*p == '>')
710                                 p++;
711                         if (pri & ~(LOG_FACMASK | LOG_PRIMASK))
712                                 pri = (LOG_USER | LOG_NOTICE);
713                 }
714
715                 while ((c = *p++)) {
716                         if (c == '\n')
717                                 c = ' ';
718                         if (!(c & ~0x1f) && c != '\t') {
719                                 *q++ = '^';
720                                 c += '@'; /* ^@, ^A, ^B... */
721                         }
722                         *q++ = c;
723                 }
724                 *q = '\0';
725
726                 /* Now log it */
727                 timestamp_and_log(pri, G.parsebuf, q - G.parsebuf);
728         }
729 }
730
731 #ifdef SYSLOGD_MARK
732 static void do_mark(int sig)
733 {
734         if (G.markInterval) {
735                 timestamp_and_log_internal("-- MARK --");
736                 alarm(G.markInterval);
737         }
738 }
739 #endif
740
741 /* Don't inline: prevent struct sockaddr_un to take up space on stack
742  * permanently */
743 static NOINLINE int create_socket(void)
744 {
745         struct sockaddr_un sunx;
746         int sock_fd;
747         char *dev_log_name;
748
749 #if ENABLE_FEATURE_SYSTEMD
750         if (sd_listen_fds() == 1)
751                 return SD_LISTEN_FDS_START;
752 #endif
753
754         memset(&sunx, 0, sizeof(sunx));
755         sunx.sun_family = AF_UNIX;
756
757         /* Unlink old /dev/log or object it points to. */
758         /* (if it exists, bind will fail) */
759         strcpy(sunx.sun_path, "/dev/log");
760         dev_log_name = xmalloc_follow_symlinks("/dev/log");
761         if (dev_log_name) {
762                 safe_strncpy(sunx.sun_path, dev_log_name, sizeof(sunx.sun_path));
763                 free(dev_log_name);
764         }
765         unlink(sunx.sun_path);
766
767         sock_fd = xsocket(AF_UNIX, SOCK_DGRAM, 0);
768         xbind(sock_fd, (struct sockaddr *) &sunx, sizeof(sunx));
769         chmod("/dev/log", 0666);
770
771         return sock_fd;
772 }
773
774 #if ENABLE_FEATURE_REMOTE_LOG
775 static int try_to_resolve_remote(remoteHost_t *rh)
776 {
777         if (!rh->remoteAddr) {
778                 unsigned now = monotonic_sec();
779
780                 /* Don't resolve name too often - DNS timeouts can be big */
781                 if ((now - rh->last_dns_resolve) < DNS_WAIT_SEC)
782                         return -1;
783                 rh->last_dns_resolve = now;
784                 rh->remoteAddr = host2sockaddr(rh->remoteHostname, 514);
785                 if (!rh->remoteAddr)
786                         return -1;
787         }
788         return xsocket(rh->remoteAddr->u.sa.sa_family, SOCK_DGRAM, 0);
789 }
790 #endif
791
792 static void do_syslogd(void) NORETURN;
793 static void do_syslogd(void)
794 {
795         int sock_fd;
796 #if ENABLE_FEATURE_REMOTE_LOG
797         llist_t *item;
798 #endif
799 #if ENABLE_FEATURE_SYSLOGD_DUP
800         int last_sz = -1;
801         char *last_buf;
802         char *recvbuf = G.recvbuf;
803 #else
804 #define recvbuf (G.recvbuf)
805 #endif
806
807         /* Set up signal handlers (so that they interrupt read()) */
808         signal_no_SA_RESTART_empty_mask(SIGTERM, record_signo);
809         signal_no_SA_RESTART_empty_mask(SIGINT, record_signo);
810         //signal_no_SA_RESTART_empty_mask(SIGQUIT, record_signo);
811         signal(SIGHUP, SIG_IGN);
812 #ifdef SYSLOGD_MARK
813         signal(SIGALRM, do_mark);
814         alarm(G.markInterval);
815 #endif
816         sock_fd = create_socket();
817
818         if (ENABLE_FEATURE_IPC_SYSLOG && (option_mask32 & OPT_circularlog)) {
819                 ipcsyslog_init();
820         }
821
822         timestamp_and_log_internal("syslogd started: BusyBox v" BB_VER);
823
824         while (!bb_got_signal) {
825                 ssize_t sz;
826
827 #if ENABLE_FEATURE_SYSLOGD_DUP
828                 last_buf = recvbuf;
829                 if (recvbuf == G.recvbuf)
830                         recvbuf = G.recvbuf + MAX_READ;
831                 else
832                         recvbuf = G.recvbuf;
833 #endif
834  read_again:
835                 sz = read(sock_fd, recvbuf, MAX_READ - 1);
836                 if (sz < 0) {
837                         if (!bb_got_signal)
838                                 bb_perror_msg("read from /dev/log");
839                         break;
840                 }
841
842                 /* Drop trailing '\n' and NULs (typically there is one NUL) */
843                 while (1) {
844                         if (sz == 0)
845                                 goto read_again;
846                         /* man 3 syslog says: "A trailing newline is added when needed".
847                          * However, neither glibc nor uclibc do this:
848                          * syslog(prio, "test")   sends "test\0" to /dev/log,
849                          * syslog(prio, "test\n") sends "test\n\0".
850                          * IOW: newline is passed verbatim!
851                          * I take it to mean that it's syslogd's job
852                          * to make those look identical in the log files. */
853                         if (recvbuf[sz-1] != '\0' && recvbuf[sz-1] != '\n')
854                                 break;
855                         sz--;
856                 }
857 #if ENABLE_FEATURE_SYSLOGD_DUP
858                 if ((option_mask32 & OPT_dup) && (sz == last_sz))
859                         if (memcmp(last_buf, recvbuf, sz) == 0)
860                                 continue;
861                 last_sz = sz;
862 #endif
863 #if ENABLE_FEATURE_REMOTE_LOG
864                 /* Stock syslogd sends it '\n'-terminated
865                  * over network, mimic that */
866                 recvbuf[sz] = '\n';
867
868                 /* We are not modifying log messages in any way before send */
869                 /* Remote site cannot trust _us_ anyway and need to do validation again */
870                 for (item = G.remoteHosts; item != NULL; item = item->link) {
871                         remoteHost_t *rh = (remoteHost_t *)item->data;
872
873                         if (rh->remoteFD == -1) {
874                                 rh->remoteFD = try_to_resolve_remote(rh);
875                                 if (rh->remoteFD == -1)
876                                         continue;
877                         }
878
879                         /* Send message to remote logger.
880                          * On some errors, close and set remoteFD to -1
881                          * so that DNS resolution is retried.
882                          */
883                         if (sendto(rh->remoteFD, recvbuf, sz+1,
884                                         MSG_DONTWAIT | MSG_NOSIGNAL,
885                                         &(rh->remoteAddr->u.sa), rh->remoteAddr->len) == -1
886                         ) {
887                                 switch (errno) {
888                                 case ECONNRESET:
889                                 case ENOTCONN: /* paranoia */
890                                 case EPIPE:
891                                         close(rh->remoteFD);
892                                         rh->remoteFD = -1;
893                                         free(rh->remoteAddr);
894                                         rh->remoteAddr = NULL;
895                                 }
896                         }
897                 }
898 #endif
899                 if (!ENABLE_FEATURE_REMOTE_LOG || (option_mask32 & OPT_locallog)) {
900                         recvbuf[sz] = '\0'; /* ensure it *is* NUL terminated */
901                         split_escape_and_log(recvbuf, sz);
902                 }
903         } /* while (!bb_got_signal) */
904
905         timestamp_and_log_internal("syslogd exiting");
906         puts("syslogd exiting");
907         if (ENABLE_FEATURE_IPC_SYSLOG)
908                 ipcsyslog_cleanup();
909         kill_myself_with_sig(bb_got_signal);
910 #undef recvbuf
911 }
912
913 int syslogd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
914 int syslogd_main(int argc UNUSED_PARAM, char **argv)
915 {
916         int opts;
917         char OPTION_DECL;
918 #if ENABLE_FEATURE_REMOTE_LOG
919         llist_t *remoteAddrList = NULL;
920 #endif
921
922         INIT_G();
923
924         /* No non-option params, -R can occur multiple times */
925         opt_complementary = "=0" IF_FEATURE_REMOTE_LOG(":R::");
926         opts = getopt32(argv, OPTION_STR, OPTION_PARAM);
927 #if ENABLE_FEATURE_REMOTE_LOG
928         while (remoteAddrList) {
929                 remoteHost_t *rh = xzalloc(sizeof(*rh));
930                 rh->remoteHostname = llist_pop(&remoteAddrList);
931                 rh->remoteFD = -1;
932                 rh->last_dns_resolve = monotonic_sec() - DNS_WAIT_SEC - 1;
933                 llist_add_to(&G.remoteHosts, rh);
934         }
935 #endif
936
937 #ifdef SYSLOGD_MARK
938         if (opts & OPT_mark) // -m
939                 G.markInterval = xatou_range(opt_m, 0, INT_MAX/60) * 60;
940 #endif
941         //if (opts & OPT_nofork) // -n
942         //if (opts & OPT_outfile) // -O
943         if (opts & OPT_loglevel) // -l
944                 G.logLevel = xatou_range(opt_l, 1, 8);
945         //if (opts & OPT_small) // -S
946 #if ENABLE_FEATURE_ROTATE_LOGFILE
947         if (opts & OPT_filesize) // -s
948                 G.logFileSize = xatou_range(opt_s, 0, INT_MAX/1024) * 1024;
949         if (opts & OPT_rotatecnt) // -b
950                 G.logFileRotate = xatou_range(opt_b, 0, 99);
951 #endif
952 #if ENABLE_FEATURE_IPC_SYSLOG
953         if (opt_C) // -Cn
954                 G.shm_size = xatoul_range(opt_C, 4, INT_MAX/1024) * 1024;
955 #endif
956         /* If they have not specified remote logging, then log locally */
957         if (ENABLE_FEATURE_REMOTE_LOG && !(opts & OPT_remotelog)) // -R
958                 option_mask32 |= OPT_locallog;
959 #if ENABLE_FEATURE_SYSLOGD_CFG
960         parse_syslogdcfg(opt_f);
961 #endif
962
963         /* Store away localhost's name before the fork */
964         G.hostname = safe_gethostname();
965         *strchrnul(G.hostname, '.') = '\0';
966
967         if (!(opts & OPT_nofork)) {
968                 bb_daemonize_or_rexec(DAEMON_CHDIR_ROOT, argv);
969         }
970         //umask(0); - why??
971         write_pidfile("/var/run/syslogd.pid");
972         do_syslogd();
973         /* return EXIT_SUCCESS; */
974 }
975
976 /* Clean up. Needed because we are included from syslogd_and_logger.c */
977 #undef DEBUG
978 #undef SYSLOGD_MARK
979 #undef SYSLOGD_WRLOCK
980 #undef G
981 #undef GLOBALS
982 #undef INIT_G
983 #undef OPTION_STR
984 #undef OPTION_DECL
985 #undef OPTION_PARAM