xref: /freebsd/usr.bin/look/look.c (revision e1e636193db45630c7881246d25902e57c43d24e)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1991, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * David Hitz of Auspex Systems, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 /*
36  * look -- find lines in a sorted list.
37  *
38  * The man page said that TABs and SPACEs participate in -d comparisons.
39  * In fact, they were ignored.  This implements historic practice, not
40  * the manual page.
41  */
42 
43 #include <sys/types.h>
44 #include <sys/mman.h>
45 #include <sys/stat.h>
46 
47 #include <err.h>
48 #include <errno.h>
49 #include <fcntl.h>
50 #include <getopt.h>
51 #include <limits.h>
52 #include <locale.h>
53 #include <stdint.h>
54 #include <stdio.h>
55 #include <stdlib.h>
56 #include <string.h>
57 #include <unistd.h>
58 #include <wchar.h>
59 #include <wctype.h>
60 
61 #include "pathnames.h"
62 
63 static char _path_words[] = _PATH_WORDS;
64 
65 #define	EQUAL		0
66 #define	GREATER		1
67 #define	LESS		(-1)
68 
69 static int dflag, fflag;
70 
71 static char	*binary_search(wchar_t *, unsigned char *, unsigned char *);
72 static int	 compare(wchar_t *, unsigned char *, unsigned char *);
73 static char	*linear_search(wchar_t *, unsigned char *, unsigned char *);
74 static int	 look(wchar_t *, unsigned char *, unsigned char *);
75 static wchar_t	*prepkey(const char *, wchar_t);
76 static void	 print_from(wchar_t *, unsigned char *, unsigned char *);
77 
78 static void usage(void) __dead2;
79 
80 static struct option longopts[] = {
81 	{ "alternative",no_argument,	NULL, 'a' },
82 	{ "alphanum",	no_argument,	NULL, 'd' },
83 	{ "ignore-case",no_argument,	NULL, 'i' },
84 	{ "terminate",	required_argument, NULL, 't'},
85 	{ NULL,		0,		NULL, 0 },
86 };
87 
88 int
89 main(int argc, char *argv[])
90 {
91 	struct stat sb;
92 	int ch, fd, match;
93 	wchar_t termchar;
94 	unsigned char *back, *front;
95 	unsigned const char *file;
96 	wchar_t *key;
97 
98 	(void) setlocale(LC_CTYPE, "");
99 
100 	file = _path_words;
101 	termchar = L'\0';
102 	while ((ch = getopt_long(argc, argv, "+adft:", longopts, NULL)) != -1)
103 		switch(ch) {
104 		case 'a':
105 			/* COMPATIBILITY */
106 			break;
107 		case 'd':
108 			dflag = 1;
109 			break;
110 		case 'f':
111 			fflag = 1;
112 			break;
113 		case 't':
114 			if (mbrtowc(&termchar, optarg, MB_LEN_MAX, NULL) !=
115 			    strlen(optarg))
116 				errx(2, "invalid termination character");
117 			break;
118 		case '?':
119 		default:
120 			usage();
121 		}
122 	argc -= optind;
123 	argv += optind;
124 
125 	if (argc == 0)
126 		usage();
127 	if (argc == 1) 			/* But set -df by default. */
128 		dflag = fflag = 1;
129 	key = prepkey(*argv++, termchar);
130 	if (argc >= 2)
131 		file = *argv++;
132 
133 	match = 1;
134 
135 	do {
136 		if ((fd = open(file, O_RDONLY, 0)) < 0 || fstat(fd, &sb))
137 			err(2, "%s", file);
138 		if ((uintmax_t)sb.st_size > (uintmax_t)SIZE_T_MAX)
139 			errx(2, "%s: %s", file, strerror(EFBIG));
140 		if (sb.st_size == 0) {
141 			close(fd);
142 			continue;
143 		}
144 		if ((front = mmap(NULL, (size_t)sb.st_size, PROT_READ, MAP_SHARED, fd, (off_t)0)) == MAP_FAILED)
145 			err(2, "%s", file);
146 		back = front + sb.st_size;
147 		match *= (look(key, front, back));
148 		close(fd);
149 	} while (argc-- > 2 && (file = *argv++));
150 
151 	exit(match);
152 }
153 
154 static wchar_t *
155 prepkey(const char *string, wchar_t termchar)
156 {
157 	const char *readp;
158 	wchar_t *key, *writep;
159 	wchar_t ch;
160 	size_t clen;
161 
162 	/*
163 	 * Reformat search string and convert to wide character representation
164 	 * to avoid doing it multiple times later.
165 	 */
166 	if ((key = malloc(sizeof(wchar_t) * (strlen(string) + 1))) == NULL)
167 		err(2, NULL);
168 	readp = string;
169 	writep = key;
170 	while ((clen = mbrtowc(&ch, readp, MB_LEN_MAX, NULL)) != 0) {
171 		if (clen == (size_t)-1 || clen == (size_t)-2)
172 			errc(2, EILSEQ, NULL);
173 		if (fflag)
174 			ch = towlower(ch);
175 		if (!dflag || iswalnum(ch))
176 			*writep++ = ch;
177 		readp += clen;
178 	}
179 	*writep = L'\0';
180 	if (termchar != L'\0' && (writep = wcschr(key, termchar)) != NULL)
181 		*++writep = L'\0';
182 	return (key);
183 }
184 
185 static int
186 look(wchar_t *string, unsigned char *front, unsigned char *back)
187 {
188 
189 	front = binary_search(string, front, back);
190 	front = linear_search(string, front, back);
191 
192 	if (front)
193 		print_from(string, front, back);
194 	return (front ? 0 : 1);
195 }
196 
197 
198 /*
199  * Binary search for "string" in memory between "front" and "back".
200  *
201  * This routine is expected to return a pointer to the start of a line at
202  * *or before* the first word matching "string".  Relaxing the constraint
203  * this way simplifies the algorithm.
204  *
205  * Invariants:
206  * 	front points to the beginning of a line at or before the first
207  *	matching string.
208  *
209  * 	back points to the beginning of a line at or after the first
210  *	matching line.
211  *
212  * Base of the Invariants.
213  * 	front = NULL;
214  *	back = EOF;
215  *
216  * Advancing the Invariants:
217  *
218  * 	p = first newline after halfway point from front to back.
219  *
220  * 	If the string at "p" is not greater than the string to match,
221  *	p is the new front.  Otherwise it is the new back.
222  *
223  * Termination:
224  *
225  * 	The definition of the routine allows it return at any point,
226  *	since front is always at or before the line to print.
227  *
228  * 	In fact, it returns when the chosen "p" equals "back".  This
229  *	implies that there exists a string is least half as long as
230  *	(back - front), which in turn implies that a linear search will
231  *	be no more expensive than the cost of simply printing a string or two.
232  *
233  * 	Trying to continue with binary search at this point would be
234  *	more trouble than it's worth.
235  */
236 #define	SKIP_PAST_NEWLINE(p, back) \
237 	while (p < back && *p++ != '\n');
238 
239 static char *
240 binary_search(wchar_t *string, unsigned char *front, unsigned char *back)
241 {
242 	unsigned char *p;
243 
244 	p = front + (back - front) / 2;
245 	SKIP_PAST_NEWLINE(p, back);
246 
247 	/*
248 	 * If the file changes underneath us, make sure we don't
249 	 * infinitely loop.
250 	 */
251 	while (p < back && back > front) {
252 		if (compare(string, p, back) == GREATER)
253 			front = p;
254 		else
255 			back = p;
256 		p = front + (back - front) / 2;
257 		SKIP_PAST_NEWLINE(p, back);
258 	}
259 	return (front);
260 }
261 
262 /*
263  * Find the first line that starts with string, linearly searching from front
264  * to back.
265  *
266  * Return NULL for no such line.
267  *
268  * This routine assumes:
269  *
270  * 	o front points at the first character in a line.
271  *	o front is before or at the first line to be printed.
272  */
273 static char *
274 linear_search(wchar_t *string, unsigned char *front, unsigned char *back)
275 {
276 	while (front < back) {
277 		switch (compare(string, front, back)) {
278 		case EQUAL:		/* Found it. */
279 			return (front);
280 		case LESS:		/* No such string. */
281 			return (NULL);
282 		case GREATER:		/* Keep going. */
283 			break;
284 		}
285 		SKIP_PAST_NEWLINE(front, back);
286 	}
287 	return (NULL);
288 }
289 
290 /*
291  * Print as many lines as match string, starting at front.
292  */
293 static void
294 print_from(wchar_t *string, unsigned char *front, unsigned char *back)
295 {
296 	for (; front < back && compare(string, front, back) == EQUAL; ++front) {
297 		for (; front < back && *front != '\n'; ++front)
298 			if (putchar(*front) == EOF)
299 				err(2, "stdout");
300 		if (putchar('\n') == EOF)
301 			err(2, "stdout");
302 	}
303 }
304 
305 /*
306  * Return LESS, GREATER, or EQUAL depending on how the string1 compares with
307  * string2 (s1 ??? s2).
308  *
309  * 	o Matches up to len(s1) are EQUAL.
310  *	o Matches up to len(s2) are GREATER.
311  *
312  * Compare understands about the -f and -d flags, and treats comparisons
313  * appropriately.
314  *
315  * The string "s1" is null terminated.  The string s2 is '\n' terminated (or
316  * "back" terminated).
317  */
318 static int
319 compare(wchar_t *s1, unsigned char *s2, unsigned char *back)
320 {
321 	wchar_t ch1, ch2;
322 	size_t len2;
323 
324 	for (; *s1 && s2 < back && *s2 != '\n'; ++s1, s2 += len2) {
325 		ch1 = *s1;
326 		len2 = mbrtowc(&ch2, s2, back - s2, NULL);
327 		if (len2 == (size_t)-1 || len2 == (size_t)-2) {
328 			ch2 = *s2;
329 			len2 = 1;
330 		}
331 		if (fflag)
332 			ch2 = towlower(ch2);
333 		if (dflag && !iswalnum(ch2)) {
334 			/* Ignore character in comparison. */
335 			--s1;
336 			continue;
337 		}
338 		if (ch1 != ch2)
339 			return (ch1 < ch2 ? LESS : GREATER);
340 	}
341 	return (*s1 ? GREATER : EQUAL);
342 }
343 
344 static void
345 usage(void)
346 {
347 	(void)fprintf(stderr, "usage: look [-df] [-t char] string [file ...]\n");
348 	exit(2);
349 }
350