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