3
0

svlogd.c 31 KB

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