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