xref: /freebsd/usr.bin/tail/tail.c (revision ec965063070e5753c166cf592c9336444b74720a)
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 #include <sys/cdefs.h>
36 
37 __FBSDID("$FreeBSD$");
38 
39 #ifndef lint
40 static const char copyright[] =
41 "@(#) Copyright (c) 1991, 1993\n\
42 	The Regents of the University of California.  All rights reserved.\n";
43 #endif
44 
45 #ifndef lint
46 static const char sccsid[] = "@(#)tail.c	8.1 (Berkeley) 6/6/93";
47 #endif
48 
49 #include <sys/capsicum.h>
50 #include <sys/types.h>
51 #include <sys/stat.h>
52 
53 #include <capsicum_helpers.h>
54 #include <err.h>
55 #include <errno.h>
56 #include <getopt.h>
57 #include <stdio.h>
58 #include <stdlib.h>
59 #include <string.h>
60 #include <unistd.h>
61 
62 #include <libutil.h>
63 
64 #include <libcasper.h>
65 #include <casper/cap_fileargs.h>
66 
67 #include "extern.h"
68 
69 int Fflag, fflag, qflag, rflag, rval, no_files, vflag;
70 fileargs_t *fa;
71 
72 static void obsolete(char **);
73 static void usage(void);
74 
75 static const struct option long_opts[] =
76 {
77 	{"blocks",	required_argument,	NULL, 'b'},
78 	{"bytes",	required_argument,	NULL, 'c'},
79 	{"lines",	required_argument,	NULL, 'n'},
80 	{"quiet",	no_argument,		NULL, 'q'},
81 	{"silent",	no_argument,		NULL, 'q'},
82 	{"verbose",	no_argument,		NULL, 'v'},
83 	{NULL,		no_argument,		NULL, 0}
84 };
85 
86 int
87 main(int argc, char *argv[])
88 {
89 	struct stat sb;
90 	const char *fn;
91 	FILE *fp;
92 	off_t off;
93 	enum STYLE style;
94 	int ch, first;
95 	file_info_t file, *filep, *files;
96 	cap_rights_t rights;
97 
98 	/*
99 	 * Tail's options are weird.  First, -n10 is the same as -n-10, not
100 	 * -n+10.  Second, the number options are 1 based and not offsets,
101 	 * so -n+1 is the first line, and -c-1 is the last byte.  Third, the
102 	 * number options for the -r option specify the number of things that
103 	 * get displayed, not the starting point in the file.  The one major
104 	 * incompatibility in this version as compared to historical versions
105 	 * is that the 'r' option couldn't be modified by the -lbc options,
106 	 * i.e. it was always done in lines.  This version treats -rc as a
107 	 * number of characters in reverse order.  Finally, the default for
108 	 * -r is the entire file, not 10 lines.
109 	 */
110 #define	ARG(units, forward, backward) {					\
111 	if (style)							\
112 		usage();						\
113 	if (expand_number(optarg, &off))				\
114 		err(1, "illegal offset -- %s", optarg);			\
115 	if (off > INT64_MAX / units || off < INT64_MIN / units )	\
116 		errx(1, "illegal offset -- %s", optarg);		\
117 	switch(optarg[0]) {						\
118 	case '+':							\
119 		if (off)						\
120 			off -= (units);					\
121 		style = (forward);					\
122 		break;							\
123 	case '-':							\
124 		off = -off;						\
125 		/* FALLTHROUGH */					\
126 	default:							\
127 		style = (backward);					\
128 		break;							\
129 	}								\
130 }
131 
132 	obsolete(argv);
133 	style = NOTSET;
134 	off = 0;
135 	while ((ch = getopt_long(argc, argv, "+Fb:c:fn:qrv", long_opts, NULL)) !=
136 	    -1)
137 		switch(ch) {
138 		case 'F':	/* -F is superset of (and implies) -f */
139 			Fflag = fflag = 1;
140 			break;
141 		case 'b':
142 			ARG(512, FBYTES, RBYTES);
143 			break;
144 		case 'c':
145 			ARG(1, FBYTES, RBYTES);
146 			break;
147 		case 'f':
148 			fflag = 1;
149 			break;
150 		case 'n':
151 			ARG(1, FLINES, RLINES);
152 			break;
153 		case 'q':
154 			qflag = 1;
155 			vflag = 0;
156 			break;
157 		case 'r':
158 			rflag = 1;
159 			break;
160 		case 'v':
161 			vflag = 1;
162 			qflag = 0;
163 			break;
164 		case '?':
165 		default:
166 			usage();
167 		}
168 	argc -= optind;
169 	argv += optind;
170 
171 	no_files = argc ? argc : 1;
172 
173 	cap_rights_init(&rights, CAP_FSTAT, CAP_FSTATFS, CAP_FCNTL,
174 	    CAP_MMAP_R);
175 	if (fflag)
176 		cap_rights_set(&rights, CAP_EVENT);
177 	if (caph_rights_limit(STDIN_FILENO, &rights) < 0 ||
178 	    caph_limit_stderr() < 0 || caph_limit_stdout() < 0)
179 		err(1, "can't limit stdio rights");
180 
181 	fa = fileargs_init(argc, argv, O_RDONLY, 0, &rights, FA_OPEN);
182 	if (fa == NULL)
183 		err(1, "unable to init casper");
184 
185 	caph_cache_catpages();
186 	if (caph_enter_casper() < 0)
187 		err(1, "unable to enter capability mode");
188 
189 	/*
190 	 * If displaying in reverse, don't permit follow option, and convert
191 	 * style values.
192 	 */
193 	if (rflag) {
194 		if (fflag)
195 			usage();
196 		if (style == FBYTES)
197 			style = RBYTES;
198 		else if (style == FLINES)
199 			style = RLINES;
200 	}
201 
202 	/*
203 	 * If style not specified, the default is the whole file for -r, and
204 	 * the last 10 lines if not -r.
205 	 */
206 	if (style == NOTSET) {
207 		if (rflag) {
208 			off = 0;
209 			style = REVERSE;
210 		} else {
211 			off = 10;
212 			style = RLINES;
213 		}
214 	}
215 
216 	if (*argv && fflag) {
217 		files = malloc(no_files * sizeof(struct file_info));
218 		if (files == NULL)
219 			err(1, "Couldn't malloc space for file descriptors.");
220 
221 		for (filep = files; (fn = *argv++); filep++) {
222 			filep->file_name = fn;
223 			filep->fp = fileargs_fopen(fa, filep->file_name, "r");
224 			if (filep->fp == NULL ||
225 			    fstat(fileno(filep->fp), &filep->st)) {
226 				if (filep->fp != NULL) {
227 					fclose(filep->fp);
228 					filep->fp = NULL;
229 				}
230 				if (!Fflag || errno != ENOENT)
231 					ierr(filep->file_name);
232 			}
233 		}
234 		follow(files, style, off);
235 		free(files);
236 	} else if (*argv) {
237 		for (first = 1; (fn = *argv++);) {
238 			if ((fp = fileargs_fopen(fa, fn, "r")) == NULL ||
239 			    fstat(fileno(fp), &sb)) {
240 				ierr(fn);
241 				continue;
242 			}
243 			if (vflag || (qflag == 0 && argc > 1)) {
244 				printfn(fn, !first);
245 				first = 0;
246 			}
247 
248 			if (rflag)
249 				reverse(fp, fn, style, off, &sb);
250 			else
251 				forward(fp, fn, style, off, &sb);
252 		}
253 	} else {
254 		fn = "stdin";
255 
256 		if (fstat(fileno(stdin), &sb)) {
257 			ierr(fn);
258 			exit(1);
259 		}
260 
261 		/*
262 		 * Determine if input is a pipe.  4.4BSD will set the SOCKET
263 		 * bit in the st_mode field for pipes.  Fix this then.
264 		 */
265 		if (lseek(fileno(stdin), (off_t)0, SEEK_CUR) == -1 &&
266 		    errno == ESPIPE) {
267 			errno = 0;
268 			fflag = 0;		/* POSIX.2 requires this. */
269 		}
270 
271 		if (rflag) {
272 			reverse(stdin, fn, style, off, &sb);
273 		} else if (fflag) {
274 			file.file_name = fn;
275 			file.fp = stdin;
276 			file.st = sb;
277 			follow(&file, style, off);
278 		} else {
279 			forward(stdin, fn, style, off, &sb);
280 		}
281 	}
282 	fileargs_free(fa);
283 	exit(rval);
284 }
285 
286 /*
287  * Convert the obsolete argument form into something that getopt can handle.
288  * This means that anything of the form [+-][0-9][0-9]*[lbc][Ffr] that isn't
289  * the option argument for a -b, -c or -n option gets converted.
290  */
291 static void
292 obsolete(char *argv[])
293 {
294 	char *ap, *p, *t;
295 	size_t len;
296 	char *start;
297 
298 	while ((ap = *++argv)) {
299 		/* Return if "--" or not an option of any form. */
300 		if (ap[0] != '-') {
301 			if (ap[0] != '+')
302 				return;
303 		} else if (ap[1] == '-')
304 			return;
305 
306 		switch(*++ap) {
307 		/* Old-style option. */
308 		case '0': case '1': case '2': case '3': case '4':
309 		case '5': case '6': case '7': case '8': case '9':
310 
311 			/* Malloc space for dash, new option and argument. */
312 			len = strlen(*argv);
313 			if ((start = p = malloc(len + 3)) == NULL)
314 				err(1, "malloc");
315 			*p++ = '-';
316 
317 			/*
318 			 * Go to the end of the option argument.  Save off any
319 			 * trailing options (-3lf) and translate any trailing
320 			 * output style characters.
321 			 */
322 			t = *argv + len - 1;
323 			if (*t == 'F' || *t == 'f' || *t == 'r') {
324 				*p++ = *t;
325 				*t-- = '\0';
326 			}
327 			switch(*t) {
328 			case 'b':
329 				*p++ = 'b';
330 				*t = '\0';
331 				break;
332 			case 'c':
333 				*p++ = 'c';
334 				*t = '\0';
335 				break;
336 			case 'l':
337 				*t = '\0';
338 				/* FALLTHROUGH */
339 			case '0': case '1': case '2': case '3': case '4':
340 			case '5': case '6': case '7': case '8': case '9':
341 				*p++ = 'n';
342 				break;
343 			default:
344 				errx(1, "illegal option -- %s", *argv);
345 			}
346 			*p++ = *argv[0];
347 			(void)strcpy(p, ap);
348 			*argv = start;
349 			continue;
350 
351 		/*
352 		 * Options w/ arguments, skip the argument and continue
353 		 * with the next option.
354 		 */
355 		case 'b':
356 		case 'c':
357 		case 'n':
358 			if (!ap[1])
359 				++argv;
360 			/* FALLTHROUGH */
361 		/* Options w/o arguments, continue with the next option. */
362 		case 'F':
363 		case 'f':
364 		case 'r':
365 			continue;
366 
367 		/* Illegal option, return and let getopt handle it. */
368 		default:
369 			return;
370 		}
371 	}
372 }
373 
374 static void
375 usage(void)
376 {
377 	(void)fprintf(stderr,
378 	    "usage: tail [-F | -f | -r] [-q] [-b # | -c # | -n #]"
379 	    " [file ...]\n");
380 	exit(1);
381 }
382