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