syslogd.c 26 KB

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