util.c revision 322560
1/*	$NetBSD: util.c,v 1.9 2011/02/27 17:33:37 joerg Exp $	*/
2/*	$FreeBSD: stable/11/usr.bin/grep/util.c 322560 2017-08-16 00:47:53Z kevans $	*/
3/*	$OpenBSD: util.c,v 1.39 2010/07/02 22:18:03 tedu Exp $	*/
4
5/*-
6 * Copyright (c) 1999 James Howard and Dag-Erling Co��dan Sm��rgrav
7 * Copyright (C) 2008-2010 Gabor Kovesdan <gabor@FreeBSD.org>
8 * All rights reserved.
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 *
19 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
30 */
31
32#include <sys/cdefs.h>
33__FBSDID("$FreeBSD: stable/11/usr.bin/grep/util.c 322560 2017-08-16 00:47:53Z kevans $");
34
35#include <sys/stat.h>
36#include <sys/types.h>
37
38#include <ctype.h>
39#include <err.h>
40#include <errno.h>
41#include <fnmatch.h>
42#include <fts.h>
43#include <libgen.h>
44#include <stdbool.h>
45#include <stdio.h>
46#include <stdlib.h>
47#include <string.h>
48#include <unistd.h>
49#include <wchar.h>
50#include <wctype.h>
51
52#include "fastmatch.h"
53#include "grep.h"
54
55static int	 linesqueued;
56static int	 procline(struct str *l, int);
57
58bool
59file_matching(const char *fname)
60{
61	char *fname_base;
62	bool ret;
63
64	ret = finclude ? false : true;
65	fname_base = basename(fname);
66
67	for (unsigned int i = 0; i < fpatterns; ++i) {
68		if (fnmatch(fpattern[i].pat, fname, 0) == 0 ||
69		    fnmatch(fpattern[i].pat, fname_base, 0) == 0) {
70			if (fpattern[i].mode == EXCL_PAT)
71				return (false);
72			else
73				ret = true;
74		}
75	}
76	return (ret);
77}
78
79static inline bool
80dir_matching(const char *dname)
81{
82	bool ret;
83
84	ret = dinclude ? false : true;
85
86	for (unsigned int i = 0; i < dpatterns; ++i) {
87		if (dname != NULL &&
88		    fnmatch(dpattern[i].pat, dname, 0) == 0) {
89			if (dpattern[i].mode == EXCL_PAT)
90				return (false);
91			else
92				ret = true;
93		}
94	}
95	return (ret);
96}
97
98/*
99 * Processes a directory when a recursive search is performed with
100 * the -R option.  Each appropriate file is passed to procfile().
101 */
102int
103grep_tree(char **argv)
104{
105	FTS *fts;
106	FTSENT *p;
107	int c, fts_flags;
108	bool ok;
109
110	c = fts_flags = 0;
111
112	switch(linkbehave) {
113	case LINK_EXPLICIT:
114		fts_flags = FTS_COMFOLLOW;
115		break;
116	case LINK_SKIP:
117		fts_flags = FTS_PHYSICAL;
118		break;
119	default:
120		fts_flags = FTS_LOGICAL;
121
122	}
123
124	fts_flags |= FTS_NOSTAT | FTS_NOCHDIR;
125
126	if (!(fts = fts_open(argv, fts_flags, NULL)))
127		err(2, "fts_open");
128	while ((p = fts_read(fts)) != NULL) {
129		switch (p->fts_info) {
130		case FTS_DNR:
131			/* FALLTHROUGH */
132		case FTS_ERR:
133			file_err = true;
134			if(!sflag)
135				warnx("%s: %s", p->fts_path, strerror(p->fts_errno));
136			break;
137		case FTS_D:
138			/* FALLTHROUGH */
139		case FTS_DP:
140			if (dexclude || dinclude)
141				if (!dir_matching(p->fts_name) ||
142				    !dir_matching(p->fts_path))
143					fts_set(fts, p, FTS_SKIP);
144			break;
145		case FTS_DC:
146			/* Print a warning for recursive directory loop */
147			warnx("warning: %s: recursive directory loop",
148				p->fts_path);
149			break;
150		default:
151			/* Check for file exclusion/inclusion */
152			ok = true;
153			if (fexclude || finclude)
154				ok &= file_matching(p->fts_path);
155
156			if (ok)
157				c += procfile(p->fts_path);
158			break;
159		}
160	}
161
162	fts_close(fts);
163	return (c);
164}
165
166/*
167 * Opens a file and processes it.  Each file is processed line-by-line
168 * passing the lines to procline().
169 */
170int
171procfile(const char *fn)
172{
173	struct file *f;
174	struct stat sb;
175	struct str ln;
176	mode_t s;
177	int c, t;
178
179	mcount = mlimit;
180
181	if (strcmp(fn, "-") == 0) {
182		fn = label != NULL ? label : getstr(1);
183		f = grep_open(NULL);
184	} else {
185		if (!stat(fn, &sb)) {
186			/* Check if we need to process the file */
187			s = sb.st_mode & S_IFMT;
188			if (s == S_IFDIR && dirbehave == DIR_SKIP)
189				return (0);
190			if ((s == S_IFIFO || s == S_IFCHR || s == S_IFBLK
191				|| s == S_IFSOCK) && devbehave == DEV_SKIP)
192					return (0);
193		}
194		f = grep_open(fn);
195	}
196	if (f == NULL) {
197		file_err = true;
198		if (!sflag)
199			warn("%s", fn);
200		return (0);
201	}
202
203	ln.file = grep_malloc(strlen(fn) + 1);
204	strcpy(ln.file, fn);
205	ln.line_no = 0;
206	ln.len = 0;
207	linesqueued = 0;
208	tail = 0;
209	ln.off = -1;
210
211	for (c = 0;  c == 0 || !(lflag || qflag); ) {
212		ln.off += ln.len + 1;
213		if ((ln.dat = grep_fgetln(f, &ln.len)) == NULL || ln.len == 0) {
214			if (ln.line_no == 0 && matchall)
215				exit(0);
216			else
217				break;
218		}
219		if (ln.len > 0 && ln.dat[ln.len - 1] == fileeol)
220			--ln.len;
221		ln.line_no++;
222
223		/* Return if we need to skip a binary file */
224		if (f->binary && binbehave == BINFILE_SKIP) {
225			grep_close(f);
226			free(ln.file);
227			free(f);
228			return (0);
229		}
230		/* Process the file line-by-line */
231		if ((t = procline(&ln, f->binary)) == 0 && Bflag > 0) {
232			enqueue(&ln);
233			linesqueued++;
234		}
235		c += t;
236		if (mflag && mcount <= 0)
237			break;
238	}
239	if (Bflag > 0)
240		clearqueue();
241	grep_close(f);
242
243	if (cflag) {
244		if (!hflag)
245			printf("%s:", ln.file);
246		printf("%u\n", c);
247	}
248	if (lflag && !qflag && c != 0)
249		printf("%s%c", fn, nullflag ? 0 : '\n');
250	if (Lflag && !qflag && c == 0)
251		printf("%s%c", fn, nullflag ? 0 : '\n');
252	if (c && !cflag && !lflag && !Lflag &&
253	    binbehave == BINFILE_BIN && f->binary && !qflag)
254		printf(getstr(8), fn);
255
256	free(ln.file);
257	free(f);
258	return (c);
259}
260
261#define iswword(x)	(iswalnum((x)) || (x) == L'_')
262
263/*
264 * Processes a line comparing it with the specified patterns.  Each pattern
265 * is looped to be compared along with the full string, saving each and every
266 * match, which is necessary to colorize the output and to count the
267 * matches.  The matching lines are passed to printline() to display the
268 * appropriate output.
269 */
270static int
271procline(struct str *l, int nottext)
272{
273	regmatch_t matches[MAX_LINE_MATCHES];
274	regmatch_t pmatch, lastmatch;
275	size_t st = 0, nst = 0;
276	unsigned int i;
277	int c = 0, m = 0, r = 0, lastmatches = 0, leflags = eflags;
278	int startm = 0;
279
280	/* Initialize to avoid a false positive warning from GCC. */
281	lastmatch.rm_so = lastmatch.rm_eo = 0;
282
283	/* Loop to process the whole line */
284	while (st <= l->len) {
285		lastmatches = 0;
286		startm = m;
287		if (st > 0)
288			leflags |= REG_NOTBOL;
289		/* Loop to compare with all the patterns */
290		for (i = 0; i < patterns; i++) {
291			pmatch.rm_so = st;
292			pmatch.rm_eo = l->len;
293			if (fg_pattern[i].pattern)
294				r = fastexec(&fg_pattern[i],
295				    l->dat, 1, &pmatch, leflags);
296			else
297				r = regexec(&r_pattern[i], l->dat, 1,
298				    &pmatch, leflags);
299			r = (r == 0) ? 0 : REG_NOMATCH;
300			if (r == REG_NOMATCH)
301				continue;
302			/* Check for full match */
303			if (r == 0 && xflag)
304				if (pmatch.rm_so != 0 ||
305				    (size_t)pmatch.rm_eo != l->len)
306					r = REG_NOMATCH;
307			/* Check for whole word match */
308			if (r == 0 && (wflag || fg_pattern[i].word)) {
309				wchar_t wbegin, wend;
310
311				wbegin = wend = L' ';
312				if (pmatch.rm_so != 0 &&
313				    sscanf(&l->dat[pmatch.rm_so - 1],
314				    "%lc", &wbegin) != 1)
315					r = REG_NOMATCH;
316				else if ((size_t)pmatch.rm_eo !=
317				    l->len &&
318				    sscanf(&l->dat[pmatch.rm_eo],
319				    "%lc", &wend) != 1)
320					r = REG_NOMATCH;
321				else if (iswword(wbegin) ||
322				    iswword(wend))
323					r = REG_NOMATCH;
324			}
325			if (r == 0) {
326				lastmatches++;
327				lastmatch = pmatch;
328				if (m == 0)
329					c++;
330
331				if (m < MAX_LINE_MATCHES) {
332					/* Replace previous match if the new one is earlier and/or longer */
333					if (m > startm) {
334						if (pmatch.rm_so < matches[m-1].rm_so ||
335						    (pmatch.rm_so == matches[m-1].rm_so && (pmatch.rm_eo - pmatch.rm_so) > (matches[m-1].rm_eo - matches[m-1].rm_so))) {
336							matches[m-1] = pmatch;
337							nst = pmatch.rm_eo;
338						}
339					} else {
340						/* Advance as normal if not */
341						matches[m++] = pmatch;
342						nst = pmatch.rm_eo;
343					}
344				}
345
346				/* matches - skip further patterns */
347				if ((color == NULL && !oflag) ||
348				    qflag || lflag)
349					break;
350			}
351		}
352
353		if (vflag) {
354			c = !c;
355			break;
356		}
357
358		/* One pass if we are not recording matches */
359		if (!wflag && ((color == NULL && !oflag) || qflag || lflag || Lflag))
360			break;
361
362		/* If we didn't have any matches or REG_NOSUB set */
363		if (lastmatches == 0 || (cflags & REG_NOSUB))
364			nst = l->len;
365
366		if (lastmatches == 0)
367			/* No matches */
368			break;
369		else if (st == nst && lastmatch.rm_so == lastmatch.rm_eo)
370			/* Zero-length match -- advance one more so we don't get stuck */
371			nst++;
372
373		/* Advance st based on previous matches */
374		st = nst;
375	}
376
377
378	/* Count the matches if we have a match limit */
379	if (mflag)
380		mcount -= c;
381
382	if (c && binbehave == BINFILE_BIN && nottext)
383		return (c); /* Binary file */
384
385	/* Dealing with the context */
386	if ((tail || c) && !cflag && !qflag && !lflag && !Lflag) {
387		if (c) {
388			if (!first && !prev && !tail && Aflag)
389				printf("--\n");
390			tail = Aflag;
391			if (Bflag > 0) {
392				if (!first && !prev)
393					printf("--\n");
394				printqueue();
395			}
396			linesqueued = 0;
397			printline(l, ':', matches, m);
398		} else {
399			printline(l, '-', matches, m);
400			tail--;
401		}
402	}
403
404	if (c) {
405		prev = true;
406		first = false;
407	} else
408		prev = false;
409
410	return (c);
411}
412
413/*
414 * Safe malloc() for internal use.
415 */
416void *
417grep_malloc(size_t size)
418{
419	void *ptr;
420
421	if ((ptr = malloc(size)) == NULL)
422		err(2, "malloc");
423	return (ptr);
424}
425
426/*
427 * Safe calloc() for internal use.
428 */
429void *
430grep_calloc(size_t nmemb, size_t size)
431{
432	void *ptr;
433
434	if ((ptr = calloc(nmemb, size)) == NULL)
435		err(2, "calloc");
436	return (ptr);
437}
438
439/*
440 * Safe realloc() for internal use.
441 */
442void *
443grep_realloc(void *ptr, size_t size)
444{
445
446	if ((ptr = realloc(ptr, size)) == NULL)
447		err(2, "realloc");
448	return (ptr);
449}
450
451/*
452 * Safe strdup() for internal use.
453 */
454char *
455grep_strdup(const char *str)
456{
457	char *ret;
458
459	if ((ret = strdup(str)) == NULL)
460		err(2, "strdup");
461	return (ret);
462}
463
464/*
465 * Prints a matching line according to the command line options.
466 */
467void
468printline(struct str *line, int sep, regmatch_t *matches, int m)
469{
470	size_t a = 0;
471	int i, n = 0;
472
473	/* If matchall, everything matches but don't actually print for -o */
474	if (oflag && matchall)
475		return;
476
477	if (!hflag) {
478		if (!nullflag) {
479			fputs(line->file, stdout);
480			++n;
481		} else {
482			printf("%s", line->file);
483			putchar(0);
484		}
485	}
486	if (nflag) {
487		if (n > 0)
488			putchar(sep);
489		printf("%d", line->line_no);
490		++n;
491	}
492	if (bflag) {
493		if (n > 0)
494			putchar(sep);
495		printf("%lld", (long long)line->off);
496		++n;
497	}
498	if (n)
499		putchar(sep);
500	/* --color and -o */
501	if ((oflag || color) && m > 0) {
502		for (i = 0; i < m; i++) {
503			/* Don't output zero length matches */
504			if (matches[i].rm_so == matches[i].rm_eo)
505				continue;
506			if (!oflag)
507				fwrite(line->dat + a, matches[i].rm_so - a, 1,
508				    stdout);
509			if (color)
510				fprintf(stdout, "\33[%sm\33[K", color);
511
512				fwrite(line->dat + matches[i].rm_so,
513				    matches[i].rm_eo - matches[i].rm_so, 1,
514				    stdout);
515			if (color)
516				fprintf(stdout, "\33[m\33[K");
517			a = matches[i].rm_eo;
518			if (oflag)
519				putchar('\n');
520		}
521		if (!oflag) {
522			if (line->len - a > 0)
523				fwrite(line->dat + a, line->len - a, 1, stdout);
524			putchar('\n');
525		}
526	} else {
527		fwrite(line->dat, line->len, 1, stdout);
528		putchar(fileeol);
529	}
530}
531