340697f888576cc8a551e48c0431d53f577b3a75
[oweals/busybox.git] / coreutils / tail.c
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 tarball for details.
8  */
9
10 /* BB_AUDIT SUSv3 compliant (need fancy for -c) */
11 /* BB_AUDIT GNU compatible -c, -q, and -v options in 'fancy' configuration. */
12 /* http://www.opengroup.org/onlinepubs/007904975/utilities/tail.html */
13
14 /* Mar 16, 2003      Manuel Novoa III   (mjn3@codepoet.org)
15  *
16  * Pretty much rewritten to fix numerous bugs and reduce realloc() calls.
17  * Bugs fixed (although I may have forgotten one or two... it was pretty bad)
18  * 1) mixing printf/write without fflush()ing stdout
19  * 2) no check that any open files are present
20  * 3) optstring had -q taking an arg
21  * 4) no error checking on write in some cases, and a warning even then
22  * 5) q and s interaction bug
23  * 6) no check for lseek error
24  * 7) lseek attempted when count==0 even if arg was +0 (from top)
25  */
26
27 #include "libbb.h"
28
29 static const struct suffix_mult tail_suffixes[] = {
30         { "b", 512 },
31         { "k", 1024 },
32         { "m", 1024*1024 },
33         { }
34 };
35
36 struct globals {
37         bool status;
38 };
39 #define G (*(struct globals*)&bb_common_bufsiz1)
40
41 static void tail_xprint_header(const char *fmt, const char *filename)
42 {
43         if (fdprintf(STDOUT_FILENO, fmt, filename) < 0)
44                 bb_perror_nomsg_and_die();
45 }
46
47 static ssize_t tail_read(int fd, char *buf, size_t count)
48 {
49         ssize_t r;
50         off_t current;
51         struct stat sbuf;
52
53         /* (A good comment is missing here) */
54         current = lseek(fd, 0, SEEK_CUR);
55         /* /proc files report zero st_size, don't lseek them. */
56         if (fstat(fd, &sbuf) == 0 && sbuf.st_size)
57                 if (sbuf.st_size < current)
58                         lseek(fd, 0, SEEK_SET);
59
60         r = full_read(fd, buf, count);
61         if (r < 0) {
62                 bb_perror_msg(bb_msg_read_error);
63                 G.status = EXIT_FAILURE;
64         }
65
66         return r;
67 }
68
69 static const char header_fmt[] ALIGN1 = "\n==> %s <==\n";
70
71 static unsigned eat_num(const char *p)
72 {
73         if (*p == '-')
74                 p++;
75         else if (*p == '+') {
76                 p++;
77                 G.status = 1; /* mark that we saw "+" */
78         }
79         return xatou_sfx(p, tail_suffixes);
80 }
81
82 int tail_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
83 int tail_main(int argc, char **argv)
84 {
85         unsigned count = 10;
86         unsigned sleep_period = 1;
87         bool from_top;
88         int header_threshhold = 1;
89         const char *str_c, *str_n;
90         USE_FEATURE_FANCY_TAIL(const char *str_s;)
91
92         char *tailbuf;
93         size_t tailbufsize;
94         int taillen = 0;
95         int newlines_seen = 0;
96         int nfiles, nread, nwrite, seen, i, opt;
97
98         int *fds;
99         char *s, *buf;
100         const char *fmt;
101
102 #if ENABLE_INCLUDE_SUSv2 || ENABLE_FEATURE_FANCY_TAIL
103         /* Allow legacy syntax of an initial numeric option without -n. */
104         if (argc >= 2 && (argv[1][0] == '+' || argv[1][0] == '-')
105          && isdigit(argv[1][1])
106         ) {
107                 /* replacing arg[0] with "-n" can segfault, so... */
108                 argv[1] = xasprintf("-n%s", argv[1]);
109 #if 0 /* If we ever decide to make tail NOFORK */
110                 char *s = alloca(strlen(argv[1]) + 3);
111                 sprintf(s, "-n%s", argv[1]);
112                 argv[1] = s;
113 #endif
114         }
115 #endif
116
117         opt = getopt32(argv, "fc:n:" USE_FEATURE_FANCY_TAIL("qs:v"),
118                         &str_c, &str_n USE_FEATURE_FANCY_TAIL(,&str_s));
119 #define FOLLOW (opt & 0x1)
120 #define COUNT_BYTES (opt & 0x2)
121         //if (opt & 0x1) // -f
122         if (opt & 0x2) count = eat_num(str_c); // -c
123         if (opt & 0x4) count = eat_num(str_n); // -n
124 #if ENABLE_FEATURE_FANCY_TAIL
125         if (opt & 0x8) header_threshhold = INT_MAX; // -q
126         if (opt & 0x10) sleep_period = xatou(str_s); // -s
127         if (opt & 0x20) header_threshhold = 0; // -v
128 #endif
129         argc -= optind;
130         argv += optind;
131         from_top = G.status; /* 1 if there was "-c +N" or "-n +N" */
132         G.status = EXIT_SUCCESS;
133
134         /* open all the files */
135         fds = xmalloc(sizeof(int) * (argc + 1));
136         nfiles = i = 0;
137         if (argc == 0) {
138                 struct stat statbuf;
139
140                 if (!fstat(STDIN_FILENO, &statbuf) && S_ISFIFO(statbuf.st_mode)) {
141                         opt &= ~1; /* clear FOLLOW */
142                 }
143                 *argv = (char *) bb_msg_standard_input;
144         }
145         do {
146                 FILE* fil = fopen_or_warn_stdin(argv[i]);
147                 if (!fil) {
148                         G.status = EXIT_FAILURE;
149                         continue;
150                 }
151                 fds[nfiles] = fileno(fil);
152                 argv[nfiles++] = argv[i];
153         } while (++i < argc);
154
155         if (!nfiles)
156                 bb_error_msg_and_die("no files");
157
158         /* prepare the buffer */
159         tailbufsize = BUFSIZ;
160         if (!from_top && COUNT_BYTES) {
161                 if (tailbufsize < count + BUFSIZ) {
162                         tailbufsize = count + BUFSIZ;
163                 }
164         }
165         tailbuf = xmalloc(tailbufsize);
166
167         /* tail the files */
168         fmt = header_fmt + 1;   /* Skip header leading newline on first output. */
169         i = 0;
170         do {
171                 off_t current;
172
173                 if (nfiles > header_threshhold) {
174                         tail_xprint_header(fmt, argv[i]);
175                         fmt = header_fmt;
176                 }
177
178                 /* Optimizing count-bytes case if the file is seekable.
179                  * Beware of backing up too far.
180                  * Also we exclude files with size 0 (because of /proc/xxx) */
181                 current = lseek(fds[i], 0, SEEK_END);
182                 if (current > 0) {
183                         if (!from_top) {
184                                 if (count == 0)
185                                         continue; /* showing zero lines is easy :) */
186                                 if (COUNT_BYTES) {
187                                         current -= count;
188                                         if (current < 0)
189                                                 current = 0;
190                                         xlseek(fds[i], current, SEEK_SET);
191                                         bb_copyfd_size(fds[i], STDOUT_FILENO, count);
192                                         continue;
193                                 }
194                         }
195                 }
196
197                 buf = tailbuf;
198                 taillen = 0;
199                 seen = 1;
200                 newlines_seen = 0;
201                 while ((nread = tail_read(fds[i], buf, tailbufsize-taillen)) > 0) {
202                         if (from_top) {
203                                 nwrite = nread;
204                                 if (seen < count) {
205                                         if (COUNT_BYTES) {
206                                                 nwrite -= (count - seen);
207                                                 seen = count;
208                                         } else {
209                                                 s = buf;
210                                                 do {
211                                                         --nwrite;
212                                                         if (*s++ == '\n' && ++seen == count) {
213                                                                 break;
214                                                         }
215                                                 } while (nwrite);
216                                         }
217                                 }
218                                 xwrite(STDOUT_FILENO, buf + nread - nwrite, nwrite);
219                         } else if (count) {
220                                 if (COUNT_BYTES) {
221                                         taillen += nread;
222                                         if (taillen > count) {
223                                                 memmove(tailbuf, tailbuf + taillen - count, count);
224                                                 taillen = count;
225                                         }
226                                 } else {
227                                         int k = nread;
228                                         int newlines_in_buf = 0;
229
230                                         do { /* count '\n' in last read */
231                                                 k--;
232                                                 if (buf[k] == '\n') {
233                                                         newlines_in_buf++;
234                                                 }
235                                         } while (k);
236
237                                         if (newlines_seen + newlines_in_buf < count) {
238                                                 newlines_seen += newlines_in_buf;
239                                                 taillen += nread;
240                                         } else {
241                                                 int extra = (buf[nread-1] != '\n');
242
243                                                 k = newlines_seen + newlines_in_buf + extra - count;
244                                                 s = tailbuf;
245                                                 while (k) {
246                                                         if (*s == '\n') {
247                                                                 k--;
248                                                         }
249                                                         s++;
250                                                 }
251                                                 taillen += nread - (s - tailbuf);
252                                                 memmove(tailbuf, s, taillen);
253                                                 newlines_seen = count - extra;
254                                         }
255                                         if (tailbufsize < taillen + BUFSIZ) {
256                                                 tailbufsize = taillen + BUFSIZ;
257                                                 tailbuf = xrealloc(tailbuf, tailbufsize);
258                                         }
259                                 }
260                                 buf = tailbuf + taillen;
261                         }
262                 } /* while (tail_read() > 0) */
263                 if (!from_top) {
264                         xwrite(STDOUT_FILENO, tailbuf, taillen);
265                 }
266         } while (++i < nfiles);
267
268         buf = xrealloc(tailbuf, BUFSIZ);
269
270         fmt = NULL;
271
272         if (FOLLOW) while (1) {
273                 sleep(sleep_period);
274                 i = 0;
275                 do {
276                         if (nfiles > header_threshhold) {
277                                 fmt = header_fmt;
278                         }
279                         while ((nread = tail_read(fds[i], buf, BUFSIZ)) > 0) {
280                                 if (fmt) {
281                                         tail_xprint_header(fmt, argv[i]);
282                                         fmt = NULL;
283                                 }
284                                 xwrite(STDOUT_FILENO, buf, nread);
285                         }
286                 } while (++i < nfiles);
287         }
288         if (ENABLE_FEATURE_CLEAN_UP) {
289                 free(fds);
290         }
291         return G.status;
292 }