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