tail.c 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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"
  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 extra tail options (-q, -s, -v, and -F)"
  30. //config: default y
  31. //config: depends on TAIL
  32. //config: help
  33. //config: The options (-q, -s, -v and -F) are provided by GNU tail, but
  34. //config: are not specific in the SUSv3 standard.
  35. //config:
  36. //config: -q Never output headers giving file names
  37. //config: -s SEC Wait SEC seconds between reads with -f
  38. //config: -v Always output headers giving file names
  39. //config: -F Same as -f, but keep retrying
  40. //applet:IF_TAIL(APPLET(tail, BB_DIR_USR_BIN, BB_SUID_DROP))
  41. //kbuild:lib-$(CONFIG_TAIL) += tail.o
  42. /* BB_AUDIT SUSv3 compliant (need fancy for -c) */
  43. /* BB_AUDIT GNU compatible -c, -q, and -v options in 'fancy' configuration. */
  44. /* http://www.opengroup.org/onlinepubs/007904975/utilities/tail.html */
  45. //usage:#define tail_trivial_usage
  46. //usage: "[OPTIONS] [FILE]..."
  47. //usage:#define tail_full_usage "\n\n"
  48. //usage: "Print last 10 lines of each FILE (or stdin) to stdout.\n"
  49. //usage: "With more than one FILE, precede each with a filename header.\n"
  50. //usage: "\n -f Print data as file grows"
  51. //usage: "\n -c [+]N[kbm] Print last N bytes"
  52. //usage: "\n -n N[kbm] Print last N lines"
  53. //usage: "\n -n +N[kbm] Start on Nth line and print the rest"
  54. //usage: IF_FEATURE_FANCY_TAIL(
  55. //usage: "\n -q Never print headers"
  56. //usage: "\n -s SECONDS Wait SECONDS between reads with -f"
  57. //usage: "\n -v Always print headers"
  58. //usage: "\n -F Same as -f, but keep retrying"
  59. //usage: "\n"
  60. //usage: "\nN may be suffixed by k (x1024), b (x512), or m (x1024^2)."
  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_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_threshhold = 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. IF_FEATURE_FANCY_TAIL(opt_complementary = "Ff";)
  127. opt = getopt32(argv, "fc:n:" IF_FEATURE_FANCY_TAIL("qs:+vF"),
  128. &str_c, &str_n IF_FEATURE_FANCY_TAIL(,&sleep_period));
  129. #define FOLLOW (opt & 0x1)
  130. #define COUNT_BYTES (opt & 0x2)
  131. //if (opt & 0x1) // -f
  132. if (opt & 0x2) count = eat_num(str_c); // -c
  133. if (opt & 0x4) count = eat_num(str_n); // -n
  134. #if ENABLE_FEATURE_FANCY_TAIL
  135. /* q: make it impossible for nfiles to be > header_threshhold */
  136. if (opt & 0x8) header_threshhold = UINT_MAX; // -q
  137. //if (opt & 0x10) // -s
  138. if (opt & 0x20) header_threshhold = 0; // -v
  139. # define FOLLOW_RETRY (opt & 0x40)
  140. #else
  141. # define FOLLOW_RETRY 0
  142. #endif
  143. argc -= optind;
  144. argv += optind;
  145. /* open all the files */
  146. fds = xmalloc(sizeof(fds[0]) * (argc + 1));
  147. if (!argv[0]) {
  148. struct stat statbuf;
  149. if (fstat(STDIN_FILENO, &statbuf) == 0
  150. && S_ISFIFO(statbuf.st_mode)
  151. ) {
  152. opt &= ~1; /* clear FOLLOW */
  153. }
  154. argv[0] = (char *) bb_msg_standard_input;
  155. }
  156. nfiles = i = 0;
  157. do {
  158. int fd = open_or_warn_stdin(argv[i]);
  159. if (fd < 0 && !FOLLOW_RETRY) {
  160. G.exitcode = EXIT_FAILURE;
  161. continue;
  162. }
  163. fds[nfiles] = fd;
  164. argv[nfiles++] = argv[i];
  165. } while (++i < argc);
  166. if (!nfiles)
  167. bb_error_msg_and_die("no files");
  168. /* prepare the buffer */
  169. tailbufsize = BUFSIZ;
  170. if (!G.from_top && COUNT_BYTES) {
  171. if (tailbufsize < count + BUFSIZ) {
  172. tailbufsize = count + BUFSIZ;
  173. }
  174. }
  175. /* tail -c1024m REGULAR_FILE doesn't really need 1G mem block.
  176. * (In fact, it doesn't need ANY memory). So delay allocation.
  177. */
  178. tailbuf = NULL;
  179. /* tail the files */
  180. fmt = header_fmt_str + 1; /* skip leading newline in the header on the first output */
  181. i = 0;
  182. do {
  183. char *buf;
  184. int taillen;
  185. int newlines_seen;
  186. unsigned seen;
  187. int nread;
  188. int fd = fds[i];
  189. if (ENABLE_FEATURE_FANCY_TAIL && fd < 0)
  190. continue; /* may happen with -F */
  191. if (nfiles > header_threshhold) {
  192. tail_xprint_header(fmt, argv[i]);
  193. fmt = header_fmt_str;
  194. }
  195. if (!G.from_top) {
  196. off_t current = lseek(fd, 0, SEEK_END);
  197. if (current > 0) {
  198. unsigned off;
  199. if (COUNT_BYTES) {
  200. /* Optimizing count-bytes case if the file is seekable.
  201. * Beware of backing up too far.
  202. * Also we exclude files with size 0 (because of /proc/xxx) */
  203. if (count == 0)
  204. continue; /* showing zero bytes is easy :) */
  205. current -= count;
  206. if (current < 0)
  207. current = 0;
  208. xlseek(fd, current, SEEK_SET);
  209. bb_copyfd_size(fd, STDOUT_FILENO, count);
  210. continue;
  211. }
  212. #if 1 /* This is technically incorrect for *LONG* strings, but very useful */
  213. /* Optimizing count-lines case if the file is seekable.
  214. * We assume the lines are <64k.
  215. * (Users complain that tail takes too long
  216. * on multi-gigabyte files) */
  217. off = (count | 0xf); /* for small counts, be more paranoid */
  218. if (off > (INT_MAX / (64*1024)))
  219. off = (INT_MAX / (64*1024));
  220. current -= off * (64*1024);
  221. if (current < 0)
  222. current = 0;
  223. xlseek(fd, current, SEEK_SET);
  224. #endif
  225. }
  226. }
  227. if (!tailbuf)
  228. tailbuf = xmalloc(tailbufsize);
  229. buf = tailbuf;
  230. taillen = 0;
  231. /* "We saw 1st line/byte".
  232. * Used only by +N code ("start from Nth", 1-based): */
  233. seen = 1;
  234. newlines_seen = 0;
  235. while ((nread = tail_read(fd, buf, tailbufsize - taillen)) > 0) {
  236. if (G.from_top) {
  237. int nwrite = nread;
  238. if (seen < count) {
  239. /* We need to skip a few more bytes/lines */
  240. if (COUNT_BYTES) {
  241. nwrite -= (count - seen);
  242. seen += nread;
  243. } else {
  244. char *s = buf;
  245. do {
  246. --nwrite;
  247. if (*s++ == '\n' && ++seen == count) {
  248. break;
  249. }
  250. } while (nwrite);
  251. }
  252. }
  253. if (nwrite > 0)
  254. xwrite(STDOUT_FILENO, buf + nread - nwrite, nwrite);
  255. } else if (count) {
  256. if (COUNT_BYTES) {
  257. taillen += nread;
  258. if (taillen > (int)count) {
  259. memmove(tailbuf, tailbuf + taillen - count, count);
  260. taillen = count;
  261. }
  262. } else {
  263. int k = nread;
  264. int newlines_in_buf = 0;
  265. do { /* count '\n' in last read */
  266. k--;
  267. if (buf[k] == '\n') {
  268. newlines_in_buf++;
  269. }
  270. } while (k);
  271. if (newlines_seen + newlines_in_buf < (int)count) {
  272. newlines_seen += newlines_in_buf;
  273. taillen += nread;
  274. } else {
  275. int extra = (buf[nread-1] != '\n');
  276. char *s;
  277. k = newlines_seen + newlines_in_buf + extra - count;
  278. s = tailbuf;
  279. while (k) {
  280. if (*s == '\n') {
  281. k--;
  282. }
  283. s++;
  284. }
  285. taillen += nread - (s - tailbuf);
  286. memmove(tailbuf, s, taillen);
  287. newlines_seen = count - extra;
  288. }
  289. if (tailbufsize < (size_t)taillen + BUFSIZ) {
  290. tailbufsize = taillen + BUFSIZ;
  291. tailbuf = xrealloc(tailbuf, tailbufsize);
  292. }
  293. }
  294. buf = tailbuf + taillen;
  295. }
  296. } /* while (tail_read() > 0) */
  297. if (!G.from_top) {
  298. xwrite(STDOUT_FILENO, tailbuf, taillen);
  299. }
  300. } while (++i < nfiles);
  301. prev_fd = fds[i-1];
  302. tailbuf = xrealloc(tailbuf, BUFSIZ);
  303. fmt = NULL;
  304. if (FOLLOW) while (1) {
  305. sleep(sleep_period);
  306. i = 0;
  307. do {
  308. int nread;
  309. const char *filename = argv[i];
  310. int fd = fds[i];
  311. if (FOLLOW_RETRY) {
  312. struct stat sbuf, fsbuf;
  313. if (fd < 0
  314. || fstat(fd, &fsbuf) < 0
  315. || stat(filename, &sbuf) < 0
  316. || fsbuf.st_dev != sbuf.st_dev
  317. || fsbuf.st_ino != sbuf.st_ino
  318. ) {
  319. int new_fd;
  320. if (fd >= 0)
  321. close(fd);
  322. new_fd = open(filename, O_RDONLY);
  323. if (new_fd >= 0) {
  324. bb_error_msg("%s has %s; following end of new file",
  325. filename, (fd < 0) ? "appeared" : "been replaced"
  326. );
  327. } else if (fd >= 0) {
  328. bb_perror_msg("%s has become inaccessible", filename);
  329. }
  330. fds[i] = fd = new_fd;
  331. }
  332. }
  333. if (ENABLE_FEATURE_FANCY_TAIL && fd < 0)
  334. continue;
  335. if (nfiles > header_threshhold) {
  336. fmt = header_fmt_str;
  337. }
  338. for (;;) {
  339. /* tail -f keeps following files even if they are truncated */
  340. struct stat sbuf;
  341. /* /proc files report zero st_size, don't lseek them */
  342. if (fstat(fd, &sbuf) == 0 && sbuf.st_size > 0) {
  343. off_t current = lseek(fd, 0, SEEK_CUR);
  344. if (sbuf.st_size < current)
  345. xlseek(fd, 0, SEEK_SET);
  346. }
  347. nread = tail_read(fd, tailbuf, BUFSIZ);
  348. if (nread <= 0)
  349. break;
  350. if (fmt && (fd != prev_fd)) {
  351. tail_xprint_header(fmt, filename);
  352. fmt = NULL;
  353. prev_fd = fd;
  354. }
  355. xwrite(STDOUT_FILENO, tailbuf, nread);
  356. }
  357. } while (++i < nfiles);
  358. } /* while (1) */
  359. if (ENABLE_FEATURE_CLEAN_UP) {
  360. free(fds);
  361. free(tailbuf);
  362. }
  363. return G.exitcode;
  364. }