syslogd.c 28 KB

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