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