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