Merge branch 'vendor/DHCPCD'
[dragonfly.git] / usr.bin / tail / forward.c
1 /*-
2  * Copyright (c) 1991, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Edward Sze-Tyan Wang.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  * @(#)forward.c        8.1 (Berkeley) 6/6/93
33  * $FreeBSD: src/usr.bin/tail/forward.c,v 1.11.6.7 2003/01/07 05:26:22 tjr Exp $
34  */
35
36 #include <sys/types.h>
37 #include <sys/stat.h>
38 #include <sys/time.h>
39 #include <sys/mman.h>
40 #ifndef BOOTSTRAPPING
41 #include <sys/event.h>
42 #endif
43
44 #include <limits.h>
45 #include <fcntl.h>
46 #include <errno.h>
47 #include <unistd.h>
48 #include <stdio.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #include <err.h>
52 #include "extern.h"
53
54 static void rlines(FILE *, off_t, struct stat *);
55
56 /* defines for inner loop actions */
57 #define USE_SLEEP       0
58 #ifndef BOOTSTRAPPING
59 #define USE_KQUEUE      1
60 #define ADD_EVENTS      2
61
62 struct kevent *ev;
63 #endif
64 int action = USE_SLEEP;
65 int kq;
66
67 /*
68  * forward -- display the file, from an offset, forward.
69  *
70  * There are eight separate cases for this -- regular and non-regular
71  * files, by bytes or lines and from the beginning or end of the file.
72  *
73  * FBYTES       byte offset from the beginning of the file
74  *      REG     seek
75  *      NOREG   read, counting bytes
76  *
77  * FLINES       line offset from the beginning of the file
78  *      REG     read, counting lines
79  *      NOREG   read, counting lines
80  *
81  * RBYTES       byte offset from the end of the file
82  *      REG     seek
83  *      NOREG   cyclically read characters into a wrap-around buffer
84  *
85  * RLINES
86  *      REG     mmap the file and step back until reach the correct offset.
87  *      NOREG   cyclically read lines into a wrap-around array of buffers
88  */
89 void
90 forward(FILE *fp, enum STYLE style, off_t off, struct stat *sbp)
91 {
92         int ch;
93
94         switch(style) {
95         case FBYTES:
96                 if (off == 0)
97                         break;
98                 if (S_ISREG(sbp->st_mode)) {
99                         if (sbp->st_size < off)
100                                 off = sbp->st_size;
101                         if (fseeko(fp, off, SEEK_SET) == -1) {
102                                 ierr();
103                                 return;
104                         }
105                 } else while (off--)
106                         if ((ch = getc(fp)) == EOF) {
107                                 if (ferror(fp)) {
108                                         ierr();
109                                         return;
110                                 }
111                                 break;
112                         }
113                 break;
114         case FLINES:
115                 if (off == 0)
116                         break;
117                 for (;;) {
118                         if ((ch = getc(fp)) == EOF) {
119                                 if (ferror(fp)) {
120                                         ierr();
121                                         return;
122                                 }
123                                 break;
124                         }
125                         if (ch == '\n' && !--off)
126                                 break;
127                 }
128                 break;
129         case RBYTES:
130                 if (S_ISREG(sbp->st_mode)) {
131                         if (sbp->st_size >= off &&
132                             fseeko(fp, -off, SEEK_END) == -1) {
133                                 ierr();
134                                 return;
135                         }
136                 } else if (off == 0) {
137                         while (getc(fp) != EOF);
138                         if (ferror(fp)) {
139                                 ierr();
140                                 return;
141                         }
142                 } else
143                         if (display_bytes(fp, off))
144                                 return;
145                 break;
146         case RLINES:
147                 if (S_ISREG(sbp->st_mode))
148                         if (!off) {
149                                 if (fseeko(fp, (off_t)0, SEEK_END) == -1) {
150                                         ierr();
151                                         return;
152                                 }
153                         } else
154                                 rlines(fp, off, sbp);
155                 else if (off == 0) {
156                         while (getc(fp) != EOF);
157                         if (ferror(fp)) {
158                                 ierr();
159                                 return;
160                         }
161                 } else
162                         if (display_lines(fp, off))
163                                 return;
164                 break;
165         case REVERSE:
166                 errx(1, "internal error: forward style cannot be REVERSE");
167                 /* NOTREACHED */
168         }
169
170         while ((ch = getc(fp)) != EOF) {
171                 if (putchar(ch) == EOF)
172                         oerr();
173         }
174         if (ferror(fp)) {
175                 ierr();
176                 return;
177         }
178         fflush(stdout);
179 }
180
181 /*
182  * rlines -- display the last offset lines of the file.
183  */
184 static void
185 rlines(FILE *fp, off_t off, struct stat *sbp)
186 {
187         struct mapinfo map;
188         off_t curoff, size;
189         int i;
190
191         if (!(size = sbp->st_size))
192                 return;
193         map.start = NULL;
194         map.fd = fileno(fp);
195         map.mapoff = map.maxoff = size;
196
197         /*
198          * Last char is special, ignore whether newline or not. Note that
199          * size == 0 is dealt with above, and size == 1 sets curoff to -1.
200          */
201         curoff = size - 2;
202         while (curoff >= 0) {
203                 if (curoff < map.mapoff && maparound(&map, curoff) != 0) {
204                         ierr();
205                         return;
206                 }
207                 for (i = curoff - map.mapoff; i >= 0; i--)
208                         if (map.start[i] == '\n' && --off == 0)
209                                 break;
210                 /* `i' is either the map offset of a '\n', or -1. */
211                 curoff = map.mapoff + i;
212                 if (i >= 0)
213                         break;
214         }
215         curoff++;
216         if (mapprint(&map, curoff, size - curoff) != 0) {
217                 ierr();
218                 exit(1);
219         }
220
221         /* Set the file pointer to reflect the length displayed. */
222         if (fseeko(fp, sbp->st_size, SEEK_SET) == -1) {
223                 ierr();
224                 return;
225         }
226         if (map.start != NULL && munmap(map.start, map.maplen)) {
227                 ierr();
228                 return;
229         }
230 }
231
232 /*
233  * follow -- display the file, from an offset, forward.
234  */
235 #ifndef BOOTSTRAPPING
236 static void
237 show(file_info_t *file, int at_index)
238 {
239         int ch, first;
240
241         first = 1;
242         while ((ch = getc(file->fp)) != EOF) {
243                 if (first && no_files > 1) {
244                         showfilename(at_index, file->file_name);
245                         first = 0;
246                 }
247                 if (putchar(ch) == EOF)
248                         oerr();
249         }
250         fflush(stdout);
251         if (ferror(file->fp)) {
252                 file->fp = NULL;
253                 ierr();
254         } else {
255                 clearerr(file->fp);
256         }
257 }
258 #endif
259
260 void
261 showfilename(int at_index, const char *filename)
262 {
263         static int last_index = -1;
264         static int continuing = 0;
265
266         if (last_index == at_index)
267                 return;
268         if (!qflag) {
269                 if (continuing)
270                         printf("\n");
271                 printf("==> %s <==\n", filename);
272         }
273         continuing = 1;
274         last_index = at_index;
275 }
276
277 #ifndef BOOTSTRAPPING
278 static void
279 set_events(file_info_t *files)
280 {
281         int i, n;
282         file_info_t *file;
283         struct timespec ts;
284
285         ts.tv_sec = 0;
286         ts.tv_nsec = 0;
287
288         n = 0;
289         action = USE_KQUEUE;
290         for (i = 0, file = files; i < no_files; i++, file++) {
291                 if (file->fp == NULL)
292                         continue;
293                 if (Fflag && fileno(file->fp) != STDIN_FILENO) {
294                         EV_SET(&ev[n], fileno(file->fp), EVFILT_VNODE,
295                                EV_ADD | EV_ENABLE | EV_CLEAR,
296                                NOTE_DELETE | NOTE_RENAME, 0, 0);
297                         n++;
298                 }
299                 EV_SET(&ev[n], fileno(file->fp), EVFILT_READ,
300                        EV_ADD | EV_ENABLE | EV_CLEAR, 0, 0, 0);
301                 n++;
302         }
303
304         if (kevent(kq, ev, n, NULL, 0, &ts) < 0)
305                 action = USE_SLEEP;
306 }
307
308 void
309 follow(file_info_t *files, enum STYLE style, off_t off)
310 {
311         int active, i, n;
312         file_info_t *file;
313         struct stat sb2;
314         struct timespec ts;
315
316         /* Position each of the files */
317         file = files;
318         active = 0;
319         n = 0;
320         for (i = 0; i < no_files; i++, file++) {
321                 if (file->fp) {
322                         active = 1;
323                         n++;
324                         if (no_files > 1)
325                                 showfilename(i, file->file_name);
326                         forward(file->fp, style, off, &file->st);
327                         if (Fflag && fileno(file->fp) != STDIN_FILENO)
328                                 n++;
329                 }
330         }
331
332         if (!active)
333                 return;
334
335         kq = kqueue();
336         if (kq == -1)
337                 err(1, "kqueue");
338         ev = malloc(n * sizeof(struct kevent));
339         if (ev == NULL)
340                 err(1, "Couldn't allocate memory for kevents.");
341         set_events(files);
342
343         for (;;) {
344                 for (i = 0, file = files; i < no_files; i++, file++) {
345                         if (file->fp == NULL)
346                                 continue;
347                         if (Fflag && fileno(file->fp) != STDIN_FILENO) {
348                                 if (stat(file->file_name, &sb2) == -1) {
349                                         /*
350                                          * file was rotated, skip it until it
351                                          * reappears.
352                                          */
353                                         continue;
354                                 }
355                                 if (sb2.st_ino != file->st.st_ino ||
356                                     sb2.st_dev != file->st.st_dev ||
357                                     sb2.st_nlink == 0) {
358                                         file->fp = freopen(file->file_name, "r",
359                                                            file->fp);
360                                         if (file->fp == NULL) {
361                                                 ierr();
362                                                 continue;
363                                         } else {
364                                                 memcpy(&file->st, &sb2,
365                                                        sizeof(struct stat));
366                                                 set_events(files);
367                                         }
368                                 }
369                         }
370                         show(file, i);
371                 }
372
373                 switch (action) {
374                 case USE_KQUEUE:
375                         ts.tv_sec = 1;
376                         ts.tv_nsec = 0;
377                         /*
378                          * In the -F case, we set a timeout to ensure that
379                          * we re-stat the file at least once every second.
380                          */
381                         n = kevent(kq, NULL, 0, ev, 1, Fflag ? &ts : NULL);
382                         if (n == -1)
383                                 err(1, "kevent");
384                         if (n == 0) {
385                                 /* timeout */
386                                 break;
387                         } else if (ev->filter == EVFILT_READ && ev->data < 0) {
388                                 /* file shrank, reposition to end */
389                                 if (lseek(ev->ident, 0, SEEK_END) == -1) {
390                                         ierr();
391                                         continue;
392                                 }
393                         }
394                         break;
395
396                 case USE_SLEEP:
397                         usleep(250000);
398                         break;
399                 }
400         }
401 }
402 #endif