3
0

svlogd.c 24 KB

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