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