e3f89d2eea5424c1661e02a6fb9ac54c337d3d59
[people/mcb30/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:c:"
93 #ifdef CONFIG_FEATURE_FANCY_TAIL
94         "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         int count_bytes = 0;
108
109         char *tailbuf;
110         size_t tailbufsize;
111         int taillen = 0;
112         int newline = 0;
113
114         int *fds, nfiles, nread, nwrite, seen, i, opt;
115         char *s, *buf;
116         const char *fmt;
117
118         /* Allow legacy syntax of an initial numeric option without -n. */
119         if (argc >=2 && ((argv[1][0] == '+') || ((argv[1][0] == '-')
120                         /* && (isdigit)(argv[1][1]) */
121                         && (((unsigned int)(argv[1][1] - '0')) <= 9))))
122         {
123                 optind = 2;
124                 optarg = argv[1];
125                 goto GET_COUNT;
126         }
127
128         while ((opt = getopt(argc, argv, tail_opts)) > 0) {
129                 switch (opt) {
130                         case 'f':
131                                 follow = 1;
132                                 break;
133                         case 'c':
134                                 count_bytes = 1;
135                                 /* FALLS THROUGH */
136                         case 'n':
137                         GET_COUNT:
138                                 count = bb_xgetlarg10_sfx(optarg, tail_suffixes);
139                                 /* Note: Leading whitespace is an error trapped above. */
140                                 if (*optarg == '+') {
141                                         from_top = 1;
142                                 } else {
143                                         from_top = 0;
144                                 }
145                                 if (count < 0) {
146                                         count = -count;
147                                 }
148                                 break;
149 #ifdef CONFIG_FEATURE_FANCY_TAIL
150                         case 'q':
151                                 header_threshhold = INT_MAX;
152                                 break;
153                         case 's':
154                                 sleep_period =bb_xgetularg10_bnd(optarg, 0, UINT_MAX);
155                                 break;
156                         case 'v':
157                                 header_threshhold = 0;
158                                 break;
159 #endif
160                         default:
161                                 bb_show_usage();
162                 }
163         }
164
165         /* open all the files */
166         fds = (int *)xmalloc(sizeof(int) * (argc - optind + 1));
167
168         argv += optind;
169         nfiles = i = 0;
170
171         if ((argc -= optind) == 0) {
172                 struct stat statbuf;
173
174                 if (!fstat(STDIN_FILENO, &statbuf) && S_ISFIFO(statbuf.st_mode)) {
175                         follow = 0;
176                 }
177                 /* --argv; */
178                 *argv = (char *) bb_msg_standard_input;
179                 goto DO_STDIN;
180         }
181
182         do {
183                 if ((argv[i][0] == '-') && !argv[i][1]) {
184                 DO_STDIN:
185                         fds[nfiles] = STDIN_FILENO;
186                 } else if ((fds[nfiles] = open(argv[i], O_RDONLY)) < 0) {
187                         bb_perror_msg("%s", argv[i]);
188                         status = EXIT_FAILURE;
189                         continue;
190                 }
191                 argv[nfiles] = argv[i];
192                 ++nfiles;
193         } while (++i < argc);
194
195         if (!nfiles) {
196                 bb_error_msg_and_die("no files");
197         }
198
199         tailbufsize = BUFSIZ;
200
201         /* tail the files */
202         if (from_top < count_bytes) {   /* Each is 0 or 1, so true iff 0 < 1. */
203                 /* Hence, !from_top && count_bytes */
204                 if (tailbufsize < count) {
205                         tailbufsize = count + BUFSIZ;
206                 }
207         }
208
209         buf = tailbuf = xmalloc(tailbufsize);
210
211         fmt = header_fmt + 1;   /* Skip header leading newline on first output. */
212         i = 0;
213         do {
214                 /* Be careful.  It would be possible to optimize the count-bytes
215                  * case if the file is seekable.  If you do though, remember that
216                  * starting file position may not be the beginning of the file.
217                  * Beware of backing up too far.  See example in wc.c.
218                  */
219                 if ((!(count|from_top)) && (lseek(fds[i], 0, SEEK_END) >= 0)) {
220                         continue;
221                 }
222
223                 if (nfiles > header_threshhold) {
224                         tail_xprint_header(fmt, argv[i]);
225                         fmt = header_fmt;
226                 }
227
228                 buf = tailbuf;
229                 taillen = 0;
230                 seen = 1;
231                 newline = 0;
232
233                 while ((nread = tail_read(fds[i], buf, tailbufsize-taillen)) > 0) {
234                         if (from_top) {
235                                 nwrite = nread;
236                                 if (seen < count) {
237                                         if (count_bytes) {
238                                                 nwrite -= (count - seen);
239                                                 seen = count;
240                                         } else {
241                                                 s = buf;
242                                                 do {
243                                                         --nwrite;
244                                                         if ((*s++ == '\n') && (++seen == count)) {
245                                                                 break;
246                                                         }
247                                                 } while (nwrite);
248                                         }
249                                 }
250                                 tail_xbb_full_write(buf + nread - nwrite, nwrite);
251                         } else if (count) {
252                                 if (count_bytes) {
253                                         taillen += nread;
254                                         if (taillen > count) {
255                                                 memmove(tailbuf, tailbuf + taillen - count, count);
256                                                 taillen = count;
257                                         }
258                                 } else {
259                                         int k = nread;
260                                         int nbuf = 0;
261
262                                         while (k) {
263                                                 --k;
264                                                 if (buf[k] == '\n') {
265                                                         ++nbuf;
266                                                 }
267                                         }
268
269                                         if (newline + nbuf < count) {
270                                                 newline += nbuf;
271                                                 taillen += nread;
272
273                                         } else {
274                                                 int extra = 0;
275                                                 if (buf[nread-1] != '\n') {
276                                                         extra = 1;
277                                                 }
278
279                                                 k = newline + nbuf + extra - count;
280                                                 s = tailbuf;
281                                                 while (k) {
282                                                         if (*s == '\n') {
283                                                                 --k;
284                                                         }
285                                                         ++s;
286                                                 }
287
288                                                 taillen += nread - (s - tailbuf);
289                                                 memmove(tailbuf, s, taillen);
290                                                 newline = count - extra;
291                                         }
292                                         if (tailbufsize < taillen + BUFSIZ) {
293                                                 tailbufsize = taillen + BUFSIZ;
294                                                 tailbuf = xrealloc(tailbuf, tailbufsize);
295                                         }
296                                 }
297                                 buf = tailbuf + taillen;
298                         }
299                 }
300
301                 if (!from_top) {
302                         tail_xbb_full_write(tailbuf, taillen);
303                 }
304
305                 taillen = 0;
306         } while (++i < nfiles);
307
308         buf = xrealloc(tailbuf, BUFSIZ);
309
310         fmt = NULL;
311
312         while (follow) {
313                 sleep(sleep_period);
314                 i = 0;
315                 do {
316                         if (nfiles > header_threshhold) {
317                                 fmt = header_fmt;
318                         }
319                         while ((nread = tail_read(fds[i], buf, sizeof(buf))) > 0) {
320                                 if (fmt) {
321                                         tail_xprint_header(fmt, argv[i]);
322                                         fmt = NULL;
323                                 }
324                                 tail_xbb_full_write(buf, nread);
325                         }
326                 } while (++i < nfiles);
327         }
328
329         return status;
330 }