xref: /openbsd-src/usr.bin/tail/reverse.c (revision 91f110e064cd7c194e59e019b83bb7496c1c84d4)
1 /*	$OpenBSD: reverse.c,v 1.19 2009/10/27 23:59:44 deraadt Exp $	*/
2 /*	$NetBSD: reverse.c,v 1.6 1994/11/23 07:42:10 jtc Exp $	*/
3 
4 /*-
5  * Copyright (c) 1991, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * This code is derived from software contributed to Berkeley by
9  * Edward Sze-Tyan Wang.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 
36 #include <sys/stat.h>
37 
38 #include <err.h>
39 #include <stdio.h>
40 #include <stdlib.h>
41 #include <unistd.h>
42 
43 #include "extern.h"
44 
45 static void r_buf(FILE *);
46 static int r_reg(FILE *, enum STYLE, off_t, struct stat *);
47 
48 #define COPYCHAR(fp, ch)				\
49 	do {						\
50 		if ((ch = getc(fp)) == EOF) {		\
51 			ierr();				\
52 			return (0);			\
53 		}					\
54 		if (putchar(ch) == EOF) {		\
55 			oerr();				\
56 			return (0);			\
57 		}					\
58 	} while (0)
59 
60 /*
61  * reverse -- display input in reverse order by line.
62  *
63  * There are six separate cases for this -- regular and non-regular
64  * files by bytes, lines or the whole file.
65  *
66  * BYTES	display N bytes
67  *	REG	reverse scan and display the lines
68  *	NOREG	cyclically read characters into a wrap-around buffer
69  *
70  * LINES	display N lines
71  *	REG	reverse scan and display the lines
72  *	NOREG	cyclically read lines into a wrap-around array of buffers
73  *
74  * FILE		display the entire file
75  *	REG	reverse scan and display the lines
76  *	NOREG	cyclically read input into a linked list of buffers
77  */
78 void
79 reverse(FILE *fp, enum STYLE style, off_t off, struct stat *sbp)
80 {
81 	if (style != REVERSE && off == 0)
82 		return;
83 
84 	if (!S_ISREG(sbp->st_mode) || r_reg(fp, style, off, sbp) != 0)
85 		switch(style) {
86 		case FBYTES:
87 		case RBYTES:
88 			(void)bytes(fp, off);
89 			break;
90 		case FLINES:
91 		case RLINES:
92 			(void)lines(fp, off);
93 			break;
94 		case REVERSE:
95 			r_buf(fp);
96 			break;
97 		}
98 }
99 
100 /*
101  * r_reg -- display a regular file in reverse order by line.
102  */
103 static int
104 r_reg(FILE *fp, enum STYLE style, off_t off, struct stat *sbp)
105 {
106 	off_t start, pos, end;
107 	int ch;
108 
109 	end = sbp->st_size;
110 	if (end == 0)
111 		return (0);
112 
113 	/* Position before char, ignore last char whether newline or not */
114 	pos = end-2;
115 	ch = EOF;
116 	start = 0;
117 
118 	if (style == RBYTES && off < end)
119 		start = end - off;
120 
121 	for (; pos >= start; pos--) {
122 		/* A seek per char isn't a problem with a smart stdio */
123 		if (fseeko(fp, pos, SEEK_SET) != 0) {
124 			ierr();
125 			return (0);
126 		}
127 		if ((ch = getc(fp)) == '\n') {
128 			while (--end > pos)
129 				COPYCHAR(fp, ch);
130 			end++;
131 			if (style == RLINES && --off == 0)
132 				break;
133 		}
134 		else if (ch == EOF) {
135 			ierr();
136 			return (0);
137 		}
138 	}
139 	if (pos < start) {
140 		if (ch != EOF && ungetc(ch, fp) == EOF) {
141 			ierr();
142 			return (0);
143 		}
144 		while (--end >= start)
145 			COPYCHAR(fp, ch);
146 	}
147 	return (0);
148 }
149 
150 typedef struct bf {
151 	struct bf *next;
152 	struct bf *prev;
153 	size_t len;
154 	char *l;
155 } BF;
156 
157 /*
158  * r_buf -- display a non-regular file in reverse order by line.
159  *
160  * This is the function that saves the entire input, storing the data in a
161  * doubly linked list of buffers and then displays them in reverse order.
162  * It has the usual nastiness of trying to find the newlines, as there's no
163  * guarantee that a newline occurs anywhere in the file, let alone in any
164  * particular buffer.  If we run out of memory, input is discarded (and the
165  * user warned).
166  */
167 static void
168 r_buf(FILE *fp)
169 {
170 	BF *mark, *tr, *tl = NULL;
171 	int ch;
172 	size_t len, llen;
173 	char *p;
174 	off_t enomem;
175 
176 #define	BSZ	(128 * 1024)
177 	for (mark = NULL, enomem = 0;;) {
178 		/*
179 		 * Allocate a new block and link it into place in a doubly
180 		 * linked list.  If out of memory, toss the LRU block and
181 		 * keep going.
182 		 */
183 		if (enomem || (tl = malloc(sizeof(BF))) == NULL ||
184 		    (tl->l = malloc(BSZ)) == NULL) {
185 			if (!mark)
186 				err(1, NULL);
187 			tl = enomem ? tl->next : mark;
188 			enomem += tl->len;
189 		} else if (mark) {
190 			tl->next = mark;
191 			tl->prev = mark->prev;
192 			mark->prev->next = tl;
193 			mark->prev = tl;
194 		} else {
195 			mark = tl;
196 			mark->next = mark->prev = mark;
197 		}
198 
199 		if (!enomem)
200 			tl->len = 0;
201 
202 		/* Fill the block with input data. */
203 		for (p = tl->l, len = 0;
204 		    len < BSZ && (ch = getc(fp)) != EOF; ++len)
205 			*p++ = ch;
206 
207 		/*
208 		 * If no input data for this block and we tossed some data,
209 		 * recover it.
210 		 */
211 		if (!len) {
212 			if (enomem)
213 				enomem -= tl->len;
214 			tl = tl->prev;
215 			break;
216 		}
217 
218 		tl->len = len;
219 		if (ch == EOF)
220 			break;
221 	}
222 
223 	if (enomem) {
224 		(void)fprintf(stderr,
225 		    "tail: warning: %lld bytes discarded\n", (long long)enomem);
226 		rval = 1;
227 	}
228 
229 	/*
230 	 * Step through the blocks in the reverse order read.  The last char
231 	 * is special, ignore whether newline or not.
232 	 */
233 	for (mark = tl;;) {
234 		for (p = tl->l + (len = tl->len) - 1, llen = 0; len--;
235 		    --p, ++llen)
236 			if (*p == '\n') {
237 				if (llen) {
238 					WR(p + 1, llen);
239 					llen = 0;
240 				}
241 				if (tl == mark)
242 					continue;
243 				for (tr = tl->next; tr->len; tr = tr->next) {
244 					WR(tr->l, tr->len);
245 					tr->len = 0;
246 					if (tr == mark)
247 						break;
248 				}
249 			}
250 		tl->len = llen;
251 		if ((tl = tl->prev) == mark)
252 			break;
253 	}
254 	tl = tl->next;
255 	if (tl->len) {
256 		WR(tl->l, tl->len);
257 		tl->len = 0;
258 	}
259 	while ((tl = tl->next)->len) {
260 		WR(tl->l, tl->len);
261 		tl->len = 0;
262 	}
263 }
264