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>
52 static int linesqueued;
53 static int procline(struct str *l, int);
56 file_matching(const char *fname)
60 ret = finclude ? false : true;
62 for (unsigned int i = 0; i < fpatterns; ++i) {
63 if (fnmatch(fpattern[i].pat,
64 fname, 0) == 0 || fnmatch(fpattern[i].pat,
65 basename(fname), 0) == 0) {
66 if (fpattern[i].mode == EXCL_PAT)
76 dir_matching(const char *dname)
80 ret = dinclude ? false : true;
82 for (unsigned int i = 0; i < dpatterns; ++i) {
84 fnmatch(dname, dpattern[i].pat, 0) == 0) {
85 if (dpattern[i].mode == EXCL_PAT)
95 * Processes a directory when a recursive search is performed with
96 * the -R option. Each appropriate file is passed to procfile().
99 grep_tree(char **argv)
103 char *d, *dir = NULL;
111 fts_flags = FTS_COMFOLLOW;
114 fts_flags = FTS_PHYSICAL;
117 fts_flags = FTS_LOGICAL;
121 fts_flags |= FTS_NOSTAT | FTS_NOCHDIR;
123 if (!(fts = fts_open(argv, fts_flags, NULL)))
125 while ((p = fts_read(fts)) != NULL) {
126 switch (p->fts_info) {
130 errx(2, "%s: %s", p->fts_path, strerror(p->fts_errno));
137 /* Print a warning for recursive directory loop */
138 warnx("warning: %s: recursive directory loop",
142 /* Check for file exclusion/inclusion */
144 if (dexclude || dinclude) {
145 if ((d = strrchr(p->fts_path, '/')) != NULL) {
146 dir = grep_malloc(sizeof(char) *
147 (d - p->fts_path + 1));
148 memcpy(dir, p->fts_path,
150 dir[d - p->fts_path] = '\0';
152 ok = dir_matching(dir);
156 if (fexclude || finclude)
157 ok &= file_matching(p->fts_path);
160 c += procfile(p->fts_path);
170 * Opens a file and processes it. Each file is processed line-by-line
171 * passing the lines to procline().
174 procfile(const char *fn)
182 if (mflag && (mcount <= 0))
185 if (strcmp(fn, "-") == 0) {
186 fn = label != NULL ? label : getstr(1);
189 if (!stat(fn, &sb)) {
190 /* Check if we need to process the file */
191 s = sb.st_mode & S_IFMT;
192 if (s == S_IFDIR && dirbehave == DIR_SKIP)
194 if ((s == S_IFIFO || s == S_IFCHR || s == S_IFBLK
195 || s == S_IFSOCK) && devbehave == DEV_SKIP)
208 ln.file = grep_malloc(strlen(fn) + 1);
216 for (c = 0; c == 0 || !(lflag || qflag); ) {
217 ln.off += ln.len + 1;
218 if ((ln.dat = grep_fgetln(f, &ln.len)) == NULL || ln.len == 0) {
219 if (ln.line_no == 0 && matchall)
224 if (ln.len > 0 && ln.dat[ln.len - 1] == '\n')
228 /* Return if we need to skip a binary file */
229 if (f->binary && binbehave == BINFILE_SKIP) {
235 /* Process the file line-by-line */
236 if ((t = procline(&ln, f->binary)) == 0 && Bflag > 0) {
242 /* Count the matches if we have a match limit */
255 printf("%s:", ln.file);
258 if (lflag && !qflag && c != 0)
260 if (Lflag && !qflag && c == 0)
262 if (c && !cflag && !lflag && !Lflag &&
263 binbehave == BINFILE_BIN && f->binary && !qflag)
264 printf(getstr(8), fn);
271 #define iswword(x) (iswalnum((x)) || (x) == L'_')
274 * Processes a line comparing it with the specified patterns. Each pattern
275 * is looped to be compared along with the full string, saving each and every
276 * match, which is necessary to colorize the output and to count the
277 * matches. The matching lines are passed to printline() to display the
278 * appropriate output.
281 procline(struct str *l, int nottext)
283 regmatch_t matches[MAX_LINE_MATCHES];
287 int c = 0, m = 0, r = 0;
290 /* Loop to process the whole line */
291 while (st <= l->len) {
293 pmatch.rm_eo = l->len;
295 /* Loop to compare with all the patterns */
296 for (i = 0; i < patterns; i++) {
298 * XXX: grep_search() is a workaround for speed up and should be
299 * removed in the future. See fastgrep.c.
301 if (fg_pattern[i].pattern) {
302 r = grep_search(&fg_pattern[i],
303 (unsigned char *)l->dat,
305 r = (r == 0) ? 0 : REG_NOMATCH;
308 r = regexec(&r_pattern[i], l->dat, 1,
310 r = (r == 0) ? 0 : REG_NOMATCH;
313 if (r == REG_NOMATCH)
315 /* Check for full match */
317 if (pmatch.rm_so != 0 ||
318 (size_t)pmatch.rm_eo != l->len)
320 /* Check for whole word match */
321 if (r == 0 && wflag && pmatch.rm_so != 0) {
324 wbegin = wend = L' ';
325 if (pmatch.rm_so != 0 &&
326 sscanf(&l->dat[pmatch.rm_so - 1],
327 "%lc", &wbegin) != 1)
329 else if ((size_t)pmatch.rm_eo != l->len &&
330 sscanf(&l->dat[pmatch.rm_eo],
333 else if (iswword(wbegin) || iswword(wend))
339 if (m < MAX_LINE_MATCHES)
340 matches[m++] = pmatch;
341 /* matches - skip further patterns */
342 if ((color != NULL && !oflag) || qflag || lflag)
351 /* One pass if we are not recording matches */
352 if ((color != NULL && !oflag) || qflag || lflag)
355 if (st == (size_t)pmatch.rm_so)
356 break; /* No matches */
361 if (c && binbehave == BINFILE_BIN && nottext)
362 return (c); /* Binary file */
364 /* Dealing with the context */
365 if ((tail || c) && !cflag && !qflag && !lflag && !Lflag) {
367 if (!first && !prev && !tail && Aflag)
376 printline(l, ':', matches, m);
378 printline(l, '-', matches, m);
393 * Safe malloc() for internal use.
396 grep_malloc(size_t size)
400 if ((ptr = malloc(size)) == NULL)
406 * Safe calloc() for internal use.
409 grep_calloc(size_t nmemb, size_t size)
413 if ((ptr = calloc(nmemb, size)) == NULL)
419 * Safe realloc() for internal use.
422 grep_realloc(void *ptr, size_t size)
425 if ((ptr = realloc(ptr, size)) == NULL)
431 * Safe strdup() for internal use.
434 grep_strdup(const char *str)
438 if ((ret = strdup(str)) == NULL)
444 * Prints a matching line according to the command line options.
447 printline(struct str *line, int sep, regmatch_t *matches, int m)
454 fputs(line->file, stdout);
456 printf("%s", line->file);
464 printf("%d", line->line_no);
470 printf("%lld", (long long)line->off);
476 if ((oflag || color) && m > 0) {
477 for (i = 0; i < m; i++) {
479 fwrite(line->dat + a, matches[i].rm_so - a, 1,
482 fprintf(stdout, "\33[%sm\33[K", color);
484 fwrite(line->dat + matches[i].rm_so,
485 matches[i].rm_eo - matches[i].rm_so, 1,
488 fprintf(stdout, "\33[m\33[K");
489 a = matches[i].rm_eo;
494 if (line->len - a > 0)
495 fwrite(line->dat + a, line->len - a, 1, stdout);
499 fwrite(line->dat, line->len, 1, stdout);