]> CyberLeo.Net >> Repos - FreeBSD/releng/9.2.git/blob - usr.bin/look/look.c
- Copy stable/9 to releng/9.2 as part of the 9.2-RELEASE cycle.
[FreeBSD/releng/9.2.git] / usr.bin / look / look.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  * David Hitz of Auspex Systems, Inc.
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  * 4. 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
33 #ifndef lint
34 static const char copyright[] =
35 "@(#) Copyright (c) 1991, 1993\n\
36         The Regents of the University of California.  All rights reserved.\n";
37 #endif /* not lint */
38
39 #ifndef lint
40 #if 0
41 static char sccsid[] = "@(#)look.c      8.2 (Berkeley) 5/4/95";
42 #endif
43 #endif /* not lint */
44 #include <sys/cdefs.h>
45 __FBSDID("$FreeBSD$");
46
47 /*
48  * look -- find lines in a sorted list.
49  *
50  * The man page said that TABs and SPACEs participate in -d comparisons.
51  * In fact, they were ignored.  This implements historic practice, not
52  * the manual page.
53  */
54
55 #include <sys/types.h>
56 #include <sys/mman.h>
57 #include <sys/stat.h>
58
59 #include <err.h>
60 #include <errno.h>
61 #include <fcntl.h>
62 #include <limits.h>
63 #include <locale.h>
64 #include <stdio.h>
65 #include <stdlib.h>
66 #include <string.h>
67 #include <unistd.h>
68 #include <wchar.h>
69 #include <wctype.h>
70
71 #include "pathnames.h"
72
73 static char _path_words[] = _PATH_WORDS;
74
75 #define EQUAL           0
76 #define GREATER         1
77 #define LESS            (-1)
78
79 int dflag, fflag;
80
81 char    *binary_search(wchar_t *, unsigned char *, unsigned char *);
82 int      compare(wchar_t *, unsigned char *, unsigned char *);
83 char    *linear_search(wchar_t *, unsigned char *, unsigned char *);
84 int      look(wchar_t *, unsigned char *, unsigned char *);
85 wchar_t *prepkey(const char *, wchar_t);
86 void     print_from(wchar_t *, unsigned char *, unsigned char *);
87
88 static void usage(void);
89
90 int
91 main(int argc, char *argv[])
92 {
93         struct stat sb;
94         int ch, fd, match;
95         wchar_t termchar;
96         unsigned char *back, *front;
97         unsigned const char *file;
98         wchar_t *key;
99
100         (void) setlocale(LC_CTYPE, "");
101
102         file = _path_words;
103         termchar = L'\0';
104         while ((ch = getopt(argc, argv, "dft:")) != -1)
105                 switch(ch) {
106                 case 'd':
107                         dflag = 1;
108                         break;
109                 case 'f':
110                         fflag = 1;
111                         break;
112                 case 't':
113                         if (mbrtowc(&termchar, optarg, MB_LEN_MAX, NULL) !=
114                             strlen(optarg))
115                                 errx(2, "invalid termination character");
116                         break;
117                 case '?':
118                 default:
119                         usage();
120                 }
121         argc -= optind;
122         argv += optind;
123
124         if (argc == 0)
125                 usage();
126         if (argc == 1)                  /* But set -df by default. */
127                 dflag = fflag = 1;
128         key = prepkey(*argv++, termchar);
129         if (argc >= 2)
130                 file = *argv++;
131
132         match = 1;
133
134         do {
135                 if ((fd = open(file, O_RDONLY, 0)) < 0 || fstat(fd, &sb))
136                         err(2, "%s", file);
137                 if (sb.st_size > SIZE_T_MAX)
138                         errx(2, "%s: %s", file, strerror(EFBIG));
139                 if (sb.st_size == 0) {
140                         close(fd);
141                         continue;
142                 }
143                 if ((front = mmap(NULL, (size_t)sb.st_size, PROT_READ, MAP_SHARED, fd, (off_t)0)) == MAP_FAILED)
144                         err(2, "%s", file);
145                 back = front + sb.st_size;
146                 match *= (look(key, front, back));
147                 close(fd);
148         } while (argc-- > 2 && (file = *argv++));
149
150         exit(match);
151 }
152
153 wchar_t *
154 prepkey(const char *string, wchar_t termchar)
155 {
156         const char *readp;
157         wchar_t *key, *writep;
158         wchar_t ch;
159         size_t clen;
160
161         /*
162          * Reformat search string and convert to wide character representation
163          * to avoid doing it multiple times later.
164          */
165         if ((key = malloc(sizeof(wchar_t) * (strlen(string) + 1))) == NULL)
166                 err(2, NULL);
167         readp = string;
168         writep = key;
169         while ((clen = mbrtowc(&ch, readp, MB_LEN_MAX, NULL)) != 0) {
170                 if (clen == (size_t)-1 || clen == (size_t)-2)
171                         errc(2, EILSEQ, NULL);
172                 if (fflag)
173                         ch = towlower(ch);
174                 if (!dflag || iswalnum(ch))
175                         *writep++ = ch;
176                 readp += clen;
177         }
178         *writep = L'\0';
179         if (termchar != L'\0' && (writep = wcschr(key, termchar)) != NULL)
180                 *++writep = L'\0';
181         return (key);
182 }
183
184 int
185 look(wchar_t *string, unsigned char *front, unsigned char *back)
186 {
187
188         front = binary_search(string, front, back);
189         front = linear_search(string, front, back);
190
191         if (front)
192                 print_from(string, front, back);
193         return (front ? 0 : 1);
194 }
195
196
197 /*
198  * Binary search for "string" in memory between "front" and "back".
199  *
200  * This routine is expected to return a pointer to the start of a line at
201  * *or before* the first word matching "string".  Relaxing the constraint
202  * this way simplifies the algorithm.
203  *
204  * Invariants:
205  *      front points to the beginning of a line at or before the first
206  *      matching string.
207  *
208  *      back points to the beginning of a line at or after the first
209  *      matching line.
210  *
211  * Base of the Invariants.
212  *      front = NULL;
213  *      back = EOF;
214  *
215  * Advancing the Invariants:
216  *
217  *      p = first newline after halfway point from front to back.
218  *
219  *      If the string at "p" is not greater than the string to match,
220  *      p is the new front.  Otherwise it is the new back.
221  *
222  * Termination:
223  *
224  *      The definition of the routine allows it return at any point,
225  *      since front is always at or before the line to print.
226  *
227  *      In fact, it returns when the chosen "p" equals "back".  This
228  *      implies that there exists a string is least half as long as
229  *      (back - front), which in turn implies that a linear search will
230  *      be no more expensive than the cost of simply printing a string or two.
231  *
232  *      Trying to continue with binary search at this point would be
233  *      more trouble than it's worth.
234  */
235 #define SKIP_PAST_NEWLINE(p, back) \
236         while (p < back && *p++ != '\n');
237
238 char *
239 binary_search(wchar_t *string, unsigned char *front, unsigned char *back)
240 {
241         unsigned char *p;
242
243         p = front + (back - front) / 2;
244         SKIP_PAST_NEWLINE(p, back);
245
246         /*
247          * If the file changes underneath us, make sure we don't
248          * infinitely loop.
249          */
250         while (p < back && back > front) {
251                 if (compare(string, p, back) == GREATER)
252                         front = p;
253                 else
254                         back = p;
255                 p = front + (back - front) / 2;
256                 SKIP_PAST_NEWLINE(p, back);
257         }
258         return (front);
259 }
260
261 /*
262  * Find the first line that starts with string, linearly searching from front
263  * to back.
264  *
265  * Return NULL for no such line.
266  *
267  * This routine assumes:
268  *
269  *      o front points at the first character in a line.
270  *      o front is before or at the first line to be printed.
271  */
272 char *
273 linear_search(wchar_t *string, unsigned char *front, unsigned char *back)
274 {
275         while (front < back) {
276                 switch (compare(string, front, back)) {
277                 case EQUAL:             /* Found it. */
278                         return (front);
279                 case LESS:              /* No such string. */
280                         return (NULL);
281                 case GREATER:           /* Keep going. */
282                         break;
283                 }
284                 SKIP_PAST_NEWLINE(front, back);
285         }
286         return (NULL);
287 }
288
289 /*
290  * Print as many lines as match string, starting at front.
291  */
292 void
293 print_from(wchar_t *string, unsigned char *front, unsigned char *back)
294 {
295         for (; front < back && compare(string, front, back) == EQUAL; ++front) {
296                 for (; front < back && *front != '\n'; ++front)
297                         if (putchar(*front) == EOF)
298                                 err(2, "stdout");
299                 if (putchar('\n') == EOF)
300                         err(2, "stdout");
301         }
302 }
303
304 /*
305  * Return LESS, GREATER, or EQUAL depending on how the string1 compares with
306  * string2 (s1 ??? s2).
307  *
308  *      o Matches up to len(s1) are EQUAL.
309  *      o Matches up to len(s2) are GREATER.
310  *
311  * Compare understands about the -f and -d flags, and treats comparisons
312  * appropriately.
313  *
314  * The string "s1" is null terminated.  The string s2 is '\n' terminated (or
315  * "back" terminated).
316  */
317 int
318 compare(wchar_t *s1, unsigned char *s2, unsigned char *back)
319 {
320         wchar_t ch1, ch2;
321         size_t len2;
322
323         for (; *s1 && s2 < back && *s2 != '\n'; ++s1, s2 += len2) {
324                 ch1 = *s1;
325                 len2 = mbrtowc(&ch2, s2, back - s2, NULL);
326                 if (len2 == (size_t)-1 || len2 == (size_t)-2) {
327                         ch2 = *s2;
328                         len2 = 1;
329                 }
330                 if (fflag)
331                         ch2 = towlower(ch2);
332                 if (dflag && !iswalnum(ch2)) {
333                         /* Ignore character in comparison. */
334                         --s1;
335                         continue;
336                 }
337                 if (ch1 != ch2)
338                         return (ch1 < ch2 ? LESS : GREATER);
339         }
340         return (*s1 ? GREATER : EQUAL);
341 }
342
343 static void
344 usage(void)
345 {
346         (void)fprintf(stderr, "usage: look [-df] [-t char] string [file ...]\n");
347         exit(2);
348 }