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