svlogd.c 32 KB

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