xref: /freebsd/usr.bin/tail/forward.c (revision 6e0da4f753ed6b5d26395001a6194b4fdea70177)
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 static void show(file_info_t *);
64 static void set_events(file_info_t *files);
65 
66 /* defines for inner loop actions */
67 #define USE_SLEEP	0
68 #define USE_KQUEUE	1
69 #define ADD_EVENTS	2
70 
71 struct kevent *ev;
72 int action = USE_SLEEP;
73 int kq;
74 
75 /*
76  * forward -- display the file, from an offset, forward.
77  *
78  * There are eight separate cases for this -- regular and non-regular
79  * files, by bytes or lines and from the beginning or end of the file.
80  *
81  * FBYTES	byte offset from the beginning of the file
82  *	REG	seek
83  *	NOREG	read, counting bytes
84  *
85  * FLINES	line offset from the beginning of the file
86  *	REG	read, counting lines
87  *	NOREG	read, counting lines
88  *
89  * RBYTES	byte offset from the end of the file
90  *	REG	seek
91  *	NOREG	cyclically read characters into a wrap-around buffer
92  *
93  * RLINES
94  *	REG	mmap the file and step back until reach the correct offset.
95  *	NOREG	cyclically read lines into a wrap-around array of buffers
96  */
97 void
98 forward(FILE *fp, enum STYLE style, off_t off, struct stat *sbp)
99 {
100 	int ch;
101 
102 	switch(style) {
103 	case FBYTES:
104 		if (off == 0)
105 			break;
106 		if (S_ISREG(sbp->st_mode)) {
107 			if (sbp->st_size < off)
108 				off = sbp->st_size;
109 			if (fseeko(fp, off, SEEK_SET) == -1) {
110 				ierr();
111 				return;
112 			}
113 		} else while (off--)
114 			if ((ch = getc(fp)) == EOF) {
115 				if (ferror(fp)) {
116 					ierr();
117 					return;
118 				}
119 				break;
120 			}
121 		break;
122 	case FLINES:
123 		if (off == 0)
124 			break;
125 		for (;;) {
126 			if ((ch = getc(fp)) == EOF) {
127 				if (ferror(fp)) {
128 					ierr();
129 					return;
130 				}
131 				break;
132 			}
133 			if (ch == '\n' && !--off)
134 				break;
135 		}
136 		break;
137 	case RBYTES:
138 		if (S_ISREG(sbp->st_mode)) {
139 			if (sbp->st_size >= off &&
140 			    fseeko(fp, -off, SEEK_END) == -1) {
141 				ierr();
142 				return;
143 			}
144 		} else if (off == 0) {
145 			while (getc(fp) != EOF);
146 			if (ferror(fp)) {
147 				ierr();
148 				return;
149 			}
150 		} else
151 			if (bytes(fp, off))
152 				return;
153 		break;
154 	case RLINES:
155 		if (S_ISREG(sbp->st_mode))
156 			if (!off) {
157 				if (fseeko(fp, (off_t)0, SEEK_END) == -1) {
158 					ierr();
159 					return;
160 				}
161 			} else
162 				rlines(fp, off, sbp);
163 		else if (off == 0) {
164 			while (getc(fp) != EOF);
165 			if (ferror(fp)) {
166 				ierr();
167 				return;
168 			}
169 		} else
170 			if (lines(fp, off))
171 				return;
172 		break;
173 	default:
174 		break;
175 	}
176 
177 	while ((ch = getc(fp)) != EOF)
178 		if (putchar(ch) == EOF)
179 			oerr();
180 	if (ferror(fp)) {
181 		ierr();
182 		return;
183 	}
184 	(void)fflush(stdout);
185 }
186 
187 /*
188  * rlines -- display the last offset lines of the file.
189  */
190 static void
191 rlines(fp, off, sbp)
192 	FILE *fp;
193 	off_t off;
194 	struct stat *sbp;
195 {
196 	struct mapinfo map;
197 	off_t curoff, size;
198 	int i;
199 
200 	if (!(size = sbp->st_size))
201 		return;
202 	map.start = NULL;
203 	map.fd = fileno(fp);
204 	map.mapoff = map.maxoff = size;
205 
206 	/*
207 	 * Last char is special, ignore whether newline or not. Note that
208 	 * size == 0 is dealt with above, and size == 1 sets curoff to -1.
209 	 */
210 	curoff = size - 2;
211 	while (curoff >= 0) {
212 		if (curoff < map.mapoff && maparound(&map, curoff) != 0) {
213 			ierr();
214 			return;
215 		}
216 		for (i = curoff - map.mapoff; i >= 0; i--)
217 			if (map.start[i] == '\n' && --off == 0)
218 				break;
219 		/* `i' is either the map offset of a '\n', or -1. */
220 		curoff = map.mapoff + i;
221 		if (i >= 0)
222 			break;
223 	}
224 	curoff++;
225 	if (mapprint(&map, curoff, size - curoff) != 0) {
226 		ierr();
227 		exit(1);
228 	}
229 
230 	/* Set the file pointer to reflect the length displayed. */
231 	if (fseeko(fp, sbp->st_size, SEEK_SET) == -1) {
232 		ierr();
233 		return;
234 	}
235 	if (map.start != NULL && munmap(map.start, map.maplen)) {
236 		ierr();
237 		return;
238 	}
239 }
240 
241 /*
242  * follow -- display the file, from an offset, forward.
243  *
244  */
245 
246 static void
247 show(file_info_t *file)
248 {
249     int ch;
250     static file_info_t *last;
251 
252     while ((ch = getc(file->fp)) != EOF) {
253 	if (last != file && no_files > 1) {
254 		(void)printf("\n==> %s <==\n", file->file_name);
255 		last = file;
256 	}
257 	if (putchar(ch) == EOF)
258 		oerr();
259     }
260     (void)fflush(stdout);
261     if (ferror(file->fp)) {
262 	    file->fp = NULL;
263 	    ierr();
264     } else
265 	    clearerr(file->fp);
266 }
267 
268 static void
269 set_events(file_info_t *files)
270 {
271 	int i, n = 0;
272 	file_info_t *file;
273 	struct timespec ts;
274 
275 	ts.tv_sec = 0;
276 	ts.tv_nsec = 0;
277 
278 	action = USE_KQUEUE;
279 	for (i = 0, file = files; i < no_files; i++, file++) {
280 		if (! file->fp)
281 			continue;
282 		if (Fflag && fileno(file->fp) != STDIN_FILENO) {
283 			EV_SET(&ev[n], fileno(file->fp), EVFILT_VNODE,
284 			    EV_ADD | EV_ENABLE | EV_CLEAR,
285 			    NOTE_DELETE | NOTE_RENAME, 0, 0);
286 			n++;
287 		}
288 		EV_SET(&ev[n], fileno(file->fp), EVFILT_READ,
289 		    EV_ADD | EV_ENABLE | EV_CLEAR, 0, 0, 0);
290 		n++;
291 	}
292 
293 	if (kevent(kq, ev, n, NULL, 0, &ts) < 0) {
294 		action = USE_SLEEP;
295 	}
296 }
297 
298 void
299 follow(file_info_t *files, enum STYLE style, off_t off)
300 {
301 	int active, i, n = -1;
302 	struct stat sb2;
303 	file_info_t *file;
304 	struct timespec ts;
305 
306 	/* Position each of the files */
307 
308 	file = files;
309 	active = 0;
310 	n = 0;
311 	for (i = 0; i < no_files; i++, file++) {
312 		if (file->fp) {
313 			active = 1;
314 			n++;
315 			if (no_files > 1)
316 				(void)printf("\n==> %s <==\n", file->file_name);
317 			forward(file->fp, style, off, &file->st);
318 			if (Fflag && fileno(file->fp) != STDIN_FILENO)
319 			    n++;
320 		}
321 	}
322 	if (! active)
323 		return;
324 
325 	kq = kqueue();
326 	if (kq < 0)
327 		err(1, "kqueue");
328 	ev = malloc(n * sizeof(struct kevent));
329 	if (! ev)
330 	    err(1, "Couldn't allocate memory for kevents.");
331 	set_events(files);
332 
333 	for (;;) {
334 		for (i = 0, file = files; i < no_files; i++, file++) {
335 			if (! file->fp)
336 				continue;
337 			if (Fflag && file->fp && fileno(file->fp) != STDIN_FILENO) {
338 				if (stat(file->file_name, &sb2) != 0) {
339 					/* file was rotated, skip it until it reappears */
340 					continue;
341 				}
342 				if (sb2.st_ino != file->st.st_ino ||
343 				    sb2.st_dev != file->st.st_dev ||
344 				    sb2.st_nlink == 0) {
345 					file->fp = freopen(file->file_name, "r", file->fp);
346 					if (file->fp == NULL) {
347 						ierr();
348 						continue;
349 					} else {
350 						memcpy(&file->st, &sb2, sizeof(struct stat));
351 						set_events(files);
352 					}
353 				}
354 			}
355 			show(file);
356 		}
357 
358 		switch (action) {
359 		case USE_KQUEUE:
360 			ts.tv_sec = 1;
361 			ts.tv_nsec = 0;
362 			/*
363 			 * In the -F case we set a timeout to ensure that
364 			 * we re-stat the file at least once every second.
365 			 */
366 			n = kevent(kq, NULL, 0, ev, 1, Fflag ? &ts : NULL);
367 			if (n < 0)
368 				err(1, "kevent");
369 			if (n == 0) {
370 				/* timeout */
371 				break;
372 			} else if (ev->filter == EVFILT_READ && ev->data < 0) {
373 				 /* file shrank, reposition to end */
374 				if (lseek(ev->ident, (off_t)0, SEEK_END) == -1) {
375 					ierr();
376 					continue;
377 				}
378 			}
379 			break;
380 
381 		case USE_SLEEP:
382 			(void) usleep(250000);
383 			break;
384 		}
385 	}
386 }
387