3
0

syslogd.c 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078
  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: IF_FEATURE_REMOTE_LOG(
  24. //usage: "\n -R HOST[:PORT] Log to HOST:PORT (default PORT:514)"
  25. //usage: "\n -L Log locally and via network (default is network only if -R)"
  26. //usage: )
  27. //usage: IF_FEATURE_IPC_SYSLOG(
  28. /* NB: -Csize shouldn't have space (because size is optional) */
  29. //usage: "\n -C[size_kb] Log to shared mem buffer (use logread to read it)"
  30. //usage: )
  31. //usage: IF_FEATURE_KMSG_SYSLOG(
  32. //usage: "\n -K Log to kernel printk buffer (use dmesg to read it)"
  33. //usage: )
  34. //usage: "\n -O FILE Log to FILE (default:/var/log/messages, stdout if -)"
  35. //usage: IF_FEATURE_ROTATE_LOGFILE(
  36. //usage: "\n -s SIZE Max size (KB) before rotation (default:200KB, 0=off)"
  37. //usage: "\n -b N N rotated logs to keep (default:1, max=99, 0=purge)"
  38. //usage: )
  39. //usage: "\n -l N Log only messages more urgent than prio N (1-8)"
  40. //usage: "\n -S Smaller output"
  41. //usage: IF_FEATURE_SYSLOGD_DUP(
  42. //usage: "\n -D Drop duplicates"
  43. //usage: )
  44. //usage: IF_FEATURE_SYSLOGD_CFG(
  45. //usage: "\n -f FILE Use FILE as config (default:/etc/syslog.conf)"
  46. //usage: )
  47. /* //usage: "\n -m MIN Minutes between MARK lines (default:20, 0=off)" */
  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. time_t last_log_time;
  101. #if ENABLE_FEATURE_ROTATE_LOGFILE
  102. unsigned size;
  103. uint8_t isRegular;
  104. #endif
  105. } logFile_t;
  106. #if ENABLE_FEATURE_SYSLOGD_CFG
  107. typedef struct logRule_t {
  108. uint8_t enabled_facility_priomap[LOG_NFACILITIES];
  109. struct logFile_t *file;
  110. struct logRule_t *next;
  111. } logRule_t;
  112. #endif
  113. /* Allows us to have smaller initializer. Ugly. */
  114. #define GLOBALS \
  115. logFile_t logFile; \
  116. /* interval between marks in seconds */ \
  117. /*int markInterval;*/ \
  118. /* level of messages to be logged */ \
  119. int logLevel; \
  120. IF_FEATURE_ROTATE_LOGFILE( \
  121. /* max size of file before rotation */ \
  122. unsigned logFileSize; \
  123. /* number of rotated message files */ \
  124. unsigned logFileRotate; \
  125. ) \
  126. IF_FEATURE_IPC_SYSLOG( \
  127. int shmid; /* ipc shared memory id */ \
  128. int s_semid; /* ipc semaphore id */ \
  129. int shm_size; \
  130. struct sembuf SMwup[1]; \
  131. struct sembuf SMwdn[3]; \
  132. ) \
  133. IF_FEATURE_SYSLOGD_CFG( \
  134. logRule_t *log_rules; \
  135. ) \
  136. IF_FEATURE_KMSG_SYSLOG( \
  137. int kmsgfd; \
  138. int primask; \
  139. )
  140. struct init_globals {
  141. GLOBALS
  142. };
  143. struct globals {
  144. GLOBALS
  145. #if ENABLE_FEATURE_REMOTE_LOG
  146. llist_t *remoteHosts;
  147. #endif
  148. #if ENABLE_FEATURE_IPC_SYSLOG
  149. struct shbuf_ds *shbuf;
  150. #endif
  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. full_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. /* fd can't be 0 (we connect fd 0 to /dev/log socket) */
  528. /* fd is 1 if "-O -" is in use */
  529. if (log_file->fd > 1) {
  530. /* Reopen log files every second. This allows admin
  531. * to delete the files and not worry about restarting us.
  532. * This costs almost nothing since it happens
  533. * _at most_ once a second for each file, and happens
  534. * only when each file is actually written.
  535. */
  536. if (!now)
  537. now = time(NULL);
  538. if (log_file->last_log_time != now) {
  539. log_file->last_log_time = now;
  540. close(log_file->fd);
  541. goto reopen;
  542. }
  543. }
  544. else if (log_file->fd == 1) {
  545. /* We are logging to stdout: do nothing */
  546. }
  547. else {
  548. if (LONE_DASH(log_file->path)) {
  549. log_file->fd = 1;
  550. /* log_file->isRegular = 0; - already is */
  551. } else {
  552. reopen:
  553. log_file->fd = open(log_file->path, O_WRONLY | O_CREAT
  554. | O_NOCTTY | O_APPEND | O_NONBLOCK,
  555. 0666);
  556. if (log_file->fd < 0) {
  557. /* cannot open logfile? - print to /dev/console then */
  558. int fd = device_open(DEV_CONSOLE, O_WRONLY | O_NOCTTY | O_NONBLOCK);
  559. if (fd < 0)
  560. fd = 2; /* then stderr, dammit */
  561. full_write(fd, msg, len);
  562. if (fd != 2)
  563. close(fd);
  564. return;
  565. }
  566. #if ENABLE_FEATURE_ROTATE_LOGFILE
  567. {
  568. struct stat statf;
  569. log_file->isRegular = (fstat(log_file->fd, &statf) == 0 && S_ISREG(statf.st_mode));
  570. /* bug (mostly harmless): can wrap around if file > 4gb */
  571. log_file->size = statf.st_size;
  572. }
  573. #endif
  574. }
  575. }
  576. #ifdef SYSLOGD_WRLOCK
  577. fl.l_whence = SEEK_SET;
  578. fl.l_start = 0;
  579. fl.l_len = 1;
  580. fl.l_type = F_WRLCK;
  581. fcntl(log_file->fd, F_SETLKW, &fl);
  582. #endif
  583. #if ENABLE_FEATURE_ROTATE_LOGFILE
  584. if (G.logFileSize && log_file->isRegular && log_file->size > G.logFileSize) {
  585. if (G.logFileRotate) { /* always 0..99 */
  586. int i = strlen(log_file->path) + 3 + 1;
  587. char oldFile[i];
  588. char newFile[i];
  589. i = G.logFileRotate - 1;
  590. /* rename: f.8 -> f.9; f.7 -> f.8; ... */
  591. while (1) {
  592. sprintf(newFile, "%s.%d", log_file->path, i);
  593. if (i == 0) break;
  594. sprintf(oldFile, "%s.%d", log_file->path, --i);
  595. /* ignore errors - file might be missing */
  596. rename(oldFile, newFile);
  597. }
  598. /* newFile == "f.0" now */
  599. rename(log_file->path, newFile);
  600. }
  601. /* We may or may not have just renamed the file away;
  602. * if we didn't rename because we aren't keeping any backlog,
  603. * then it's time to clobber the file. If we did rename it...,
  604. * incredibly, if F and F.0 are hardlinks, POSIX _demands_
  605. * that rename returns 0 but does not remove F!!!
  606. * (hardlinked F/F.0 pair was observed after
  607. * power failure during rename()).
  608. * So ensure old file is gone in any case:
  609. */
  610. unlink(log_file->path);
  611. #ifdef SYSLOGD_WRLOCK
  612. fl.l_type = F_UNLCK;
  613. fcntl(log_file->fd, F_SETLKW, &fl);
  614. #endif
  615. close(log_file->fd);
  616. goto reopen;
  617. }
  618. /* TODO: what to do on write errors ("disk full")? */
  619. len = full_write(log_file->fd, msg, len);
  620. if (len > 0)
  621. log_file->size += len;
  622. #else
  623. full_write(log_file->fd, msg, len);
  624. #endif
  625. #ifdef SYSLOGD_WRLOCK
  626. fl.l_type = F_UNLCK;
  627. fcntl(log_file->fd, F_SETLKW, &fl);
  628. #endif
  629. }
  630. static void parse_fac_prio_20(int pri, char *res20)
  631. {
  632. const CODE *c_pri, *c_fac;
  633. c_fac = find_by_val(LOG_FAC(pri) << 3, facilitynames);
  634. if (c_fac) {
  635. c_pri = find_by_val(LOG_PRI(pri), prioritynames);
  636. if (c_pri) {
  637. snprintf(res20, 20, "%s.%s", c_fac->c_name, c_pri->c_name);
  638. return;
  639. }
  640. }
  641. snprintf(res20, 20, "<%d>", pri);
  642. }
  643. /* len parameter is used only for "is there a timestamp?" check.
  644. * NB: some callers cheat and supply len==0 when they know
  645. * that there is no timestamp, short-circuiting the test. */
  646. static void timestamp_and_log(int pri, char *msg, int len)
  647. {
  648. char *timestamp;
  649. time_t now;
  650. /* Jan 18 00:11:22 msg... */
  651. /* 01234567890123456 */
  652. if (len < 16 || msg[3] != ' ' || msg[6] != ' '
  653. || msg[9] != ':' || msg[12] != ':' || msg[15] != ' '
  654. ) {
  655. time(&now);
  656. timestamp = ctime(&now) + 4; /* skip day of week */
  657. } else {
  658. now = 0;
  659. timestamp = msg;
  660. msg += 16;
  661. }
  662. timestamp[15] = '\0';
  663. if (option_mask32 & OPT_kmsg) {
  664. log_to_kmsg(pri, msg);
  665. return;
  666. }
  667. if (option_mask32 & OPT_small)
  668. sprintf(G.printbuf, "%s %s\n", timestamp, msg);
  669. else {
  670. char res[20];
  671. parse_fac_prio_20(pri, res);
  672. sprintf(G.printbuf, "%s %.64s %s %s\n", timestamp, G.hostname, res, msg);
  673. }
  674. /* Log message locally (to file or shared mem) */
  675. #if ENABLE_FEATURE_SYSLOGD_CFG
  676. {
  677. bool match = 0;
  678. logRule_t *rule;
  679. uint8_t facility = LOG_FAC(pri);
  680. uint8_t prio_bit = 1 << LOG_PRI(pri);
  681. for (rule = G.log_rules; rule; rule = rule->next) {
  682. if (rule->enabled_facility_priomap[facility] & prio_bit) {
  683. log_locally(now, G.printbuf, rule->file);
  684. match = 1;
  685. }
  686. }
  687. if (match)
  688. return;
  689. }
  690. #endif
  691. if (LOG_PRI(pri) < G.logLevel) {
  692. #if ENABLE_FEATURE_IPC_SYSLOG
  693. if ((option_mask32 & OPT_circularlog) && G.shbuf) {
  694. log_to_shmem(G.printbuf);
  695. return;
  696. }
  697. #endif
  698. log_locally(now, G.printbuf, &G.logFile);
  699. }
  700. }
  701. static void timestamp_and_log_internal(const char *msg)
  702. {
  703. /* -L, or no -R */
  704. if (ENABLE_FEATURE_REMOTE_LOG && !(option_mask32 & OPT_locallog))
  705. return;
  706. timestamp_and_log(LOG_SYSLOG | LOG_INFO, (char*)msg, 0);
  707. }
  708. /* tmpbuf[len] is a NUL byte (set by caller), but there can be other,
  709. * embedded NULs. Split messages on each of these NULs, parse prio,
  710. * escape control chars and log each locally. */
  711. static void split_escape_and_log(char *tmpbuf, int len)
  712. {
  713. char *p = tmpbuf;
  714. tmpbuf += len;
  715. while (p < tmpbuf) {
  716. char c;
  717. char *q = G.parsebuf;
  718. int pri = (LOG_USER | LOG_NOTICE);
  719. if (*p == '<') {
  720. /* Parse the magic priority number */
  721. pri = bb_strtou(p + 1, &p, 10);
  722. if (*p == '>')
  723. p++;
  724. if (pri & ~(LOG_FACMASK | LOG_PRIMASK))
  725. pri = (LOG_USER | LOG_NOTICE);
  726. }
  727. while ((c = *p++)) {
  728. if (c == '\n')
  729. c = ' ';
  730. if (!(c & ~0x1f) && c != '\t') {
  731. *q++ = '^';
  732. c += '@'; /* ^@, ^A, ^B... */
  733. }
  734. *q++ = c;
  735. }
  736. *q = '\0';
  737. /* Now log it */
  738. timestamp_and_log(pri, G.parsebuf, q - G.parsebuf);
  739. }
  740. }
  741. #ifdef SYSLOGD_MARK
  742. static void do_mark(int sig)
  743. {
  744. if (G.markInterval) {
  745. timestamp_and_log_internal("-- MARK --");
  746. alarm(G.markInterval);
  747. }
  748. }
  749. #endif
  750. /* Don't inline: prevent struct sockaddr_un to take up space on stack
  751. * permanently */
  752. static NOINLINE int create_socket(void)
  753. {
  754. struct sockaddr_un sunx;
  755. int sock_fd;
  756. char *dev_log_name;
  757. #if ENABLE_FEATURE_SYSTEMD
  758. if (sd_listen_fds() == 1)
  759. return SD_LISTEN_FDS_START;
  760. #endif
  761. memset(&sunx, 0, sizeof(sunx));
  762. sunx.sun_family = AF_UNIX;
  763. /* Unlink old /dev/log or object it points to. */
  764. /* (if it exists, bind will fail) */
  765. strcpy(sunx.sun_path, _PATH_LOG);
  766. dev_log_name = xmalloc_follow_symlinks(_PATH_LOG);
  767. if (dev_log_name) {
  768. safe_strncpy(sunx.sun_path, dev_log_name, sizeof(sunx.sun_path));
  769. free(dev_log_name);
  770. }
  771. unlink(sunx.sun_path);
  772. sock_fd = xsocket(AF_UNIX, SOCK_DGRAM, 0);
  773. xbind(sock_fd, (struct sockaddr *) &sunx, sizeof(sunx));
  774. chmod(_PATH_LOG, 0666);
  775. return sock_fd;
  776. }
  777. #if ENABLE_FEATURE_REMOTE_LOG
  778. static int try_to_resolve_remote(remoteHost_t *rh)
  779. {
  780. if (!rh->remoteAddr) {
  781. unsigned now = monotonic_sec();
  782. /* Don't resolve name too often - DNS timeouts can be big */
  783. if ((now - rh->last_dns_resolve) < DNS_WAIT_SEC)
  784. return -1;
  785. rh->last_dns_resolve = now;
  786. rh->remoteAddr = host2sockaddr(rh->remoteHostname, 514);
  787. if (!rh->remoteAddr)
  788. return -1;
  789. }
  790. return xsocket(rh->remoteAddr->u.sa.sa_family, SOCK_DGRAM, 0);
  791. }
  792. #endif
  793. static void do_syslogd(void) NORETURN;
  794. static void do_syslogd(void)
  795. {
  796. #if ENABLE_FEATURE_REMOTE_LOG
  797. llist_t *item;
  798. #endif
  799. #if ENABLE_FEATURE_SYSLOGD_DUP
  800. int last_sz = -1;
  801. char *last_buf;
  802. char *recvbuf = G.recvbuf;
  803. #else
  804. #define recvbuf (G.recvbuf)
  805. #endif
  806. /* Set up signal handlers (so that they interrupt read()) */
  807. signal_no_SA_RESTART_empty_mask(SIGTERM, record_signo);
  808. signal_no_SA_RESTART_empty_mask(SIGINT, record_signo);
  809. //signal_no_SA_RESTART_empty_mask(SIGQUIT, record_signo);
  810. signal(SIGHUP, SIG_IGN);
  811. #ifdef SYSLOGD_MARK
  812. signal(SIGALRM, do_mark);
  813. alarm(G.markInterval);
  814. #endif
  815. xmove_fd(create_socket(), STDIN_FILENO);
  816. if (option_mask32 & OPT_circularlog)
  817. ipcsyslog_init();
  818. if (option_mask32 & OPT_kmsg)
  819. kmsg_init();
  820. timestamp_and_log_internal("syslogd started: BusyBox v" BB_VER);
  821. while (!bb_got_signal) {
  822. ssize_t sz;
  823. #if ENABLE_FEATURE_SYSLOGD_DUP
  824. last_buf = recvbuf;
  825. if (recvbuf == G.recvbuf)
  826. recvbuf = G.recvbuf + MAX_READ;
  827. else
  828. recvbuf = G.recvbuf;
  829. #endif
  830. read_again:
  831. sz = read(STDIN_FILENO, recvbuf, MAX_READ - 1);
  832. if (sz < 0) {
  833. if (!bb_got_signal)
  834. bb_perror_msg("read from %s", _PATH_LOG);
  835. break;
  836. }
  837. /* Drop trailing '\n' and NULs (typically there is one NUL) */
  838. while (1) {
  839. if (sz == 0)
  840. goto read_again;
  841. /* man 3 syslog says: "A trailing newline is added when needed".
  842. * However, neither glibc nor uclibc do this:
  843. * syslog(prio, "test") sends "test\0" to /dev/log,
  844. * syslog(prio, "test\n") sends "test\n\0".
  845. * IOW: newline is passed verbatim!
  846. * I take it to mean that it's syslogd's job
  847. * to make those look identical in the log files. */
  848. if (recvbuf[sz-1] != '\0' && recvbuf[sz-1] != '\n')
  849. break;
  850. sz--;
  851. }
  852. #if ENABLE_FEATURE_SYSLOGD_DUP
  853. if ((option_mask32 & OPT_dup) && (sz == last_sz))
  854. if (memcmp(last_buf, recvbuf, sz) == 0)
  855. continue;
  856. last_sz = sz;
  857. #endif
  858. #if ENABLE_FEATURE_REMOTE_LOG
  859. /* Stock syslogd sends it '\n'-terminated
  860. * over network, mimic that */
  861. recvbuf[sz] = '\n';
  862. /* We are not modifying log messages in any way before send */
  863. /* Remote site cannot trust _us_ anyway and need to do validation again */
  864. for (item = G.remoteHosts; item != NULL; item = item->link) {
  865. remoteHost_t *rh = (remoteHost_t *)item->data;
  866. if (rh->remoteFD == -1) {
  867. rh->remoteFD = try_to_resolve_remote(rh);
  868. if (rh->remoteFD == -1)
  869. continue;
  870. }
  871. /* Send message to remote logger.
  872. * On some errors, close and set remoteFD to -1
  873. * so that DNS resolution is retried.
  874. */
  875. if (sendto(rh->remoteFD, recvbuf, sz+1,
  876. MSG_DONTWAIT | MSG_NOSIGNAL,
  877. &(rh->remoteAddr->u.sa), rh->remoteAddr->len) == -1
  878. ) {
  879. switch (errno) {
  880. case ECONNRESET:
  881. case ENOTCONN: /* paranoia */
  882. case EPIPE:
  883. close(rh->remoteFD);
  884. rh->remoteFD = -1;
  885. free(rh->remoteAddr);
  886. rh->remoteAddr = NULL;
  887. }
  888. }
  889. }
  890. #endif
  891. if (!ENABLE_FEATURE_REMOTE_LOG || (option_mask32 & OPT_locallog)) {
  892. recvbuf[sz] = '\0'; /* ensure it *is* NUL terminated */
  893. split_escape_and_log(recvbuf, sz);
  894. }
  895. } /* while (!bb_got_signal) */
  896. timestamp_and_log_internal("syslogd exiting");
  897. remove_pidfile(CONFIG_PID_FILE_PATH "/syslogd.pid");
  898. ipcsyslog_cleanup();
  899. if (option_mask32 & OPT_kmsg)
  900. kmsg_cleanup();
  901. kill_myself_with_sig(bb_got_signal);
  902. #undef recvbuf
  903. }
  904. int syslogd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  905. int syslogd_main(int argc UNUSED_PARAM, char **argv)
  906. {
  907. int opts;
  908. char OPTION_DECL;
  909. #if ENABLE_FEATURE_REMOTE_LOG
  910. llist_t *remoteAddrList = NULL;
  911. #endif
  912. INIT_G();
  913. /* No non-option params, -R can occur multiple times */
  914. opt_complementary = "=0" IF_FEATURE_REMOTE_LOG(":R::");
  915. opts = getopt32(argv, OPTION_STR, OPTION_PARAM);
  916. #if ENABLE_FEATURE_REMOTE_LOG
  917. while (remoteAddrList) {
  918. remoteHost_t *rh = xzalloc(sizeof(*rh));
  919. rh->remoteHostname = llist_pop(&remoteAddrList);
  920. rh->remoteFD = -1;
  921. rh->last_dns_resolve = monotonic_sec() - DNS_WAIT_SEC - 1;
  922. llist_add_to(&G.remoteHosts, rh);
  923. }
  924. #endif
  925. #ifdef SYSLOGD_MARK
  926. if (opts & OPT_mark) // -m
  927. G.markInterval = xatou_range(opt_m, 0, INT_MAX/60) * 60;
  928. #endif
  929. //if (opts & OPT_nofork) // -n
  930. //if (opts & OPT_outfile) // -O
  931. if (opts & OPT_loglevel) // -l
  932. G.logLevel = xatou_range(opt_l, 1, 8);
  933. //if (opts & OPT_small) // -S
  934. #if ENABLE_FEATURE_ROTATE_LOGFILE
  935. if (opts & OPT_filesize) // -s
  936. G.logFileSize = xatou_range(opt_s, 0, INT_MAX/1024) * 1024;
  937. if (opts & OPT_rotatecnt) // -b
  938. G.logFileRotate = xatou_range(opt_b, 0, 99);
  939. #endif
  940. #if ENABLE_FEATURE_IPC_SYSLOG
  941. if (opt_C) // -Cn
  942. G.shm_size = xatoul_range(opt_C, 4, INT_MAX/1024) * 1024;
  943. #endif
  944. /* If they have not specified remote logging, then log locally */
  945. if (ENABLE_FEATURE_REMOTE_LOG && !(opts & OPT_remotelog)) // -R
  946. option_mask32 |= OPT_locallog;
  947. #if ENABLE_FEATURE_SYSLOGD_CFG
  948. parse_syslogdcfg(opt_f);
  949. #endif
  950. /* Store away localhost's name before the fork */
  951. G.hostname = safe_gethostname();
  952. *strchrnul(G.hostname, '.') = '\0';
  953. if (!(opts & OPT_nofork)) {
  954. bb_daemonize_or_rexec(DAEMON_CHDIR_ROOT, argv);
  955. }
  956. //umask(0); - why??
  957. write_pidfile(CONFIG_PID_FILE_PATH "/syslogd.pid");
  958. do_syslogd();
  959. /* return EXIT_SUCCESS; */
  960. }
  961. /* Clean up. Needed because we are included from syslogd_and_logger.c */
  962. #undef DEBUG
  963. #undef SYSLOGD_MARK
  964. #undef SYSLOGD_WRLOCK
  965. #undef G
  966. #undef GLOBALS
  967. #undef INIT_G
  968. #undef OPTION_STR
  969. #undef OPTION_DECL
  970. #undef OPTION_PARAM