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