Merge commit 'bf62a5c5b223db5d80a4a241cf0cfb34f8c8ca73'
[unleashed.git] / bin / grep / util.c
bloba25c57eabaff1e45cb5bc564ca5c0bd334cd945d
1 /* $NetBSD: util.c,v 1.9 2011/02/27 17:33:37 joerg Exp $ */
2 /* $FreeBSD$ */
3 /* $OpenBSD: util.c,v 1.39 2010/07/02 22:18:03 tedu Exp $ */
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 * Copyright (C) 2017 Kyle Evans <kevans@FreeBSD.org>
9 * All rights reserved.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
20 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
33 #include <sys/stat.h>
34 #include <sys/types.h>
36 #include <ctype.h>
37 #include <err.h>
38 #include <errno.h>
39 #include <fnmatch.h>
40 #include <fts.h>
41 #include <libgen.h>
42 #include <stdbool.h>
43 #include <stdio.h>
44 #include <stdlib.h>
45 #include <string.h>
46 #include <unistd.h>
47 #include <wchar.h>
48 #include <wctype.h>
50 #ifndef WITHOUT_FASTMATCH
51 #include "fastmatch.h"
52 #endif
53 #include "grep.h"
54 #include "freebsd-compat.h"
56 static bool first_match = true;
59 * Parsing context; used to hold things like matches made and
60 * other useful bits
62 struct parsec {
63 regmatch_t matches[MAX_MATCHES]; /* Matches made */
64 struct str ln; /* Current line */
65 size_t lnstart; /* Position in line */
66 size_t matchidx; /* Latest match index */
67 int printed; /* Metadata printed? */
68 bool binary; /* Binary file? */
71 #ifdef WITH_INTERNAL_NOSPEC
72 static int litexec(const struct pat *pat, const char *string,
73 size_t nmatch, regmatch_t pmatch[]);
74 #endif
75 static int procline(struct parsec *pc);
76 static void printline(struct parsec *pc, int sep);
77 static void printline_metadata(struct str *line, int sep);
79 bool
80 file_matching(const char *fname)
82 char *fname_base, *fname_buf;
83 bool ret;
85 ret = finclude ? false : true;
86 fname_buf = strdup(fname);
87 if (fname_buf == NULL)
88 err(2, "strdup");
89 fname_base = basename(fname_buf);
91 for (unsigned int i = 0; i < fpatterns; ++i) {
92 if (fnmatch(fpattern[i].pat, fname, 0) == 0 ||
93 fnmatch(fpattern[i].pat, fname_base, 0) == 0) {
94 if (fpattern[i].mode == EXCL_PAT) {
95 ret = false;
96 break;
97 } else
98 ret = true;
101 free(fname_buf);
102 return (ret);
105 static inline bool
106 dir_matching(const char *dname)
108 bool ret;
110 ret = dinclude ? false : true;
112 for (unsigned int i = 0; i < dpatterns; ++i) {
113 if (dname != NULL &&
114 fnmatch(dpattern[i].pat, dname, 0) == 0) {
115 if (dpattern[i].mode == EXCL_PAT)
116 return (false);
117 else
118 ret = true;
121 return (ret);
125 * Processes a directory when a recursive search is performed with
126 * the -R option. Each appropriate file is passed to procfile().
129 grep_tree(char **argv)
131 FTS *fts;
132 FTSENT *p;
133 int c, fts_flags;
134 bool ok;
135 const char *wd[] = { ".", NULL };
137 c = fts_flags = 0;
139 switch(linkbehave) {
140 case LINK_EXPLICIT:
141 fts_flags = FTS_COMFOLLOW;
142 break;
143 case LINK_SKIP:
144 fts_flags = FTS_PHYSICAL;
145 break;
146 default:
147 fts_flags = FTS_LOGICAL;
151 fts_flags |= FTS_NOSTAT | FTS_NOCHDIR;
153 fts = fts_open((argv[0] == NULL) ?
154 __DECONST(char * const *, wd) : argv, fts_flags, NULL);
155 if (fts == NULL)
156 err(2, "fts_open");
157 while ((p = fts_read(fts)) != NULL) {
158 switch (p->fts_info) {
159 case FTS_DNR:
160 /* FALLTHROUGH */
161 case FTS_ERR:
162 file_err = true;
163 if(!sflag)
164 warnx("%s: %s", p->fts_path, strerror(p->fts_errno));
165 break;
166 case FTS_D:
167 /* FALLTHROUGH */
168 case FTS_DP:
169 if (dexclude || dinclude)
170 if (!dir_matching(p->fts_name) ||
171 !dir_matching(p->fts_path))
172 fts_set(fts, p, FTS_SKIP);
173 break;
174 case FTS_DC:
175 /* Print a warning for recursive directory loop */
176 warnx("warning: %s: recursive directory loop",
177 p->fts_path);
178 break;
179 default:
180 /* Check for file exclusion/inclusion */
181 ok = true;
182 if (fexclude || finclude)
183 ok &= file_matching(p->fts_path);
185 if (ok)
186 c += procfile(p->fts_path);
187 break;
191 fts_close(fts);
192 return (c);
196 * Opens a file and processes it. Each file is processed line-by-line
197 * passing the lines to procline().
200 procfile(const char *fn)
202 struct parsec pc;
203 long long tail;
204 struct file *f;
205 struct stat sb;
206 struct str *ln;
207 mode_t s;
208 int c, last_outed, t;
209 bool doctx, printmatch, same_file;
211 if (strcmp(fn, "-") == 0) {
212 fn = label != NULL ? label : getstr(1);
213 f = grep_open(NULL);
214 } else {
215 if (!stat(fn, &sb)) {
216 /* Check if we need to process the file */
217 s = sb.st_mode & S_IFMT;
218 if (s == S_IFDIR && dirbehave == DIR_SKIP)
219 return (0);
220 if ((s == S_IFIFO || s == S_IFCHR || s == S_IFBLK
221 || s == S_IFSOCK) && devbehave == DEV_SKIP)
222 return (0);
224 f = grep_open(fn);
226 if (f == NULL) {
227 file_err = true;
228 if (!sflag)
229 warn("%s", fn);
230 return (0);
233 /* Convenience */
234 ln = &pc.ln;
235 pc.ln.file = grep_malloc(strlen(fn) + 1);
236 strcpy(pc.ln.file, fn);
237 pc.ln.line_no = 0;
238 pc.ln.len = 0;
239 pc.ln.boff = 0;
240 pc.ln.off = -1;
241 pc.binary = f->binary;
242 pc.printed = 0;
243 tail = 0;
244 last_outed = 0;
245 same_file = false;
246 doctx = false;
247 printmatch = true;
248 if ((pc.binary && binbehave == BINFILE_BIN) || cflag || qflag ||
249 lflag || Lflag)
250 printmatch = false;
251 if (printmatch && (Aflag != 0 || Bflag != 0))
252 doctx = true;
253 mcount = mlimit;
255 for (c = 0; c == 0 || !(lflag || qflag); ) {
256 /* Reset per-line statistics */
257 pc.printed = 0;
258 pc.matchidx = 0;
259 pc.lnstart = 0;
260 pc.ln.boff = 0;
261 pc.ln.off += pc.ln.len + 1;
262 if ((pc.ln.dat = grep_fgetln(f, &pc.ln.len)) == NULL ||
263 pc.ln.len == 0)
264 break;
266 if (pc.ln.len > 0 && pc.ln.dat[pc.ln.len - 1] == fileeol)
267 --pc.ln.len;
268 pc.ln.line_no++;
270 /* Return if we need to skip a binary file */
271 if (pc.binary && binbehave == BINFILE_SKIP) {
272 grep_close(f);
273 free(pc.ln.file);
274 free(f);
275 return (0);
278 if ((t = procline(&pc)) == 0)
279 ++c;
281 /* Deal with any -B context or context separators */
282 if (t == 0 && doctx) {
283 if (!first_match && (!same_file || last_outed > 0))
284 printf("--\n");
285 if (Bflag > 0)
286 printqueue();
287 tail = Aflag;
289 /* Print the matching line, but only if not quiet/binary */
290 if (t == 0 && printmatch) {
291 printline(&pc, ':');
292 while (pc.matchidx >= MAX_MATCHES) {
293 /* Reset matchidx and try again */
294 pc.matchidx = 0;
295 if (procline(&pc) == 0)
296 printline(&pc, ':');
297 else
298 break;
300 first_match = false;
301 same_file = true;
302 last_outed = 0;
304 if (t != 0 && doctx) {
305 /* Deal with any -A context */
306 if (tail > 0) {
307 grep_printline(&pc.ln, '-');
308 tail--;
309 if (Bflag > 0)
310 clearqueue();
311 } else {
313 * Enqueue non-matching lines for -B context.
314 * If we're not actually doing -B context or if
315 * the enqueue resulted in a line being rotated
316 * out, then go ahead and increment last_outed
317 * to signify a gap between context/match.
319 if (Bflag == 0 || (Bflag > 0 && enqueue(ln)))
320 ++last_outed;
324 /* Count the matches if we have a match limit */
325 if (t == 0 && mflag) {
326 --mcount;
327 if (mflag && mcount <= 0)
328 break;
332 if (Bflag > 0)
333 clearqueue();
334 grep_close(f);
336 if (cflag) {
337 if (!hflag)
338 printf("%s:", pc.ln.file);
339 printf("%u\n", c);
341 if (lflag && !qflag && c != 0)
342 printf("%s%c", fn, nullflag ? 0 : '\n');
343 if (Lflag && !qflag && c == 0)
344 printf("%s%c", fn, nullflag ? 0 : '\n');
345 if (c && !cflag && !lflag && !Lflag &&
346 binbehave == BINFILE_BIN && f->binary && !qflag)
347 printf(getstr(8), fn);
349 free(pc.ln.file);
350 free(f);
351 return (c);
354 #ifdef WITH_INTERNAL_NOSPEC
356 * Internal implementation of literal string search within a string, modeled
357 * after regexec(3), for use when the regex(3) implementation doesn't offer
358 * either REG_NOSPEC or REG_LITERAL. This does not apply in the default FreeBSD
359 * config, but in other scenarios such as building against libgnuregex or on
360 * some non-FreeBSD OSes.
362 static int
363 litexec(const struct pat *pat, const char *string, size_t nmatch,
364 regmatch_t pmatch[])
366 char *(*strstr_fn)(const char *, const char *);
367 char *sub, *subject;
368 const char *search;
369 size_t idx, n, ofs, stringlen;
371 if (cflags & REG_ICASE)
372 strstr_fn = strcasestr;
373 else
374 strstr_fn = strstr;
375 idx = 0;
376 ofs = pmatch[0].rm_so;
377 stringlen = pmatch[0].rm_eo;
378 if (ofs >= stringlen)
379 return (REG_NOMATCH);
380 subject = strndup(string, stringlen);
381 if (subject == NULL)
382 return (REG_ESPACE);
383 for (n = 0; ofs < stringlen;) {
384 search = (subject + ofs);
385 if ((unsigned long)pat->len > strlen(search))
386 break;
387 sub = strstr_fn(search, pat->pat);
389 * Ignoring the empty string possibility due to context: grep optimizes
390 * for empty patterns and will never reach this point.
392 if (sub == NULL)
393 break;
394 ++n;
395 /* Fill in pmatch if necessary */
396 if (nmatch > 0) {
397 pmatch[idx].rm_so = ofs + (sub - search);
398 pmatch[idx].rm_eo = pmatch[idx].rm_so + pat->len;
399 if (++idx == nmatch)
400 break;
401 ofs = pmatch[idx].rm_so + 1;
402 } else
403 /* We only needed to know if we match or not */
404 break;
406 free(subject);
407 if (n > 0 && nmatch > 0)
408 for (n = idx; n < nmatch; ++n)
409 pmatch[n].rm_so = pmatch[n].rm_eo = -1;
411 return (n > 0 ? 0 : REG_NOMATCH);
413 #endif /* WITH_INTERNAL_NOSPEC */
415 #define iswword(x) (iswalnum((x)) || (x) == L'_')
418 * Processes a line comparing it with the specified patterns. Each pattern
419 * is looped to be compared along with the full string, saving each and every
420 * match, which is necessary to colorize the output and to count the
421 * matches. The matching lines are passed to printline() to display the
422 * appropriate output.
424 static int
425 procline(struct parsec *pc)
427 regmatch_t pmatch, lastmatch, chkmatch;
428 wchar_t wbegin, wend;
429 size_t st, nst;
430 unsigned int i;
431 int c = 0, r = 0, lastmatches = 0, leflags = eflags;
432 size_t startm = 0, matchidx;
433 unsigned int retry;
435 matchidx = pc->matchidx;
437 /* Special case: empty pattern with -w flag, check first character */
438 if (matchall && wflag) {
439 if (pc->ln.len == 0)
440 return (0);
441 wend = L' ';
442 if (sscanf(&pc->ln.dat[0], "%lc", &wend) != 1 || iswword(wend))
443 return (1);
444 else
445 return (0);
446 } else if (matchall)
447 return (0);
449 st = pc->lnstart;
450 nst = 0;
451 /* Initialize to avoid a false positive warning from GCC. */
452 lastmatch.rm_so = lastmatch.rm_eo = 0;
454 /* Loop to process the whole line */
455 while (st <= pc->ln.len) {
456 lastmatches = 0;
457 startm = matchidx;
458 retry = 0;
459 if (st > 0 && pc->ln.dat[st - 1] != fileeol)
460 leflags |= REG_NOTBOL;
461 /* Loop to compare with all the patterns */
462 for (i = 0; i < patterns; i++) {
463 pmatch.rm_so = st;
464 pmatch.rm_eo = pc->ln.len;
465 #ifdef WITH_INTERNAL_NOSPEC
466 if (grepbehave == GREP_FIXED)
467 r = litexec(&pattern[i], pc->ln.dat, 1, &pmatch);
468 else
469 #endif
470 #ifndef WITHOUT_FASTMATCH
471 if (fg_pattern[i].pattern)
472 r = fastexec(&fg_pattern[i],
473 pc->ln.dat, 1, &pmatch, leflags);
474 else
475 #endif
476 r = regexec(&r_pattern[i], pc->ln.dat, 1,
477 &pmatch, leflags);
478 if (r != 0)
479 continue;
480 /* Check for full match */
481 if (xflag && (pmatch.rm_so != 0 ||
482 (size_t)pmatch.rm_eo != pc->ln.len))
483 continue;
484 /* Check for whole word match */
485 #ifndef WITHOUT_FASTMATCH
486 if (wflag || fg_pattern[i].word) {
487 #else
488 if (wflag) {
489 #endif
490 wbegin = wend = L' ';
491 if (pmatch.rm_so != 0 &&
492 sscanf(&pc->ln.dat[pmatch.rm_so - 1],
493 "%lc", &wbegin) != 1)
494 r = REG_NOMATCH;
495 else if ((size_t)pmatch.rm_eo !=
496 pc->ln.len &&
497 sscanf(&pc->ln.dat[pmatch.rm_eo],
498 "%lc", &wend) != 1)
499 r = REG_NOMATCH;
500 else if (iswword(wbegin) ||
501 iswword(wend))
502 r = REG_NOMATCH;
504 * If we're doing whole word matching and we
505 * matched once, then we should try the pattern
506 * again after advancing just past the start of
507 * the earliest match. This allows the pattern
508 * to match later on in the line and possibly
509 * still match a whole word.
511 if (r == REG_NOMATCH &&
512 (retry == pc->lnstart ||
513 (unsigned int)pmatch.rm_so + 1 < retry))
514 retry = pmatch.rm_so + 1;
515 if (r == REG_NOMATCH)
516 continue;
518 lastmatches++;
519 lastmatch = pmatch;
521 if (matchidx == 0)
522 c++;
525 * Replace previous match if the new one is earlier
526 * and/or longer. This will lead to some amount of
527 * extra work if -o/--color are specified, but it's
528 * worth it from a correctness point of view.
530 if (matchidx > startm) {
531 chkmatch = pc->matches[matchidx - 1];
532 if (pmatch.rm_so < chkmatch.rm_so ||
533 (pmatch.rm_so == chkmatch.rm_so &&
534 (pmatch.rm_eo - pmatch.rm_so) >
535 (chkmatch.rm_eo - chkmatch.rm_so))) {
536 pc->matches[matchidx - 1] = pmatch;
537 nst = pmatch.rm_eo;
539 } else {
540 /* Advance as normal if not */
541 pc->matches[matchidx++] = pmatch;
542 nst = pmatch.rm_eo;
544 /* avoid excessive matching - skip further patterns */
545 if ((color == NULL && !oflag) || qflag || lflag ||
546 matchidx >= MAX_MATCHES) {
547 pc->lnstart = nst;
548 lastmatches = 0;
549 break;
554 * Advance to just past the start of the earliest match, try
555 * again just in case we still have a chance to match later in
556 * the string.
558 if (lastmatches == 0 && retry > pc->lnstart) {
559 st = retry;
560 continue;
563 /* One pass if we are not recording matches */
564 if (!wflag && ((color == NULL && !oflag) || qflag || lflag || Lflag))
565 break;
567 /* If we didn't have any matches or REG_NOSUB set */
568 if (lastmatches == 0 || (cflags & REG_NOSUB))
569 nst = pc->ln.len;
571 if (lastmatches == 0)
572 /* No matches */
573 break;
574 else if (st == nst && lastmatch.rm_so == lastmatch.rm_eo)
575 /* Zero-length match -- advance one more so we don't get stuck */
576 nst++;
578 /* Advance st based on previous matches */
579 st = nst;
580 pc->lnstart = st;
583 /* Reflect the new matchidx in the context */
584 pc->matchidx = matchidx;
585 if (vflag)
586 c = !c;
587 return (c ? 0 : 1);
591 * Safe malloc() for internal use.
593 void *
594 grep_malloc(size_t size)
596 void *ptr;
598 if ((ptr = malloc(size)) == NULL)
599 err(2, "malloc");
600 return (ptr);
604 * Safe calloc() for internal use.
606 void *
607 grep_calloc(size_t nmemb, size_t size)
609 void *ptr;
611 if ((ptr = calloc(nmemb, size)) == NULL)
612 err(2, "calloc");
613 return (ptr);
617 * Safe realloc() for internal use.
619 void *
620 grep_realloc(void *ptr, size_t size)
623 if ((ptr = realloc(ptr, size)) == NULL)
624 err(2, "realloc");
625 return (ptr);
629 * Safe strdup() for internal use.
631 char *
632 grep_strdup(const char *str)
634 char *ret;
636 if ((ret = strdup(str)) == NULL)
637 err(2, "strdup");
638 return (ret);
642 * Print an entire line as-is, there are no inline matches to consider. This is
643 * used for printing context.
645 void grep_printline(struct str *line, int sep) {
646 printline_metadata(line, sep);
647 fwrite(line->dat, line->len, 1, stdout);
648 putchar(fileeol);
651 static void
652 printline_metadata(struct str *line, int sep)
654 bool printsep;
656 printsep = false;
657 if (!hflag) {
658 if (!nullflag) {
659 fputs(line->file, stdout);
660 printsep = true;
661 } else {
662 printf("%s", line->file);
663 putchar(0);
666 if (nflag) {
667 if (printsep)
668 putchar(sep);
669 printf("%d", line->line_no);
670 printsep = true;
672 if (bflag) {
673 if (printsep)
674 putchar(sep);
675 printf("%lld", (long long)(line->off + line->boff));
676 printsep = true;
678 if (printsep)
679 putchar(sep);
683 * Prints a matching line according to the command line options.
685 static void
686 printline(struct parsec *pc, int sep)
688 size_t a = 0;
689 size_t i, matchidx;
690 regmatch_t match;
692 /* If matchall, everything matches but don't actually print for -o */
693 if (oflag && matchall)
694 return;
696 matchidx = pc->matchidx;
698 /* --color and -o */
699 if ((oflag || color) && matchidx > 0) {
700 /* Only print metadata once per line if --color */
701 if (!oflag && pc->printed == 0)
702 printline_metadata(&pc->ln, sep);
703 for (i = 0; i < matchidx; i++) {
704 match = pc->matches[i];
705 /* Don't output zero length matches */
706 if (match.rm_so == match.rm_eo)
707 continue;
709 * Metadata is printed on a per-line basis, so every
710 * match gets file metadata with the -o flag.
712 if (oflag) {
713 pc->ln.boff = match.rm_so;
714 printline_metadata(&pc->ln, sep);
715 } else
716 fwrite(pc->ln.dat + a, match.rm_so - a, 1,
717 stdout);
718 if (color)
719 fprintf(stdout, "\33[%sm\33[K", color);
720 fwrite(pc->ln.dat + match.rm_so,
721 match.rm_eo - match.rm_so, 1, stdout);
722 if (color)
723 fprintf(stdout, "\33[m\33[K");
724 a = match.rm_eo;
725 if (oflag)
726 putchar('\n');
728 if (!oflag) {
729 if (pc->ln.len - a > 0)
730 fwrite(pc->ln.dat + a, pc->ln.len - a, 1,
731 stdout);
732 putchar('\n');
734 } else
735 grep_printline(&pc->ln, sep);
736 pc->printed++;