8e0adf5b5c5e927ee71a8c40450bee962be875f8
[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  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  * General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20  *
21  */
22
23 /* BB_AUDIT SUSv3 compliant (need fancy for -c) */
24 /* BB_AUDIT GNU compatible -c, -q, and -v options in 'fancy' configuration. */
25 /* http://www.opengroup.org/onlinepubs/007904975/utilities/tail.html */
26
27 /* Mar 16, 2003      Manuel Novoa III   (mjn3@codepoet.org)
28  *
29  * Pretty much rewritten to fix numerous bugs and reduce realloc() calls.
30  * Bugs fixed (although I may have forgotten one or two... it was pretty bad)
31  * 1) mixing printf/write without fflush()ing stdout
32  * 2) no check that any open files are present
33  * 3) optstring had -q taking an arg
34  * 4) no error checking on write in some cases, and a warning even then
35  * 5) q and s interaction bug
36  * 6) no check for lseek error
37  * 7) lseek attempted when count==0 even if arg was +0 (from top)
38  */
39
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <ctype.h>
44 #include <unistd.h>
45 #include <fcntl.h>
46 #include <sys/stat.h>
47 #include "busybox.h"
48
49 static const struct suffix_mult tail_suffixes[] = {
50         { "b", 512 },
51         { "k", 1024 },
52         { "m", 1048576 },
53         { NULL, 0 }
54 };
55
56 static int status
57 #if EXIT_SUCCESS != 0
58         = EXIT_SUCCESS  /* If it is 0 (paranoid check), let bss initialize it. */
59 #endif
60         ;
61
62 static void tail_xprint_header(const char *fmt, const char *filename)
63 {
64         /* If we get an output error, there is really no sense in continuing. */
65         if (dprintf(STDOUT_FILENO, fmt, filename) < 0) {
66                 bb_perror_nomsg_and_die();
67         }
68 }
69
70 /* len should probably be size_t */
71 static void tail_xbb_full_write(const char *buf, size_t len)
72 {
73         /* If we get a write error, there is really no sense in continuing. */
74         if (bb_full_write(STDOUT_FILENO, buf, len) < 0) {
75                 bb_perror_nomsg_and_die();
76         }
77 }
78
79 static ssize_t tail_read(int fd, char *buf, size_t count)
80 {
81         ssize_t r;
82
83         if ((r = safe_read(fd, buf, count)) < 0) {
84                 bb_perror_msg("read");
85                 status = EXIT_FAILURE;
86         }
87
88         return r;
89 }
90
91 static const char tail_opts[] =
92         "fn:"
93 #ifdef CONFIG_FEATURE_FANCY_TAIL
94         "c:qs:v"
95 #endif
96         ;
97
98 static const char header_fmt[] = "\n==> %s <==\n";
99
100 int tail_main(int argc, char **argv)
101 {
102         long count = 10;
103         unsigned int sleep_period = 1;
104         int from_top = 0;
105         int follow = 0;
106         int header_threshhold = 1;
107 #ifdef CONFIG_FEATURE_FANCY_TAIL
108         int count_bytes = 0;
109 #endif
110
111         char *tailbuf;
112         size_t tailbufsize;
113         int taillen = 0;
114         int newline = 0;
115
116         int *fds, nfiles, nread, nwrite, seen, i, opt;
117         char *s, *buf;
118         const char *fmt;
119
120         /* Allow legacy syntax of an initial numeric option without -n. */
121         if ((argv[1][0] == '+')
122                 || ((argv[1][0] == '-')
123                         /* && (isdigit)(argv[1][1]) */
124                         && (((unsigned int)(argv[1][1] - '0')) <= 9))
125                 ) {
126                 optind = 2;
127                 optarg = argv[1];
128                 goto GET_COUNT;
129         }
130
131         while ((opt = getopt(argc, argv, tail_opts)) > 0) {
132                 switch (opt) {
133                         case 'f':
134                                 follow = 1;
135                                 break;
136 #ifdef CONFIG_FEATURE_FANCY_TAIL
137                         case 'c':
138                                 count_bytes = 1;
139                                 /* FALLS THROUGH */
140 #endif
141                         case 'n':
142                         GET_COUNT:
143                                 count = bb_xgetlarg10_sfx(optarg, tail_suffixes);
144                                 /* Note: Leading whitespace is an error trapped above. */
145                                 if (*optarg == '+') {
146                                         from_top = 1;
147                                 } else {
148                                         from_top = 0;
149                                 }
150                                 if (count < 0) {
151                                         count = -count;
152                                 }
153                                 break;
154 #ifdef CONFIG_FEATURE_FANCY_TAIL
155                         case 'q':
156                                 header_threshhold = INT_MAX;
157                                 break;
158                         case 's':
159                                 sleep_period =bb_xgetularg10_bnd(optarg, 0, UINT_MAX);
160                                 break;
161                         case 'v':
162                                 header_threshhold = 0;
163                                 break;
164 #endif
165                         default:
166                                 bb_show_usage();
167                 }
168         }
169
170         /* open all the files */
171         fds = (int *)xmalloc(sizeof(int) * (argc - optind + 1));
172
173         argv += optind;
174         nfiles = i = 0;
175
176         if ((argc -= optind) == 0) {
177                 struct stat statbuf;
178
179                 if (!fstat(STDIN_FILENO, &statbuf) && S_ISFIFO(statbuf.st_mode)) {
180                         follow = 0;
181                 }
182                 /* --argv; */
183                 *argv = (char *) bb_msg_standard_input;
184                 goto DO_STDIN;
185         }
186
187         do {
188                 if ((argv[i][0] == '-') && !argv[i][1]) {
189                 DO_STDIN:
190                         fds[nfiles] = STDIN_FILENO;
191                 } else if ((fds[nfiles] = open(argv[i], O_RDONLY)) < 0) {
192                         bb_perror_msg("%s", argv[i]);
193                         status = EXIT_FAILURE;
194                         continue;
195                 }
196                 argv[nfiles] = argv[i];
197                 ++nfiles;
198         } while (++i < argc);
199
200         if (!nfiles) {
201                 bb_error_msg_and_die("no files");
202         }
203
204         tailbufsize = BUFSIZ;
205 #ifdef CONFIG_FEATURE_FANCY_TAIL
206         /* tail the files */
207         if (from_top < count_bytes) {   /* Each is 0 or 1, so true iff 0 < 1. */
208                 /* Hence, !from_top && count_bytes */
209                 if (tailbufsize < count) {
210                         tailbufsize = count + BUFSIZ;
211                 }
212         }
213 #endif
214         buf = tailbuf = xmalloc(tailbufsize);
215
216         fmt = header_fmt + 1;   /* Skip header leading newline on first output. */
217         i = 0;
218         do {
219                 /* Be careful.  It would be possible to optimize the count-bytes
220                  * case if the file is seekable.  If you do though, remember that
221                  * starting file position may not be the beginning of the file.
222                  * Beware of backing up too far.  See example in wc.c.
223                  */
224                 if ((!(count|from_top)) && (lseek(fds[i], 0, SEEK_END) >= 0)) {
225                         continue;
226                 }
227
228                 if (nfiles > header_threshhold) {
229                         tail_xprint_header(fmt, argv[i]);
230                         fmt = header_fmt;
231                 }
232
233                 buf = tailbuf;
234                 taillen = 0;
235                 seen = 1;
236
237                 while ((nread = tail_read(fds[i], buf, tailbufsize-taillen)) > 0) {
238                         if (from_top) {
239                                 nwrite = nread;
240                                 if (seen < count) {
241 #ifdef CONFIG_FEATURE_FANCY_TAIL
242                                         if (count_bytes) {
243                                                 nwrite -= (count - seen);
244                                                 seen = count;
245                                         } else
246 #endif
247                                         {
248                                                 s = buf;
249                                                 do {
250                                                         --nwrite;
251                                                         if ((*s++ == '\n') && (++seen == count)) {
252                                                                 break;
253                                                         }
254                                                 } while (nwrite);
255                                         }
256                                 }
257                                 tail_xbb_full_write(buf + nread - nwrite, nwrite);
258                         } else if (count) {
259 #ifdef CONFIG_FEATURE_FANCY_TAIL
260                                 if (count_bytes) {
261                                         taillen += nread;
262                                         if (taillen > count) {
263                                                 memmove(tailbuf, tailbuf + taillen - count, count);
264                                                 taillen = count;
265                                         }
266                                 } else
267 #endif
268                                 {
269                                         int k = nread;
270                                         int nbuf = 0;
271
272                                         while (k) {
273                                                 --k;
274                                                 if (buf[k] == '\n') {
275                                                         ++nbuf;
276                                                 }
277                                         }
278
279                                         if (newline + nbuf < count) {
280                                                 newline += nbuf;
281                                                 taillen += nread;
282
283                                         } else {
284                                                 int extra = 0;
285                                                 if (buf[nread-1] != '\n') {
286                                                         extra = 1;
287                                                 }
288
289                                                 k = newline + nbuf + extra - count;
290                                                 s = tailbuf;
291                                                 while (k) {
292                                                         if (*s == '\n') {
293                                                                 --k;
294                                                         }
295                                                         ++s;
296                                                 }
297
298                                                 taillen += nread - (s - tailbuf);
299                                                 memmove(tailbuf, s, taillen);
300                                                 newline = count - extra;
301                                         }
302                                         if (tailbufsize < taillen + BUFSIZ) {
303                                                 tailbufsize = taillen + BUFSIZ;
304                                                 tailbuf = xrealloc(tailbuf, tailbufsize);
305                                         }
306                                 }
307                                 buf = tailbuf + taillen;
308                         }
309                 }
310
311                 if (!from_top) {
312                         tail_xbb_full_write(tailbuf, taillen);
313                 }
314
315                 taillen = 0;
316         } while (++i < nfiles);
317
318         buf = xrealloc(tailbuf, BUFSIZ);
319
320         fmt = NULL;
321
322         while (follow) {
323                 sleep(sleep_period);
324                 i = 0;
325                 do {
326                         if (nfiles > header_threshhold) {
327                                 fmt = header_fmt;
328                         }
329                         while ((nread = tail_read(fds[i], buf, sizeof(buf))) > 0) {
330                                 if (fmt) {
331                                         tail_xprint_header(fmt, argv[i]);
332                                         fmt = NULL;
333                                 }
334                                 tail_xbb_full_write(buf, nread);
335                         }
336                 } while (++i < nfiles);
337         }
338
339         return status;
340 }