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 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
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 opt = getopt32(argv, IF_FEATURE_FANCY_TAIL("^")
144 "fc:n:"IF_FEATURE_FANCY_TAIL("qs:+vF")
145 IF_FEATURE_FANCY_TAIL("\0" "Ff"),
146 &str_c, &str_n IF_FEATURE_FANCY_TAIL(,&sleep_period)
148 #define FOLLOW (opt & 0x1)
149 #define COUNT_BYTES (opt & 0x2)
150 //if (opt & 0x1) // -f
151 if (opt & 0x2) count = eat_num(str_c); // -c
152 if (opt & 0x4) count = eat_num(str_n); // -n
153 #if ENABLE_FEATURE_FANCY_TAIL
154 /* q: make it impossible for nfiles to be > header_threshhold */
155 if (opt & 0x8) header_threshhold = UINT_MAX; // -q
156 //if (opt & 0x10) // -s
157 if (opt & 0x20) header_threshhold = 0; // -v
158 # define FOLLOW_RETRY (opt & 0x40)
160 # define FOLLOW_RETRY 0
165 /* open all the files */
166 fds = xmalloc(sizeof(fds[0]) * (argc + 1));
170 if (fstat(STDIN_FILENO, &statbuf) == 0
171 && S_ISFIFO(statbuf.st_mode)
173 opt &= ~1; /* clear FOLLOW */
175 argv[0] = (char *) bb_msg_standard_input;
179 int fd = open_or_warn_stdin(argv[i]);
180 if (fd < 0 && !FOLLOW_RETRY) {
181 G.exitcode = EXIT_FAILURE;
185 argv[nfiles++] = argv[i];
186 } while (++i < argc);
189 bb_error_msg_and_die("no files");
191 /* prepare the buffer */
192 tailbufsize = BUFSIZ;
193 if (!G.from_top && COUNT_BYTES) {
194 if (tailbufsize < count + BUFSIZ) {
195 tailbufsize = count + BUFSIZ;
198 /* tail -c1024m REGULAR_FILE doesn't really need 1G mem block.
199 * (In fact, it doesn't need ANY memory). So delay allocation.
205 fmt = header_fmt_str + 1; /* skip leading newline in the header on the first output */
215 if (ENABLE_FEATURE_FANCY_TAIL && fd < 0)
216 continue; /* may happen with -F */
218 if (nfiles > header_threshhold) {
219 tail_xprint_header(fmt, argv[i]);
220 fmt = header_fmt_str;
224 off_t current = lseek(fd, 0, SEEK_END);
228 /* Optimizing count-bytes case if the file is seekable.
229 * Beware of backing up too far.
230 * Also we exclude files with size 0 (because of /proc/xxx) */
232 continue; /* showing zero bytes is easy :) */
236 xlseek(fd, current, SEEK_SET);
237 bb_copyfd_size(fd, STDOUT_FILENO, count);
240 #if 1 /* This is technically incorrect for *LONG* strings, but very useful */
241 /* Optimizing count-lines case if the file is seekable.
242 * We assume the lines are <64k.
243 * (Users complain that tail takes too long
244 * on multi-gigabyte files) */
245 off = (count | 0xf); /* for small counts, be more paranoid */
246 if (off > (INT_MAX / (64*1024)))
247 off = (INT_MAX / (64*1024));
248 current -= off * (64*1024);
251 xlseek(fd, current, SEEK_SET);
257 tailbuf = xmalloc(tailbufsize);
261 /* "We saw 1st line/byte".
262 * Used only by +N code ("start from Nth", 1-based): */
265 while ((nread = tail_read(fd, buf, tailbufsize - taillen)) > 0) {
269 /* We need to skip a few more bytes/lines */
271 nwrite -= (count - seen);
277 if (*s++ == '\n' && ++seen == count) {
284 xwrite(STDOUT_FILENO, buf + nread - nwrite, nwrite);
288 if (taillen > (int)count) {
289 memmove(tailbuf, tailbuf + taillen - count, count);
294 int newlines_in_buf = 0;
296 do { /* count '\n' in last read */
298 if (buf[k] == '\n') {
303 if (newlines_seen + newlines_in_buf < (int)count) {
304 newlines_seen += newlines_in_buf;
307 int extra = (buf[nread-1] != '\n');
310 k = newlines_seen + newlines_in_buf + extra - count;
318 taillen += nread - (s - tailbuf);
319 memmove(tailbuf, s, taillen);
320 newlines_seen = count - extra;
322 if (tailbufsize < (size_t)taillen + BUFSIZ) {
323 tailbufsize = taillen + BUFSIZ;
324 tailbuf = xrealloc(tailbuf, tailbufsize);
327 buf = tailbuf + taillen;
329 } /* while (tail_read() > 0) */
331 xwrite(STDOUT_FILENO, tailbuf, taillen);
333 } while (++i < nfiles);
336 tailbuf = xrealloc(tailbuf, BUFSIZ);
340 if (FOLLOW) while (1) {
346 const char *filename = argv[i];
350 struct stat sbuf, fsbuf;
353 || fstat(fd, &fsbuf) < 0
354 || stat(filename, &sbuf) < 0
355 || fsbuf.st_dev != sbuf.st_dev
356 || fsbuf.st_ino != sbuf.st_ino
362 new_fd = open(filename, O_RDONLY);
364 bb_error_msg("%s has %s; following end of new file",
365 filename, (fd < 0) ? "appeared" : "been replaced"
367 } else if (fd >= 0) {
368 bb_perror_msg("%s has become inaccessible", filename);
370 fds[i] = fd = new_fd;
373 if (ENABLE_FEATURE_FANCY_TAIL && fd < 0)
375 if (nfiles > header_threshhold) {
376 fmt = header_fmt_str;
379 /* tail -f keeps following files even if they are truncated */
381 /* /proc files report zero st_size, don't lseek them */
382 if (fstat(fd, &sbuf) == 0 && sbuf.st_size > 0) {
383 off_t current = lseek(fd, 0, SEEK_CUR);
384 if (sbuf.st_size < current)
385 xlseek(fd, 0, SEEK_SET);
388 nread = tail_read(fd, tailbuf, BUFSIZ);
391 if (fmt && (fd != prev_fd)) {
392 tail_xprint_header(fmt, filename);
396 xwrite(STDOUT_FILENO, tailbuf, nread);
398 } while (++i < nfiles);
401 if (ENABLE_FEATURE_CLEAN_UP) {