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