tail.c 9.6 KB

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