3
0

svlogd.c 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165
  1. /*
  2. Copyright (c) 2001-2006, Gerrit Pape
  3. All rights reserved.
  4. Redistribution and use in source and binary forms, with or without
  5. modification, are permitted provided that the following conditions are met:
  6. 1. Redistributions of source code must retain the above copyright notice,
  7. this list of conditions and the following disclaimer.
  8. 2. Redistributions in binary form must reproduce the above copyright
  9. notice, this list of conditions and the following disclaimer in the
  10. documentation and/or other materials provided with the distribution.
  11. 3. The name of the author may not be used to endorse or promote products
  12. derived from this software without specific prior written permission.
  13. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
  14. WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  15. MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
  16. EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  17. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  18. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
  19. OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  20. WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
  21. OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  22. ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  23. */
  24. /* Busyboxed by Denys Vlasenko <vda.linux@googlemail.com> */
  25. /* TODO: depends on runit_lib.c - review and reduce/eliminate */
  26. /*
  27. Config files
  28. On startup, and after receiving a HUP signal, svlogd checks for each
  29. log directory log if the configuration file log/config exists,
  30. and if so, reads the file line by line and adjusts configuration
  31. for log as follows:
  32. If the line is empty, or starts with a #, it is ignored. A line
  33. of the form
  34. ssize
  35. sets the maximum file size of current when svlogd should rotate
  36. the current log file to size bytes. Default is 1000000.
  37. If size is zero, svlogd doesnt rotate log files
  38. You should set size to at least (2 * len).
  39. nnum
  40. sets the number of old log files svlogd should maintain to num.
  41. If svlogd sees more that num old log files in log after log file
  42. rotation, it deletes the oldest one. Default is 10.
  43. If num is zero, svlogd doesnt remove old log files.
  44. Nmin
  45. sets the minimum number of old log files svlogd should maintain
  46. to min. min must be less than num. If min is set, and svlogd
  47. cannot write to current because the filesystem is full,
  48. and it sees more than min old log files, it deletes the oldest one.
  49. ttimeout
  50. sets the maximum age of the current log file when svlogd should
  51. rotate the current log file to timeout seconds. If current
  52. is timeout seconds old, and is not empty, svlogd forces log file rotation.
  53. !processor
  54. tells svlogd to feed each recent log file through processor
  55. (see above) on log file rotation. By default log files are not processed.
  56. ua.b.c.d[:port]
  57. tells svlogd to transmit the first len characters of selected
  58. log messages to the IP address a.b.c.d, port number port.
  59. If port isnt set, the default port for syslog is used (514).
  60. len can be set through the -l option, see below. If svlogd
  61. has trouble sending udp packets, it writes error messages
  62. to the log directory. Attention: logging through udp is unreliable,
  63. and should be used in private networks only.
  64. Ua.b.c.d[:port]
  65. is the same as the u line above, but the log messages are no longer
  66. written to the log directory, but transmitted through udp only.
  67. Error messages from svlogd concerning sending udp packages still go
  68. to the log directory.
  69. pprefix
  70. tells svlogd to prefix each line to be written to the log directory,
  71. to standard error, or through UDP, with prefix.
  72. If a line starts with a -, +, e, or E, svlogd matches the first len characters
  73. of each log message against pattern and acts accordingly:
  74. -pattern
  75. the log message is deselected.
  76. +pattern
  77. the log message is selected.
  78. epattern
  79. the log message is selected to be printed to standard error.
  80. Epattern
  81. the log message is deselected to be printed to standard error.
  82. Initially each line is selected to be written to log/current. Deselected
  83. log messages are discarded from log. Initially each line is deselected
  84. to be written to standard err. Log messages selected for standard error
  85. are written to standard error.
  86. Pattern Matching
  87. svlogd matches a log message against the string pattern as follows:
  88. pattern is applied to the log message one character by one, starting
  89. with the first. A character not a star (*) and not a plus (+) matches itself.
  90. A plus matches the next character in pattern in the log message one
  91. or more times. A star before the end of pattern matches any string
  92. in the log message that does not include the next character in pattern.
  93. A star at the end of pattern matches any string.
  94. Timestamps optionally added by svlogd are not considered part
  95. of the log message.
  96. An svlogd pattern is not a regular expression. For example consider
  97. a log message like this
  98. 2005-12-18_09:13:50.97618 tcpsvd: info: pid 1977 from 10.4.1.14
  99. The following pattern doesnt match
  100. -*pid*
  101. because the first star matches up to the first p in tcpsvd,
  102. and then the match fails because i is not s. To match this
  103. log message, you can use a pattern like this instead
  104. -*: *: pid *
  105. */
  106. #include <sys/poll.h>
  107. #include <sys/file.h>
  108. #include "libbb.h"
  109. #include "runit_lib.h"
  110. #define LESS(a,b) ((int)((unsigned)(b) - (unsigned)(a)) > 0)
  111. #define FMT_PTIME 30
  112. struct logdir {
  113. ////char *btmp;
  114. /* pattern list to match, in "aa\0bb\0\cc\0\0" form */
  115. char *inst;
  116. char *processor;
  117. char *name;
  118. unsigned size;
  119. unsigned sizemax;
  120. unsigned nmax;
  121. unsigned nmin;
  122. unsigned rotate_period;
  123. int ppid;
  124. int fddir;
  125. int fdcur;
  126. FILE* filecur; ////
  127. int fdlock;
  128. unsigned next_rotate;
  129. char fnsave[FMT_PTIME];
  130. char match;
  131. char matcherr;
  132. };
  133. struct globals {
  134. struct logdir *dir;
  135. unsigned verbose;
  136. int linemax;
  137. ////int buflen;
  138. int linelen;
  139. int fdwdir;
  140. char **fndir;
  141. int wstat;
  142. unsigned nearest_rotate;
  143. void* (*memRchr)(const void *, int, size_t);
  144. smallint exitasap;
  145. smallint rotateasap;
  146. smallint reopenasap;
  147. smallint linecomplete;
  148. smallint tmaxflag;
  149. char repl;
  150. const char *replace;
  151. int fl_flag_0;
  152. unsigned dirn;
  153. sigset_t blocked_sigset;
  154. };
  155. #define G (*(struct globals*)ptr_to_globals)
  156. #define dir (G.dir )
  157. #define verbose (G.verbose )
  158. #define linemax (G.linemax )
  159. #define buflen (G.buflen )
  160. #define linelen (G.linelen )
  161. #define fndir (G.fndir )
  162. #define fdwdir (G.fdwdir )
  163. #define wstat (G.wstat )
  164. #define memRchr (G.memRchr )
  165. #define nearest_rotate (G.nearest_rotate)
  166. #define exitasap (G.exitasap )
  167. #define rotateasap (G.rotateasap )
  168. #define reopenasap (G.reopenasap )
  169. #define linecomplete (G.linecomplete )
  170. #define tmaxflag (G.tmaxflag )
  171. #define repl (G.repl )
  172. #define replace (G.replace )
  173. #define blocked_sigset (G.blocked_sigset)
  174. #define fl_flag_0 (G.fl_flag_0 )
  175. #define dirn (G.dirn )
  176. #define INIT_G() do { \
  177. SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
  178. linemax = 1000; \
  179. /*buflen = 1024;*/ \
  180. linecomplete = 1; \
  181. replace = ""; \
  182. } while (0)
  183. #define line bb_common_bufsiz1
  184. #define FATAL "fatal: "
  185. #define WARNING "warning: "
  186. #define PAUSE "pausing: "
  187. #define INFO "info: "
  188. static void fatalx(const char *m0)
  189. {
  190. bb_error_msg_and_die(FATAL"%s", m0);
  191. }
  192. static void warn(const char *m0)
  193. {
  194. bb_perror_msg(WARNING"%s", m0);
  195. }
  196. static void warn2(const char *m0, const char *m1)
  197. {
  198. bb_perror_msg(WARNING"%s: %s", m0, m1);
  199. }
  200. static void warnx(const char *m0, const char *m1)
  201. {
  202. bb_error_msg(WARNING"%s: %s", m0, m1);
  203. }
  204. static void pause_nomem(void)
  205. {
  206. bb_error_msg(PAUSE"out of memory");
  207. sleep(3);
  208. }
  209. static void pause1cannot(const char *m0)
  210. {
  211. bb_perror_msg(PAUSE"can't %s", m0);
  212. sleep(3);
  213. }
  214. static void pause2cannot(const char *m0, const char *m1)
  215. {
  216. bb_perror_msg(PAUSE"can't %s %s", m0, m1);
  217. sleep(3);
  218. }
  219. static char* wstrdup(const char *str)
  220. {
  221. char *s;
  222. while (!(s = strdup(str)))
  223. pause_nomem();
  224. return s;
  225. }
  226. /*** ex fmt_ptime.[ch] ***/
  227. /* NUL terminated */
  228. static void fmt_time_human_30nul(char *s)
  229. {
  230. struct tm *t;
  231. struct timeval tv;
  232. gettimeofday(&tv, NULL);
  233. t = gmtime(&(tv.tv_sec));
  234. sprintf(s, "%04u-%02u-%02u_%02u:%02u:%02u.%06u000",
  235. (unsigned)(1900 + t->tm_year),
  236. (unsigned)(t->tm_mon + 1),
  237. (unsigned)(t->tm_mday),
  238. (unsigned)(t->tm_hour),
  239. (unsigned)(t->tm_min),
  240. (unsigned)(t->tm_sec),
  241. (unsigned)(tv.tv_usec)
  242. );
  243. /* 4+1 + 2+1 + 2+1 + 2+1 + 2+1 + 2+1 + 9 = */
  244. /* 5 + 3 + 3 + 3 + 3 + 3 + 9 = */
  245. /* 20 (up to '.' inclusive) + 9 (not including '\0') */
  246. }
  247. /* NOT terminated! */
  248. static void fmt_time_bernstein_25(char *s)
  249. {
  250. uint32_t pack[3];
  251. struct timeval tv;
  252. unsigned sec_hi;
  253. gettimeofday(&tv, NULL);
  254. sec_hi = (0x400000000000000aULL + tv.tv_sec) >> 32;
  255. tv.tv_sec = (time_t)(0x400000000000000aULL) + tv.tv_sec;
  256. tv.tv_usec *= 1000;
  257. /* Network order is big-endian: most significant byte first.
  258. * This is exactly what we want here */
  259. pack[0] = htonl(sec_hi);
  260. pack[1] = htonl(tv.tv_sec);
  261. pack[2] = htonl(tv.tv_usec);
  262. *s++ = '@';
  263. bin2hex(s, (char*)pack, 12);
  264. }
  265. static void processorstart(struct logdir *ld)
  266. {
  267. char sv_ch;
  268. int pid;
  269. if (!ld->processor) return;
  270. if (ld->ppid) {
  271. warnx("processor already running", ld->name);
  272. return;
  273. }
  274. /* vfork'ed child trashes this byte, save... */
  275. sv_ch = ld->fnsave[26];
  276. while ((pid = vfork()) == -1)
  277. pause2cannot("vfork for processor", ld->name);
  278. if (!pid) {
  279. int fd;
  280. /* child */
  281. /* Non-ignored signals revert to SIG_DFL on exec anyway */
  282. /*bb_signals(0
  283. + (1 << SIGTERM)
  284. + (1 << SIGALRM)
  285. + (1 << SIGHUP)
  286. , SIG_DFL);*/
  287. sig_unblock(SIGTERM);
  288. sig_unblock(SIGALRM);
  289. sig_unblock(SIGHUP);
  290. if (verbose)
  291. bb_error_msg(INFO"processing: %s/%s", ld->name, ld->fnsave);
  292. fd = xopen(ld->fnsave, O_RDONLY|O_NDELAY);
  293. xmove_fd(fd, 0);
  294. ld->fnsave[26] = 't'; /* <- that's why we need sv_ch! */
  295. fd = xopen(ld->fnsave, O_WRONLY|O_NDELAY|O_TRUNC|O_CREAT);
  296. xmove_fd(fd, 1);
  297. fd = open_read("state");
  298. if (fd == -1) {
  299. if (errno != ENOENT)
  300. bb_perror_msg_and_die(FATAL"can't %s processor %s", "open state for", ld->name);
  301. close(xopen("state", O_WRONLY|O_NDELAY|O_TRUNC|O_CREAT));
  302. fd = xopen("state", O_RDONLY|O_NDELAY);
  303. }
  304. xmove_fd(fd, 4);
  305. fd = xopen("newstate", O_WRONLY|O_NDELAY|O_TRUNC|O_CREAT);
  306. xmove_fd(fd, 5);
  307. // getenv("SHELL")?
  308. execl("/bin/sh", "/bin/sh" + 5, "-c", ld->processor, (char*) NULL);
  309. bb_perror_msg_and_die(FATAL"can't %s processor %s", "run", ld->name);
  310. }
  311. ld->fnsave[26] = sv_ch; /* ...restore */
  312. ld->ppid = pid;
  313. }
  314. static unsigned processorstop(struct logdir *ld)
  315. {
  316. char f[28];
  317. if (ld->ppid) {
  318. sig_unblock(SIGHUP);
  319. while (safe_waitpid(ld->ppid, &wstat, 0) == -1)
  320. pause2cannot("wait for processor", ld->name);
  321. sig_block(SIGHUP);
  322. ld->ppid = 0;
  323. }
  324. if (ld->fddir == -1)
  325. return 1;
  326. while (fchdir(ld->fddir) == -1)
  327. pause2cannot("change directory, want processor", ld->name);
  328. if (WEXITSTATUS(wstat) != 0) {
  329. warnx("processor failed, restart", ld->name);
  330. ld->fnsave[26] = 't';
  331. unlink(ld->fnsave);
  332. ld->fnsave[26] = 'u';
  333. processorstart(ld);
  334. while (fchdir(fdwdir) == -1)
  335. pause1cannot("change to initial working directory");
  336. return ld->processor ? 0 : 1;
  337. }
  338. ld->fnsave[26] = 't';
  339. memcpy(f, ld->fnsave, 26);
  340. f[26] = 's';
  341. f[27] = '\0';
  342. while (rename(ld->fnsave, f) == -1)
  343. pause2cannot("rename processed", ld->name);
  344. while (chmod(f, 0744) == -1)
  345. pause2cannot("set mode of processed", ld->name);
  346. ld->fnsave[26] = 'u';
  347. if (unlink(ld->fnsave) == -1)
  348. bb_error_msg(WARNING"can't unlink: %s/%s", ld->name, ld->fnsave);
  349. while (rename("newstate", "state") == -1)
  350. pause2cannot("rename state", ld->name);
  351. if (verbose)
  352. bb_error_msg(INFO"processed: %s/%s", ld->name, f);
  353. while (fchdir(fdwdir) == -1)
  354. pause1cannot("change to initial working directory");
  355. return 1;
  356. }
  357. static void rmoldest(struct logdir *ld)
  358. {
  359. DIR *d;
  360. struct dirent *f;
  361. char oldest[FMT_PTIME];
  362. int n = 0;
  363. oldest[0] = 'A'; oldest[1] = oldest[27] = 0;
  364. while (!(d = opendir(".")))
  365. pause2cannot("open directory, want rotate", ld->name);
  366. errno = 0;
  367. while ((f = readdir(d))) {
  368. if ((f->d_name[0] == '@') && (strlen(f->d_name) == 27)) {
  369. if (f->d_name[26] == 't') {
  370. if (unlink(f->d_name) == -1)
  371. warn2("can't unlink processor leftover", f->d_name);
  372. } else {
  373. ++n;
  374. if (strcmp(f->d_name, oldest) < 0)
  375. memcpy(oldest, f->d_name, 27);
  376. }
  377. errno = 0;
  378. }
  379. }
  380. if (errno)
  381. warn2("can't read directory", ld->name);
  382. closedir(d);
  383. if (ld->nmax && (n > ld->nmax)) {
  384. if (verbose)
  385. bb_error_msg(INFO"delete: %s/%s", ld->name, oldest);
  386. if ((*oldest == '@') && (unlink(oldest) == -1))
  387. warn2("can't unlink oldest logfile", ld->name);
  388. }
  389. }
  390. static unsigned rotate(struct logdir *ld)
  391. {
  392. struct stat st;
  393. unsigned now;
  394. if (ld->fddir == -1) {
  395. ld->rotate_period = 0;
  396. return 0;
  397. }
  398. if (ld->ppid)
  399. while (!processorstop(ld))
  400. continue;
  401. while (fchdir(ld->fddir) == -1)
  402. pause2cannot("change directory, want rotate", ld->name);
  403. /* create new filename */
  404. ld->fnsave[25] = '.';
  405. ld->fnsave[26] = 's';
  406. if (ld->processor)
  407. ld->fnsave[26] = 'u';
  408. ld->fnsave[27] = '\0';
  409. do {
  410. fmt_time_bernstein_25(ld->fnsave);
  411. errno = 0;
  412. stat(ld->fnsave, &st);
  413. } while (errno != ENOENT);
  414. now = monotonic_sec();
  415. if (ld->rotate_period && LESS(ld->next_rotate, now)) {
  416. ld->next_rotate = now + ld->rotate_period;
  417. if (LESS(ld->next_rotate, nearest_rotate))
  418. nearest_rotate = ld->next_rotate;
  419. }
  420. if (ld->size > 0) {
  421. while (fflush(ld->filecur) || fsync(ld->fdcur) == -1)
  422. pause2cannot("fsync current logfile", ld->name);
  423. while (fchmod(ld->fdcur, 0744) == -1)
  424. pause2cannot("set mode of current", ld->name);
  425. ////close(ld->fdcur);
  426. fclose(ld->filecur);
  427. if (verbose) {
  428. bb_error_msg(INFO"rename: %s/current %s %u", ld->name,
  429. ld->fnsave, ld->size);
  430. }
  431. while (rename("current", ld->fnsave) == -1)
  432. pause2cannot("rename current", ld->name);
  433. while ((ld->fdcur = open("current", O_WRONLY|O_NDELAY|O_APPEND|O_CREAT, 0600)) == -1)
  434. pause2cannot("create new current", ld->name);
  435. while ((ld->filecur = fdopen(ld->fdcur, "a")) == NULL) ////
  436. pause2cannot("create new current", ld->name); /* very unlikely */
  437. setvbuf(ld->filecur, NULL, _IOFBF, linelen); ////
  438. close_on_exec_on(ld->fdcur);
  439. ld->size = 0;
  440. while (fchmod(ld->fdcur, 0644) == -1)
  441. pause2cannot("set mode of current", ld->name);
  442. rmoldest(ld);
  443. processorstart(ld);
  444. }
  445. while (fchdir(fdwdir) == -1)
  446. pause1cannot("change to initial working directory");
  447. return 1;
  448. }
  449. static int buffer_pwrite(int n, char *s, unsigned len)
  450. {
  451. int i;
  452. struct logdir *ld = &dir[n];
  453. if (ld->sizemax) {
  454. if (ld->size >= ld->sizemax)
  455. rotate(ld);
  456. if (len > (ld->sizemax - ld->size))
  457. len = ld->sizemax - ld->size;
  458. }
  459. while (1) {
  460. ////i = full_write(ld->fdcur, s, len);
  461. ////if (i != -1) break;
  462. i = fwrite(s, 1, len, ld->filecur);
  463. if (i == len) break;
  464. if ((errno == ENOSPC) && (ld->nmin < ld->nmax)) {
  465. DIR *d;
  466. struct dirent *f;
  467. char oldest[FMT_PTIME];
  468. int j = 0;
  469. while (fchdir(ld->fddir) == -1)
  470. pause2cannot("change directory, want remove old logfile",
  471. ld->name);
  472. oldest[0] = 'A';
  473. oldest[1] = oldest[27] = '\0';
  474. while (!(d = opendir(".")))
  475. pause2cannot("open directory, want remove old logfile",
  476. ld->name);
  477. errno = 0;
  478. while ((f = readdir(d)))
  479. if ((f->d_name[0] == '@') && (strlen(f->d_name) == 27)) {
  480. ++j;
  481. if (strcmp(f->d_name, oldest) < 0)
  482. memcpy(oldest, f->d_name, 27);
  483. }
  484. if (errno) warn2("can't read directory, want remove old logfile",
  485. ld->name);
  486. closedir(d);
  487. errno = ENOSPC;
  488. if (j > ld->nmin) {
  489. if (*oldest == '@') {
  490. bb_error_msg(WARNING"out of disk space, delete: %s/%s",
  491. ld->name, oldest);
  492. errno = 0;
  493. if (unlink(oldest) == -1) {
  494. warn2("can't unlink oldest logfile", ld->name);
  495. errno = ENOSPC;
  496. }
  497. while (fchdir(fdwdir) == -1)
  498. pause1cannot("change to initial working directory");
  499. }
  500. }
  501. }
  502. if (errno)
  503. pause2cannot("write to current", ld->name);
  504. }
  505. ld->size += i;
  506. if (ld->sizemax)
  507. if (s[i-1] == '\n')
  508. if (ld->size >= (ld->sizemax - linemax))
  509. rotate(ld);
  510. return i;
  511. }
  512. static void logdir_close(struct logdir *ld)
  513. {
  514. if (ld->fddir == -1)
  515. return;
  516. if (verbose)
  517. bb_error_msg(INFO"close: %s", ld->name);
  518. close(ld->fddir);
  519. ld->fddir = -1;
  520. if (ld->fdcur == -1)
  521. return; /* impossible */
  522. while (fflush(ld->filecur) || fsync(ld->fdcur) == -1)
  523. pause2cannot("fsync current logfile", ld->name);
  524. while (fchmod(ld->fdcur, 0744) == -1)
  525. pause2cannot("set mode of current", ld->name);
  526. ////close(ld->fdcur);
  527. fclose(ld->filecur);
  528. ld->fdcur = -1;
  529. if (ld->fdlock == -1)
  530. return; /* impossible */
  531. close(ld->fdlock);
  532. ld->fdlock = -1;
  533. free(ld->processor);
  534. ld->processor = NULL;
  535. }
  536. static unsigned logdir_open(struct logdir *ld, const char *fn)
  537. {
  538. char buf[128];
  539. unsigned now;
  540. char *new, *s, *np;
  541. int i;
  542. struct stat st;
  543. now = monotonic_sec();
  544. ld->fddir = open(fn, O_RDONLY|O_NDELAY);
  545. if (ld->fddir == -1) {
  546. warn2("can't open log directory", (char*)fn);
  547. return 0;
  548. }
  549. close_on_exec_on(ld->fddir);
  550. if (fchdir(ld->fddir) == -1) {
  551. logdir_close(ld);
  552. warn2("can't change directory", (char*)fn);
  553. return 0;
  554. }
  555. ld->fdlock = open("lock", O_WRONLY|O_NDELAY|O_APPEND|O_CREAT, 0600);
  556. if ((ld->fdlock == -1)
  557. || (lock_exnb(ld->fdlock) == -1)
  558. ) {
  559. logdir_close(ld);
  560. warn2("can't lock directory", (char*)fn);
  561. while (fchdir(fdwdir) == -1)
  562. pause1cannot("change to initial working directory");
  563. return 0;
  564. }
  565. close_on_exec_on(ld->fdlock);
  566. ld->size = 0;
  567. ld->sizemax = 1000000;
  568. ld->nmax = ld->nmin = 10;
  569. ld->rotate_period = 0;
  570. ld->name = (char*)fn;
  571. ld->ppid = 0;
  572. ld->match = '+';
  573. free(ld->inst); ld->inst = NULL;
  574. free(ld->processor); ld->processor = NULL;
  575. /* read config */
  576. i = open_read_close("config", buf, sizeof(buf) - 1);
  577. if (i < 0 && errno != ENOENT)
  578. bb_perror_msg(WARNING"%s/config", ld->name);
  579. if (i > 0) {
  580. buf[i] = '\0';
  581. if (verbose)
  582. bb_error_msg(INFO"read: %s/config", ld->name);
  583. s = buf;
  584. while (s) {
  585. np = strchr(s, '\n');
  586. if (np)
  587. *np++ = '\0';
  588. switch (s[0]) {
  589. case '+':
  590. case '-':
  591. case 'e':
  592. case 'E':
  593. /* Filtering requires one-line buffering,
  594. * resetting the "find newline" function
  595. * accordingly */
  596. memRchr = memchr;
  597. /* Add '\n'-terminated line to ld->inst */
  598. while (1) {
  599. int l = asprintf(&new, "%s%s\n", ld->inst ? : "", s);
  600. if (l >= 0 && new)
  601. break;
  602. pause_nomem();
  603. }
  604. free(ld->inst);
  605. ld->inst = new;
  606. break;
  607. case 's': {
  608. static const struct suffix_mult km_suffixes[] = {
  609. { "k", 1024 },
  610. { "m", 1024*1024 },
  611. { }
  612. };
  613. ld->sizemax = xatou_sfx(&s[1], km_suffixes);
  614. break;
  615. }
  616. case 'n':
  617. ld->nmax = xatoi_u(&s[1]);
  618. break;
  619. case 'N':
  620. ld->nmin = xatoi_u(&s[1]);
  621. break;
  622. case 't': {
  623. static const struct suffix_mult mh_suffixes[] = {
  624. { "m", 60 },
  625. { "h", 60*60 },
  626. /*{ "d", 24*60*60 },*/
  627. { }
  628. };
  629. ld->rotate_period = xatou_sfx(&s[1], mh_suffixes);
  630. if (ld->rotate_period) {
  631. ld->next_rotate = now + ld->rotate_period;
  632. if (!tmaxflag || LESS(ld->next_rotate, nearest_rotate))
  633. nearest_rotate = ld->next_rotate;
  634. tmaxflag = 1;
  635. }
  636. break;
  637. }
  638. case '!':
  639. if (s[1]) {
  640. free(ld->processor);
  641. ld->processor = wstrdup(s);
  642. }
  643. break;
  644. }
  645. s = np;
  646. }
  647. /* Convert "aa\nbb\ncc\n\0" to "aa\0bb\0cc\0\0" */
  648. s = ld->inst;
  649. while (s) {
  650. np = strchr(s, '\n');
  651. if (np)
  652. *np++ = '\0';
  653. s = np;
  654. }
  655. }
  656. /* open current */
  657. i = stat("current", &st);
  658. if (i != -1) {
  659. if (st.st_size && !(st.st_mode & S_IXUSR)) {
  660. ld->fnsave[25] = '.';
  661. ld->fnsave[26] = 'u';
  662. ld->fnsave[27] = '\0';
  663. do {
  664. fmt_time_bernstein_25(ld->fnsave);
  665. errno = 0;
  666. stat(ld->fnsave, &st);
  667. } while (errno != ENOENT);
  668. while (rename("current", ld->fnsave) == -1)
  669. pause2cannot("rename current", ld->name);
  670. rmoldest(ld);
  671. i = -1;
  672. } else {
  673. /* st.st_size can be not just bigger, but WIDER!
  674. * This code is safe: if st.st_size > 4GB, we select
  675. * ld->sizemax (because it's "unsigned") */
  676. ld->size = (st.st_size > ld->sizemax) ? ld->sizemax : st.st_size;
  677. }
  678. } else {
  679. if (errno != ENOENT) {
  680. logdir_close(ld);
  681. warn2("can't stat current", ld->name);
  682. while (fchdir(fdwdir) == -1)
  683. pause1cannot("change to initial working directory");
  684. return 0;
  685. }
  686. }
  687. while ((ld->fdcur = open("current", O_WRONLY|O_NDELAY|O_APPEND|O_CREAT, 0600)) == -1)
  688. pause2cannot("open current", ld->name);
  689. /* we presume this cannot fail */
  690. ld->filecur = fdopen(ld->fdcur, "a"); ////
  691. setvbuf(ld->filecur, NULL, _IOFBF, linelen); ////
  692. close_on_exec_on(ld->fdcur);
  693. while (fchmod(ld->fdcur, 0644) == -1)
  694. pause2cannot("set mode of current", ld->name);
  695. if (verbose) {
  696. if (i == 0) bb_error_msg(INFO"append: %s/current", ld->name);
  697. else bb_error_msg(INFO"new: %s/current", ld->name);
  698. }
  699. while (fchdir(fdwdir) == -1)
  700. pause1cannot("change to initial working directory");
  701. return 1;
  702. }
  703. static void logdirs_reopen(void)
  704. {
  705. int l;
  706. int ok = 0;
  707. tmaxflag = 0;
  708. for (l = 0; l < dirn; ++l) {
  709. logdir_close(&dir[l]);
  710. if (logdir_open(&dir[l], fndir[l]))
  711. ok = 1;
  712. }
  713. if (!ok)
  714. fatalx("no functional log directories");
  715. }
  716. /* Will look good in libbb one day */
  717. static ssize_t ndelay_read(int fd, void *buf, size_t count)
  718. {
  719. if (!(fl_flag_0 & O_NONBLOCK))
  720. fcntl(fd, F_SETFL, fl_flag_0 | O_NONBLOCK);
  721. count = safe_read(fd, buf, count);
  722. if (!(fl_flag_0 & O_NONBLOCK))
  723. fcntl(fd, F_SETFL, fl_flag_0);
  724. return count;
  725. }
  726. /* Used for reading stdin */
  727. static int buffer_pread(/*int fd, */char *s, unsigned len)
  728. {
  729. unsigned now;
  730. struct pollfd input;
  731. int i;
  732. input.fd = STDIN_FILENO;
  733. input.events = POLLIN;
  734. do {
  735. if (rotateasap) {
  736. for (i = 0; i < dirn; ++i)
  737. rotate(dir + i);
  738. rotateasap = 0;
  739. }
  740. if (exitasap) {
  741. if (linecomplete)
  742. return 0;
  743. len = 1;
  744. }
  745. if (reopenasap) {
  746. logdirs_reopen();
  747. reopenasap = 0;
  748. }
  749. now = monotonic_sec();
  750. nearest_rotate = now + (45 * 60 + 45);
  751. for (i = 0; i < dirn; ++i) {
  752. if (dir[i].rotate_period) {
  753. if (LESS(dir[i].next_rotate, now))
  754. rotate(dir + i);
  755. if (LESS(dir[i].next_rotate, nearest_rotate))
  756. nearest_rotate = dir[i].next_rotate;
  757. }
  758. }
  759. sigprocmask(SIG_UNBLOCK, &blocked_sigset, NULL);
  760. i = nearest_rotate - now;
  761. if (i > 1000000)
  762. i = 1000000;
  763. if (i <= 0)
  764. i = 1;
  765. poll(&input, 1, i * 1000);
  766. sigprocmask(SIG_BLOCK, &blocked_sigset, NULL);
  767. i = ndelay_read(STDIN_FILENO, s, len);
  768. if (i >= 0)
  769. break;
  770. if (errno == EINTR)
  771. continue;
  772. if (errno != EAGAIN) {
  773. warn("can't read standard input");
  774. break;
  775. }
  776. /* else: EAGAIN - normal, repeat silently */
  777. } while (!exitasap);
  778. if (i > 0) {
  779. int cnt;
  780. linecomplete = (s[i-1] == '\n');
  781. if (!repl)
  782. return i;
  783. cnt = i;
  784. while (--cnt >= 0) {
  785. char ch = *s;
  786. if (ch != '\n') {
  787. if (ch < 32 || ch > 126)
  788. *s = repl;
  789. else {
  790. int j;
  791. for (j = 0; replace[j]; ++j) {
  792. if (ch == replace[j]) {
  793. *s = repl;
  794. break;
  795. }
  796. }
  797. }
  798. }
  799. s++;
  800. }
  801. }
  802. return i;
  803. }
  804. static void sig_term_handler(int sig_no UNUSED_PARAM)
  805. {
  806. if (verbose)
  807. bb_error_msg(INFO"sig%s received", "term");
  808. exitasap = 1;
  809. }
  810. static void sig_child_handler(int sig_no UNUSED_PARAM)
  811. {
  812. pid_t pid;
  813. int l;
  814. if (verbose)
  815. bb_error_msg(INFO"sig%s received", "child");
  816. while ((pid = wait_any_nohang(&wstat)) > 0) {
  817. for (l = 0; l < dirn; ++l) {
  818. if (dir[l].ppid == pid) {
  819. dir[l].ppid = 0;
  820. processorstop(&dir[l]);
  821. break;
  822. }
  823. }
  824. }
  825. }
  826. static void sig_alarm_handler(int sig_no UNUSED_PARAM)
  827. {
  828. if (verbose)
  829. bb_error_msg(INFO"sig%s received", "alarm");
  830. rotateasap = 1;
  831. }
  832. static void sig_hangup_handler(int sig_no UNUSED_PARAM)
  833. {
  834. if (verbose)
  835. bb_error_msg(INFO"sig%s received", "hangup");
  836. reopenasap = 1;
  837. }
  838. static void logmatch(struct logdir *ld)
  839. {
  840. char *s;
  841. ld->match = '+';
  842. ld->matcherr = 'E';
  843. s = ld->inst;
  844. while (s && s[0]) {
  845. switch (s[0]) {
  846. case '+':
  847. case '-':
  848. if (pmatch(s+1, line, linelen))
  849. ld->match = s[0];
  850. break;
  851. case 'e':
  852. case 'E':
  853. if (pmatch(s+1, line, linelen))
  854. ld->matcherr = s[0];
  855. break;
  856. }
  857. s += strlen(s) + 1;
  858. }
  859. }
  860. int svlogd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  861. int svlogd_main(int argc, char **argv)
  862. {
  863. char *r, *l, *b;
  864. ssize_t stdin_cnt = 0;
  865. int i;
  866. unsigned opt;
  867. unsigned timestamp = 0;
  868. INIT_G();
  869. opt_complementary = "tt:vv";
  870. opt = getopt32(argv, "r:R:l:b:tv",
  871. &r, &replace, &l, &b, &timestamp, &verbose);
  872. if (opt & 1) { // -r
  873. repl = r[0];
  874. if (!repl || r[1])
  875. bb_show_usage();
  876. }
  877. if (opt & 2) if (!repl) repl = '_'; // -R
  878. if (opt & 4) { // -l
  879. linemax = xatou_range(l, 0, BUFSIZ-26);
  880. if (linemax == 0)
  881. linemax = BUFSIZ-26;
  882. if (linemax < 256)
  883. linemax = 256;
  884. }
  885. ////if (opt & 8) { // -b
  886. //// buflen = xatoi_u(b);
  887. //// if (buflen == 0) buflen = 1024;
  888. ////}
  889. //if (opt & 0x10) timestamp++; // -t
  890. //if (opt & 0x20) verbose++; // -v
  891. //if (timestamp > 2) timestamp = 2;
  892. argv += optind;
  893. argc -= optind;
  894. dirn = argc;
  895. if (dirn <= 0)
  896. bb_show_usage();
  897. ////if (buflen <= linemax) bb_show_usage();
  898. fdwdir = xopen(".", O_RDONLY|O_NDELAY);
  899. close_on_exec_on(fdwdir);
  900. dir = xzalloc(dirn * sizeof(dir[0]));
  901. for (i = 0; i < dirn; ++i) {
  902. dir[i].fddir = -1;
  903. dir[i].fdcur = -1;
  904. ////dir[i].btmp = xmalloc(buflen);
  905. /*dir[i].ppid = 0;*/
  906. }
  907. /* line = xmalloc(linemax + (timestamp ? 26 : 0)); */
  908. fndir = argv;
  909. /* We cannot set NONBLOCK on fd #0 permanently - this setting
  910. * _isn't_ per-process! It is shared among all other processes
  911. * with the same stdin */
  912. fl_flag_0 = fcntl(0, F_GETFL);
  913. sigemptyset(&blocked_sigset);
  914. sigaddset(&blocked_sigset, SIGTERM);
  915. sigaddset(&blocked_sigset, SIGCHLD);
  916. sigaddset(&blocked_sigset, SIGALRM);
  917. sigaddset(&blocked_sigset, SIGHUP);
  918. sigprocmask(SIG_BLOCK, &blocked_sigset, NULL);
  919. bb_signals_recursive_norestart(1 << SIGTERM, sig_term_handler);
  920. bb_signals_recursive_norestart(1 << SIGCHLD, sig_child_handler);
  921. bb_signals_recursive_norestart(1 << SIGALRM, sig_alarm_handler);
  922. bb_signals_recursive_norestart(1 << SIGHUP, sig_hangup_handler);
  923. /* Without timestamps, we don't have to print each line
  924. * separately, so we can look for _last_ newline, not first,
  925. * thus batching writes. If filtering is enabled in config,
  926. * logdirs_reopen resets it to memchr.
  927. */
  928. memRchr = (timestamp ? memchr : memrchr);
  929. logdirs_reopen();
  930. setvbuf(stderr, NULL, _IOFBF, linelen);
  931. /* Each iteration processes one or more lines */
  932. while (1) {
  933. char stamp[FMT_PTIME];
  934. char *lineptr;
  935. char *printptr;
  936. char *np;
  937. int printlen;
  938. char ch;
  939. lineptr = line;
  940. if (timestamp)
  941. lineptr += 26;
  942. /* lineptr[0..linemax-1] - buffer for stdin */
  943. /* (possibly has some unprocessed data from prev loop) */
  944. /* Refill the buffer if needed */
  945. np = memRchr(lineptr, '\n', stdin_cnt);
  946. if (!np && !exitasap) {
  947. i = linemax - stdin_cnt; /* avail. bytes at tail */
  948. if (i >= 128) {
  949. i = buffer_pread(/*0, */lineptr + stdin_cnt, i);
  950. if (i <= 0) /* EOF or error on stdin */
  951. exitasap = 1;
  952. else {
  953. np = memRchr(lineptr + stdin_cnt, '\n', i);
  954. stdin_cnt += i;
  955. }
  956. }
  957. }
  958. if (stdin_cnt <= 0 && exitasap)
  959. break;
  960. /* Search for '\n' (in fact, np already holds the result) */
  961. linelen = stdin_cnt;
  962. if (np) {
  963. print_to_nl: /* NB: starting from here lineptr may point
  964. * farther out into line[] */
  965. linelen = np - lineptr + 1;
  966. }
  967. /* linelen == no of chars incl. '\n' (or == stdin_cnt) */
  968. ch = lineptr[linelen-1];
  969. /* Biggest performance hit was coming from the fact
  970. * that we did not buffer writes. We were reading many lines
  971. * in one read() above, but wrote one line per write().
  972. * We are using stdio to fix that */
  973. /* write out lineptr[0..linelen-1] to each log destination
  974. * (or lineptr[-26..linelen-1] if timestamping) */
  975. printlen = linelen;
  976. printptr = lineptr;
  977. if (timestamp) {
  978. if (timestamp == 1)
  979. fmt_time_bernstein_25(stamp);
  980. else /* 2: */
  981. fmt_time_human_30nul(stamp);
  982. printlen += 26;
  983. printptr -= 26;
  984. memcpy(printptr, stamp, 25);
  985. printptr[25] = ' ';
  986. }
  987. for (i = 0; i < dirn; ++i) {
  988. struct logdir *ld = &dir[i];
  989. if (ld->fddir == -1)
  990. continue;
  991. if (ld->inst)
  992. logmatch(ld);
  993. if (ld->matcherr == 'e') {
  994. /* runit-1.8.0 compat: if timestamping, do it on stderr too */
  995. ////full_write(STDERR_FILENO, printptr, printlen);
  996. fwrite(printptr, 1, printlen, stderr);
  997. }
  998. if (ld->match != '+')
  999. continue;
  1000. buffer_pwrite(i, printptr, printlen);
  1001. }
  1002. /* If we didn't see '\n' (long input line), */
  1003. /* read/write repeatedly until we see it */
  1004. while (ch != '\n') {
  1005. /* lineptr is emptied now, safe to use as buffer */
  1006. stdin_cnt = exitasap ? -1 : buffer_pread(/*0, */lineptr, linemax);
  1007. if (stdin_cnt <= 0) { /* EOF or error on stdin */
  1008. exitasap = 1;
  1009. lineptr[0] = ch = '\n';
  1010. linelen = 1;
  1011. stdin_cnt = 1;
  1012. } else {
  1013. linelen = stdin_cnt;
  1014. np = memRchr(lineptr, '\n', stdin_cnt);
  1015. if (np)
  1016. linelen = np - lineptr + 1;
  1017. ch = lineptr[linelen-1];
  1018. }
  1019. /* linelen == no of chars incl. '\n' (or == stdin_cnt) */
  1020. for (i = 0; i < dirn; ++i) {
  1021. if (dir[i].fddir == -1)
  1022. continue;
  1023. if (dir[i].matcherr == 'e') {
  1024. ////full_write(STDERR_FILENO, lineptr, linelen);
  1025. fwrite(lineptr, 1, linelen, stderr);
  1026. }
  1027. if (dir[i].match != '+')
  1028. continue;
  1029. buffer_pwrite(i, lineptr, linelen);
  1030. }
  1031. }
  1032. stdin_cnt -= linelen;
  1033. if (stdin_cnt > 0) {
  1034. lineptr += linelen;
  1035. /* If we see another '\n', we don't need to read
  1036. * next piece of input: can print what we have */
  1037. np = memRchr(lineptr, '\n', stdin_cnt);
  1038. if (np)
  1039. goto print_to_nl;
  1040. /* Move unprocessed data to the front of line */
  1041. memmove((timestamp ? line+26 : line), lineptr, stdin_cnt);
  1042. }
  1043. fflush(NULL);////
  1044. }
  1045. for (i = 0; i < dirn; ++i) {
  1046. if (dir[i].ppid)
  1047. while (!processorstop(&dir[i]))
  1048. continue;
  1049. logdir_close(&dir[i]);
  1050. }
  1051. return 0;
  1052. }