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