11590Srgrimes/*-
21590Srgrimes * Copyright (c) 1991, 1993
31590Srgrimes *	The Regents of the University of California.  All rights reserved.
41590Srgrimes *
51590Srgrimes * This code is derived from software contributed to Berkeley by
61590Srgrimes * David Hitz of Auspex Systems, Inc.
71590Srgrimes *
81590Srgrimes * Redistribution and use in source and binary forms, with or without
91590Srgrimes * modification, are permitted provided that the following conditions
101590Srgrimes * are met:
111590Srgrimes * 1. Redistributions of source code must retain the above copyright
121590Srgrimes *    notice, this list of conditions and the following disclaimer.
131590Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
141590Srgrimes *    notice, this list of conditions and the following disclaimer in the
151590Srgrimes *    documentation and/or other materials provided with the distribution.
161590Srgrimes * 4. Neither the name of the University nor the names of its contributors
171590Srgrimes *    may be used to endorse or promote products derived from this software
181590Srgrimes *    without specific prior written permission.
191590Srgrimes *
201590Srgrimes * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
211590Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
221590Srgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
231590Srgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
241590Srgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
251590Srgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
261590Srgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
271590Srgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
281590Srgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
291590Srgrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
301590Srgrimes * SUCH DAMAGE.
311590Srgrimes */
321590Srgrimes
331590Srgrimes#ifndef lint
3427623Scharnierstatic const char copyright[] =
351590Srgrimes"@(#) Copyright (c) 1991, 1993\n\
361590Srgrimes	The Regents of the University of California.  All rights reserved.\n";
371590Srgrimes#endif /* not lint */
381590Srgrimes
391590Srgrimes#ifndef lint
4027623Scharnier#if 0
4123693Speterstatic char sccsid[] = "@(#)look.c	8.2 (Berkeley) 5/4/95";
4227623Scharnier#endif
431590Srgrimes#endif /* not lint */
4499112Sobrien#include <sys/cdefs.h>
4599112Sobrien__FBSDID("$FreeBSD$");
461590Srgrimes
471590Srgrimes/*
481590Srgrimes * look -- find lines in a sorted list.
498874Srgrimes *
501590Srgrimes * The man page said that TABs and SPACEs participate in -d comparisons.
511590Srgrimes * In fact, they were ignored.  This implements historic practice, not
521590Srgrimes * the manual page.
531590Srgrimes */
541590Srgrimes
551590Srgrimes#include <sys/types.h>
561590Srgrimes#include <sys/mman.h>
571590Srgrimes#include <sys/stat.h>
581590Srgrimes
5927623Scharnier#include <err.h>
601590Srgrimes#include <errno.h>
611590Srgrimes#include <fcntl.h>
6223693Speter#include <limits.h>
6327623Scharnier#include <locale.h>
64226468Sed#include <stdint.h>
651590Srgrimes#include <stdio.h>
661590Srgrimes#include <stdlib.h>
671590Srgrimes#include <string.h>
6823693Speter#include <unistd.h>
69132394Stjr#include <wchar.h>
70132394Stjr#include <wctype.h>
7123693Speter
721590Srgrimes#include "pathnames.h"
731590Srgrimes
7495646Smarkmstatic char _path_words[] = _PATH_WORDS;
7595646Smarkm
761590Srgrimes#define	EQUAL		0
771590Srgrimes#define	GREATER		1
781590Srgrimes#define	LESS		(-1)
791590Srgrimes
80227171Sedstatic int dflag, fflag;
811590Srgrimes
82227171Sedstatic char	*binary_search(wchar_t *, unsigned char *, unsigned char *);
83227171Sedstatic int	 compare(wchar_t *, unsigned char *, unsigned char *);
84227171Sedstatic char	*linear_search(wchar_t *, unsigned char *, unsigned char *);
85227171Sedstatic int	 look(wchar_t *, unsigned char *, unsigned char *);
86227171Sedstatic wchar_t	*prepkey(const char *, wchar_t);
87227171Sedstatic void	 print_from(wchar_t *, unsigned char *, unsigned char *);
881590Srgrimes
8992920Simpstatic void usage(void);
901590Srgrimes
9127623Scharnierint
92102944Sdwmalonemain(int argc, char *argv[])
931590Srgrimes{
941590Srgrimes	struct stat sb;
95132394Stjr	int ch, fd, match;
96132394Stjr	wchar_t termchar;
97132394Stjr	unsigned char *back, *front;
9887288Sdwmalone	unsigned const char *file;
99132394Stjr	wchar_t *key;
1001590Srgrimes
10111900Sache	(void) setlocale(LC_CTYPE, "");
10211900Sache
10395646Smarkm	file = _path_words;
104132394Stjr	termchar = L'\0';
10524360Simp	while ((ch = getopt(argc, argv, "dft:")) != -1)
1061590Srgrimes		switch(ch) {
1071590Srgrimes		case 'd':
1081590Srgrimes			dflag = 1;
1091590Srgrimes			break;
1101590Srgrimes		case 'f':
1111590Srgrimes			fflag = 1;
1121590Srgrimes			break;
1131590Srgrimes		case 't':
114132394Stjr			if (mbrtowc(&termchar, optarg, MB_LEN_MAX, NULL) !=
115132394Stjr			    strlen(optarg))
116132394Stjr				errx(2, "invalid termination character");
1171590Srgrimes			break;
1181590Srgrimes		case '?':
1191590Srgrimes		default:
1201590Srgrimes			usage();
1211590Srgrimes		}
1221590Srgrimes	argc -= optind;
1231590Srgrimes	argv += optind;
1241590Srgrimes
12538701Swosch	if (argc == 0)
12638701Swosch		usage();
12738701Swosch	if (argc == 1) 			/* But set -df by default. */
1281590Srgrimes		dflag = fflag = 1;
129132394Stjr	key = prepkey(*argv++, termchar);
13038701Swosch	if (argc >= 2)
13138701Swosch		file = *argv++;
1321590Srgrimes
13338701Swosch	match = 1;
1341590Srgrimes
13538701Swosch	do {
13638701Swosch		if ((fd = open(file, O_RDONLY, 0)) < 0 || fstat(fd, &sb))
13738701Swosch			err(2, "%s", file);
138226444Sed		if ((uintmax_t)sb.st_size > (uintmax_t)SIZE_T_MAX)
13938701Swosch			errx(2, "%s: %s", file, strerror(EFBIG));
140196558Scperciva		if (sb.st_size == 0) {
141196558Scperciva			close(fd);
142196558Scperciva			continue;
143196558Scperciva		}
14438701Swosch		if ((front = mmap(NULL, (size_t)sb.st_size, PROT_READ, MAP_SHARED, fd, (off_t)0)) == MAP_FAILED)
14538701Swosch			err(2, "%s", file);
14638701Swosch		back = front + sb.st_size;
147132394Stjr		match *= (look(key, front, back));
14838701Swosch		close(fd);
14938701Swosch	} while (argc-- > 2 && (file = *argv++));
15038701Swosch
15138701Swosch	exit(match);
1521590Srgrimes}
1531590Srgrimes
154227171Sedstatic wchar_t *
155132394Stjrprepkey(const char *string, wchar_t termchar)
1561590Srgrimes{
157132394Stjr	const char *readp;
158132394Stjr	wchar_t *key, *writep;
159132394Stjr	wchar_t ch;
160132394Stjr	size_t clen;
1611590Srgrimes
162132394Stjr	/*
163132394Stjr	 * Reformat search string and convert to wide character representation
164132394Stjr	 * to avoid doing it multiple times later.
165132394Stjr	 */
166132394Stjr	if ((key = malloc(sizeof(wchar_t) * (strlen(string) + 1))) == NULL)
167132394Stjr		err(2, NULL);
168132394Stjr	readp = string;
169132394Stjr	writep = key;
170132394Stjr	while ((clen = mbrtowc(&ch, readp, MB_LEN_MAX, NULL)) != 0) {
171132394Stjr		if (clen == (size_t)-1 || clen == (size_t)-2)
172132394Stjr			errc(2, EILSEQ, NULL);
1731590Srgrimes		if (fflag)
174132394Stjr			ch = towlower(ch);
175132394Stjr		if (!dflag || iswalnum(ch))
176132394Stjr			*writep++ = ch;
177132394Stjr		readp += clen;
1781590Srgrimes	}
179132394Stjr	*writep = L'\0';
180132394Stjr	if (termchar != L'\0' && (writep = wcschr(key, termchar)) != NULL)
181132394Stjr		*++writep = L'\0';
182132394Stjr	return (key);
183132394Stjr}
1841590Srgrimes
185227171Sedstatic int
186132394Stjrlook(wchar_t *string, unsigned char *front, unsigned char *back)
187132394Stjr{
188132394Stjr
1891590Srgrimes	front = binary_search(string, front, back);
1901590Srgrimes	front = linear_search(string, front, back);
1911590Srgrimes
1921590Srgrimes	if (front)
1931590Srgrimes		print_from(string, front, back);
1941590Srgrimes	return (front ? 0 : 1);
1951590Srgrimes}
1961590Srgrimes
1971590Srgrimes
1981590Srgrimes/*
1991590Srgrimes * Binary search for "string" in memory between "front" and "back".
2008874Srgrimes *
2011590Srgrimes * This routine is expected to return a pointer to the start of a line at
2021590Srgrimes * *or before* the first word matching "string".  Relaxing the constraint
2031590Srgrimes * this way simplifies the algorithm.
2048874Srgrimes *
2051590Srgrimes * Invariants:
2068874Srgrimes * 	front points to the beginning of a line at or before the first
2071590Srgrimes *	matching string.
2088874Srgrimes *
2098874Srgrimes * 	back points to the beginning of a line at or after the first
2101590Srgrimes *	matching line.
2118874Srgrimes *
2121590Srgrimes * Base of the Invariants.
2138874Srgrimes * 	front = NULL;
2141590Srgrimes *	back = EOF;
2158874Srgrimes *
2161590Srgrimes * Advancing the Invariants:
2178874Srgrimes *
2181590Srgrimes * 	p = first newline after halfway point from front to back.
2198874Srgrimes *
2208874Srgrimes * 	If the string at "p" is not greater than the string to match,
2211590Srgrimes *	p is the new front.  Otherwise it is the new back.
2228874Srgrimes *
2231590Srgrimes * Termination:
2248874Srgrimes *
2258874Srgrimes * 	The definition of the routine allows it return at any point,
2261590Srgrimes *	since front is always at or before the line to print.
2278874Srgrimes *
2288874Srgrimes * 	In fact, it returns when the chosen "p" equals "back".  This
2298874Srgrimes *	implies that there exists a string is least half as long as
2308874Srgrimes *	(back - front), which in turn implies that a linear search will
2311590Srgrimes *	be no more expensive than the cost of simply printing a string or two.
2328874Srgrimes *
2338874Srgrimes * 	Trying to continue with binary search at this point would be
2341590Srgrimes *	more trouble than it's worth.
2351590Srgrimes */
2361590Srgrimes#define	SKIP_PAST_NEWLINE(p, back) \
2371590Srgrimes	while (p < back && *p++ != '\n');
2381590Srgrimes
239227171Sedstatic char *
240132394Stjrbinary_search(wchar_t *string, unsigned char *front, unsigned char *back)
2411590Srgrimes{
242102944Sdwmalone	unsigned char *p;
2431590Srgrimes
2441590Srgrimes	p = front + (back - front) / 2;
2451590Srgrimes	SKIP_PAST_NEWLINE(p, back);
2461590Srgrimes
2471590Srgrimes	/*
2481590Srgrimes	 * If the file changes underneath us, make sure we don't
2491590Srgrimes	 * infinitely loop.
2501590Srgrimes	 */
2511590Srgrimes	while (p < back && back > front) {
2521590Srgrimes		if (compare(string, p, back) == GREATER)
2531590Srgrimes			front = p;
2541590Srgrimes		else
2551590Srgrimes			back = p;
2561590Srgrimes		p = front + (back - front) / 2;
2571590Srgrimes		SKIP_PAST_NEWLINE(p, back);
2581590Srgrimes	}
2591590Srgrimes	return (front);
2601590Srgrimes}
2611590Srgrimes
2621590Srgrimes/*
2631590Srgrimes * Find the first line that starts with string, linearly searching from front
2641590Srgrimes * to back.
2658874Srgrimes *
2661590Srgrimes * Return NULL for no such line.
2678874Srgrimes *
2681590Srgrimes * This routine assumes:
2698874Srgrimes *
2708874Srgrimes * 	o front points at the first character in a line.
2711590Srgrimes *	o front is before or at the first line to be printed.
2721590Srgrimes */
273227171Sedstatic char *
274132394Stjrlinear_search(wchar_t *string, unsigned char *front, unsigned char *back)
2751590Srgrimes{
2761590Srgrimes	while (front < back) {
2771590Srgrimes		switch (compare(string, front, back)) {
2781590Srgrimes		case EQUAL:		/* Found it. */
2791590Srgrimes			return (front);
2801590Srgrimes		case LESS:		/* No such string. */
2811590Srgrimes			return (NULL);
2821590Srgrimes		case GREATER:		/* Keep going. */
2831590Srgrimes			break;
2841590Srgrimes		}
2851590Srgrimes		SKIP_PAST_NEWLINE(front, back);
2861590Srgrimes	}
2871590Srgrimes	return (NULL);
2881590Srgrimes}
2891590Srgrimes
2901590Srgrimes/*
2911590Srgrimes * Print as many lines as match string, starting at front.
2921590Srgrimes */
293227171Sedstatic void
294132394Stjrprint_from(wchar_t *string, unsigned char *front, unsigned char *back)
2951590Srgrimes{
2961590Srgrimes	for (; front < back && compare(string, front, back) == EQUAL; ++front) {
2971590Srgrimes		for (; front < back && *front != '\n'; ++front)
2981590Srgrimes			if (putchar(*front) == EOF)
29927623Scharnier				err(2, "stdout");
3001590Srgrimes		if (putchar('\n') == EOF)
30127623Scharnier			err(2, "stdout");
3021590Srgrimes	}
3031590Srgrimes}
3041590Srgrimes
3051590Srgrimes/*
3061590Srgrimes * Return LESS, GREATER, or EQUAL depending on how the string1 compares with
3071590Srgrimes * string2 (s1 ??? s2).
3088874Srgrimes *
3098874Srgrimes * 	o Matches up to len(s1) are EQUAL.
3101590Srgrimes *	o Matches up to len(s2) are GREATER.
3118874Srgrimes *
3121590Srgrimes * Compare understands about the -f and -d flags, and treats comparisons
3131590Srgrimes * appropriately.
3148874Srgrimes *
3151590Srgrimes * The string "s1" is null terminated.  The string s2 is '\n' terminated (or
3161590Srgrimes * "back" terminated).
3171590Srgrimes */
318227171Sedstatic int
319132394Stjrcompare(wchar_t *s1, unsigned char *s2, unsigned char *back)
3201590Srgrimes{
321132394Stjr	wchar_t ch1, ch2;
322132394Stjr	size_t len2;
3231590Srgrimes
324132394Stjr	for (; *s1 && s2 < back && *s2 != '\n'; ++s1, s2 += len2) {
325132394Stjr		ch1 = *s1;
326132394Stjr		len2 = mbrtowc(&ch2, s2, back - s2, NULL);
327132394Stjr		if (len2 == (size_t)-1 || len2 == (size_t)-2) {
328132394Stjr			ch2 = *s2;
329132394Stjr			len2 = 1;
330132394Stjr		}
3311590Srgrimes		if (fflag)
332132394Stjr			ch2 = towlower(ch2);
333132394Stjr		if (dflag && !iswalnum(ch2)) {
334132394Stjr			/* Ignore character in comparison. */
335132394Stjr			--s1;
3361590Srgrimes			continue;
3371590Srgrimes		}
338132394Stjr		if (ch1 != ch2)
339132394Stjr			return (ch1 < ch2 ? LESS : GREATER);
3401590Srgrimes	}
3411590Srgrimes	return (*s1 ? GREATER : EQUAL);
3421590Srgrimes}
3431590Srgrimes
3441590Srgrimesstatic void
345102944Sdwmaloneusage(void)
3461590Srgrimes{
34738701Swosch	(void)fprintf(stderr, "usage: look [-df] [-t char] string [file ...]\n");
3481590Srgrimes	exit(2);
3491590Srgrimes}
350