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