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