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