1 /* vi: set sw=4 ts=4: */
3 * Mini tail implementation for busybox
5 * Copyright (C) 2001 by Matt Kraai <kraai@alumni.carnegiemellon.edu>
7 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
9 /* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
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)
22 //config: bool "tail (7.1 kb)"
25 //config: tail is used to print the last specified number of lines
28 //config:config FEATURE_FANCY_TAIL
29 //config: bool "Enable -q, -s, -v, and -F options"
31 //config: depends on TAIL
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
40 //applet:IF_TAIL(APPLET(tail, BB_DIR_USR_BIN, BB_SUID_DROP))
42 //kbuild:lib-$(CONFIG_TAIL) += tail.o
44 /* BB_AUDIT SUSv3 compliant (need fancy for -c) */
45 /* BB_AUDIT GNU compatible -c, -q, and -v options in 'fancy' configuration. */
46 /* http://www.opengroup.org/onlinepubs/007904975/utilities/tail.html */
48 //usage:#define tail_trivial_usage
49 //usage: "[OPTIONS] [FILE]..."
50 //usage:#define tail_full_usage "\n\n"
51 //usage: "Print last 10 lines of each FILE (or stdin) to stdout.\n"
52 //usage: "With more than one FILE, precede each with a filename header.\n"
53 //usage: "\n -f Print data as file grows"
54 //usage: "\n -c [+]N[kbm] Print last N bytes"
55 //usage: "\n -n N[kbm] Print last N lines"
56 //usage: "\n -n +N[kbm] Start on Nth line and print the rest"
57 //usage: IF_FEATURE_FANCY_TAIL(
58 //usage: "\n -q Never print headers"
59 //usage: "\n -s SECONDS Wait SECONDS between reads with -f"
60 //usage: "\n -v Always print headers"
61 //usage: "\n -F Same as -f, but keep retrying"
63 //usage: "\nN may be suffixed by k (x1024), b (x512), or m (x1024^2)."
66 //usage:#define tail_example_usage
67 //usage: "$ tail -n 1 /etc/resolv.conf\n"
68 //usage: "nameserver 10.0.0.1\n"
71 #include "common_bufsiz.h"
77 #define G (*(struct globals*)bb_common_bufsiz1)
78 #define INIT_G() do { setup_common_bufsiz(); } while (0)
80 static void tail_xprint_header(const char *fmt, const char *filename)
82 if (fdprintf(STDOUT_FILENO, fmt, filename) < 0)
83 bb_perror_nomsg_and_die();
86 static ssize_t tail_read(int fd, char *buf, size_t count)
90 r = full_read(fd, buf, count);
92 bb_perror_msg(bb_msg_read_error);
93 G.exitcode = EXIT_FAILURE;
99 #define header_fmt_str "\n==> %s <==\n"
101 static unsigned eat_num(const char *p)
105 else if (*p == '+') {
109 return xatou_sfx(p, bkm_suffixes);
112 int tail_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
113 int tail_main(int argc, char **argv)
116 unsigned sleep_period = 1;
117 const char *str_c, *str_n;
121 unsigned header_threshhold = 1;
131 #if ENABLE_INCLUDE_SUSv2 || ENABLE_FEATURE_FANCY_TAIL
132 /* Allow legacy syntax of an initial numeric option without -n. */
133 if (argv[1] && (argv[1][0] == '+' || argv[1][0] == '-')
134 && isdigit(argv[1][1])
136 count = eat_num(argv[1]);
142 /* -s NUM, -F imlies -f */
143 IF_FEATURE_FANCY_TAIL(opt_complementary = "Ff";)
144 opt = getopt32(argv, "fc:n:" IF_FEATURE_FANCY_TAIL("qs:+vF"),
145 &str_c, &str_n IF_FEATURE_FANCY_TAIL(,&sleep_period));
146 #define FOLLOW (opt & 0x1)
147 #define COUNT_BYTES (opt & 0x2)
148 //if (opt & 0x1) // -f
149 if (opt & 0x2) count = eat_num(str_c); // -c
150 if (opt & 0x4) count = eat_num(str_n); // -n
151 #if ENABLE_FEATURE_FANCY_TAIL
152 /* q: make it impossible for nfiles to be > header_threshhold */
153 if (opt & 0x8) header_threshhold = UINT_MAX; // -q
154 //if (opt & 0x10) // -s
155 if (opt & 0x20) header_threshhold = 0; // -v
156 # define FOLLOW_RETRY (opt & 0x40)
158 # define FOLLOW_RETRY 0
163 /* open all the files */
164 fds = xmalloc(sizeof(fds[0]) * (argc + 1));
168 if (fstat(STDIN_FILENO, &statbuf) == 0
169 && S_ISFIFO(statbuf.st_mode)
171 opt &= ~1; /* clear FOLLOW */
173 argv[0] = (char *) bb_msg_standard_input;
177 int fd = open_or_warn_stdin(argv[i]);
178 if (fd < 0 && !FOLLOW_RETRY) {
179 G.exitcode = EXIT_FAILURE;
183 argv[nfiles++] = argv[i];
184 } while (++i < argc);
187 bb_error_msg_and_die("no files");
189 /* prepare the buffer */
190 tailbufsize = BUFSIZ;
191 if (!G.from_top && COUNT_BYTES) {
192 if (tailbufsize < count + BUFSIZ) {
193 tailbufsize = count + BUFSIZ;
196 /* tail -c1024m REGULAR_FILE doesn't really need 1G mem block.
197 * (In fact, it doesn't need ANY memory). So delay allocation.
203 fmt = header_fmt_str + 1; /* skip leading newline in the header on the first output */
213 if (ENABLE_FEATURE_FANCY_TAIL && fd < 0)
214 continue; /* may happen with -F */
216 if (nfiles > header_threshhold) {
217 tail_xprint_header(fmt, argv[i]);
218 fmt = header_fmt_str;
222 off_t current = lseek(fd, 0, SEEK_END);
226 /* Optimizing count-bytes case if the file is seekable.
227 * Beware of backing up too far.
228 * Also we exclude files with size 0 (because of /proc/xxx) */
230 continue; /* showing zero bytes is easy :) */
234 xlseek(fd, current, SEEK_SET);
235 bb_copyfd_size(fd, STDOUT_FILENO, count);
238 #if 1 /* This is technically incorrect for *LONG* strings, but very useful */
239 /* Optimizing count-lines case if the file is seekable.
240 * We assume the lines are <64k.
241 * (Users complain that tail takes too long
242 * on multi-gigabyte files) */
243 off = (count | 0xf); /* for small counts, be more paranoid */
244 if (off > (INT_MAX / (64*1024)))
245 off = (INT_MAX / (64*1024));
246 current -= off * (64*1024);
249 xlseek(fd, current, SEEK_SET);
255 tailbuf = xmalloc(tailbufsize);
259 /* "We saw 1st line/byte".
260 * Used only by +N code ("start from Nth", 1-based): */
263 while ((nread = tail_read(fd, buf, tailbufsize - taillen)) > 0) {
267 /* We need to skip a few more bytes/lines */
269 nwrite -= (count - seen);
275 if (*s++ == '\n' && ++seen == count) {
282 xwrite(STDOUT_FILENO, buf + nread - nwrite, nwrite);
286 if (taillen > (int)count) {
287 memmove(tailbuf, tailbuf + taillen - count, count);
292 int newlines_in_buf = 0;
294 do { /* count '\n' in last read */
296 if (buf[k] == '\n') {
301 if (newlines_seen + newlines_in_buf < (int)count) {
302 newlines_seen += newlines_in_buf;
305 int extra = (buf[nread-1] != '\n');
308 k = newlines_seen + newlines_in_buf + extra - count;
316 taillen += nread - (s - tailbuf);
317 memmove(tailbuf, s, taillen);
318 newlines_seen = count - extra;
320 if (tailbufsize < (size_t)taillen + BUFSIZ) {
321 tailbufsize = taillen + BUFSIZ;
322 tailbuf = xrealloc(tailbuf, tailbufsize);
325 buf = tailbuf + taillen;
327 } /* while (tail_read() > 0) */
329 xwrite(STDOUT_FILENO, tailbuf, taillen);
331 } while (++i < nfiles);
334 tailbuf = xrealloc(tailbuf, BUFSIZ);
338 if (FOLLOW) while (1) {
344 const char *filename = argv[i];
348 struct stat sbuf, fsbuf;
351 || fstat(fd, &fsbuf) < 0
352 || stat(filename, &sbuf) < 0
353 || fsbuf.st_dev != sbuf.st_dev
354 || fsbuf.st_ino != sbuf.st_ino
360 new_fd = open(filename, O_RDONLY);
362 bb_error_msg("%s has %s; following end of new file",
363 filename, (fd < 0) ? "appeared" : "been replaced"
365 } else if (fd >= 0) {
366 bb_perror_msg("%s has become inaccessible", filename);
368 fds[i] = fd = new_fd;
371 if (ENABLE_FEATURE_FANCY_TAIL && fd < 0)
373 if (nfiles > header_threshhold) {
374 fmt = header_fmt_str;
377 /* tail -f keeps following files even if they are truncated */
379 /* /proc files report zero st_size, don't lseek them */
380 if (fstat(fd, &sbuf) == 0 && sbuf.st_size > 0) {
381 off_t current = lseek(fd, 0, SEEK_CUR);
382 if (sbuf.st_size < current)
383 xlseek(fd, 0, SEEK_SET);
386 nread = tail_read(fd, tailbuf, BUFSIZ);
389 if (fmt && (fd != prev_fd)) {
390 tail_xprint_header(fmt, filename);
394 xwrite(STDOUT_FILENO, tailbuf, nread);
396 } while (++i < nfiles);
399 if (ENABLE_FEATURE_CLEAN_UP) {