3
0

svlogd.c 26 KB

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