xref: /freebsd/usr.bin/look/look.c (revision f9bc005b8ef3b507a5ecbc2d7fe4411ef70eff38)
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/capsicum.h>
45 #include <sys/mman.h>
46 #include <sys/stat.h>
47 
48 #include <capsicum_helpers.h>
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) __dead2;
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 struct files {
91 	int fd;
92 	int err;
93 	const char *path;
94 };
95 
96 int
97 main(int argc, char *argv[])
98 {
99 	struct stat sb;
100 	int ch, match;
101 	size_t nfiles;
102 	wchar_t termchar;
103 	cap_rights_t rights;
104 	struct files *files;
105 	unsigned char *back, *front;
106 	wchar_t *key;
107 
108 	(void) setlocale(LC_CTYPE, "");
109 
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 	argc--;
140 
141 	match = 1;
142 
143 	cap_rights_init(&rights, CAP_MMAP_R, CAP_READ, CAP_FSTAT);
144 	nfiles = !argc ? 1 : argc;
145 	if ((files = malloc(nfiles * sizeof(struct files))) == NULL)
146 		err(2, NULL);
147 	for (size_t idx = 0; idx < nfiles; idx++) {
148 		files[idx].path = !argc ? _path_words : argv[idx];
149 		if ((files[idx].fd = open(files[idx].path, O_RDONLY, 0)) < 0) {
150 			files[idx].err = errno;
151 			continue;
152 		}
153 		files[idx].err = 0;
154 		if (caph_rights_limit(files[idx].fd, &rights) != 0)
155 			err(2, "unable to limit rights for %s", files[idx].path);
156 	}
157 
158 	caph_cache_catpages();
159 	if (caph_enter() != 0)
160 		err(EXIT_FAILURE, "failed to enter capability mode");
161 
162 	for (size_t idx = 0; idx < nfiles; idx++) {
163 		if (files[idx].err)
164 			errc(2, files[idx].err, "%s", files[idx].path);
165 		if (fstat(files[idx].fd, &sb))
166 			err(2, "%s", files[idx].path);
167 		if ((uintmax_t)sb.st_size > (uintmax_t)SIZE_T_MAX)
168 			errx(2, "%s: %s", files[idx].path, strerror(EFBIG));
169 		if (sb.st_size == 0) {
170 			close(files[idx].fd);
171 			continue;
172 		}
173 		if ((front = mmap(NULL, (size_t)sb.st_size, PROT_READ,
174 		    MAP_SHARED, files[idx].fd, (off_t)0)) == MAP_FAILED)
175 			err(2, "%s", files[idx].path);
176 		back = front + sb.st_size;
177 		match *= (look(key, front, back));
178 		close(files[idx].fd);
179 	}
180 
181 	free(files);
182 	exit(match);
183 }
184 
185 static wchar_t *
186 prepkey(const char *string, wchar_t termchar)
187 {
188 	const char *readp;
189 	wchar_t *key, *writep;
190 	wchar_t ch;
191 	size_t clen;
192 
193 	/*
194 	 * Reformat search string and convert to wide character representation
195 	 * to avoid doing it multiple times later.
196 	 */
197 	if ((key = malloc(sizeof(wchar_t) * (strlen(string) + 1))) == NULL)
198 		err(2, NULL);
199 	readp = string;
200 	writep = key;
201 	while ((clen = mbrtowc(&ch, readp, MB_LEN_MAX, NULL)) != 0) {
202 		if (clen == (size_t)-1 || clen == (size_t)-2)
203 			errc(2, EILSEQ, NULL);
204 		if (fflag)
205 			ch = towlower(ch);
206 		if (!dflag || iswalnum(ch))
207 			*writep++ = ch;
208 		readp += clen;
209 	}
210 	*writep = L'\0';
211 	if (termchar != L'\0' && (writep = wcschr(key, termchar)) != NULL)
212 		*++writep = L'\0';
213 	return (key);
214 }
215 
216 static int
217 look(wchar_t *string, unsigned char *front, unsigned char *back)
218 {
219 
220 	front = binary_search(string, front, back);
221 	front = linear_search(string, front, back);
222 
223 	if (front)
224 		print_from(string, front, back);
225 	return (front ? 0 : 1);
226 }
227 
228 
229 /*
230  * Binary search for "string" in memory between "front" and "back".
231  *
232  * This routine is expected to return a pointer to the start of a line at
233  * *or before* the first word matching "string".  Relaxing the constraint
234  * this way simplifies the algorithm.
235  *
236  * Invariants:
237  * 	front points to the beginning of a line at or before the first
238  *	matching string.
239  *
240  * 	back points to the beginning of a line at or after the first
241  *	matching line.
242  *
243  * Base of the Invariants.
244  * 	front = NULL;
245  *	back = EOF;
246  *
247  * Advancing the Invariants:
248  *
249  * 	p = first newline after halfway point from front to back.
250  *
251  * 	If the string at "p" is not greater than the string to match,
252  *	p is the new front.  Otherwise it is the new back.
253  *
254  * Termination:
255  *
256  * 	The definition of the routine allows it return at any point,
257  *	since front is always at or before the line to print.
258  *
259  * 	In fact, it returns when the chosen "p" equals "back".  This
260  *	implies that there exists a string is least half as long as
261  *	(back - front), which in turn implies that a linear search will
262  *	be no more expensive than the cost of simply printing a string or two.
263  *
264  * 	Trying to continue with binary search at this point would be
265  *	more trouble than it's worth.
266  */
267 #define	SKIP_PAST_NEWLINE(p, back) \
268 	while (p < back && *p++ != '\n');
269 
270 static char *
271 binary_search(wchar_t *string, unsigned char *front, unsigned char *back)
272 {
273 	unsigned char *p;
274 
275 	p = front + (back - front) / 2;
276 	SKIP_PAST_NEWLINE(p, back);
277 
278 	/*
279 	 * If the file changes underneath us, make sure we don't
280 	 * infinitely loop.
281 	 */
282 	while (p < back && back > front) {
283 		if (compare(string, p, back) == GREATER)
284 			front = p;
285 		else
286 			back = p;
287 		p = front + (back - front) / 2;
288 		SKIP_PAST_NEWLINE(p, back);
289 	}
290 	return (front);
291 }
292 
293 /*
294  * Find the first line that starts with string, linearly searching from front
295  * to back.
296  *
297  * Return NULL for no such line.
298  *
299  * This routine assumes:
300  *
301  * 	o front points at the first character in a line.
302  *	o front is before or at the first line to be printed.
303  */
304 static char *
305 linear_search(wchar_t *string, unsigned char *front, unsigned char *back)
306 {
307 	while (front < back) {
308 		switch (compare(string, front, back)) {
309 		case EQUAL:		/* Found it. */
310 			return (front);
311 		case LESS:		/* No such string. */
312 			return (NULL);
313 		case GREATER:		/* Keep going. */
314 			break;
315 		}
316 		SKIP_PAST_NEWLINE(front, back);
317 	}
318 	return (NULL);
319 }
320 
321 /*
322  * Print as many lines as match string, starting at front.
323  */
324 static void
325 print_from(wchar_t *string, unsigned char *front, unsigned char *back)
326 {
327 	for (; front < back && compare(string, front, back) == EQUAL; ++front) {
328 		for (; front < back && *front != '\n'; ++front)
329 			if (putchar(*front) == EOF)
330 				err(2, "stdout");
331 		if (putchar('\n') == EOF)
332 			err(2, "stdout");
333 	}
334 }
335 
336 /*
337  * Return LESS, GREATER, or EQUAL depending on how the string1 compares with
338  * string2 (s1 ??? s2).
339  *
340  * 	o Matches up to len(s1) are EQUAL.
341  *	o Matches up to len(s2) are GREATER.
342  *
343  * Compare understands about the -f and -d flags, and treats comparisons
344  * appropriately.
345  *
346  * The string "s1" is null terminated.  The string s2 is '\n' terminated (or
347  * "back" terminated).
348  */
349 static int
350 compare(wchar_t *s1, unsigned char *s2, unsigned char *back)
351 {
352 	wchar_t ch1, ch2;
353 	size_t len2;
354 
355 	for (; *s1 && s2 < back && *s2 != '\n'; ++s1, s2 += len2) {
356 		ch1 = *s1;
357 		len2 = mbrtowc(&ch2, s2, back - s2, NULL);
358 		if (len2 == (size_t)-1 || len2 == (size_t)-2) {
359 			ch2 = *s2;
360 			len2 = 1;
361 		}
362 		if (fflag)
363 			ch2 = towlower(ch2);
364 		if (dflag && !iswalnum(ch2)) {
365 			/* Ignore character in comparison. */
366 			--s1;
367 			continue;
368 		}
369 		if (ch1 != ch2)
370 			return (ch1 < ch2 ? LESS : GREATER);
371 	}
372 	return (*s1 ? GREATER : EQUAL);
373 }
374 
375 static void
376 usage(void)
377 {
378 	(void)fprintf(stderr, "usage: look [-df] [-t char] string [file ...]\n");
379 	exit(2);
380 }
381