3
0

svlogd.c 31 KB

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