tail.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Mini tail implementation for busybox
  4. *
  5. * Copyright (C) 2001 by Matt Kraai <kraai@alumni.carnegiemellon.edu>
  6. *
  7. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  8. */
  9. /* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
  10. *
  11. * Pretty much rewritten to fix numerous bugs and reduce realloc() calls.
  12. * Bugs fixed (although I may have forgotten one or two... it was pretty bad)
  13. * 1) mixing printf/write without fflush()ing stdout
  14. * 2) no check that any open files are present
  15. * 3) optstring had -q taking an arg
  16. * 4) no error checking on write in some cases, and a warning even then
  17. * 5) q and s interaction bug
  18. * 6) no check for lseek error
  19. * 7) lseek attempted when count==0 even if arg was +0 (from top)
  20. */
  21. //config:config TAIL
  22. //config: bool "tail (6.8 kb)"
  23. //config: default y
  24. //config: help
  25. //config: tail is used to print the last specified number of lines
  26. //config: from files.
  27. //config:
  28. //config:config FEATURE_FANCY_TAIL
  29. //config: bool "Enable -q, -s, -v, and -F options"
  30. //config: default y
  31. //config: depends on TAIL
  32. //config: help
  33. //config: These options are provided by GNU tail, but
  34. //config: are not specified in the SUSv3 standard:
  35. //config: -q Never output headers giving file names
  36. //config: -s SEC Wait SEC seconds between reads with -f
  37. //config: -v Always output headers giving file names
  38. //config: -F Same as -f, but keep retrying
  39. //applet:IF_TAIL(APPLET(tail, BB_DIR_USR_BIN, BB_SUID_DROP))
  40. //kbuild:lib-$(CONFIG_TAIL) += tail.o
  41. /* BB_AUDIT SUSv3 compliant (need fancy for -c) */
  42. /* BB_AUDIT GNU compatible -c, -q, and -v options in 'fancy' configuration. */
  43. /* http://www.opengroup.org/onlinepubs/007904975/utilities/tail.html */
  44. //usage:#define tail_trivial_usage
  45. //usage: "[OPTIONS] [FILE]..."
  46. //usage:#define tail_full_usage "\n\n"
  47. //usage: "Print last 10 lines of FILEs (or stdin) to.\n"
  48. //usage: "With more than one FILE, precede each with a filename header.\n"
  49. //usage: "\n -c [+]N[bkm] Print last N bytes"
  50. //usage: "\n -n N[bkm] Print last N lines"
  51. //usage: "\n -n +N[bkm] Start on Nth line and print the rest"
  52. //usage: "\n (b:*512 k:*1024 m:*1024^2)"
  53. //usage: IF_FEATURE_FANCY_TAIL(
  54. //usage: "\n -q Never print headers"
  55. //usage: "\n -v Always print headers"
  56. //usage: )
  57. //usage: "\n -f Print data as file grows"
  58. //usage: IF_FEATURE_FANCY_TAIL(
  59. //usage: "\n -F Same as -f, but keep retrying"
  60. //usage: "\n -s SECONDS Wait SECONDS between reads with -f"
  61. //usage: )
  62. //usage:
  63. //usage:#define tail_example_usage
  64. //usage: "$ tail -n 1 /etc/resolv.conf\n"
  65. //usage: "nameserver 10.0.0.1\n"
  66. #include "libbb.h"
  67. #include "common_bufsiz.h"
  68. struct globals {
  69. bool from_top;
  70. bool exitcode;
  71. } FIX_ALIASING;
  72. #define G (*(struct globals*)bb_common_bufsiz1)
  73. #define INIT_G() do { setup_common_bufsiz(); } while (0)
  74. static void tail_xprint_header(const char *fmt, const char *filename)
  75. {
  76. if (fdprintf(STDOUT_FILENO, fmt, filename) < 0)
  77. bb_perror_nomsg_and_die();
  78. }
  79. static ssize_t tail_read(int fd, char *buf, size_t count)
  80. {
  81. ssize_t r;
  82. r = full_read(fd, buf, count);
  83. if (r < 0) {
  84. bb_simple_perror_msg(bb_msg_read_error);
  85. G.exitcode = EXIT_FAILURE;
  86. }
  87. return r;
  88. }
  89. #define header_fmt_str "\n==> %s <==\n"
  90. static unsigned eat_num(const char *p)
  91. {
  92. if (*p == '-')
  93. p++;
  94. else if (*p == '+') {
  95. p++;
  96. G.from_top = 1;
  97. }
  98. return xatou_sfx(p, bkm_suffixes);
  99. }
  100. int tail_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  101. int tail_main(int argc, char **argv)
  102. {
  103. unsigned count = 10;
  104. unsigned sleep_period = 1;
  105. const char *str_c, *str_n;
  106. char *tailbuf;
  107. size_t tailbufsize;
  108. unsigned header_threshold = 1;
  109. unsigned nfiles;
  110. int i, opt;
  111. int *fds;
  112. const char *fmt;
  113. int prev_fd;
  114. INIT_G();
  115. #if ENABLE_INCLUDE_SUSv2 || ENABLE_FEATURE_FANCY_TAIL
  116. /* Allow legacy syntax of an initial numeric option without -n. */
  117. if (argv[1] && (argv[1][0] == '+' || argv[1][0] == '-')
  118. && isdigit(argv[1][1])
  119. ) {
  120. count = eat_num(argv[1]);
  121. argv++;
  122. argc--;
  123. }
  124. #endif
  125. /* -s NUM, -F imlies -f */
  126. opt = getopt32(argv, IF_FEATURE_FANCY_TAIL("^")
  127. "fc:n:"IF_FEATURE_FANCY_TAIL("qs:+vF")
  128. IF_FEATURE_FANCY_TAIL("\0" "Ff"),
  129. &str_c, &str_n IF_FEATURE_FANCY_TAIL(,&sleep_period)
  130. );
  131. #define FOLLOW (opt & 0x1)
  132. #define COUNT_BYTES (opt & 0x2)
  133. //if (opt & 0x1) // -f
  134. if (opt & 0x2) count = eat_num(str_c); // -c
  135. if (opt & 0x4) count = eat_num(str_n); // -n
  136. #if ENABLE_FEATURE_FANCY_TAIL
  137. /* q: make it impossible for nfiles to be > header_threshold */
  138. if (opt & 0x8) header_threshold = UINT_MAX; // -q
  139. //if (opt & 0x10) // -s
  140. if (opt & 0x20) header_threshold = 0; // -v
  141. # define FOLLOW_RETRY (opt & 0x40)
  142. #else
  143. # define FOLLOW_RETRY 0
  144. #endif
  145. argc -= optind;
  146. argv += optind;
  147. /* open all the files */
  148. fds = xmalloc(sizeof(fds[0]) * (argc + 1));
  149. if (!argv[0]) {
  150. struct stat statbuf;
  151. if (fstat(STDIN_FILENO, &statbuf) == 0
  152. && S_ISFIFO(statbuf.st_mode)
  153. ) {
  154. opt &= ~1; /* clear FOLLOW */
  155. }
  156. argv[0] = (char *) bb_msg_standard_input;
  157. }
  158. nfiles = i = 0;
  159. do {
  160. int fd = open_or_warn_stdin(argv[i]);
  161. if (fd < 0 && !FOLLOW_RETRY) {
  162. G.exitcode = EXIT_FAILURE;
  163. continue;
  164. }
  165. fds[nfiles] = fd;
  166. argv[nfiles++] = argv[i];
  167. } while (++i < argc);
  168. if (!nfiles)
  169. bb_simple_error_msg_and_die("no files");
  170. /* prepare the buffer */
  171. tailbufsize = BUFSIZ;
  172. if (!G.from_top && COUNT_BYTES) {
  173. if (tailbufsize < count + BUFSIZ) {
  174. tailbufsize = count + BUFSIZ;
  175. }
  176. }
  177. /* tail -c1024m REGULAR_FILE doesn't really need 1G mem block.
  178. * (In fact, it doesn't need ANY memory). So delay allocation.
  179. */
  180. tailbuf = NULL;
  181. /* tail the files */
  182. fmt = header_fmt_str + 1; /* skip leading newline in the header on the first output */
  183. i = 0;
  184. do {
  185. char *buf;
  186. int taillen;
  187. int newlines_seen;
  188. unsigned seen;
  189. int nread;
  190. int fd = fds[i];
  191. if (ENABLE_FEATURE_FANCY_TAIL && fd < 0)
  192. continue; /* may happen with -F */
  193. if (nfiles > header_threshold) {
  194. tail_xprint_header(fmt, argv[i]);
  195. fmt = header_fmt_str;
  196. }
  197. if (!G.from_top) {
  198. off_t current = lseek(fd, 0, SEEK_END);
  199. if (current > 0) {
  200. unsigned off;
  201. if (COUNT_BYTES) {
  202. /* Optimizing count-bytes case if the file is seekable.
  203. * Beware of backing up too far.
  204. * Also we exclude files with size 0 (because of /proc/xxx) */
  205. if (count == 0)
  206. continue; /* showing zero bytes is easy :) */
  207. current -= count;
  208. if (current < 0)
  209. current = 0;
  210. xlseek(fd, current, SEEK_SET);
  211. bb_copyfd_size(fd, STDOUT_FILENO, count);
  212. continue;
  213. }
  214. #if 1 /* This is technically incorrect for *LONG* strings, but very useful */
  215. /* Optimizing count-lines case if the file is seekable.
  216. * We assume the lines are <64k.
  217. * (Users complain that tail takes too long
  218. * on multi-gigabyte files) */
  219. off = (count | 0xf); /* for small counts, be more paranoid */
  220. if (off > (INT_MAX / (64*1024)))
  221. off = (INT_MAX / (64*1024));
  222. current -= off * (64*1024);
  223. if (current < 0)
  224. current = 0;
  225. xlseek(fd, current, SEEK_SET);
  226. #endif
  227. }
  228. }
  229. if (!tailbuf)
  230. tailbuf = xmalloc(tailbufsize);
  231. buf = tailbuf;
  232. taillen = 0;
  233. /* "We saw 1st line/byte".
  234. * Used only by +N code ("start from Nth", 1-based): */
  235. seen = 1;
  236. newlines_seen = 0;
  237. while ((nread = tail_read(fd, buf, tailbufsize - taillen)) > 0) {
  238. if (G.from_top) {
  239. int nwrite = nread;
  240. if (seen < count) {
  241. /* We need to skip a few more bytes/lines */
  242. if (COUNT_BYTES) {
  243. nwrite -= (count - seen);
  244. seen += nread;
  245. } else {
  246. char *s = buf;
  247. do {
  248. --nwrite;
  249. if (*s++ == '\n' && ++seen == count) {
  250. break;
  251. }
  252. } while (nwrite);
  253. }
  254. }
  255. if (nwrite > 0)
  256. xwrite(STDOUT_FILENO, buf + nread - nwrite, nwrite);
  257. } else if (count) {
  258. if (COUNT_BYTES) {
  259. taillen += nread;
  260. if (taillen > (int)count) {
  261. memmove(tailbuf, tailbuf + taillen - count, count);
  262. taillen = count;
  263. }
  264. } else {
  265. int k = nread;
  266. int newlines_in_buf = 0;
  267. do { /* count '\n' in last read */
  268. k--;
  269. if (buf[k] == '\n') {
  270. newlines_in_buf++;
  271. }
  272. } while (k);
  273. if (newlines_seen + newlines_in_buf < (int)count) {
  274. newlines_seen += newlines_in_buf;
  275. taillen += nread;
  276. } else {
  277. int extra = (buf[nread-1] != '\n');
  278. char *s;
  279. k = newlines_seen + newlines_in_buf + extra - count;
  280. s = tailbuf;
  281. while (k) {
  282. if (*s == '\n') {
  283. k--;
  284. }
  285. s++;
  286. }
  287. taillen += nread - (s - tailbuf);
  288. memmove(tailbuf, s, taillen);
  289. newlines_seen = count - extra;
  290. }
  291. if (tailbufsize < (size_t)taillen + BUFSIZ) {
  292. tailbufsize = taillen + BUFSIZ;
  293. tailbuf = xrealloc(tailbuf, tailbufsize);
  294. }
  295. }
  296. buf = tailbuf + taillen;
  297. }
  298. } /* while (tail_read() > 0) */
  299. if (!G.from_top) {
  300. xwrite(STDOUT_FILENO, tailbuf, taillen);
  301. }
  302. } while (++i < nfiles);
  303. prev_fd = fds[i-1];
  304. tailbuf = xrealloc(tailbuf, BUFSIZ);
  305. fmt = NULL;
  306. if (FOLLOW) while (1) {
  307. sleep(sleep_period);
  308. i = 0;
  309. do {
  310. int nread;
  311. const char *filename = argv[i];
  312. int fd = fds[i];
  313. int new_fd = -1;
  314. struct stat sbuf;
  315. if (FOLLOW_RETRY) {
  316. struct stat fsbuf;
  317. if (fd < 0
  318. || fstat(fd, &fsbuf) < 0
  319. || stat(filename, &sbuf) < 0
  320. || fsbuf.st_dev != sbuf.st_dev
  321. || fsbuf.st_ino != sbuf.st_ino
  322. ) {
  323. /* Looks like file has been created/renamed/deleted */
  324. new_fd = open(filename, O_RDONLY);
  325. if (new_fd >= 0) {
  326. bb_error_msg("%s has %s; following end of new file",
  327. filename, (fd < 0) ? "appeared" : "been replaced"
  328. );
  329. if (fd < 0) {
  330. /* No previously open fd for this file,
  331. * start using new_fd immediately. */
  332. fds[i] = fd = new_fd;
  333. new_fd = -1;
  334. }
  335. } else if (fd >= 0) {
  336. bb_perror_msg("%s has been renamed or deleted", filename);
  337. }
  338. }
  339. }
  340. if (ENABLE_FEATURE_FANCY_TAIL && fd < 0)
  341. continue;
  342. if (nfiles > header_threshold) {
  343. fmt = header_fmt_str;
  344. }
  345. for (;;) {
  346. /* tail -f keeps following files even if they are truncated */
  347. /* /proc files report zero st_size, don't lseek them */
  348. if (fstat(fd, &sbuf) == 0
  349. /* && S_ISREG(sbuf.st_mode) TODO? */
  350. && sbuf.st_size > 0
  351. ) {
  352. off_t current = lseek(fd, 0, SEEK_CUR);
  353. if (sbuf.st_size < current) {
  354. //bb_perror_msg("%s: file truncated", filename); - says coreutils 8.32
  355. xlseek(fd, 0, SEEK_SET);
  356. }
  357. }
  358. nread = tail_read(fd, tailbuf, BUFSIZ);
  359. if (nread <= 0) {
  360. if (new_fd < 0)
  361. break;
  362. /* Switch to "tail -F"ing the new file */
  363. xmove_fd(new_fd, fd);
  364. new_fd = -1;
  365. continue;
  366. }
  367. if (fmt && (fd != prev_fd)) {
  368. tail_xprint_header(fmt, filename);
  369. fmt = NULL;
  370. prev_fd = fd;
  371. }
  372. xwrite(STDOUT_FILENO, tailbuf, nread);
  373. }
  374. } while (++i < nfiles);
  375. } /* while (1) */
  376. if (ENABLE_FEATURE_CLEAN_UP) {
  377. free(fds);
  378. free(tailbuf);
  379. }
  380. return G.exitcode;
  381. }