xref: /netbsd-src/usr.bin/grep/util.c (revision 1b9578b8c2c1f848eeb16dabbfd7d1f0d9fdefbd)
1 /*	$NetBSD: util.c,v 1.13 2011/04/18 23:22:42 joerg Exp $	*/
2 /*	$FreeBSD: head/usr.bin/grep/util.c 211496 2010-08-19 09:28:59Z des $	*/
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 #if HAVE_NBTOOL_CONFIG_H
33 #include "nbtool_config.h"
34 #endif
35 
36 #include <sys/cdefs.h>
37 __RCSID("$NetBSD: util.c,v 1.13 2011/04/18 23:22:42 joerg Exp $");
38 
39 #include <sys/stat.h>
40 #include <sys/types.h>
41 
42 #include <ctype.h>
43 #include <err.h>
44 #include <errno.h>
45 #include <fnmatch.h>
46 #include <fts.h>
47 #include <libgen.h>
48 #include <stdbool.h>
49 #include <stdio.h>
50 #include <stdlib.h>
51 #include <string.h>
52 #include <unistd.h>
53 #include <wchar.h>
54 #include <wctype.h>
55 
56 #include "grep.h"
57 
58 static bool	 first, first_global = true;
59 static unsigned long long since_printed;
60 
61 static int	 procline(struct str *l, int);
62 
63 bool
64 file_matching(const char *fname)
65 {
66 	char *fname_base, *fname_copy;
67 	unsigned int i;
68 	bool ret;
69 
70 	ret = finclude ? false : true;
71 	fname_copy = grep_strdup(fname);
72 	fname_base = basename(fname_copy);
73 
74 	for (i = 0; i < fpatterns; ++i) {
75 		if (fnmatch(fpattern[i].pat, fname, 0) == 0 ||
76 		    fnmatch(fpattern[i].pat, fname_base, 0) == 0) {
77 			if (fpattern[i].mode == EXCL_PAT)
78 				return (false);
79 			else
80 				ret = true;
81 		}
82 	}
83 	free(fname_copy);
84 	return (ret);
85 }
86 
87 static inline bool
88 dir_matching(const char *dname)
89 {
90 	unsigned int i;
91 	bool ret;
92 
93 	ret = dinclude ? false : true;
94 
95 	for (i = 0; i < dpatterns; ++i) {
96 		if (dname != NULL &&
97 		    fnmatch(dname, dpattern[i].pat, 0) == 0) {
98 			if (dpattern[i].mode == EXCL_PAT)
99 				return (false);
100 			else
101 				ret = true;
102 		}
103 	}
104 	return (ret);
105 }
106 
107 /*
108  * Processes a directory when a recursive search is performed with
109  * the -R option.  Each appropriate file is passed to procfile().
110  */
111 int
112 grep_tree(char **argv)
113 {
114 	FTS *fts;
115 	FTSENT *p;
116 	char *d, *dir = NULL;
117 	int c, fts_flags;
118 	bool ok;
119 
120 	c = fts_flags = 0;
121 
122 	switch(linkbehave) {
123 	case LINK_EXPLICIT:
124 		fts_flags = FTS_COMFOLLOW;
125 		break;
126 	case LINK_SKIP:
127 		fts_flags = FTS_PHYSICAL;
128 		break;
129 	default:
130 		fts_flags = FTS_LOGICAL;
131 
132 	}
133 
134 	fts_flags |= FTS_NOSTAT | FTS_NOCHDIR;
135 
136 	if (!(fts = fts_open(argv, fts_flags, NULL)))
137 		err(2, "fts_open");
138 	while ((p = fts_read(fts)) != NULL) {
139 		switch (p->fts_info) {
140 		case FTS_DNR:
141 			/* FALLTHROUGH */
142 		case FTS_ERR:
143 			errx(2, "%s: %s", p->fts_path, strerror(p->fts_errno));
144 			break;
145 		case FTS_D:
146 			/* FALLTHROUGH */
147 		case FTS_DP:
148 			break;
149 		case FTS_DC:
150 			/* Print a warning for recursive directory loop */
151 			warnx("warning: %s: recursive directory loop",
152 				p->fts_path);
153 			break;
154 		default:
155 			/* Check for file exclusion/inclusion */
156 			ok = true;
157 			if (dexclude || dinclude) {
158 				if ((d = strrchr(p->fts_path, '/')) != NULL) {
159 					dir = grep_malloc(sizeof(char) *
160 					    (d - p->fts_path + 1));
161 					memcpy(dir, p->fts_path,
162 					    d - p->fts_path);
163 					dir[d - p->fts_path] = '\0';
164 				}
165 				ok = dir_matching(dir);
166 				free(dir);
167 				dir = NULL;
168 			}
169 			if (fexclude || finclude)
170 				ok &= file_matching(p->fts_path);
171 
172 			if (ok)
173 				c += procfile(p->fts_path);
174 			break;
175 		}
176 	}
177 
178 	fts_close(fts);
179 	return (c);
180 }
181 
182 /*
183  * Opens a file and processes it.  Each file is processed line-by-line
184  * passing the lines to procline().
185  */
186 int
187 procfile(const char *fn)
188 {
189 	struct file *f;
190 	struct stat sb;
191 	struct str ln;
192 	mode_t s;
193 	int c, t;
194 
195 	if (mflag && (mcount <= 0))
196 		return (0);
197 
198 	if (strcmp(fn, "-") == 0) {
199 		fn = label != NULL ? label : getstr(1);
200 		f = grep_open(NULL);
201 	} else {
202 		if (!stat(fn, &sb)) {
203 			/* Check if we need to process the file */
204 			s = sb.st_mode & S_IFMT;
205 			if (s == S_IFDIR && dirbehave == DIR_SKIP)
206 				return (0);
207 			if ((s == S_IFIFO || s == S_IFCHR || s == S_IFBLK
208 				|| s == S_IFSOCK) && devbehave == DEV_SKIP)
209 					return (0);
210 		}
211 		f = grep_open(fn);
212 	}
213 	if (f == NULL) {
214 		if (!sflag)
215 			warn("%s", fn);
216 		if (errno == ENOENT)
217 			notfound = true;
218 		return (0);
219 	}
220 
221 	ln.file = grep_malloc(strlen(fn) + 1);
222 	strcpy(ln.file, fn);
223 	ln.line_no = 0;
224 	ln.len = 0;
225 	tail = 0;
226 	ln.off = -1;
227 
228 	for (first = true, c = 0;  c == 0 || !(lflag || qflag); ) {
229 		ln.off += ln.len + 1;
230 		if ((ln.dat = grep_fgetln(f, &ln.len)) == NULL || ln.len == 0) {
231 			if (ln.line_no == 0 && matchall)
232 				exit(0);
233 			else
234 				break;
235 		}
236 		if (ln.len > 0 && ln.dat[ln.len - 1] == line_sep)
237 			--ln.len;
238 		ln.line_no++;
239 
240 		/* Return if we need to skip a binary file */
241 		if (f->binary && binbehave == BINFILE_SKIP) {
242 			grep_close(f);
243 			free(ln.file);
244 			free(f);
245 			return (0);
246 		}
247 		/* Process the file line-by-line */
248 		t = procline(&ln, f->binary);
249 		c += t;
250 
251 		/* Count the matches if we have a match limit */
252 		if (mflag) {
253 			mcount -= t;
254 			if (mcount <= 0)
255 				break;
256 		}
257 	}
258 	if (Bflag > 0)
259 		clearqueue();
260 	grep_close(f);
261 
262 	if (cflag) {
263 		if (!hflag)
264 			printf("%s:", ln.file);
265 		printf("%u%c", c, line_sep);
266 	}
267 	if (lflag && !qflag && c != 0)
268 		printf("%s%c", fn, line_sep);
269 	if (Lflag && !qflag && c == 0)
270 		printf("%s%c", fn, line_sep);
271 	if (c && !cflag && !lflag && !Lflag &&
272 	    binbehave == BINFILE_BIN && f->binary && !qflag)
273 		printf(getstr(8), fn);
274 
275 	free(ln.file);
276 	free(f);
277 	return (c);
278 }
279 
280 #define iswword(x)	(iswalnum((x)) || (x) == L'_')
281 
282 /*
283  * Processes a line comparing it with the specified patterns.  Each pattern
284  * is looped to be compared along with the full string, saving each and every
285  * match, which is necessary to colorize the output and to count the
286  * matches.  The matching lines are passed to printline() to display the
287  * appropriate output.
288  */
289 static int
290 procline(struct str *l, int nottext)
291 {
292 	regmatch_t matches[MAX_LINE_MATCHES];
293 	regmatch_t pmatch;
294 	size_t st = 0;
295 	unsigned int i;
296 	int c = 0, m = 0, r = 0;
297 
298 	if (!matchall) {
299 		/* Loop to process the whole line */
300 		while (st <= l->len) {
301 			pmatch.rm_so = st;
302 			pmatch.rm_eo = l->len;
303 
304 			/* Loop to compare with all the patterns */
305 			for (i = 0; i < patterns; i++) {
306 /*
307  * XXX: grep_search() is a workaround for speed up and should be
308  * removed in the future.  See fastgrep.c.
309  */
310 				if (fg_pattern[i].pattern) {
311 					r = grep_search(&fg_pattern[i],
312 					    (unsigned char *)l->dat,
313 					    l->len, &pmatch);
314 					r = (r == 0) ? 0 : REG_NOMATCH;
315 					st = pmatch.rm_eo;
316 				} else {
317 					r = regexec(&r_pattern[i], l->dat, 1,
318 					    &pmatch, eflags);
319 					r = (r == 0) ? 0 : REG_NOMATCH;
320 					st = pmatch.rm_eo;
321 				}
322 				if (r == REG_NOMATCH)
323 					continue;
324 				/* Check for full match */
325 				if (r == 0 && xflag)
326 					if (pmatch.rm_so != 0 ||
327 					    (size_t)pmatch.rm_eo != l->len)
328 						r = REG_NOMATCH;
329 				/* Check for whole word match */
330 				if (r == 0 && fg_pattern[i].word &&
331 				    pmatch.rm_so != 0) {
332 					wint_t wbegin, wend;
333 
334 					wbegin = wend = L' ';
335 					if (pmatch.rm_so != 0 &&
336 					    sscanf(&l->dat[pmatch.rm_so - 1],
337 					    "%lc", &wbegin) != 1)
338 						r = REG_NOMATCH;
339 					else if ((size_t)pmatch.rm_eo != l->len &&
340 					    sscanf(&l->dat[pmatch.rm_eo],
341 					    "%lc", &wend) != 1)
342 						r = REG_NOMATCH;
343 					else if (iswword(wbegin) || iswword(wend))
344 						r = REG_NOMATCH;
345 				}
346 				if (r == 0) {
347 					if (m == 0)
348 						c++;
349 					if (m < MAX_LINE_MATCHES)
350 						matches[m++] = pmatch;
351 					/* matches - skip further patterns */
352 					if ((color != NULL && !oflag) || qflag || lflag)
353 						break;
354 				}
355 			}
356 
357 			if (vflag) {
358 				c = !c;
359 				break;
360 			}
361 			/* One pass if we are not recording matches */
362 			if ((color != NULL && !oflag) || qflag || lflag)
363 				break;
364 
365 			if (st == (size_t)pmatch.rm_so)
366 				break; 	/* No matches */
367 		}
368 	} else
369 		c = !vflag;
370 
371 	if (c && binbehave == BINFILE_BIN && nottext)
372 		return (c); /* Binary file */
373 
374 	/* Dealing with the context */
375 	if ((tail || c) && !cflag && !qflag && !lflag && !Lflag) {
376 		if (c) {
377 			if ((Aflag || Bflag) && !first_global &&
378 			    (first || since_printed > Bflag))
379 				printf("--\n");
380 			tail = Aflag;
381 			if (Bflag > 0)
382 				printqueue();
383 			printline(l, ':', matches, m);
384 		} else {
385 			printline(l, '-', matches, m);
386 			tail--;
387 		}
388 		first = false;
389 		first_global = false;
390 		since_printed = 0;
391 	} else {
392 		if (Bflag)
393 			enqueue(l);
394 		since_printed++;
395 	}
396 	return (c);
397 }
398 
399 /*
400  * Safe malloc() for internal use.
401  */
402 void *
403 grep_malloc(size_t size)
404 {
405 	void *ptr;
406 
407 	if ((ptr = malloc(size)) == NULL)
408 		err(2, "malloc");
409 	return (ptr);
410 }
411 
412 /*
413  * Safe calloc() for internal use.
414  */
415 void *
416 grep_calloc(size_t nmemb, size_t size)
417 {
418 	void *ptr;
419 
420 	if ((ptr = calloc(nmemb, size)) == NULL)
421 		err(2, "calloc");
422 	return (ptr);
423 }
424 
425 /*
426  * Safe realloc() for internal use.
427  */
428 void *
429 grep_realloc(void *ptr, size_t size)
430 {
431 
432 	if ((ptr = realloc(ptr, size)) == NULL)
433 		err(2, "realloc");
434 	return (ptr);
435 }
436 
437 /*
438  * Safe strdup() for internal use.
439  */
440 char *
441 grep_strdup(const char *str)
442 {
443 	char *ret;
444 
445 	if ((ret = strdup(str)) == NULL)
446 		err(2, "strdup");
447 	return (ret);
448 }
449 
450 /*
451  * Prints a matching line according to the command line options.
452  */
453 void
454 printline(struct str *line, int sep, regmatch_t *matches, int m)
455 {
456 	size_t a = 0;
457 	int i, n = 0;
458 
459 	if (!hflag) {
460 		if (nullflag == 0)
461 			fputs(line->file, stdout);
462 		else {
463 			printf("%s", line->file);
464 			putchar(0);
465 		}
466 		++n;
467 	}
468 	if (nflag) {
469 		if (n > 0)
470 			putchar(sep);
471 		printf("%d", line->line_no);
472 		++n;
473 	}
474 	if (bflag) {
475 		if (n > 0)
476 			putchar(sep);
477 		printf("%lld", (long long)line->off);
478 		++n;
479 	}
480 	if (n)
481 		putchar(sep);
482 	/* --color and -o */
483 	if ((oflag || color) && m > 0) {
484 		for (i = 0; i < m; i++) {
485 			if (!oflag)
486 				fwrite(line->dat + a, matches[i].rm_so - a, 1,
487 				    stdout);
488 			if (color)
489 				fprintf(stdout, "\33[%sm\33[K", color);
490 
491 				fwrite(line->dat + matches[i].rm_so,
492 				    matches[i].rm_eo - matches[i].rm_so, 1,
493 				    stdout);
494 			if (color)
495 				fprintf(stdout, "\33[m\33[K");
496 			a = matches[i].rm_eo;
497 			if (oflag)
498 				putchar('\n');
499 		}
500 		if (!oflag) {
501 			if (line->len - a > 0)
502 				fwrite(line->dat + a, line->len - a, 1, stdout);
503 			putchar(line_sep);
504 		}
505 	} else {
506 		fwrite(line->dat, line->len, 1, stdout);
507 		putchar(line_sep);
508 	}
509 }
510