1
/* vi: set sw=4 ts=4: */
3
* Mini syslogd implementation for busybox
5
* Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
7
* Copyright (C) 2000 by Karl M. Hegbloom <karlheg@debian.org>
9
* "circular buffer" Copyright (C) 2001 by Gennady Feldman <gfeldman@gena01.com>
11
* Maintainer: Gennady Feldman <gfeldman@gena01.com> as of Mar 12, 2001
13
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
15
//config:config SYSLOGD
16
//config: bool "syslogd (13 kb)"
19
//config: The syslogd utility is used to record logs of all the
20
//config: significant events that occur on a system. Every
21
//config: message that is logged records the date and time of the
22
//config: event, and will generally also record the name of the
23
//config: application that generated the message. When used in
24
//config: conjunction with klogd, messages from the Linux kernel
25
//config: can also be recorded. This is terribly useful,
26
//config: especially for finding what happened when something goes
27
//config: wrong. And something almost always will go wrong if
28
//config: you wait long enough....
30
//config:config FEATURE_ROTATE_LOGFILE
31
//config: bool "Rotate message files"
33
//config: depends on SYSLOGD
35
//config: This enables syslogd to rotate the message files
36
//config: on his own. No need to use an external rotate script.
38
//config:config FEATURE_REMOTE_LOG
39
//config: bool "Remote Log support"
41
//config: depends on SYSLOGD
43
//config: When you enable this feature, the syslogd utility can
44
//config: be used to send system log messages to another system
45
//config: connected via a network. This allows the remote
46
//config: machine to log all the system messages, which can be
47
//config: terribly useful for reducing the number of serial
48
//config: cables you use. It can also be a very good security
49
//config: measure to prevent system logs from being tampered with
50
//config: by an intruder.
52
//config:config FEATURE_SYSLOGD_DUP
53
//config: bool "Support -D (drop dups) option"
55
//config: depends on SYSLOGD
57
//config: Option -D instructs syslogd to drop consecutive messages
58
//config: which are totally the same.
60
//config:config FEATURE_SYSLOGD_CFG
61
//config: bool "Support syslog.conf"
63
//config: depends on SYSLOGD
65
//config: Supports restricted syslogd config. See docs/syslog.conf.txt
67
//config:config FEATURE_SYSLOGD_PRECISE_TIMESTAMPS
68
//config: bool "Include milliseconds in timestamps"
70
//config: depends on SYSLOGD
72
//config: Includes milliseconds (HH:MM:SS.mmm) in timestamp when
73
//config: timestamps are added.
75
//config:config FEATURE_SYSLOGD_READ_BUFFER_SIZE
76
//config: int "Read buffer size in bytes"
78
//config: range 256 20000
79
//config: depends on SYSLOGD
81
//config: This option sets the size of the syslog read buffer.
82
//config: Actual memory usage increases around five times the
83
//config: change done here.
85
//config:config FEATURE_IPC_SYSLOG
86
//config: bool "Circular Buffer support"
88
//config: depends on SYSLOGD
90
//config: When you enable this feature, the syslogd utility will
91
//config: use a circular buffer to record system log messages.
92
//config: When the buffer is filled it will continue to overwrite
93
//config: the oldest messages. This can be very useful for
94
//config: systems with little or no permanent storage, since
95
//config: otherwise system logs can eventually fill up your
96
//config: entire filesystem, which may cause your system to
97
//config: break badly.
99
//config:config FEATURE_IPC_SYSLOG_BUFFER_SIZE
100
//config: int "Circular buffer size in Kbytes (minimum 4KB)"
102
//config: range 4 2147483647
103
//config: depends on FEATURE_IPC_SYSLOG
105
//config: This option sets the size of the circular buffer
106
//config: used to record system log messages.
108
//config:config FEATURE_KMSG_SYSLOG
109
//config: bool "Linux kernel printk buffer support"
111
//config: depends on SYSLOGD
112
//config: depends on PLATFORM_LINUX
114
//config: When you enable this feature, the syslogd utility will
115
//config: write system log message to the Linux kernel's printk buffer.
116
//config: This can be used as a smaller alternative to the syslogd IPC
117
//config: support, as klogd and logread aren't needed.
119
//config: NOTICE: Syslog facilities in log entries needs kernel 3.5+.
121
//applet:IF_SYSLOGD(APPLET(syslogd, BB_DIR_SBIN, BB_SUID_DROP))
123
//kbuild:lib-$(CONFIG_SYSLOGD) += syslogd_and_logger.o
125
//usage:#define syslogd_trivial_usage
127
//usage:#define syslogd_full_usage "\n\n"
128
//usage: "System logging utility\n"
129
//usage: IF_NOT_FEATURE_SYSLOGD_CFG(
130
//usage: "(this version of syslogd ignores /etc/syslog.conf)\n"
132
//usage: "\n -n Run in foreground"
133
//usage: IF_FEATURE_REMOTE_LOG(
134
//usage: "\n -R HOST[:PORT] Log to HOST:PORT (default PORT:514)"
135
//usage: "\n -L Log locally and via network (default is network only if -R)"
137
//usage: IF_FEATURE_IPC_SYSLOG(
138
/* NB: -Csize shouldn't have space (because size is optional) */
139
//usage: "\n -C[size_kb] Log to shared mem buffer (use logread to read it)"
141
//usage: IF_FEATURE_KMSG_SYSLOG(
142
//usage: "\n -K Log to kernel printk buffer (use dmesg to read it)"
144
//usage: "\n -O FILE Log to FILE (default: /var/log/messages, stdout if -)"
145
//usage: IF_FEATURE_ROTATE_LOGFILE(
146
//usage: "\n -s SIZE Max size (KB) before rotation (default 200KB, 0=off)"
147
//usage: "\n -b N N rotated logs to keep (default 1, max 99, 0=purge)"
149
//usage: "\n -l N Log only messages more urgent than prio N (1-8)"
150
//usage: "\n -S Smaller output"
151
//usage: "\n -t Strip client-generated timestamps"
152
//usage: IF_FEATURE_SYSLOGD_DUP(
153
//usage: "\n -D Drop duplicates"
155
//usage: IF_FEATURE_SYSLOGD_CFG(
156
//usage: "\n -f FILE Use FILE as config (default:/etc/syslog.conf)"
158
/* //usage: "\n -m MIN Minutes between MARK lines (default 20, 0=off)" */
160
//usage:#define syslogd_example_usage
161
//usage: "$ syslogd -R masterlog:514\n"
162
//usage: "$ syslogd -R 192.168.1.1:601\n"
165
* Done in syslogd_and_logger.c:
168
#define SYSLOG_NAMES_CONST
172
#define _PATH_LOG "/dev/log"
178
#if ENABLE_FEATURE_REMOTE_LOG
179
#include <netinet/in.h>
182
#if ENABLE_FEATURE_IPC_SYSLOG
191
/* MARK code is not very useful, is bloat, and broken:
192
* can deadlock if alarmed to make MARK while writing to IPC buffer
193
* (semaphores are down but do_mark routine tries to down them again) */
196
/* Write locking does not seem to be useful either */
197
#undef SYSLOGD_WRLOCK
200
MAX_READ = CONFIG_FEATURE_SYSLOGD_READ_BUFFER_SIZE,
201
DNS_WAIT_SEC = 2 * 60,
204
/* Semaphore operation structures */
206
int32_t size; /* size of data - 1 */
207
int32_t tail; /* end of message list */
208
char data[1]; /* data/messages */
211
#if ENABLE_FEATURE_REMOTE_LOG
214
unsigned last_dns_resolve;
215
len_and_sockaddr *remoteAddr;
216
const char *remoteHostname;
220
typedef struct logFile_t {
223
time_t last_log_time;
224
#if ENABLE_FEATURE_ROTATE_LOGFILE
230
#if ENABLE_FEATURE_SYSLOGD_CFG
231
typedef struct logRule_t {
232
uint8_t enabled_facility_priomap[LOG_NFACILITIES];
233
struct logFile_t *file;
234
struct logRule_t *next;
238
/* Allows us to have smaller initializer. Ugly. */
241
/* interval between marks in seconds */ \
242
/*int markInterval;*/ \
243
/* level of messages to be logged */ \
245
IF_FEATURE_ROTATE_LOGFILE( \
246
/* max size of file before rotation */ \
247
unsigned logFileSize; \
248
/* number of rotated message files */ \
249
unsigned logFileRotate; \
251
IF_FEATURE_IPC_SYSLOG( \
252
int shmid; /* ipc shared memory id */ \
253
int s_semid; /* ipc semaphore id */ \
255
struct sembuf SMwup[1]; \
256
struct sembuf SMwdn[3]; \
258
IF_FEATURE_SYSLOGD_CFG( \
259
logRule_t *log_rules; \
261
IF_FEATURE_KMSG_SYSLOG( \
266
struct init_globals {
273
#if ENABLE_FEATURE_REMOTE_LOG
274
llist_t *remoteHosts;
276
#if ENABLE_FEATURE_IPC_SYSLOG
277
struct shbuf_ds *shbuf;
279
/* localhost's name. We print only first 64 chars */
282
/* We recv into recvbuf... */
283
char recvbuf[MAX_READ * (1 + ENABLE_FEATURE_SYSLOGD_DUP)];
284
/* ...then copy to parsebuf, escaping control chars */
285
/* (can grow x2 max) */
286
char parsebuf[MAX_READ*2];
287
/* ...then sprintf into printbuf, adding timestamp (15 or 19 chars),
288
* host (64), fac.prio (20) to the message */
289
/* (growth by: 15 + 64 + 20 + delims = ~110) */
290
char printbuf[MAX_READ*2 + 128];
293
static const struct init_globals init_data = {
295
.path = "/var/log/messages",
299
.markInterval = 20 * 60,
302
#if ENABLE_FEATURE_ROTATE_LOGFILE
303
.logFileSize = 200 * 1024,
306
#if ENABLE_FEATURE_IPC_SYSLOG
309
.shm_size = ((CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE)*1024), /* default shm size */
310
.SMwup = { {1, -1, IPC_NOWAIT} },
311
.SMwdn = { {0, 0}, {1, 0}, {1, +1} },
315
#define G (*ptr_to_globals)
316
#define INIT_G() do { \
317
SET_PTR_TO_GLOBALS(memcpy(xzalloc(sizeof(G)), &init_data, sizeof(init_data))); \
323
OPTBIT_mark = 0, // -m
325
OPTBIT_outfile, // -O
326
OPTBIT_loglevel, // -l
328
OPTBIT_timestamp, // -t
329
IF_FEATURE_ROTATE_LOGFILE(OPTBIT_filesize ,) // -s
330
IF_FEATURE_ROTATE_LOGFILE(OPTBIT_rotatecnt ,) // -b
331
IF_FEATURE_REMOTE_LOG( OPTBIT_remotelog ,) // -R
332
IF_FEATURE_REMOTE_LOG( OPTBIT_locallog ,) // -L
333
IF_FEATURE_IPC_SYSLOG( OPTBIT_circularlog,) // -C
334
IF_FEATURE_SYSLOGD_DUP( OPTBIT_dup ,) // -D
335
IF_FEATURE_SYSLOGD_CFG( OPTBIT_cfg ,) // -f
336
IF_FEATURE_KMSG_SYSLOG( OPTBIT_kmsg ,) // -K
338
OPT_mark = 1 << OPTBIT_mark ,
339
OPT_nofork = 1 << OPTBIT_nofork ,
340
OPT_outfile = 1 << OPTBIT_outfile ,
341
OPT_loglevel = 1 << OPTBIT_loglevel,
342
OPT_small = 1 << OPTBIT_small ,
343
OPT_timestamp = 1 << OPTBIT_timestamp,
344
OPT_filesize = IF_FEATURE_ROTATE_LOGFILE((1 << OPTBIT_filesize )) + 0,
345
OPT_rotatecnt = IF_FEATURE_ROTATE_LOGFILE((1 << OPTBIT_rotatecnt )) + 0,
346
OPT_remotelog = IF_FEATURE_REMOTE_LOG( (1 << OPTBIT_remotelog )) + 0,
347
OPT_locallog = IF_FEATURE_REMOTE_LOG( (1 << OPTBIT_locallog )) + 0,
348
OPT_circularlog = IF_FEATURE_IPC_SYSLOG( (1 << OPTBIT_circularlog)) + 0,
349
OPT_dup = IF_FEATURE_SYSLOGD_DUP( (1 << OPTBIT_dup )) + 0,
350
OPT_cfg = IF_FEATURE_SYSLOGD_CFG( (1 << OPTBIT_cfg )) + 0,
351
OPT_kmsg = IF_FEATURE_KMSG_SYSLOG( (1 << OPTBIT_kmsg )) + 0,
353
#define OPTION_STR "m:nO:l:St" \
354
IF_FEATURE_ROTATE_LOGFILE("s:" ) \
355
IF_FEATURE_ROTATE_LOGFILE("b:" ) \
356
IF_FEATURE_REMOTE_LOG( "R:*") \
357
IF_FEATURE_REMOTE_LOG( "L" ) \
358
IF_FEATURE_IPC_SYSLOG( "C::") \
359
IF_FEATURE_SYSLOGD_DUP( "D" ) \
360
IF_FEATURE_SYSLOGD_CFG( "f:" ) \
361
IF_FEATURE_KMSG_SYSLOG( "K" )
362
#define OPTION_DECL *opt_m, *opt_l \
363
IF_FEATURE_ROTATE_LOGFILE(,*opt_s) \
364
IF_FEATURE_ROTATE_LOGFILE(,*opt_b) \
365
IF_FEATURE_IPC_SYSLOG( ,*opt_C = NULL) \
366
IF_FEATURE_SYSLOGD_CFG( ,*opt_f = NULL)
367
#define OPTION_PARAM &opt_m, &(G.logFile.path), &opt_l \
368
IF_FEATURE_ROTATE_LOGFILE(,&opt_s) \
369
IF_FEATURE_ROTATE_LOGFILE(,&opt_b) \
370
IF_FEATURE_REMOTE_LOG( ,&remoteAddrList) \
371
IF_FEATURE_IPC_SYSLOG( ,&opt_C) \
372
IF_FEATURE_SYSLOGD_CFG( ,&opt_f)
375
#if ENABLE_FEATURE_SYSLOGD_CFG
376
static const CODE* find_by_name(char *name, const CODE* c_set)
378
for (; c_set->c_name; c_set++) {
379
if (strcmp(name, c_set->c_name) == 0)
385
static const CODE* find_by_val(int val, const CODE* c_set)
387
for (; c_set->c_name; c_set++) {
388
if (c_set->c_val == val)
394
#if ENABLE_FEATURE_SYSLOGD_CFG
395
static void parse_syslogdcfg(const char *file)
399
/* tok[0] set of selectors */
400
/* tok[1] file name */
401
/* tok[2] has to be NULL */
405
parser = config_open2(file ? file : "/etc/syslog.conf",
406
file ? xfopen_for_read : fopen_for_read);
408
/* didn't find default /etc/syslog.conf */
409
/* proceed as if we built busybox without config support */
412
/* use ptr to ptr to avoid checking whether head was initialized */
413
pp_rule = &G.log_rules;
414
/* iterate through lines of config, skipping comments */
415
while (config_read(parser, tok, 3, 2, "# \t", PARSE_NORMAL | PARSE_MIN_DIE)) {
419
/* unexpected trailing token? */
423
cur_rule = *pp_rule = xzalloc(sizeof(*cur_rule));
425
cur_selector = tok[0];
426
/* iterate through selectors: "kern.info;kern.!err;..." */
430
uint8_t negated_prio; /* "kern.!err" */
431
uint8_t single_prio; /* "kern.=err" */
432
uint32_t facmap; /* bitmap of enabled facilities */
433
uint8_t primap; /* bitmap of enabled priorities */
436
next_selector = strchr(cur_selector, ';');
438
*next_selector++ = '\0';
440
t = strchr(cur_selector, '.');
443
*t++ = '\0'; /* separate facility from priority */
458
primap = 0xff; /* all 8 log levels enabled */
461
code = find_by_name(t, bb_prioritynames);
465
priority = code->c_val;
466
if (priority == INTERNAL_NOPRI) {
467
/* ensure we take "enabled_facility_priomap[fac] &= 0" branch below */
470
priority = 1 << priority;
483
if (*cur_selector == '*')
484
facmap = (1<<LOG_NFACILITIES) - 1;
489
/* iterate through facilities: "kern,daemon.<priospec>" */
491
next_facility = strchr(t, ',');
493
*next_facility++ = '\0';
494
code = find_by_name(t, bb_facilitynames);
497
/* "mark" is not a real facility, skip it */
498
if (code->c_val != INTERNAL_MARK)
499
facmap |= 1<<(LOG_FAC(code->c_val));
504
/* merge result with previous selectors */
505
for (i = 0; i < LOG_NFACILITIES; ++i) {
506
if (!(facmap & (1<<i)))
509
cur_rule->enabled_facility_priomap[i] &= primap;
511
cur_rule->enabled_facility_priomap[i] |= primap;
514
cur_selector = next_selector;
515
} while (cur_selector);
517
/* check whether current file name was mentioned in previous rules or
518
* as global logfile (G.logFile).
520
if (strcmp(G.logFile.path, tok[1]) == 0) {
521
cur_rule->file = &G.logFile;
524
/* temporarily use cur_rule as iterator, but *pp_rule still points
525
* to currently processing rule entry.
526
* NOTE: *pp_rule points to the current (and last in the list) rule.
528
for (cur_rule = G.log_rules; cur_rule != *pp_rule; cur_rule = cur_rule->next) {
529
if (strcmp(cur_rule->file->path, tok[1]) == 0) {
530
/* found - reuse the same file structure */
531
(*pp_rule)->file = cur_rule->file;
536
cur_rule->file = xzalloc(sizeof(*cur_rule->file));
537
cur_rule->file->fd = -1;
538
cur_rule->file->path = xstrdup(tok[1]);
540
pp_rule = &cur_rule->next;
542
config_close(parser);
546
bb_error_msg_and_die("error in '%s' at line %d",
547
file ? file : "/etc/syslog.conf",
552
/* circular buffer variables/structures */
553
#if ENABLE_FEATURE_IPC_SYSLOG
555
#if CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE < 4
556
#error Sorry, you must set the syslogd buffer size to at least 4KB.
557
#error Please check CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE
560
/* our shared key (syslogd.c and logread.c must be in sync) */
561
enum { KEY_ID = 0x414e4547 }; /* "GENA" */
563
static void ipcsyslog_cleanup(void)
569
shmctl(G.shmid, IPC_RMID, NULL);
571
if (G.s_semid != -1) {
572
semctl(G.s_semid, 0, IPC_RMID, 0);
576
static void ipcsyslog_init(void)
579
printf("shmget(%x, %d,...)\n", (int)KEY_ID, G.shm_size);
581
G.shmid = shmget(KEY_ID, G.shm_size, IPC_CREAT | 0644);
583
bb_simple_perror_msg_and_die("shmget");
586
G.shbuf = shmat(G.shmid, NULL, 0);
587
if (G.shbuf == (void*) -1L) { /* shmat has bizarre error return */
588
bb_simple_perror_msg_and_die("shmat");
591
memset(G.shbuf, 0, G.shm_size);
592
G.shbuf->size = G.shm_size - offsetof(struct shbuf_ds, data) - 1;
593
/*G.shbuf->tail = 0;*/
595
/* we'll trust the OS to set initial semval to 0 (let's hope) */
596
G.s_semid = semget(KEY_ID, 2, IPC_CREAT | IPC_EXCL | 1023);
597
if (G.s_semid == -1) {
598
if (errno == EEXIST) {
599
G.s_semid = semget(KEY_ID, 2, 0);
603
bb_simple_perror_msg_and_die("semget");
607
/* Write message to shared mem buffer */
608
static void log_to_shmem(const char *msg)
610
int old_tail, new_tail;
613
if (semop(G.s_semid, G.SMwdn, 3) == -1) {
614
bb_simple_perror_msg_and_die("SMwdn");
617
/* Circular Buffer Algorithm:
618
* --------------------------
619
* tail == position where to store next syslog message.
620
* tail's max value is (shbuf->size - 1)
621
* Last byte of buffer is never used and remains NUL.
623
len = strlen(msg) + 1; /* length with NUL included */
625
old_tail = G.shbuf->tail;
626
new_tail = old_tail + len;
627
if (new_tail < G.shbuf->size) {
628
/* store message, set new tail */
629
memcpy(G.shbuf->data + old_tail, msg, len);
630
G.shbuf->tail = new_tail;
632
/* k == available buffer space ahead of old tail */
633
int k = G.shbuf->size - old_tail;
634
/* copy what fits to the end of buffer, and repeat */
635
memcpy(G.shbuf->data + old_tail, msg, k);
641
if (semop(G.s_semid, G.SMwup, 1) == -1) {
642
bb_simple_perror_msg_and_die("SMwup");
645
printf("tail:%d\n", G.shbuf->tail);
648
static void ipcsyslog_cleanup(void) {}
649
static void ipcsyslog_init(void) {}
650
void log_to_shmem(const char *msg);
651
#endif /* FEATURE_IPC_SYSLOG */
653
#if ENABLE_FEATURE_KMSG_SYSLOG
654
static void kmsg_init(void)
656
G.kmsgfd = xopen("/dev/kmsg", O_WRONLY);
659
* kernel < 3.5 expects single char printk KERN_* priority prefix,
660
* from 3.5 onwards the full syslog facility/priority format is supported
662
if (get_linux_version_code() < KERNEL_VERSION(3,5,0))
663
G.primask = LOG_PRIMASK;
668
static void kmsg_cleanup(void)
670
if (ENABLE_FEATURE_CLEAN_UP)
674
/* Write message to /dev/kmsg */
675
static void log_to_kmsg(int pri, const char *msg)
678
* kernel < 3.5 expects single char printk KERN_* priority prefix,
679
* from 3.5 onwards the full syslog facility/priority format is supported
683
full_write(G.kmsgfd, G.printbuf, sprintf(G.printbuf, "<%d>%s\n", pri, msg));
686
static void kmsg_init(void) {}
687
static void kmsg_cleanup(void) {}
688
static void log_to_kmsg(int pri UNUSED_PARAM, const char *msg UNUSED_PARAM) {}
689
#endif /* FEATURE_KMSG_SYSLOG */
691
/* Print a message to the log file. */
692
static void log_locally(time_t now, char *msg, logFile_t *log_file)
694
#ifdef SYSLOGD_WRLOCK
697
int len = strlen(msg);
699
/* fd can't be 0 (we connect fd 0 to /dev/log socket) */
700
/* fd is 1 if "-O -" is in use */
701
if (log_file->fd > 1) {
702
/* Reopen log files every second. This allows admin
703
* to delete the files and not worry about restarting us.
704
* This costs almost nothing since it happens
705
* _at most_ once a second for each file, and happens
706
* only when each file is actually written.
710
if (log_file->last_log_time != now) {
711
log_file->last_log_time = now;
716
else if (log_file->fd == 1) {
717
/* We are logging to stdout: do nothing */
720
if (LONE_DASH(log_file->path)) {
722
/* log_file->isRegular = 0; - already is */
725
log_file->fd = open(log_file->path, O_WRONLY | O_CREAT
726
| O_NOCTTY | O_APPEND | O_NONBLOCK,
728
if (log_file->fd < 0) {
729
/* cannot open logfile? - print to /dev/console then */
730
int fd = device_open(DEV_CONSOLE, O_WRONLY | O_NOCTTY | O_NONBLOCK);
732
fd = 2; /* then stderr, dammit */
733
full_write(fd, msg, len);
738
#if ENABLE_FEATURE_ROTATE_LOGFILE
741
log_file->isRegular = (fstat(log_file->fd, &statf) == 0 && S_ISREG(statf.st_mode));
742
/* bug (mostly harmless): can wrap around if file > 4gb */
743
log_file->size = statf.st_size;
749
#ifdef SYSLOGD_WRLOCK
750
fl.l_whence = SEEK_SET;
754
fcntl(log_file->fd, F_SETLKW, &fl);
757
#if ENABLE_FEATURE_ROTATE_LOGFILE
758
if (G.logFileSize && log_file->isRegular && log_file->size > G.logFileSize) {
759
if (G.logFileRotate) { /* always 0..99 */
760
int i = strlen(log_file->path) + 3 + 1;
763
i = G.logFileRotate - 1;
764
/* rename: f.8 -> f.9; f.7 -> f.8; ... */
766
sprintf(newFile, "%s.%d", log_file->path, i);
768
sprintf(oldFile, "%s.%d", log_file->path, --i);
769
/* ignore errors - file might be missing */
770
rename(oldFile, newFile);
772
/* newFile == "f.0" now */
773
rename(log_file->path, newFile);
776
/* We may or may not have just renamed the file away;
777
* if we didn't rename because we aren't keeping any backlog,
778
* then it's time to clobber the file. If we did rename it...,
779
* incredibly, if F and F.0 are hardlinks, POSIX _demands_
780
* that rename returns 0 but does not remove F!!!
781
* (hardlinked F/F.0 pair was observed after
782
* power failure during rename()).
783
* So ensure old file is gone in any case:
785
unlink(log_file->path);
786
#ifdef SYSLOGD_WRLOCK
788
fcntl(log_file->fd, F_SETLKW, &fl);
793
/* TODO: what to do on write errors ("disk full")? */
794
len = full_write(log_file->fd, msg, len);
796
log_file->size += len;
798
full_write(log_file->fd, msg, len);
801
#ifdef SYSLOGD_WRLOCK
803
fcntl(log_file->fd, F_SETLKW, &fl);
807
static void parse_fac_prio_20(int pri, char *res20)
809
const CODE *c_pri, *c_fac;
811
c_fac = find_by_val(LOG_FAC(pri) << 3, bb_facilitynames);
813
c_pri = find_by_val(LOG_PRI(pri), bb_prioritynames);
815
snprintf(res20, 20, "%s.%s", c_fac->c_name, c_pri->c_name);
819
snprintf(res20, 20, "<%d>", pri);
822
/* len parameter is used only for "is there a timestamp?" check.
823
* NB: some callers cheat and supply len==0 when they know
824
* that there is no timestamp, short-circuiting the test. */
825
static void timestamp_and_log(int pri, char *msg, int len)
827
char *timestamp = NULL;
830
/* Jan 18 00:11:22 msg... */
831
/* 01234567890123456 */
832
if (len >= 16 && msg[3] == ' ' && msg[6] == ' '
833
&& msg[9] == ':' && msg[12] == ':' && msg[15] == ' '
835
if (!(option_mask32 & OPT_timestamp)) {
836
/* use message timestamp */
843
#if ENABLE_FEATURE_SYSLOGD_PRECISE_TIMESTAMPS
848
timestamp = ctime(&now) + 4; /* skip day of week */
849
/* overwrite year by milliseconds, zero terminate */
850
sprintf(timestamp + 15, ".%03u", (unsigned)tv.tv_usec / 1000u);
852
timestamp[15] = '\0';
857
timestamp = ctime(&now) + 4; /* skip day of week */
859
timestamp[15] = '\0';
862
if (option_mask32 & OPT_kmsg) {
863
log_to_kmsg(pri, msg);
867
if (option_mask32 & OPT_small)
868
sprintf(G.printbuf, "%s %s\n", timestamp, msg);
871
parse_fac_prio_20(pri, res);
872
sprintf(G.printbuf, "%s %.64s %s %s\n", timestamp, G.hostname, res, msg);
875
/* Log message locally (to file or shared mem) */
876
#if ENABLE_FEATURE_SYSLOGD_CFG
880
uint8_t facility = LOG_FAC(pri);
881
uint8_t prio_bit = 1 << LOG_PRI(pri);
883
for (rule = G.log_rules; rule; rule = rule->next) {
884
if (rule->enabled_facility_priomap[facility] & prio_bit) {
885
log_locally(now, G.printbuf, rule->file);
893
if (LOG_PRI(pri) < G.logLevel) {
894
#if ENABLE_FEATURE_IPC_SYSLOG
895
if ((option_mask32 & OPT_circularlog) && G.shbuf) {
896
log_to_shmem(G.printbuf);
900
log_locally(now, G.printbuf, &G.logFile);
904
static void timestamp_and_log_internal(const char *msg)
907
if (ENABLE_FEATURE_REMOTE_LOG && !(option_mask32 & OPT_locallog))
909
timestamp_and_log(LOG_SYSLOG | LOG_INFO, (char*)msg, 0);
912
/* tmpbuf[len] is a NUL byte (set by caller), but there can be other,
913
* embedded NULs. Split messages on each of these NULs, parse prio,
914
* escape control chars and log each locally. */
915
static void split_escape_and_log(char *tmpbuf, int len)
922
char *q = G.parsebuf;
923
int pri = (LOG_USER | LOG_NOTICE);
926
/* Parse the magic priority number */
927
pri = bb_strtou(p + 1, &p, 10);
930
if (pri & ~(LOG_FACMASK | LOG_PRIMASK))
931
pri = (LOG_USER | LOG_NOTICE);
937
if (!(c & ~0x1f) && c != '\t') {
939
c += '@'; /* ^@, ^A, ^B... */
946
timestamp_and_log(pri, G.parsebuf, q - G.parsebuf);
951
static void do_mark(int sig)
953
if (G.markInterval) {
954
timestamp_and_log_internal("-- MARK --");
955
alarm(G.markInterval);
960
/* Don't inline: prevent struct sockaddr_un to take up space on stack
962
static NOINLINE int create_socket(void)
964
struct sockaddr_un sunx;
968
memset(&sunx, 0, sizeof(sunx));
969
sunx.sun_family = AF_UNIX;
971
/* Unlink old /dev/log or object it points to. */
972
/* (if it exists, bind will fail) */
973
strcpy(sunx.sun_path, _PATH_LOG);
974
dev_log_name = xmalloc_follow_symlinks(_PATH_LOG);
976
safe_strncpy(sunx.sun_path, dev_log_name, sizeof(sunx.sun_path));
979
unlink(sunx.sun_path);
981
sock_fd = xsocket(AF_UNIX, SOCK_DGRAM, 0);
982
xbind(sock_fd, (struct sockaddr *) &sunx, sizeof(sunx));
983
chmod(_PATH_LOG, 0666);
988
#if ENABLE_FEATURE_REMOTE_LOG
989
static int try_to_resolve_remote(remoteHost_t *rh)
991
if (!rh->remoteAddr) {
992
unsigned now = monotonic_sec();
994
/* Don't resolve name too often - DNS timeouts can be big */
995
if ((now - rh->last_dns_resolve) < DNS_WAIT_SEC)
997
rh->last_dns_resolve = now;
998
rh->remoteAddr = host2sockaddr(rh->remoteHostname, 514);
1002
return xsocket(rh->remoteAddr->u.sa.sa_family, SOCK_DGRAM, 0);
1006
static void do_syslogd(void) NORETURN;
1007
static void do_syslogd(void)
1009
#if ENABLE_FEATURE_REMOTE_LOG
1012
#if ENABLE_FEATURE_SYSLOGD_DUP
1015
char *recvbuf = G.recvbuf;
1017
#define recvbuf (G.recvbuf)
1020
/* Set up signal handlers (so that they interrupt read()) */
1021
signal_no_SA_RESTART_empty_mask(SIGTERM, record_signo);
1022
signal_no_SA_RESTART_empty_mask(SIGINT, record_signo);
1023
//signal_no_SA_RESTART_empty_mask(SIGQUIT, record_signo);
1024
signal(SIGHUP, SIG_IGN);
1026
signal(SIGALRM, do_mark);
1027
alarm(G.markInterval);
1029
xmove_fd(create_socket(), STDIN_FILENO);
1031
if (option_mask32 & OPT_circularlog)
1034
if (option_mask32 & OPT_kmsg)
1037
timestamp_and_log_internal("syslogd started: BusyBox v" BB_VER);
1038
write_pidfile_std_path_and_ext("syslogd");
1040
while (!bb_got_signal) {
1043
#if ENABLE_FEATURE_SYSLOGD_DUP
1045
if (recvbuf == G.recvbuf)
1046
recvbuf = G.recvbuf + MAX_READ;
1048
recvbuf = G.recvbuf;
1051
sz = read(STDIN_FILENO, recvbuf, MAX_READ - 1);
1054
bb_perror_msg("read from %s", _PATH_LOG);
1058
/* Drop trailing '\n' and NULs (typically there is one NUL) */
1062
/* man 3 syslog says: "A trailing newline is added when needed".
1063
* However, neither glibc nor uclibc do this:
1064
* syslog(prio, "test") sends "test\0" to /dev/log,
1065
* syslog(prio, "test\n") sends "test\n\0".
1066
* IOW: newline is passed verbatim!
1067
* I take it to mean that it's syslogd's job
1068
* to make those look identical in the log files. */
1069
if (recvbuf[sz-1] != '\0' && recvbuf[sz-1] != '\n')
1073
#if ENABLE_FEATURE_SYSLOGD_DUP
1074
if ((option_mask32 & OPT_dup) && (sz == last_sz))
1075
if (memcmp(last_buf, recvbuf, sz) == 0)
1079
#if ENABLE_FEATURE_REMOTE_LOG
1080
/* Stock syslogd sends it '\n'-terminated
1081
* over network, mimic that */
1084
/* We are not modifying log messages in any way before send */
1085
/* Remote site cannot trust _us_ anyway and need to do validation again */
1086
for (item = G.remoteHosts; item != NULL; item = item->link) {
1087
remoteHost_t *rh = (remoteHost_t *)item->data;
1089
if (rh->remoteFD == -1) {
1090
rh->remoteFD = try_to_resolve_remote(rh);
1091
if (rh->remoteFD == -1)
1095
/* Send message to remote logger.
1096
* On some errors, close and set remoteFD to -1
1097
* so that DNS resolution is retried.
1099
if (sendto(rh->remoteFD, recvbuf, sz+1,
1100
MSG_DONTWAIT | MSG_NOSIGNAL,
1101
&(rh->remoteAddr->u.sa), rh->remoteAddr->len) == -1
1105
case ENOTCONN: /* paranoia */
1107
close(rh->remoteFD);
1109
free(rh->remoteAddr);
1110
rh->remoteAddr = NULL;
1115
if (!ENABLE_FEATURE_REMOTE_LOG || (option_mask32 & OPT_locallog)) {
1116
recvbuf[sz] = '\0'; /* ensure it *is* NUL terminated */
1117
split_escape_and_log(recvbuf, sz);
1119
} /* while (!bb_got_signal) */
1121
timestamp_and_log_internal("syslogd exiting");
1122
remove_pidfile_std_path_and_ext("syslogd");
1123
ipcsyslog_cleanup();
1124
if (option_mask32 & OPT_kmsg)
1126
kill_myself_with_sig(bb_got_signal);
1130
int syslogd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
1131
int syslogd_main(int argc UNUSED_PARAM, char **argv)
1135
#if ENABLE_FEATURE_REMOTE_LOG
1136
llist_t *remoteAddrList = NULL;
1141
/* No non-option params */
1142
opts = getopt32(argv, "^"OPTION_STR"\0""=0", OPTION_PARAM);
1143
#if ENABLE_FEATURE_REMOTE_LOG
1144
while (remoteAddrList) {
1145
remoteHost_t *rh = xzalloc(sizeof(*rh));
1146
rh->remoteHostname = llist_pop(&remoteAddrList);
1148
rh->last_dns_resolve = monotonic_sec() - DNS_WAIT_SEC - 1;
1149
llist_add_to(&G.remoteHosts, rh);
1154
if (opts & OPT_mark) // -m
1155
G.markInterval = xatou_range(opt_m, 0, INT_MAX/60) * 60;
1157
//if (opts & OPT_nofork) // -n
1158
//if (opts & OPT_outfile) // -O
1159
if (opts & OPT_loglevel) // -l
1160
G.logLevel = xatou_range(opt_l, 1, 8);
1161
//if (opts & OPT_small) // -S
1162
#if ENABLE_FEATURE_ROTATE_LOGFILE
1163
if (opts & OPT_filesize) // -s
1164
G.logFileSize = xatou_range(opt_s, 0, INT_MAX/1024) * 1024;
1165
if (opts & OPT_rotatecnt) // -b
1166
G.logFileRotate = xatou_range(opt_b, 0, 99);
1168
#if ENABLE_FEATURE_IPC_SYSLOG
1170
G.shm_size = xatoul_range(opt_C, 4, INT_MAX/1024) * 1024;
1172
/* If they have not specified remote logging, then log locally */
1173
if (ENABLE_FEATURE_REMOTE_LOG && !(opts & OPT_remotelog)) // -R
1174
option_mask32 |= OPT_locallog;
1175
#if ENABLE_FEATURE_SYSLOGD_CFG
1176
parse_syslogdcfg(opt_f);
1179
/* Store away localhost's name before the fork */
1180
G.hostname = safe_gethostname();
1181
*strchrnul(G.hostname, '.') = '\0';
1183
if (!(opts & OPT_nofork)) {
1184
bb_daemonize_or_rexec(DAEMON_CHDIR_ROOT, argv);
1188
/* return EXIT_SUCCESS; */
1191
/* Clean up. Needed because we are included from syslogd_and_logger.c */
1194
#undef SYSLOGD_WRLOCK