3
0

svlogd.c 25 KB

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