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