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