3
0

tail.c 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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 -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 specific 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 each FILE (or stdin) to stdout.\n"
  48. //usage: "With more than one FILE, precede each with a filename header.\n"
  49. //usage: "\n -f Print data as file grows"
  50. //usage: "\n -c [+]N[kbm] Print last N bytes"
  51. //usage: "\n -n N[kbm] Print last N lines"
  52. //usage: "\n -n +N[kbm] Start on Nth line and print the rest"
  53. //usage: IF_FEATURE_FANCY_TAIL(
  54. //usage: "\n -q Never print headers"
  55. //usage: "\n -s SECONDS Wait SECONDS between reads with -f"
  56. //usage: "\n -v Always print headers"
  57. //usage: "\n -F Same as -f, but keep retrying"
  58. //usage: "\n"
  59. //usage: "\nN may be suffixed by k (x1024), b (x512), or m (x1024^2)."
  60. //usage: )
  61. //usage:
  62. //usage:#define tail_example_usage
  63. //usage: "$ tail -n 1 /etc/resolv.conf\n"
  64. //usage: "nameserver 10.0.0.1\n"
  65. #include "libbb.h"
  66. #include "common_bufsiz.h"
  67. struct globals {
  68. bool from_top;
  69. bool exitcode;
  70. } FIX_ALIASING;
  71. #define G (*(struct globals*)bb_common_bufsiz1)
  72. #define INIT_G() do { setup_common_bufsiz(); } while (0)
  73. static void tail_xprint_header(const char *fmt, const char *filename)
  74. {
  75. if (fdprintf(STDOUT_FILENO, fmt, filename) < 0)
  76. bb_perror_nomsg_and_die();
  77. }
  78. static ssize_t tail_read(int fd, char *buf, size_t count)
  79. {
  80. ssize_t r;
  81. r = full_read(fd, buf, count);
  82. if (r < 0) {
  83. bb_perror_msg(bb_msg_read_error);
  84. G.exitcode = EXIT_FAILURE;
  85. }
  86. return r;
  87. }
  88. #define header_fmt_str "\n==> %s <==\n"
  89. static unsigned eat_num(const char *p)
  90. {
  91. if (*p == '-')
  92. p++;
  93. else if (*p == '+') {
  94. p++;
  95. G.from_top = 1;
  96. }
  97. return xatou_sfx(p, bkm_suffixes);
  98. }
  99. int tail_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  100. int tail_main(int argc, char **argv)
  101. {
  102. unsigned count = 10;
  103. unsigned sleep_period = 1;
  104. const char *str_c, *str_n;
  105. char *tailbuf;
  106. size_t tailbufsize;
  107. unsigned header_threshhold = 1;
  108. unsigned nfiles;
  109. int i, opt;
  110. int *fds;
  111. const char *fmt;
  112. int prev_fd;
  113. INIT_G();
  114. #if ENABLE_INCLUDE_SUSv2 || ENABLE_FEATURE_FANCY_TAIL
  115. /* Allow legacy syntax of an initial numeric option without -n. */
  116. if (argv[1] && (argv[1][0] == '+' || argv[1][0] == '-')
  117. && isdigit(argv[1][1])
  118. ) {
  119. count = eat_num(argv[1]);
  120. argv++;
  121. argc--;
  122. }
  123. #endif
  124. /* -s NUM, -F imlies -f */
  125. IF_FEATURE_FANCY_TAIL(opt_complementary = "Ff";)
  126. opt = getopt32(argv, "fc:n:" IF_FEATURE_FANCY_TAIL("qs:+vF"),
  127. &str_c, &str_n IF_FEATURE_FANCY_TAIL(,&sleep_period));
  128. #define FOLLOW (opt & 0x1)
  129. #define COUNT_BYTES (opt & 0x2)
  130. //if (opt & 0x1) // -f
  131. if (opt & 0x2) count = eat_num(str_c); // -c
  132. if (opt & 0x4) count = eat_num(str_n); // -n
  133. #if ENABLE_FEATURE_FANCY_TAIL
  134. /* q: make it impossible for nfiles to be > header_threshhold */
  135. if (opt & 0x8) header_threshhold = UINT_MAX; // -q
  136. //if (opt & 0x10) // -s
  137. if (opt & 0x20) header_threshhold = 0; // -v
  138. # define FOLLOW_RETRY (opt & 0x40)
  139. #else
  140. # define FOLLOW_RETRY 0
  141. #endif
  142. argc -= optind;
  143. argv += optind;
  144. /* open all the files */
  145. fds = xmalloc(sizeof(fds[0]) * (argc + 1));
  146. if (!argv[0]) {
  147. struct stat statbuf;
  148. if (fstat(STDIN_FILENO, &statbuf) == 0
  149. && S_ISFIFO(statbuf.st_mode)
  150. ) {
  151. opt &= ~1; /* clear FOLLOW */
  152. }
  153. argv[0] = (char *) bb_msg_standard_input;
  154. }
  155. nfiles = i = 0;
  156. do {
  157. int fd = open_or_warn_stdin(argv[i]);
  158. if (fd < 0 && !FOLLOW_RETRY) {
  159. G.exitcode = EXIT_FAILURE;
  160. continue;
  161. }
  162. fds[nfiles] = fd;
  163. argv[nfiles++] = argv[i];
  164. } while (++i < argc);
  165. if (!nfiles)
  166. bb_error_msg_and_die("no files");
  167. /* prepare the buffer */
  168. tailbufsize = BUFSIZ;
  169. if (!G.from_top && COUNT_BYTES) {
  170. if (tailbufsize < count + BUFSIZ) {
  171. tailbufsize = count + BUFSIZ;
  172. }
  173. }
  174. /* tail -c1024m REGULAR_FILE doesn't really need 1G mem block.
  175. * (In fact, it doesn't need ANY memory). So delay allocation.
  176. */
  177. tailbuf = NULL;
  178. /* tail the files */
  179. fmt = header_fmt_str + 1; /* skip leading newline in the header on the first output */
  180. i = 0;
  181. do {
  182. char *buf;
  183. int taillen;
  184. int newlines_seen;
  185. unsigned seen;
  186. int nread;
  187. int fd = fds[i];
  188. if (ENABLE_FEATURE_FANCY_TAIL && fd < 0)
  189. continue; /* may happen with -F */
  190. if (nfiles > header_threshhold) {
  191. tail_xprint_header(fmt, argv[i]);
  192. fmt = header_fmt_str;
  193. }
  194. if (!G.from_top) {
  195. off_t current = lseek(fd, 0, SEEK_END);
  196. if (current > 0) {
  197. unsigned off;
  198. if (COUNT_BYTES) {
  199. /* Optimizing count-bytes case if the file is seekable.
  200. * Beware of backing up too far.
  201. * Also we exclude files with size 0 (because of /proc/xxx) */
  202. if (count == 0)
  203. continue; /* showing zero bytes is easy :) */
  204. current -= count;
  205. if (current < 0)
  206. current = 0;
  207. xlseek(fd, current, SEEK_SET);
  208. bb_copyfd_size(fd, STDOUT_FILENO, count);
  209. continue;
  210. }
  211. #if 1 /* This is technically incorrect for *LONG* strings, but very useful */
  212. /* Optimizing count-lines case if the file is seekable.
  213. * We assume the lines are <64k.
  214. * (Users complain that tail takes too long
  215. * on multi-gigabyte files) */
  216. off = (count | 0xf); /* for small counts, be more paranoid */
  217. if (off > (INT_MAX / (64*1024)))
  218. off = (INT_MAX / (64*1024));
  219. current -= off * (64*1024);
  220. if (current < 0)
  221. current = 0;
  222. xlseek(fd, current, SEEK_SET);
  223. #endif
  224. }
  225. }
  226. if (!tailbuf)
  227. tailbuf = xmalloc(tailbufsize);
  228. buf = tailbuf;
  229. taillen = 0;
  230. /* "We saw 1st line/byte".
  231. * Used only by +N code ("start from Nth", 1-based): */
  232. seen = 1;
  233. newlines_seen = 0;
  234. while ((nread = tail_read(fd, buf, tailbufsize - taillen)) > 0) {
  235. if (G.from_top) {
  236. int nwrite = nread;
  237. if (seen < count) {
  238. /* We need to skip a few more bytes/lines */
  239. if (COUNT_BYTES) {
  240. nwrite -= (count - seen);
  241. seen += nread;
  242. } else {
  243. char *s = buf;
  244. do {
  245. --nwrite;
  246. if (*s++ == '\n' && ++seen == count) {
  247. break;
  248. }
  249. } while (nwrite);
  250. }
  251. }
  252. if (nwrite > 0)
  253. xwrite(STDOUT_FILENO, buf + nread - nwrite, nwrite);
  254. } else if (count) {
  255. if (COUNT_BYTES) {
  256. taillen += nread;
  257. if (taillen > (int)count) {
  258. memmove(tailbuf, tailbuf + taillen - count, count);
  259. taillen = count;
  260. }
  261. } else {
  262. int k = nread;
  263. int newlines_in_buf = 0;
  264. do { /* count '\n' in last read */
  265. k--;
  266. if (buf[k] == '\n') {
  267. newlines_in_buf++;
  268. }
  269. } while (k);
  270. if (newlines_seen + newlines_in_buf < (int)count) {
  271. newlines_seen += newlines_in_buf;
  272. taillen += nread;
  273. } else {
  274. int extra = (buf[nread-1] != '\n');
  275. char *s;
  276. k = newlines_seen + newlines_in_buf + extra - count;
  277. s = tailbuf;
  278. while (k) {
  279. if (*s == '\n') {
  280. k--;
  281. }
  282. s++;
  283. }
  284. taillen += nread - (s - tailbuf);
  285. memmove(tailbuf, s, taillen);
  286. newlines_seen = count - extra;
  287. }
  288. if (tailbufsize < (size_t)taillen + BUFSIZ) {
  289. tailbufsize = taillen + BUFSIZ;
  290. tailbuf = xrealloc(tailbuf, tailbufsize);
  291. }
  292. }
  293. buf = tailbuf + taillen;
  294. }
  295. } /* while (tail_read() > 0) */
  296. if (!G.from_top) {
  297. xwrite(STDOUT_FILENO, tailbuf, taillen);
  298. }
  299. } while (++i < nfiles);
  300. prev_fd = fds[i-1];
  301. tailbuf = xrealloc(tailbuf, BUFSIZ);
  302. fmt = NULL;
  303. if (FOLLOW) while (1) {
  304. sleep(sleep_period);
  305. i = 0;
  306. do {
  307. int nread;
  308. const char *filename = argv[i];
  309. int fd = fds[i];
  310. if (FOLLOW_RETRY) {
  311. struct stat sbuf, fsbuf;
  312. if (fd < 0
  313. || fstat(fd, &fsbuf) < 0
  314. || stat(filename, &sbuf) < 0
  315. || fsbuf.st_dev != sbuf.st_dev
  316. || fsbuf.st_ino != sbuf.st_ino
  317. ) {
  318. int new_fd;
  319. if (fd >= 0)
  320. close(fd);
  321. new_fd = open(filename, O_RDONLY);
  322. if (new_fd >= 0) {
  323. bb_error_msg("%s has %s; following end of new file",
  324. filename, (fd < 0) ? "appeared" : "been replaced"
  325. );
  326. } else if (fd >= 0) {
  327. bb_perror_msg("%s has become inaccessible", filename);
  328. }
  329. fds[i] = fd = new_fd;
  330. }
  331. }
  332. if (ENABLE_FEATURE_FANCY_TAIL && fd < 0)
  333. continue;
  334. if (nfiles > header_threshhold) {
  335. fmt = header_fmt_str;
  336. }
  337. for (;;) {
  338. /* tail -f keeps following files even if they are truncated */
  339. struct stat sbuf;
  340. /* /proc files report zero st_size, don't lseek them */
  341. if (fstat(fd, &sbuf) == 0 && sbuf.st_size > 0) {
  342. off_t current = lseek(fd, 0, SEEK_CUR);
  343. if (sbuf.st_size < current)
  344. xlseek(fd, 0, SEEK_SET);
  345. }
  346. nread = tail_read(fd, tailbuf, BUFSIZ);
  347. if (nread <= 0)
  348. break;
  349. if (fmt && (fd != prev_fd)) {
  350. tail_xprint_header(fmt, filename);
  351. fmt = NULL;
  352. prev_fd = fd;
  353. }
  354. xwrite(STDOUT_FILENO, tailbuf, nread);
  355. }
  356. } while (++i < nfiles);
  357. } /* while (1) */
  358. if (ENABLE_FEATURE_CLEAN_UP) {
  359. free(fds);
  360. free(tailbuf);
  361. }
  362. return G.exitcode;
  363. }