1 /* $OpenBSD: util.c,v 1.39 2010/07/02 22:18:03 tedu Exp $ */
4 * Copyright (c) 1999 James Howard and Dag-Erling Coïdan Smørgrav
5 * Copyright (C) 2008-2010 Gabor Kovesdan <gabor@FreeBSD.org>
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
34 #include <sys/types.h>
51 static int linesqueued;
52 static int procline(struct str *l, int);
55 * Processes a directory when a recursive search is performed with
56 * the -R option. Each appropriate file is passed to procfile().
59 grep_tree(char **argv)
72 fts_flags = FTS_COMFOLLOW;
75 fts_flags = FTS_PHYSICAL;
78 fts_flags = FTS_LOGICAL;
82 fts_flags |= FTS_NOSTAT | FTS_NOCHDIR;
84 if (!(fts = fts_open(argv, fts_flags, NULL)))
86 while ((p = fts_read(fts)) != NULL) {
87 switch (p->fts_info) {
91 errx(2, "%s: %s", p->fts_path, strerror(p->fts_errno));
98 /* Print a warning for recursive directory loop */
99 warnx("warning: %s: recursive directory loop",
103 /* Check for file exclusion/inclusion */
106 d = strrchr(p->fts_path, '/');
107 dir = grep_malloc(sizeof(char) *
108 (d - p->fts_path + 2));
109 strlcpy(dir, p->fts_path,
110 (d - p->fts_path + 1));
111 for (i = 0; i < epatterns; ++i) {
112 switch(epattern[i].type) {
114 if (fnmatch(epattern[i].pat,
115 basename(p->fts_path), 0) == 0)
116 ok = epattern[i].mode != EXCL_PAT;
120 epattern[i].pat) != NULL)
121 ok = epattern[i].mode != EXCL_PAT;
129 c += procfile(p->fts_path);
138 * Opens a file and processes it. Each file is processed line-by-line
139 * passing the lines to procline().
142 procfile(const char *fn)
150 if (mflag && (mcount <= 0))
153 if (strcmp(fn, "-") == 0) {
154 fn = label != NULL ? label : getstr(1);
155 f = grep_stdin_open();
157 if (!stat(fn, &sb)) {
158 /* Check if we need to process the file */
159 s = sb.st_mode & S_IFMT;
160 if (s == S_IFDIR && dirbehave == DIR_SKIP)
162 if ((s == S_IFIFO || s == S_IFCHR || s == S_IFBLK
163 || s == S_IFSOCK) && devbehave == DEV_SKIP)
176 ln.file = grep_malloc(strlen(fn) + 1);
184 for (c = 0; c == 0 || !(lflag || qflag); ) {
185 ln.off += ln.len + 1;
186 if ((ln.dat = grep_fgetln(f, &ln.len)) == NULL) {
187 if (ln.line_no == 0 && matchall)
192 if (ln.len > 0 && ln.dat[ln.len - 1] == '\n')
196 /* Return if we need to skip a binary file */
197 if (f->binary && binbehave == BINFILE_SKIP) {
202 /* Process the file line-by-line */
203 if ((t = procline(&ln, f->binary)) == 0 && Bflag > 0) {
209 /* Count the matches if we have a match limit */
222 printf("%s:", ln.file);
229 if (c && !cflag && !lflag && !Lflag &&
230 binbehave == BINFILE_BIN && f->binary && !qflag)
231 printf(getstr(9), fn);
237 #define iswword(x) (iswalnum((x)) || (x) == L'_')
240 * Processes a line comparing it with the specified patterns. Each pattern
241 * is looped to be compared along with the full string, saving each and every
242 * match, which is necessary to colorize the output and to count the
243 * matches. The matching lines are passed to printline() to display the
244 * appropriate output.
247 procline(struct str *l, int nottext)
249 regmatch_t matches[MAX_LINE_MATCHES];
253 int c = 0, m = 0, r = 0;
256 /* Loop to process the whole line */
257 while (st <= l->len) {
259 pmatch.rm_eo = l->len;
261 /* Loop to compare with all the patterns */
262 for (i = 0; i < patterns; i++) {
264 * XXX: grep_search() is a workaround for speed up and should be
265 * removed in the future. See fastgrep.c.
267 if (fg_pattern[i].pattern) {
268 r = grep_search(&fg_pattern[i],
269 (unsigned char *)l->dat,
271 r = (r == 0) ? 0 : REG_NOMATCH;
274 r = regexec(&r_pattern[i], l->dat, 1,
276 r = (r == 0) ? 0 : REG_NOMATCH;
279 if (r == REG_NOMATCH)
281 /* Check for full match */
283 if (pmatch.rm_so != 0 ||
284 (size_t)pmatch.rm_eo != l->len)
286 /* Check for whole word match */
287 if (r == 0 && wflag && pmatch.rm_so != 0 &&
288 (size_t)pmatch.rm_eo != l->len) {
293 size = mbstowcs(NULL, l->dat,
296 if (size == ((size_t) - 1))
299 wbegin = grep_malloc(size);
300 if (mbstowcs(wbegin, l->dat,
301 pmatch.rm_so) == ((size_t) - 1))
303 else if (sscanf(&l->dat[pmatch.rm_eo],
306 else if (iswword(wbegin[wcslen(wbegin)]) ||
315 if (m < MAX_LINE_MATCHES)
316 matches[m++] = pmatch;
317 /* matches - skip further patterns */
326 /* One pass if we are not recording matches */
327 if (!oflag && !color)
330 if (st == (size_t)pmatch.rm_so)
331 break; /* No matches */
336 if (c && binbehave == BINFILE_BIN && nottext)
337 return (c); /* Binary file */
339 /* Dealing with the context */
340 if ((tail || c) && !cflag && !qflag) {
342 if (!first && !prev && !tail && Aflag)
351 printline(l, ':', matches, m);
353 printline(l, '-', matches, m);
368 * Safe malloc() for internal use.
371 grep_malloc(size_t size)
375 if ((ptr = malloc(size)) == NULL)
381 * Safe calloc() for internal use.
384 grep_calloc(size_t nmemb, size_t size)
388 if ((ptr = calloc(nmemb, size)) == NULL)
394 * Safe realloc() for internal use.
397 grep_realloc(void *ptr, size_t size)
400 if ((ptr = realloc(ptr, size)) == NULL)
406 * Prints a matching line according to the command line options.
409 printline(struct str *line, int sep, regmatch_t *matches, int m)
416 fputs(line->file, stdout);
418 printf("%s", line->file);
426 printf("%d", line->line_no);
432 printf("%lld", (long long)line->off);
438 if ((oflag || color) && m > 0) {
439 for (i = 0; i < m; i++) {
441 fwrite(line->dat + a, matches[i].rm_so - a, 1,
444 fprintf(stdout, "\33[%sm\33[K", color);
446 fwrite(line->dat + matches[i].rm_so,
447 matches[i].rm_eo - matches[i].rm_so, 1,
450 fprintf(stdout, "\33[m\33[K");
451 a = matches[i].rm_eo;
456 if (line->len - a > 0)
457 fwrite(line->dat + a, line->len - a, 1, stdout);
461 fwrite(line->dat, line->len, 1, stdout);