~mmach/netext73/busybox

« back to all changes in this revision

Viewing changes to .pc/syslogd-decrease-stack-usage-50-bytes.patch/sysklogd/syslogd.c

  • Committer: mmach
  • Date: 2023-07-06 04:40:25 UTC
  • Revision ID: netbit73@gmail.com-20230706044025-2ia9985i8wzdn2a7
1.36.1

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
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
//config:config SYSLOGD
 
16
//config:       bool "syslogd (13 kb)"
 
17
//config:       default y
 
18
//config:       help
 
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....
 
29
//config:
 
30
//config:config FEATURE_ROTATE_LOGFILE
 
31
//config:       bool "Rotate message files"
 
32
//config:       default y
 
33
//config:       depends on SYSLOGD
 
34
//config:       help
 
35
//config:       This enables syslogd to rotate the message files
 
36
//config:       on his own. No need to use an external rotate script.
 
37
//config:
 
38
//config:config FEATURE_REMOTE_LOG
 
39
//config:       bool "Remote Log support"
 
40
//config:       default y
 
41
//config:       depends on SYSLOGD
 
42
//config:       help
 
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.
 
51
//config:
 
52
//config:config FEATURE_SYSLOGD_DUP
 
53
//config:       bool "Support -D (drop dups) option"
 
54
//config:       default y
 
55
//config:       depends on SYSLOGD
 
56
//config:       help
 
57
//config:       Option -D instructs syslogd to drop consecutive messages
 
58
//config:       which are totally the same.
 
59
//config:
 
60
//config:config FEATURE_SYSLOGD_CFG
 
61
//config:       bool "Support syslog.conf"
 
62
//config:       default y
 
63
//config:       depends on SYSLOGD
 
64
//config:       help
 
65
//config:       Supports restricted syslogd config. See docs/syslog.conf.txt
 
66
//config:
 
67
//config:config FEATURE_SYSLOGD_PRECISE_TIMESTAMPS
 
68
//config:       bool "Include milliseconds in timestamps"
 
69
//config:       default n
 
70
//config:       depends on SYSLOGD
 
71
//config:       help
 
72
//config:       Includes milliseconds (HH:MM:SS.mmm) in timestamp when
 
73
//config:       timestamps are added.
 
74
//config:
 
75
//config:config FEATURE_SYSLOGD_READ_BUFFER_SIZE
 
76
//config:       int "Read buffer size in bytes"
 
77
//config:       default 256
 
78
//config:       range 256 20000
 
79
//config:       depends on SYSLOGD
 
80
//config:       help
 
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.
 
84
//config:
 
85
//config:config FEATURE_IPC_SYSLOG
 
86
//config:       bool "Circular Buffer support"
 
87
//config:       default y
 
88
//config:       depends on SYSLOGD
 
89
//config:       help
 
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.
 
98
//config:
 
99
//config:config FEATURE_IPC_SYSLOG_BUFFER_SIZE
 
100
//config:       int "Circular buffer size in Kbytes (minimum 4KB)"
 
101
//config:       default 16
 
102
//config:       range 4 2147483647
 
103
//config:       depends on FEATURE_IPC_SYSLOG
 
104
//config:       help
 
105
//config:       This option sets the size of the circular buffer
 
106
//config:       used to record system log messages.
 
107
//config:
 
108
//config:config FEATURE_KMSG_SYSLOG
 
109
//config:       bool "Linux kernel printk buffer support"
 
110
//config:       default y
 
111
//config:       depends on SYSLOGD
 
112
//config:       depends on PLATFORM_LINUX
 
113
//config:       help
 
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.
 
118
//config:
 
119
//config:       NOTICE: Syslog facilities in log entries needs kernel 3.5+.
 
120
 
 
121
//applet:IF_SYSLOGD(APPLET(syslogd, BB_DIR_SBIN, BB_SUID_DROP))
 
122
 
 
123
//kbuild:lib-$(CONFIG_SYSLOGD) += syslogd_and_logger.o
 
124
 
 
125
//usage:#define syslogd_trivial_usage
 
126
//usage:       "[OPTIONS]"
 
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"
 
131
//usage:        )
 
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)"
 
136
//usage:        )
 
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)"
 
140
//usage:        )
 
141
//usage:        IF_FEATURE_KMSG_SYSLOG(
 
142
//usage:     "\n        -K              Log to kernel printk buffer (use dmesg to read it)"
 
143
//usage:        )
 
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)"
 
148
//usage:        )
 
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"
 
154
//usage:        )
 
155
//usage:        IF_FEATURE_SYSLOGD_CFG(
 
156
//usage:     "\n        -f FILE         Use FILE as config (default:/etc/syslog.conf)"
 
157
//usage:        )
 
158
/* //usage:  "\n        -m MIN          Minutes between MARK lines (default 20, 0=off)" */
 
159
//usage:
 
160
//usage:#define syslogd_example_usage
 
161
//usage:       "$ syslogd -R masterlog:514\n"
 
162
//usage:       "$ syslogd -R 192.168.1.1:601\n"
 
163
 
 
164
/*
 
165
 * Done in syslogd_and_logger.c:
 
166
#include "libbb.h"
 
167
#define SYSLOG_NAMES
 
168
#define SYSLOG_NAMES_CONST
 
169
#include <syslog.h>
 
170
*/
 
171
#ifndef _PATH_LOG
 
172
#define _PATH_LOG       "/dev/log"
 
173
#endif
 
174
 
 
175
#include <sys/un.h>
 
176
#include <sys/uio.h>
 
177
 
 
178
#if ENABLE_FEATURE_REMOTE_LOG
 
179
#include <netinet/in.h>
 
180
#endif
 
181
 
 
182
#if ENABLE_FEATURE_IPC_SYSLOG
 
183
#include <sys/ipc.h>
 
184
#include <sys/sem.h>
 
185
#include <sys/shm.h>
 
186
#endif
 
187
 
 
188
 
 
189
#define DEBUG 0
 
190
 
 
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) */
 
194
#undef SYSLOGD_MARK
 
195
 
 
196
/* Write locking does not seem to be useful either */
 
197
#undef SYSLOGD_WRLOCK
 
198
 
 
199
enum {
 
200
        MAX_READ = CONFIG_FEATURE_SYSLOGD_READ_BUFFER_SIZE,
 
201
        DNS_WAIT_SEC = 2 * 60,
 
202
};
 
203
 
 
204
/* Semaphore operation structures */
 
205
struct shbuf_ds {
 
206
        int32_t size;   /* size of data - 1 */
 
207
        int32_t tail;   /* end of message list */
 
208
        char data[1];   /* data/messages */
 
209
};
 
210
 
 
211
#if ENABLE_FEATURE_REMOTE_LOG
 
212
typedef struct {
 
213
        int remoteFD;
 
214
        unsigned last_dns_resolve;
 
215
        len_and_sockaddr *remoteAddr;
 
216
        const char *remoteHostname;
 
217
} remoteHost_t;
 
218
#endif
 
219
 
 
220
typedef struct logFile_t {
 
221
        const char *path;
 
222
        int fd;
 
223
        time_t last_log_time;
 
224
#if ENABLE_FEATURE_ROTATE_LOGFILE
 
225
        unsigned size;
 
226
        uint8_t isRegular;
 
227
#endif
 
228
} logFile_t;
 
229
 
 
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;
 
235
} logRule_t;
 
236
#endif
 
237
 
 
238
/* Allows us to have smaller initializer. Ugly. */
 
239
#define GLOBALS \
 
240
        logFile_t logFile;                      \
 
241
        /* interval between marks in seconds */ \
 
242
        /*int markInterval;*/                   \
 
243
        /* level of messages to be logged */    \
 
244
        int logLevel;                           \
 
245
IF_FEATURE_ROTATE_LOGFILE( \
 
246
        /* max size of file before rotation */  \
 
247
        unsigned logFileSize;                   \
 
248
        /* number of rotated message files */   \
 
249
        unsigned logFileRotate;                 \
 
250
) \
 
251
IF_FEATURE_IPC_SYSLOG( \
 
252
        int shmid; /* ipc shared memory id */   \
 
253
        int s_semid; /* ipc semaphore id */     \
 
254
        int shm_size;                           \
 
255
        struct sembuf SMwup[1];                 \
 
256
        struct sembuf SMwdn[3];                 \
 
257
) \
 
258
IF_FEATURE_SYSLOGD_CFG( \
 
259
        logRule_t *log_rules; \
 
260
) \
 
261
IF_FEATURE_KMSG_SYSLOG( \
 
262
        int kmsgfd; \
 
263
        int primask; \
 
264
)
 
265
 
 
266
struct init_globals {
 
267
        GLOBALS
 
268
};
 
269
 
 
270
struct globals {
 
271
        GLOBALS
 
272
 
 
273
#if ENABLE_FEATURE_REMOTE_LOG
 
274
        llist_t *remoteHosts;
 
275
#endif
 
276
#if ENABLE_FEATURE_IPC_SYSLOG
 
277
        struct shbuf_ds *shbuf;
 
278
#endif
 
279
        /* localhost's name. We print only first 64 chars */
 
280
        char *hostname;
 
281
 
 
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];
 
291
};
 
292
 
 
293
static const struct init_globals init_data = {
 
294
        .logFile = {
 
295
                .path = "/var/log/messages",
 
296
                .fd = -1,
 
297
        },
 
298
#ifdef SYSLOGD_MARK
 
299
        .markInterval = 20 * 60,
 
300
#endif
 
301
        .logLevel = 8,
 
302
#if ENABLE_FEATURE_ROTATE_LOGFILE
 
303
        .logFileSize = 200 * 1024,
 
304
        .logFileRotate = 1,
 
305
#endif
 
306
#if ENABLE_FEATURE_IPC_SYSLOG
 
307
        .shmid = -1,
 
308
        .s_semid = -1,
 
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} },
 
312
#endif
 
313
};
 
314
 
 
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))); \
 
318
} while (0)
 
319
 
 
320
 
 
321
/* Options */
 
322
enum {
 
323
        OPTBIT_mark = 0, // -m
 
324
        OPTBIT_nofork, // -n
 
325
        OPTBIT_outfile, // -O
 
326
        OPTBIT_loglevel, // -l
 
327
        OPTBIT_small, // -S
 
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
 
337
 
 
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,
 
352
};
 
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)
 
373
 
 
374
 
 
375
#if ENABLE_FEATURE_SYSLOGD_CFG
 
376
static const CODE* find_by_name(char *name, const CODE* c_set)
 
377
{
 
378
        for (; c_set->c_name; c_set++) {
 
379
                if (strcmp(name, c_set->c_name) == 0)
 
380
                        return c_set;
 
381
        }
 
382
        return NULL;
 
383
}
 
384
#endif
 
385
static const CODE* find_by_val(int val, const CODE* c_set)
 
386
{
 
387
        for (; c_set->c_name; c_set++) {
 
388
                if (c_set->c_val == val)
 
389
                        return c_set;
 
390
        }
 
391
        return NULL;
 
392
}
 
393
 
 
394
#if ENABLE_FEATURE_SYSLOGD_CFG
 
395
static void parse_syslogdcfg(const char *file)
 
396
{
 
397
        char *t;
 
398
        logRule_t **pp_rule;
 
399
        /* tok[0] set of selectors */
 
400
        /* tok[1] file name */
 
401
        /* tok[2] has to be NULL */
 
402
        char *tok[3];
 
403
        parser_t *parser;
 
404
 
 
405
        parser = config_open2(file ? file : "/etc/syslog.conf",
 
406
                                file ? xfopen_for_read : fopen_for_read);
 
407
        if (!parser)
 
408
                /* didn't find default /etc/syslog.conf */
 
409
                /* proceed as if we built busybox without config support */
 
410
                return;
 
411
 
 
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)) {
 
416
                char *cur_selector;
 
417
                logRule_t *cur_rule;
 
418
 
 
419
                /* unexpected trailing token? */
 
420
                if (tok[2])
 
421
                        goto cfgerr;
 
422
 
 
423
                cur_rule = *pp_rule = xzalloc(sizeof(*cur_rule));
 
424
 
 
425
                cur_selector = tok[0];
 
426
                /* iterate through selectors: "kern.info;kern.!err;..." */
 
427
                do {
 
428
                        const CODE *code;
 
429
                        char *next_selector;
 
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 */
 
434
                        unsigned i;
 
435
 
 
436
                        next_selector = strchr(cur_selector, ';');
 
437
                        if (next_selector)
 
438
                                *next_selector++ = '\0';
 
439
 
 
440
                        t = strchr(cur_selector, '.');
 
441
                        if (!t)
 
442
                                goto cfgerr;
 
443
                        *t++ = '\0'; /* separate facility from priority */
 
444
 
 
445
                        negated_prio = 0;
 
446
                        single_prio = 0;
 
447
                        if (*t == '!') {
 
448
                                negated_prio = 1;
 
449
                                ++t;
 
450
                        }
 
451
                        if (*t == '=') {
 
452
                                single_prio = 1;
 
453
                                ++t;
 
454
                        }
 
455
 
 
456
                        /* parse priority */
 
457
                        if (*t == '*')
 
458
                                primap = 0xff; /* all 8 log levels enabled */
 
459
                        else {
 
460
                                uint8_t priority;
 
461
                                code = find_by_name(t, bb_prioritynames);
 
462
                                if (!code)
 
463
                                        goto cfgerr;
 
464
                                primap = 0;
 
465
                                priority = code->c_val;
 
466
                                if (priority == INTERNAL_NOPRI) {
 
467
                                        /* ensure we take "enabled_facility_priomap[fac] &= 0" branch below */
 
468
                                        negated_prio = 1;
 
469
                                } else {
 
470
                                        priority = 1 << priority;
 
471
                                        do {
 
472
                                                primap |= priority;
 
473
                                                if (single_prio)
 
474
                                                        break;
 
475
                                                priority >>= 1;
 
476
                                        } while (priority);
 
477
                                        if (negated_prio)
 
478
                                                primap = ~primap;
 
479
                                }
 
480
                        }
 
481
 
 
482
                        /* parse facility */
 
483
                        if (*cur_selector == '*')
 
484
                                facmap = (1<<LOG_NFACILITIES) - 1;
 
485
                        else {
 
486
                                char *next_facility;
 
487
                                facmap = 0;
 
488
                                t = cur_selector;
 
489
                                /* iterate through facilities: "kern,daemon.<priospec>" */
 
490
                                do {
 
491
                                        next_facility = strchr(t, ',');
 
492
                                        if (next_facility)
 
493
                                                *next_facility++ = '\0';
 
494
                                        code = find_by_name(t, bb_facilitynames);
 
495
                                        if (!code)
 
496
                                                goto cfgerr;
 
497
                                        /* "mark" is not a real facility, skip it */
 
498
                                        if (code->c_val != INTERNAL_MARK)
 
499
                                                facmap |= 1<<(LOG_FAC(code->c_val));
 
500
                                        t = next_facility;
 
501
                                } while (t);
 
502
                        }
 
503
 
 
504
                        /* merge result with previous selectors */
 
505
                        for (i = 0; i < LOG_NFACILITIES; ++i) {
 
506
                                if (!(facmap & (1<<i)))
 
507
                                        continue;
 
508
                                if (negated_prio)
 
509
                                        cur_rule->enabled_facility_priomap[i] &= primap;
 
510
                                else
 
511
                                        cur_rule->enabled_facility_priomap[i] |= primap;
 
512
                        }
 
513
 
 
514
                        cur_selector = next_selector;
 
515
                } while (cur_selector);
 
516
 
 
517
                /* check whether current file name was mentioned in previous rules or
 
518
                 * as global logfile (G.logFile).
 
519
                 */
 
520
                if (strcmp(G.logFile.path, tok[1]) == 0) {
 
521
                        cur_rule->file = &G.logFile;
 
522
                        goto found;
 
523
                }
 
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.
 
527
                 */
 
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;
 
532
                                cur_rule = *pp_rule;
 
533
                                goto found;
 
534
                        }
 
535
                }
 
536
                cur_rule->file = xzalloc(sizeof(*cur_rule->file));
 
537
                cur_rule->file->fd = -1;
 
538
                cur_rule->file->path = xstrdup(tok[1]);
 
539
 found:
 
540
                pp_rule = &cur_rule->next;
 
541
        }
 
542
        config_close(parser);
 
543
        return;
 
544
 
 
545
 cfgerr:
 
546
        bb_error_msg_and_die("error in '%s' at line %d",
 
547
                        file ? file : "/etc/syslog.conf",
 
548
                        parser->lineno);
 
549
}
 
550
#endif
 
551
 
 
552
/* circular buffer variables/structures */
 
553
#if ENABLE_FEATURE_IPC_SYSLOG
 
554
 
 
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
 
558
#endif
 
559
 
 
560
/* our shared key (syslogd.c and logread.c must be in sync) */
 
561
enum { KEY_ID = 0x414e4547 }; /* "GENA" */
 
562
 
 
563
static void ipcsyslog_cleanup(void)
 
564
{
 
565
        if (G.shmid != -1) {
 
566
                shmdt(G.shbuf);
 
567
        }
 
568
        if (G.shmid != -1) {
 
569
                shmctl(G.shmid, IPC_RMID, NULL);
 
570
        }
 
571
        if (G.s_semid != -1) {
 
572
                semctl(G.s_semid, 0, IPC_RMID, 0);
 
573
        }
 
574
}
 
575
 
 
576
static void ipcsyslog_init(void)
 
577
{
 
578
        if (DEBUG)
 
579
                printf("shmget(%x, %d,...)\n", (int)KEY_ID, G.shm_size);
 
580
 
 
581
        G.shmid = shmget(KEY_ID, G.shm_size, IPC_CREAT | 0644);
 
582
        if (G.shmid == -1) {
 
583
                bb_simple_perror_msg_and_die("shmget");
 
584
        }
 
585
 
 
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");
 
589
        }
 
590
 
 
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;*/
 
594
 
 
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);
 
600
                        if (G.s_semid != -1)
 
601
                                return;
 
602
                }
 
603
                bb_simple_perror_msg_and_die("semget");
 
604
        }
 
605
}
 
606
 
 
607
/* Write message to shared mem buffer */
 
608
static void log_to_shmem(const char *msg)
 
609
{
 
610
        int old_tail, new_tail;
 
611
        int len;
 
612
 
 
613
        if (semop(G.s_semid, G.SMwdn, 3) == -1) {
 
614
                bb_simple_perror_msg_and_die("SMwdn");
 
615
        }
 
616
 
 
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.
 
622
         */
 
623
        len = strlen(msg) + 1; /* length with NUL included */
 
624
 again:
 
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;
 
631
        } else {
 
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);
 
636
                msg += k;
 
637
                len -= k;
 
638
                G.shbuf->tail = 0;
 
639
                goto again;
 
640
        }
 
641
        if (semop(G.s_semid, G.SMwup, 1) == -1) {
 
642
                bb_simple_perror_msg_and_die("SMwup");
 
643
        }
 
644
        if (DEBUG)
 
645
                printf("tail:%d\n", G.shbuf->tail);
 
646
}
 
647
#else
 
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 */
 
652
 
 
653
#if ENABLE_FEATURE_KMSG_SYSLOG
 
654
static void kmsg_init(void)
 
655
{
 
656
        G.kmsgfd = xopen("/dev/kmsg", O_WRONLY);
 
657
 
 
658
        /*
 
659
         * kernel < 3.5 expects single char printk KERN_* priority prefix,
 
660
         * from 3.5 onwards the full syslog facility/priority format is supported
 
661
         */
 
662
        if (get_linux_version_code() < KERNEL_VERSION(3,5,0))
 
663
                G.primask = LOG_PRIMASK;
 
664
        else
 
665
                G.primask = -1;
 
666
}
 
667
 
 
668
static void kmsg_cleanup(void)
 
669
{
 
670
        if (ENABLE_FEATURE_CLEAN_UP)
 
671
                close(G.kmsgfd);
 
672
}
 
673
 
 
674
/* Write message to /dev/kmsg */
 
675
static void log_to_kmsg(int pri, const char *msg)
 
676
{
 
677
        /*
 
678
         * kernel < 3.5 expects single char printk KERN_* priority prefix,
 
679
         * from 3.5 onwards the full syslog facility/priority format is supported
 
680
         */
 
681
        pri &= G.primask;
 
682
 
 
683
        full_write(G.kmsgfd, G.printbuf, sprintf(G.printbuf, "<%d>%s\n", pri, msg));
 
684
}
 
685
#else
 
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 */
 
690
 
 
691
/* Print a message to the log file. */
 
692
static void log_locally(time_t now, char *msg, logFile_t *log_file)
 
693
{
 
694
#ifdef SYSLOGD_WRLOCK
 
695
        struct flock fl;
 
696
#endif
 
697
        int len = strlen(msg);
 
698
 
 
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.
 
707
                 */
 
708
                if (!now)
 
709
                        now = time(NULL);
 
710
                if (log_file->last_log_time != now) {
 
711
                        log_file->last_log_time = now;
 
712
                        close(log_file->fd);
 
713
                        goto reopen;
 
714
                }
 
715
        }
 
716
        else if (log_file->fd == 1) {
 
717
                /* We are logging to stdout: do nothing */
 
718
        }
 
719
        else {
 
720
                if (LONE_DASH(log_file->path)) {
 
721
                        log_file->fd = 1;
 
722
                        /* log_file->isRegular = 0; - already is */
 
723
                } else {
 
724
 reopen:
 
725
                        log_file->fd = open(log_file->path, O_WRONLY | O_CREAT
 
726
                                        | O_NOCTTY | O_APPEND | O_NONBLOCK,
 
727
                                        0666);
 
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);
 
731
                                if (fd < 0)
 
732
                                        fd = 2; /* then stderr, dammit */
 
733
                                full_write(fd, msg, len);
 
734
                                if (fd != 2)
 
735
                                        close(fd);
 
736
                                return;
 
737
                        }
 
738
#if ENABLE_FEATURE_ROTATE_LOGFILE
 
739
                        {
 
740
                                struct stat statf;
 
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;
 
744
                        }
 
745
#endif
 
746
                }
 
747
        }
 
748
 
 
749
#ifdef SYSLOGD_WRLOCK
 
750
        fl.l_whence = SEEK_SET;
 
751
        fl.l_start = 0;
 
752
        fl.l_len = 1;
 
753
        fl.l_type = F_WRLCK;
 
754
        fcntl(log_file->fd, F_SETLKW, &fl);
 
755
#endif
 
756
 
 
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;
 
761
                        char oldFile[i];
 
762
                        char newFile[i];
 
763
                        i = G.logFileRotate - 1;
 
764
                        /* rename: f.8 -> f.9; f.7 -> f.8; ... */
 
765
                        while (1) {
 
766
                                sprintf(newFile, "%s.%d", log_file->path, i);
 
767
                                if (i == 0) break;
 
768
                                sprintf(oldFile, "%s.%d", log_file->path, --i);
 
769
                                /* ignore errors - file might be missing */
 
770
                                rename(oldFile, newFile);
 
771
                        }
 
772
                        /* newFile == "f.0" now */
 
773
                        rename(log_file->path, newFile);
 
774
                }
 
775
 
 
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:
 
784
                 */
 
785
                unlink(log_file->path);
 
786
#ifdef SYSLOGD_WRLOCK
 
787
                fl.l_type = F_UNLCK;
 
788
                fcntl(log_file->fd, F_SETLKW, &fl);
 
789
#endif
 
790
                close(log_file->fd);
 
791
                goto reopen;
 
792
        }
 
793
/* TODO: what to do on write errors ("disk full")? */
 
794
        len = full_write(log_file->fd, msg, len);
 
795
        if (len > 0)
 
796
                log_file->size += len;
 
797
#else
 
798
        full_write(log_file->fd, msg, len);
 
799
#endif
 
800
 
 
801
#ifdef SYSLOGD_WRLOCK
 
802
        fl.l_type = F_UNLCK;
 
803
        fcntl(log_file->fd, F_SETLKW, &fl);
 
804
#endif
 
805
}
 
806
 
 
807
static void parse_fac_prio_20(int pri, char *res20)
 
808
{
 
809
        const CODE *c_pri, *c_fac;
 
810
 
 
811
        c_fac = find_by_val(LOG_FAC(pri) << 3, bb_facilitynames);
 
812
        if (c_fac) {
 
813
                c_pri = find_by_val(LOG_PRI(pri), bb_prioritynames);
 
814
                if (c_pri) {
 
815
                        snprintf(res20, 20, "%s.%s", c_fac->c_name, c_pri->c_name);
 
816
                        return;
 
817
                }
 
818
        }
 
819
        snprintf(res20, 20, "<%d>", pri);
 
820
}
 
821
 
 
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)
 
826
{
 
827
        char *timestamp = NULL;
 
828
        time_t now;
 
829
 
 
830
        /* Jan 18 00:11:22 msg... */
 
831
        /* 01234567890123456 */
 
832
        if (len >= 16 && msg[3] == ' ' && msg[6] == ' '
 
833
         && msg[9] == ':' && msg[12] == ':' && msg[15] == ' '
 
834
        ) {
 
835
                if (!(option_mask32 & OPT_timestamp)) {
 
836
                        /* use message timestamp */
 
837
                        timestamp = msg;
 
838
                        now = 0;
 
839
                }
 
840
                msg += 16;
 
841
        }
 
842
 
 
843
#if ENABLE_FEATURE_SYSLOGD_PRECISE_TIMESTAMPS
 
844
        if (!timestamp) {
 
845
                struct timeval tv;
 
846
                xgettimeofday(&tv);
 
847
                now = tv.tv_sec;
 
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);
 
851
        } else {
 
852
                timestamp[15] = '\0';
 
853
        }
 
854
#else
 
855
        if (!timestamp) {
 
856
                time(&now);
 
857
                timestamp = ctime(&now) + 4; /* skip day of week */
 
858
        }
 
859
        timestamp[15] = '\0';
 
860
#endif
 
861
 
 
862
        if (option_mask32 & OPT_kmsg) {
 
863
                log_to_kmsg(pri, msg);
 
864
                return;
 
865
        }
 
866
 
 
867
        if (option_mask32 & OPT_small)
 
868
                sprintf(G.printbuf, "%s %s\n", timestamp, msg);
 
869
        else {
 
870
                char res[20];
 
871
                parse_fac_prio_20(pri, res);
 
872
                sprintf(G.printbuf, "%s %.64s %s %s\n", timestamp, G.hostname, res, msg);
 
873
        }
 
874
 
 
875
        /* Log message locally (to file or shared mem) */
 
876
#if ENABLE_FEATURE_SYSLOGD_CFG
 
877
        {
 
878
                bool match = 0;
 
879
                logRule_t *rule;
 
880
                uint8_t facility = LOG_FAC(pri);
 
881
                uint8_t prio_bit = 1 << LOG_PRI(pri);
 
882
 
 
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);
 
886
                                match = 1;
 
887
                        }
 
888
                }
 
889
                if (match)
 
890
                        return;
 
891
        }
 
892
#endif
 
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);
 
897
                        return;
 
898
                }
 
899
#endif
 
900
                log_locally(now, G.printbuf, &G.logFile);
 
901
        }
 
902
}
 
903
 
 
904
static void timestamp_and_log_internal(const char *msg)
 
905
{
 
906
        /* -L, or no -R */
 
907
        if (ENABLE_FEATURE_REMOTE_LOG && !(option_mask32 & OPT_locallog))
 
908
                return;
 
909
        timestamp_and_log(LOG_SYSLOG | LOG_INFO, (char*)msg, 0);
 
910
}
 
911
 
 
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)
 
916
{
 
917
        char *p = tmpbuf;
 
918
 
 
919
        tmpbuf += len;
 
920
        while (p < tmpbuf) {
 
921
                char c;
 
922
                char *q = G.parsebuf;
 
923
                int pri = (LOG_USER | LOG_NOTICE);
 
924
 
 
925
                if (*p == '<') {
 
926
                        /* Parse the magic priority number */
 
927
                        pri = bb_strtou(p + 1, &p, 10);
 
928
                        if (*p == '>')
 
929
                                p++;
 
930
                        if (pri & ~(LOG_FACMASK | LOG_PRIMASK))
 
931
                                pri = (LOG_USER | LOG_NOTICE);
 
932
                }
 
933
 
 
934
                while ((c = *p++)) {
 
935
                        if (c == '\n')
 
936
                                c = ' ';
 
937
                        if (!(c & ~0x1f) && c != '\t') {
 
938
                                *q++ = '^';
 
939
                                c += '@'; /* ^@, ^A, ^B... */
 
940
                        }
 
941
                        *q++ = c;
 
942
                }
 
943
                *q = '\0';
 
944
 
 
945
                /* Now log it */
 
946
                timestamp_and_log(pri, G.parsebuf, q - G.parsebuf);
 
947
        }
 
948
}
 
949
 
 
950
#ifdef SYSLOGD_MARK
 
951
static void do_mark(int sig)
 
952
{
 
953
        if (G.markInterval) {
 
954
                timestamp_and_log_internal("-- MARK --");
 
955
                alarm(G.markInterval);
 
956
        }
 
957
}
 
958
#endif
 
959
 
 
960
/* Don't inline: prevent struct sockaddr_un to take up space on stack
 
961
 * permanently */
 
962
static NOINLINE int create_socket(void)
 
963
{
 
964
        struct sockaddr_un sunx;
 
965
        int sock_fd;
 
966
        char *dev_log_name;
 
967
 
 
968
        memset(&sunx, 0, sizeof(sunx));
 
969
        sunx.sun_family = AF_UNIX;
 
970
 
 
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);
 
975
        if (dev_log_name) {
 
976
                safe_strncpy(sunx.sun_path, dev_log_name, sizeof(sunx.sun_path));
 
977
                free(dev_log_name);
 
978
        }
 
979
        unlink(sunx.sun_path);
 
980
 
 
981
        sock_fd = xsocket(AF_UNIX, SOCK_DGRAM, 0);
 
982
        xbind(sock_fd, (struct sockaddr *) &sunx, sizeof(sunx));
 
983
        chmod(_PATH_LOG, 0666);
 
984
 
 
985
        return sock_fd;
 
986
}
 
987
 
 
988
#if ENABLE_FEATURE_REMOTE_LOG
 
989
static int try_to_resolve_remote(remoteHost_t *rh)
 
990
{
 
991
        if (!rh->remoteAddr) {
 
992
                unsigned now = monotonic_sec();
 
993
 
 
994
                /* Don't resolve name too often - DNS timeouts can be big */
 
995
                if ((now - rh->last_dns_resolve) < DNS_WAIT_SEC)
 
996
                        return -1;
 
997
                rh->last_dns_resolve = now;
 
998
                rh->remoteAddr = host2sockaddr(rh->remoteHostname, 514);
 
999
                if (!rh->remoteAddr)
 
1000
                        return -1;
 
1001
        }
 
1002
        return xsocket(rh->remoteAddr->u.sa.sa_family, SOCK_DGRAM, 0);
 
1003
}
 
1004
#endif
 
1005
 
 
1006
static void do_syslogd(void) NORETURN;
 
1007
static void do_syslogd(void)
 
1008
{
 
1009
#if ENABLE_FEATURE_REMOTE_LOG
 
1010
        llist_t *item;
 
1011
#endif
 
1012
#if ENABLE_FEATURE_SYSLOGD_DUP
 
1013
        int last_sz = -1;
 
1014
        char *last_buf;
 
1015
        char *recvbuf = G.recvbuf;
 
1016
#else
 
1017
#define recvbuf (G.recvbuf)
 
1018
#endif
 
1019
 
 
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);
 
1025
#ifdef SYSLOGD_MARK
 
1026
        signal(SIGALRM, do_mark);
 
1027
        alarm(G.markInterval);
 
1028
#endif
 
1029
        xmove_fd(create_socket(), STDIN_FILENO);
 
1030
 
 
1031
        if (option_mask32 & OPT_circularlog)
 
1032
                ipcsyslog_init();
 
1033
 
 
1034
        if (option_mask32 & OPT_kmsg)
 
1035
                kmsg_init();
 
1036
 
 
1037
        timestamp_and_log_internal("syslogd started: BusyBox v" BB_VER);
 
1038
        write_pidfile_std_path_and_ext("syslogd");
 
1039
 
 
1040
        while (!bb_got_signal) {
 
1041
                ssize_t sz;
 
1042
 
 
1043
#if ENABLE_FEATURE_SYSLOGD_DUP
 
1044
                last_buf = recvbuf;
 
1045
                if (recvbuf == G.recvbuf)
 
1046
                        recvbuf = G.recvbuf + MAX_READ;
 
1047
                else
 
1048
                        recvbuf = G.recvbuf;
 
1049
#endif
 
1050
 read_again:
 
1051
                sz = read(STDIN_FILENO, recvbuf, MAX_READ - 1);
 
1052
                if (sz < 0) {
 
1053
                        if (!bb_got_signal)
 
1054
                                bb_perror_msg("read from %s", _PATH_LOG);
 
1055
                        break;
 
1056
                }
 
1057
 
 
1058
                /* Drop trailing '\n' and NULs (typically there is one NUL) */
 
1059
                while (1) {
 
1060
                        if (sz == 0)
 
1061
                                goto read_again;
 
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')
 
1070
                                break;
 
1071
                        sz--;
 
1072
                }
 
1073
#if ENABLE_FEATURE_SYSLOGD_DUP
 
1074
                if ((option_mask32 & OPT_dup) && (sz == last_sz))
 
1075
                        if (memcmp(last_buf, recvbuf, sz) == 0)
 
1076
                                continue;
 
1077
                last_sz = sz;
 
1078
#endif
 
1079
#if ENABLE_FEATURE_REMOTE_LOG
 
1080
                /* Stock syslogd sends it '\n'-terminated
 
1081
                 * over network, mimic that */
 
1082
                recvbuf[sz] = '\n';
 
1083
 
 
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;
 
1088
 
 
1089
                        if (rh->remoteFD == -1) {
 
1090
                                rh->remoteFD = try_to_resolve_remote(rh);
 
1091
                                if (rh->remoteFD == -1)
 
1092
                                        continue;
 
1093
                        }
 
1094
 
 
1095
                        /* Send message to remote logger.
 
1096
                         * On some errors, close and set remoteFD to -1
 
1097
                         * so that DNS resolution is retried.
 
1098
                         */
 
1099
                        if (sendto(rh->remoteFD, recvbuf, sz+1,
 
1100
                                        MSG_DONTWAIT | MSG_NOSIGNAL,
 
1101
                                        &(rh->remoteAddr->u.sa), rh->remoteAddr->len) == -1
 
1102
                        ) {
 
1103
                                switch (errno) {
 
1104
                                case ECONNRESET:
 
1105
                                case ENOTCONN: /* paranoia */
 
1106
                                case EPIPE:
 
1107
                                        close(rh->remoteFD);
 
1108
                                        rh->remoteFD = -1;
 
1109
                                        free(rh->remoteAddr);
 
1110
                                        rh->remoteAddr = NULL;
 
1111
                                }
 
1112
                        }
 
1113
                }
 
1114
#endif
 
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);
 
1118
                }
 
1119
        } /* while (!bb_got_signal) */
 
1120
 
 
1121
        timestamp_and_log_internal("syslogd exiting");
 
1122
        remove_pidfile_std_path_and_ext("syslogd");
 
1123
        ipcsyslog_cleanup();
 
1124
        if (option_mask32 & OPT_kmsg)
 
1125
                kmsg_cleanup();
 
1126
        kill_myself_with_sig(bb_got_signal);
 
1127
#undef recvbuf
 
1128
}
 
1129
 
 
1130
int syslogd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
 
1131
int syslogd_main(int argc UNUSED_PARAM, char **argv)
 
1132
{
 
1133
        int opts;
 
1134
        char OPTION_DECL;
 
1135
#if ENABLE_FEATURE_REMOTE_LOG
 
1136
        llist_t *remoteAddrList = NULL;
 
1137
#endif
 
1138
 
 
1139
        INIT_G();
 
1140
 
 
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);
 
1147
                rh->remoteFD = -1;
 
1148
                rh->last_dns_resolve = monotonic_sec() - DNS_WAIT_SEC - 1;
 
1149
                llist_add_to(&G.remoteHosts, rh);
 
1150
        }
 
1151
#endif
 
1152
 
 
1153
#ifdef SYSLOGD_MARK
 
1154
        if (opts & OPT_mark) // -m
 
1155
                G.markInterval = xatou_range(opt_m, 0, INT_MAX/60) * 60;
 
1156
#endif
 
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);
 
1167
#endif
 
1168
#if ENABLE_FEATURE_IPC_SYSLOG
 
1169
        if (opt_C) // -Cn
 
1170
                G.shm_size = xatoul_range(opt_C, 4, INT_MAX/1024) * 1024;
 
1171
#endif
 
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);
 
1177
#endif
 
1178
 
 
1179
        /* Store away localhost's name before the fork */
 
1180
        G.hostname = safe_gethostname();
 
1181
        *strchrnul(G.hostname, '.') = '\0';
 
1182
 
 
1183
        if (!(opts & OPT_nofork)) {
 
1184
                bb_daemonize_or_rexec(DAEMON_CHDIR_ROOT, argv);
 
1185
        }
 
1186
 
 
1187
        do_syslogd();
 
1188
        /* return EXIT_SUCCESS; */
 
1189
}
 
1190
 
 
1191
/* Clean up. Needed because we are included from syslogd_and_logger.c */
 
1192
#undef DEBUG
 
1193
#undef SYSLOGD_MARK
 
1194
#undef SYSLOGD_WRLOCK
 
1195
#undef G
 
1196
#undef GLOBALS
 
1197
#undef INIT_G
 
1198
#undef OPTION_STR
 
1199
#undef OPTION_DECL
 
1200
#undef OPTION_PARAM