xref: /freebsd/usr.bin/tail/forward.c (revision 22cf89c938886d14f5796fc49f9f020c23ea8eaf)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1991, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Edward Sze-Tyan Wang.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 
36 #ifndef lint
37 static const char sccsid[] = "@(#)forward.c	8.1 (Berkeley) 6/6/93";
38 #endif
39 
40 #include <sys/param.h>
41 #include <sys/mount.h>
42 #include <sys/types.h>
43 #include <sys/stat.h>
44 #include <sys/time.h>
45 #include <sys/mman.h>
46 #include <sys/event.h>
47 
48 #include <err.h>
49 #include <errno.h>
50 #include <fcntl.h>
51 #include <limits.h>
52 #include <stdio.h>
53 #include <stdlib.h>
54 #include <string.h>
55 #include <unistd.h>
56 
57 #include <libcasper.h>
58 #include <casper/cap_fileargs.h>
59 
60 #include "extern.h"
61 
62 static void rlines(FILE *, const char *fn, off_t, struct stat *);
63 static int 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 static struct kevent *ev;
72 static int action = USE_SLEEP;
73 static int kq;
74 
75 static const file_info_t *last;
76 
77 /*
78  * forward -- display the file, from an offset, forward.
79  *
80  * There are eight separate cases for this -- regular and non-regular
81  * files, by bytes or lines and from the beginning or end of the file.
82  *
83  * FBYTES	byte offset from the beginning of the file
84  *	REG	seek
85  *	NOREG	read, counting bytes
86  *
87  * FLINES	line offset from the beginning of the file
88  *	REG	read, counting lines
89  *	NOREG	read, counting lines
90  *
91  * RBYTES	byte offset from the end of the file
92  *	REG	seek
93  *	NOREG	cyclically read characters into a wrap-around buffer
94  *
95  * RLINES
96  *	REG	mmap the file and step back until reach the correct offset.
97  *	NOREG	cyclically read lines into a wrap-around array of buffers
98  */
99 void
100 forward(FILE *fp, const char *fn, enum STYLE style, off_t off, struct stat *sbp)
101 {
102 	int ch;
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(fn);
113 				return;
114 			}
115 		} else while (off--)
116 			if ((ch = getc(fp)) == EOF) {
117 				if (ferror(fp)) {
118 					ierr(fn);
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(fn);
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(fn);
144 				return;
145 			}
146 		} else if (off == 0) {
147 			while (getc(fp) != EOF);
148 			if (ferror(fp)) {
149 				ierr(fn);
150 				return;
151 			}
152 		} else
153 			if (bytes(fp, fn, 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(fn);
161 					return;
162 				}
163 			} else
164 				rlines(fp, fn, off, sbp);
165 		else if (off == 0) {
166 			while (getc(fp) != EOF);
167 			if (ferror(fp)) {
168 				ierr(fn);
169 				return;
170 			}
171 		} else
172 			if (lines(fp, fn, 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(fn);
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(FILE *fp, const char *fn, off_t off, struct stat *sbp)
194 {
195 	struct mapinfo map;
196 	off_t curoff, size;
197 	int i;
198 
199 	if (!(size = sbp->st_size))
200 		return;
201 	map.start = NULL;
202 	map.fd = fileno(fp);
203 	map.mapoff = map.maxoff = size;
204 
205 	/*
206 	 * Last char is special, ignore whether newline or not. Note that
207 	 * size == 0 is dealt with above, and size == 1 sets curoff to -1.
208 	 */
209 	curoff = size - 2;
210 	while (curoff >= 0) {
211 		if (curoff < map.mapoff && maparound(&map, curoff) != 0) {
212 			ierr(fn);
213 			return;
214 		}
215 		for (i = curoff - map.mapoff; i >= 0; i--)
216 			if (map.start[i] == '\n' && --off == 0)
217 				break;
218 		/* `i' is either the map offset of a '\n', or -1. */
219 		curoff = map.mapoff + i;
220 		if (i >= 0)
221 			break;
222 	}
223 	curoff++;
224 	if (mapprint(&map, curoff, size - curoff) != 0) {
225 		ierr(fn);
226 		exit(1);
227 	}
228 
229 	/* Set the file pointer to reflect the length displayed. */
230 	if (fseeko(fp, sbp->st_size, SEEK_SET) == -1) {
231 		ierr(fn);
232 		return;
233 	}
234 	if (map.start != NULL && munmap(map.start, map.maplen)) {
235 		ierr(fn);
236 		return;
237 	}
238 }
239 
240 static int
241 show(file_info_t *file)
242 {
243 	int ch;
244 
245 	while ((ch = getc(file->fp)) != EOF) {
246 		if (last != file) {
247 			if (vflag || (qflag == 0 && no_files > 1))
248 				printfn(file->file_name, 1);
249 			last = file;
250 		}
251 		if (putchar(ch) == EOF)
252 			oerr();
253 	}
254 	(void)fflush(stdout);
255 	if (ferror(file->fp)) {
256 		fclose(file->fp);
257 		file->fp = NULL;
258 		ierr(file->file_name);
259 		return 0;
260 	}
261 	clearerr(file->fp);
262 	return 1;
263 }
264 
265 static void
266 set_events(file_info_t *files)
267 {
268 	int i, n = 0;
269 	file_info_t *file;
270 	struct timespec ts;
271 	struct statfs sf;
272 
273 	ts.tv_sec = 0;
274 	ts.tv_nsec = 0;
275 
276 	action = USE_KQUEUE;
277 	for (i = 0, file = files; i < no_files; i++, file++) {
278 		if (! file->fp)
279 			continue;
280 
281 		if (fstatfs(fileno(file->fp), &sf) == 0 &&
282 		    (sf.f_flags & MNT_LOCAL) == 0) {
283 			action = USE_SLEEP;
284 			return;
285 		}
286 
287 		if (Fflag && fileno(file->fp) != STDIN_FILENO) {
288 			EV_SET(&ev[n], fileno(file->fp), EVFILT_VNODE,
289 			    EV_ADD | EV_ENABLE | EV_CLEAR,
290 			    NOTE_DELETE | NOTE_RENAME, 0, 0);
291 			n++;
292 		}
293 		EV_SET(&ev[n], fileno(file->fp), EVFILT_READ,
294 		    EV_ADD | EV_ENABLE | EV_CLEAR, 0, 0, 0);
295 		n++;
296 	}
297 
298 	if (kevent(kq, ev, n, NULL, 0, &ts) < 0) {
299 		action = USE_SLEEP;
300 	}
301 }
302 
303 /*
304  * follow -- display the file, from an offset, forward.
305  *
306  */
307 void
308 follow(file_info_t *files, enum STYLE style, off_t off)
309 {
310 	int active, ev_change, i, n = -1;
311 	struct stat sb2;
312 	file_info_t *file;
313 	FILE *ftmp;
314 	struct timespec ts;
315 
316 	/* Position each of the files */
317 
318 	file = files;
319 	active = 0;
320 	n = 0;
321 	for (i = 0; i < no_files; i++, file++) {
322 		if (file->fp) {
323 			active = 1;
324 			n++;
325 			if (vflag || (qflag == 0 && no_files > 1))
326 				printfn(file->file_name, 1);
327 			forward(file->fp, file->file_name, style, off, &file->st);
328 			if (Fflag && fileno(file->fp) != STDIN_FILENO)
329 				n++;
330 		}
331 	}
332 	if (!Fflag && !active)
333 		return;
334 
335 	last = --file;
336 
337 	kq = kqueue();
338 	if (kq < 0)
339 		err(1, "kqueue");
340 	ev = malloc(n * sizeof(struct kevent));
341 	if (! ev)
342 	    err(1, "Couldn't allocate memory for kevents.");
343 	set_events(files);
344 
345 	for (;;) {
346 		ev_change = 0;
347 		if (Fflag) {
348 			for (i = 0, file = files; i < no_files; i++, file++) {
349 				if (!file->fp) {
350 					file->fp =
351 					    fileargs_fopen(fa, file->file_name,
352 					    "r");
353 					if (file->fp != NULL &&
354 					    fstat(fileno(file->fp), &file->st)
355 					    == -1) {
356 						fclose(file->fp);
357 						file->fp = NULL;
358 					}
359 					if (file->fp != NULL)
360 						ev_change++;
361 					continue;
362 				}
363 				if (fileno(file->fp) == STDIN_FILENO)
364 					continue;
365 				ftmp = fileargs_fopen(fa, file->file_name, "r");
366 				if (ftmp == NULL ||
367 				    fstat(fileno(ftmp), &sb2) == -1) {
368 					if (errno != ENOENT)
369 						ierr(file->file_name);
370 					show(file);
371 					if (file->fp != NULL) {
372 						fclose(file->fp);
373 						file->fp = NULL;
374 					}
375 					if (ftmp != NULL) {
376 						fclose(ftmp);
377 					}
378 					ev_change++;
379 					continue;
380 				}
381 
382 				if (sb2.st_ino != file->st.st_ino ||
383 				    sb2.st_dev != file->st.st_dev ||
384 				    sb2.st_nlink == 0) {
385 					show(file);
386 					fclose(file->fp);
387 					file->fp = ftmp;
388 					memcpy(&file->st, &sb2,
389 					    sizeof(struct stat));
390 					ev_change++;
391 				} else {
392 					fclose(ftmp);
393 				}
394 			}
395 		}
396 
397 		for (i = 0, file = files; i < no_files; i++, file++)
398 			if (file->fp && !show(file))
399 				ev_change++;
400 
401 		if (ev_change)
402 			set_events(files);
403 
404 		switch (action) {
405 		case USE_KQUEUE:
406 			ts.tv_sec = 1;
407 			ts.tv_nsec = 0;
408 			/*
409 			 * In the -F case we set a timeout to ensure that
410 			 * we re-stat the file at least once every second.
411 			 * If we've recieved EINTR, ignore it. Both reasons
412 			 * for its generation are transient.
413 			 */
414 			do {
415 				n = kevent(kq, NULL, 0, ev, 1, Fflag ? &ts : NULL);
416 				if (n < 0 && errno == EINTR)
417 					continue;
418 				if (n < 0)
419 					err(1, "kevent");
420 			} while (n < 0);
421 			if (n == 0) {
422 				/* timeout */
423 				break;
424 			} else if (ev->filter == EVFILT_READ && ev->data < 0) {
425 				/* file shrank, reposition to end */
426 				if (lseek(ev->ident, (off_t)0, SEEK_END) == -1) {
427 					ierr(file->file_name);
428 					continue;
429 				}
430 			}
431 			break;
432 
433 		case USE_SLEEP:
434 			(void) usleep(250000);
435 			break;
436 		}
437 	}
438 }
439