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