As usual, I forgot "svn del"...
[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 <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <ctype.h>
31 #include <unistd.h>
32 #include <fcntl.h>
33 #include <sys/stat.h>
34 #include "busybox.h"
35
36 static const struct suffix_mult tail_suffixes[] = {
37         { "b", 512 },
38         { "k", 1024 },
39         { "m", 1048576 },
40         { NULL, 0 }
41 };
42
43 static int status;
44
45 static void tail_xbb_full_write(const char *buf, size_t len)
46 {
47         /* If we get a write error, there is really no sense in continuing. */
48         if (full_write(STDOUT_FILENO, buf, len) < 0)
49                 bb_perror_nomsg_and_die();
50 }
51
52 static void tail_xprint_header(const char *fmt, const char *filename)
53 {
54 #if defined __GLIBC__
55         if (dprintf(STDOUT_FILENO, fmt, filename) < 0) {
56                 bb_perror_nomsg_and_die();
57         }
58 #else
59         int hdr_len = strlen(fmt) + strlen(filename);
60         char *hdr = xzalloc(hdr_len);
61         sprintf(hdr, filename, filename);
62         tail_xbb_full_write(hdr, hdr_len);
63 #endif
64 }
65
66 static ssize_t tail_read(int fd, char *buf, size_t count)
67 {
68         ssize_t r;
69         off_t current,end;
70         struct stat sbuf;
71
72         end = current = lseek(fd, 0, SEEK_CUR);
73         if (!fstat(fd, &sbuf))
74                 end = sbuf.st_size;
75         lseek(fd, end < current ? 0 : current, SEEK_SET);
76         if ((r = safe_read(fd, buf, count)) < 0) {
77                 bb_perror_msg(bb_msg_read_error);
78                 status = EXIT_FAILURE;
79         }
80
81         return r;
82 }
83
84 static const char tail_opts[] =
85         "fn:c:"
86 #if ENABLE_FEATURE_FANCY_TAIL
87         "qs:v"
88 #endif
89         ;
90
91 static const char header_fmt[] = "\n==> %s <==\n";
92
93 int tail_main(int argc, char **argv)
94 {
95         long count = 10;
96         unsigned int sleep_period = 1;
97         int from_top = 0;
98         int follow = 0;
99         int header_threshhold = 1;
100         int count_bytes = 0;
101
102         char *tailbuf;
103         size_t tailbufsize;
104         int taillen = 0;
105         int newline = 0;
106
107         int *fds, nfiles, nread, nwrite, seen, i, opt;
108         char *s, *buf;
109         const char *fmt;
110
111 #if !ENABLE_DEBUG_YANK_SUSv2 || ENABLE_FEATURE_FANCY_TAIL
112         /* Allow legacy syntax of an initial numeric option without -n. */
113         if (argc >=2 && ((argv[1][0] == '+') || ((argv[1][0] == '-')
114                         /* && (isdigit)(argv[1][1]) */
115                         && (((unsigned int)(argv[1][1] - '0')) <= 9))))
116         {
117                 optind = 2;
118                 optarg = argv[1];
119                 goto GET_COUNT;
120         }
121 #endif
122
123         while ((opt = getopt(argc, argv, tail_opts)) > 0) {
124                 switch (opt) {
125                         case 'f':
126                                 follow = 1;
127                                 break;
128                         case 'c':
129                                 count_bytes = 1;
130                                 /* FALLS THROUGH */
131                         case 'n':
132 #if !ENABLE_DEBUG_YANK_SUSv2 || ENABLE_FEATURE_FANCY_TAIL
133                         GET_COUNT:
134 #endif
135                                 count = xatol_sfx(optarg, tail_suffixes);
136                                 /* Note: Leading whitespace is an error trapped above. */
137                                 if (*optarg == '+') {
138                                         from_top = 1;
139                                 } else {
140                                         from_top = 0;
141                                 }
142                                 if (count < 0) {
143                                         count = -count;
144                                 }
145                                 break;
146 #if ENABLE_FEATURE_FANCY_TAIL
147                         case 'q':
148                                 header_threshhold = INT_MAX;
149                                 break;
150                         case 's':
151                                 sleep_period = xatou(optarg);
152                                 break;
153                         case 'v':
154                                 header_threshhold = 0;
155                                 break;
156 #endif
157                         default:
158                                 bb_show_usage();
159                 }
160         }
161
162         /* open all the files */
163         fds = (int *)xmalloc(sizeof(int) * (argc - optind + 1));
164
165         argv += optind;
166         nfiles = i = 0;
167
168         if ((argc -= optind) == 0) {
169                 struct stat statbuf;
170
171                 if (!fstat(STDIN_FILENO, &statbuf) && S_ISFIFO(statbuf.st_mode)) {
172                         follow = 0;
173                 }
174                 /* --argv; */
175                 *argv = (char *) bb_msg_standard_input;
176                 goto DO_STDIN;
177         }
178
179         do {
180                 if ((argv[i][0] == '-') && !argv[i][1]) {
181                 DO_STDIN:
182                         fds[nfiles] = STDIN_FILENO;
183                 } else if ((fds[nfiles] = open(argv[i], O_RDONLY)) < 0) {
184                         bb_perror_msg("%s", argv[i]);
185                         status = EXIT_FAILURE;
186                         continue;
187                 }
188                 argv[nfiles] = argv[i];
189                 ++nfiles;
190         } while (++i < argc);
191
192         if (!nfiles) {
193                 bb_error_msg_and_die("no files");
194         }
195
196         tailbufsize = BUFSIZ;
197
198         /* tail the files */
199         if (from_top < count_bytes) {   /* Each is 0 or 1, so true iff 0 < 1. */
200                 /* Hence, !from_top && count_bytes */
201                 if (tailbufsize < count) {
202                         tailbufsize = count + BUFSIZ;
203                 }
204         }
205
206         buf = tailbuf = xmalloc(tailbufsize);
207
208         fmt = header_fmt + 1;   /* Skip header leading newline on first output. */
209         i = 0;
210         do {
211                 /* Be careful.  It would be possible to optimize the count-bytes
212                  * case if the file is seekable.  If you do though, remember that
213                  * starting file position may not be the beginning of the file.
214                  * Beware of backing up too far.  See example in wc.c.
215                  */
216                 if ((!(count|from_top)) && (lseek(fds[i], 0, SEEK_END) >= 0)) {
217                         continue;
218                 }
219
220                 if (nfiles > header_threshhold) {
221                         tail_xprint_header(fmt, argv[i]);
222                         fmt = header_fmt;
223                 }
224
225                 buf = tailbuf;
226                 taillen = 0;
227                 seen = 1;
228                 newline = 0;
229
230                 while ((nread = tail_read(fds[i], buf, tailbufsize-taillen)) > 0) {
231                         if (from_top) {
232                                 nwrite = nread;
233                                 if (seen < count) {
234                                         if (count_bytes) {
235                                                 nwrite -= (count - seen);
236                                                 seen = count;
237                                         } else {
238                                                 s = buf;
239                                                 do {
240                                                         --nwrite;
241                                                         if ((*s++ == '\n') && (++seen == count)) {
242                                                                 break;
243                                                         }
244                                                 } while (nwrite);
245                                         }
246                                 }
247                                 tail_xbb_full_write(buf + nread - nwrite, nwrite);
248                         } else if (count) {
249                                 if (count_bytes) {
250                                         taillen += nread;
251                                         if (taillen > count) {
252                                                 memmove(tailbuf, tailbuf + taillen - count, count);
253                                                 taillen = count;
254                                         }
255                                 } else {
256                                         int k = nread;
257                                         int nbuf = 0;
258
259                                         while (k) {
260                                                 --k;
261                                                 if (buf[k] == '\n') {
262                                                         ++nbuf;
263                                                 }
264                                         }
265
266                                         if (newline + nbuf < count) {
267                                                 newline += nbuf;
268                                                 taillen += nread;
269
270                                         } else {
271                                                 int extra = 0;
272                                                 if (buf[nread-1] != '\n') {
273                                                         extra = 1;
274                                                 }
275
276                                                 k = newline + nbuf + extra - count;
277                                                 s = tailbuf;
278                                                 while (k) {
279                                                         if (*s == '\n') {
280                                                                 --k;
281                                                         }
282                                                         ++s;
283                                                 }
284
285                                                 taillen += nread - (s - tailbuf);
286                                                 memmove(tailbuf, s, taillen);
287                                                 newline = count - extra;
288                                         }
289                                         if (tailbufsize < taillen + BUFSIZ) {
290                                                 tailbufsize = taillen + BUFSIZ;
291                                                 tailbuf = xrealloc(tailbuf, tailbufsize);
292                                         }
293                                 }
294                                 buf = tailbuf + taillen;
295                         }
296                 }
297
298                 if (!from_top) {
299                         tail_xbb_full_write(tailbuf, taillen);
300                 }
301
302                 taillen = 0;
303         } while (++i < nfiles);
304
305         buf = xrealloc(tailbuf, BUFSIZ);
306
307         fmt = NULL;
308
309         while (follow) {
310                 sleep(sleep_period);
311                 i = 0;
312                 do {
313                         if (nfiles > header_threshhold) {
314                                 fmt = header_fmt;
315                         }
316                         while ((nread = tail_read(fds[i], buf, sizeof(buf))) > 0) {
317                                 if (fmt) {
318                                         tail_xprint_header(fmt, argv[i]);
319                                         fmt = NULL;
320                                 }
321                                 tail_xbb_full_write(buf, nread);
322                         }
323                 } while (++i < nfiles);
324         }
325
326         return status;
327 }