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