c668c1c222fdec3de813169f069a345baeffad77
[dragonfly.git] / usr.bin / tail / reverse.c
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. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *      This product includes software developed by the University of
19  *      California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  * @(#)reverse.c        8.1 (Berkeley) 6/6/93
37  * $FreeBSD: src/usr.bin/tail/reverse.c,v 1.9.2.3 2001/12/19 20:29:31 iedowse Exp $
38  * $DragonFly: src/usr.bin/tail/reverse.c,v 1.5 2006/08/13 02:12:18 swildner Exp $
39  */
40
41 #include <sys/param.h>
42 #include <sys/stat.h>
43 #include <sys/mman.h>
44
45 #include <limits.h>
46 #include <errno.h>
47 #include <unistd.h>
48 #include <stdio.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #include <err.h>
52 #include "extern.h"
53
54 static void r_buf(FILE *);
55 static void r_reg(FILE *, enum STYLE, off_t, struct stat *);
56
57 /*
58  * reverse -- display input in reverse order by line.
59  *
60  * There are six separate cases for this -- regular and non-regular
61  * files by bytes, lines or the whole file.
62  *
63  * BYTES        display N bytes
64  *      REG     mmap the file and display the lines
65  *      NOREG   cyclically read characters into a wrap-around buffer
66  *
67  * LINES        display N lines
68  *      REG     mmap the file and display the lines
69  *      NOREG   cyclically read lines into a wrap-around array of buffers
70  *
71  * FILE         display the entire file
72  *      REG     mmap the file and display the lines
73  *      NOREG   cyclically read input into a linked list of buffers
74  */
75 void
76 reverse(FILE *fp, enum STYLE style, off_t off, struct stat *sbp)
77 {
78         if (style != REVERSE && off == 0)
79                 return;
80
81         if (S_ISREG(sbp->st_mode))
82                 r_reg(fp, style, off, sbp);
83         else
84                 switch(style) {
85                 case FBYTES:
86                 case RBYTES:
87                         display_bytes(fp, off);
88                         break;
89                 case FLINES:
90                 case RLINES:
91                         display_lines(fp, off);
92                         break;
93                 case REVERSE:
94                         r_buf(fp);
95                         break;
96                 }
97 }
98
99 /*
100  * r_reg -- display a regular file in reverse order by line.
101  */
102 static void
103 r_reg(FILE *fp, enum STYLE style, off_t off, struct stat *sbp)
104 {
105         struct mapinfo map;
106         off_t curoff, size, lineend;
107         int i;
108
109         if (!(size = sbp->st_size))
110                 return;
111
112         map.start = NULL;
113         map.mapoff = map.maxoff = size;
114         map.fd = fileno(fp);
115
116         /*
117          * Last char is special, ignore whether newline or not. Note that
118          * size == 0 is dealt with above, and size == 1 sets curoff to -1.
119          */
120         curoff = size - 2;
121         lineend = size;
122         while (curoff >= 0) {
123                 if (curoff < map.mapoff || curoff >= map.mapoff + map.maplen) {
124                         if (maparound(&map, curoff) != 0) {
125                                 ierr();
126                                 return;
127                         }
128                 }
129                 for (i = curoff - map.mapoff; i >= 0; i--) {
130                         if (style == RBYTES && --off == 0)
131                                 break;
132                         if (map.start[i] == '\n')
133                                 break;
134                 }
135                 /* `i' is either the map offset of a '\n', or -1. */
136                 curoff = map.mapoff + i;
137                 if (i < 0)
138                         continue;
139
140                 /* Print the line and update offsets. */
141                 if (mapprint(&map, curoff + 1, lineend - curoff - 1) != 0) {
142                         ierr();
143                         return;
144                 }
145                 lineend = curoff + 1;
146                 curoff--;
147
148                 if (style == RLINES)
149                         off--;
150
151                 if (off == 0 && style != REVERSE) {
152                         /* Avoid printing anything below. */
153                         curoff = 0;
154                         break;
155                 }
156         }
157         if (curoff < 0 && mapprint(&map, 0, lineend) != 0) {
158                 ierr();
159                 return;
160         }
161         if (map.start != NULL && munmap(map.start, map.maplen))
162                 ierr();
163 }
164
165 typedef struct bf {
166         struct bf *next;
167         struct bf *prev;
168         int len;
169         char *l;
170 } BF;
171
172 /*
173  * r_buf -- display a non-regular file in reverse order by line.
174  *
175  * This is the function that saves the entire input, storing the data in a
176  * doubly linked list of buffers and then displays them in reverse order.
177  * It has the usual nastiness of trying to find the newlines, as there's no
178  * guarantee that a newline occurs anywhere in the file, let alone in any
179  * particular buffer.  If we run out of memory, input is discarded (and the
180  * user warned).
181  */
182 static void
183 r_buf(FILE *fp)
184 {
185         BF *mark, *tl = NULL, *tr = NULL;
186         int ch = 0, len, llen;
187         char *p;
188         off_t enomem;
189
190 #define BSZ     (128 * 1024)
191         for (mark = NULL, enomem = 0;;) {
192                 /*
193                  * Allocate a new block and link it into place in a doubly
194                  * linked list.  If out of memory, toss the LRU block and
195                  * keep going.
196                  */
197                 if (enomem || (tl = malloc(sizeof(BF))) == NULL ||
198                     (tl->l = malloc(BSZ)) == NULL) {
199                         if (!mark)
200                                 err(1, "malloc");
201                         tl = enomem ? tl->next : mark;
202                         enomem += tl->len;
203                 } else if (mark) {
204                         tl->next = mark;
205                         tl->prev = mark->prev;
206                         mark->prev->next = tl;
207                         mark->prev = tl;
208                 } else {
209                         mark = tl;
210                         mark->next = mark->prev = mark;
211                 }
212
213                 /* Fill the block with input data. */
214                 for (p = tl->l, len = 0;
215                     len < BSZ && (ch = getc(fp)) != EOF; ++len)
216                         *p++ = ch;
217
218                 if (ferror(fp)) {
219                         ierr();
220                         return;
221                 }
222
223                 /*
224                  * If no input data for this block and we tossed some data,
225                  * recover it.
226                  */
227                 if (!len) {
228                         if (enomem)
229                                 enomem -= tl->len;
230                         tl = tl->prev;
231                         break;
232                 }
233
234                 tl->len = len;
235                 if (ch == EOF)
236                         break;
237         }
238
239         if (enomem) {
240                 warnx("warning: %qd bytes discarded", enomem);
241                 rval = 1;
242         }
243
244         /*
245          * Step through the blocks in the reverse order read.  The last char
246          * is special, ignore whether newline or not.
247          */
248         for (mark = tl;;) {
249                 for (p = tl->l + (len = tl->len) - 1, llen = 0; len--;
250                     --p, ++llen)
251                         if (*p == '\n') {
252                                 if (llen) {
253                                         WR(p + 1, llen);
254                                         llen = 0;
255                                 }
256                                 if (tl == mark)
257                                         continue;
258                                 for (tr = tl->next; tr->len; tr = tr->next) {
259                                         WR(tr->l, tr->len);
260                                         tr->len = 0;
261                                         if (tr == mark)
262                                                 break;
263                                 }
264                         }
265                 tl->len = llen;
266                 if ((tl = tl->prev) == mark)
267                         break;
268         }
269         tl = tl->next;
270         if (tl->len) {
271                 WR(tl->l, tl->len);
272                 tl->len = 0;
273         }
274         while ((tl = tl->next)->len) {
275                 WR(tl->l, tl->len);
276                 tl->len = 0;
277         }
278 }