3
0

svlogd.c 26 KB

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