util.c revision 322609
1/* $NetBSD: util.c,v 1.9 2011/02/27 17:33:37 joerg Exp $ */ 2/* $FreeBSD: stable/11/usr.bin/grep/util.c 322609 2017-08-17 04:26:04Z 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 322609 2017-08-17 04:26:04Z 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#ifndef WITHOUT_FASTMATCH 53#include "fastmatch.h" 54#endif 55#include "grep.h" 56 57static bool first_match = true; 58 59/* 60 * Parsing context; used to hold things like matches made and 61 * other useful bits 62 */ 63struct parsec { 64 regmatch_t matches[MAX_LINE_MATCHES]; /* Matches made */ 65 struct str ln; /* Current line */ 66 size_t lnstart; /* Start of line processing */ 67 size_t matchidx; /* Latest used match index */ 68 bool binary; /* Binary file? */ 69}; 70 71 72static int procline(struct parsec *pc); 73static void printline(struct parsec *pc, int sep); 74static void printline_metadata(struct str *line, int sep); 75 76bool 77file_matching(const char *fname) 78{ 79 char *fname_base, *fname_buf; 80 bool ret; 81 82 ret = finclude ? false : true; 83 fname_buf = strdup(fname); 84 if (fname_buf == NULL) 85 err(2, "strdup"); 86 fname_base = basename(fname_buf); 87 88 for (unsigned int i = 0; i < fpatterns; ++i) { 89 if (fnmatch(fpattern[i].pat, fname, 0) == 0 || 90 fnmatch(fpattern[i].pat, fname_base, 0) == 0) { 91 if (fpattern[i].mode == EXCL_PAT) { 92 ret = false; 93 break; 94 } else 95 ret = true; 96 } 97 } 98 free(fname_buf); 99 return (ret); 100} 101 102static inline bool 103dir_matching(const char *dname) 104{ 105 bool ret; 106 107 ret = dinclude ? false : true; 108 109 for (unsigned int i = 0; i < dpatterns; ++i) { 110 if (dname != NULL && 111 fnmatch(dpattern[i].pat, dname, 0) == 0) { 112 if (dpattern[i].mode == EXCL_PAT) 113 return (false); 114 else 115 ret = true; 116 } 117 } 118 return (ret); 119} 120 121/* 122 * Processes a directory when a recursive search is performed with 123 * the -R option. Each appropriate file is passed to procfile(). 124 */ 125int 126grep_tree(char **argv) 127{ 128 FTS *fts; 129 FTSENT *p; 130 int c, fts_flags; 131 bool ok; 132 const char *wd[] = { ".", NULL }; 133 134 c = fts_flags = 0; 135 136 switch(linkbehave) { 137 case LINK_EXPLICIT: 138 fts_flags = FTS_COMFOLLOW; 139 break; 140 case LINK_SKIP: 141 fts_flags = FTS_PHYSICAL; 142 break; 143 default: 144 fts_flags = FTS_LOGICAL; 145 146 } 147 148 fts_flags |= FTS_NOSTAT | FTS_NOCHDIR; 149 150 fts = fts_open((argv[0] == NULL) ? 151 __DECONST(char * const *, wd) : argv, fts_flags, NULL); 152 if (fts == NULL) 153 err(2, "fts_open"); 154 while ((p = fts_read(fts)) != NULL) { 155 switch (p->fts_info) { 156 case FTS_DNR: 157 /* FALLTHROUGH */ 158 case FTS_ERR: 159 file_err = true; 160 if(!sflag) 161 warnx("%s: %s", p->fts_path, strerror(p->fts_errno)); 162 break; 163 case FTS_D: 164 /* FALLTHROUGH */ 165 case FTS_DP: 166 if (dexclude || dinclude) 167 if (!dir_matching(p->fts_name) || 168 !dir_matching(p->fts_path)) 169 fts_set(fts, p, FTS_SKIP); 170 break; 171 case FTS_DC: 172 /* Print a warning for recursive directory loop */ 173 warnx("warning: %s: recursive directory loop", 174 p->fts_path); 175 break; 176 default: 177 /* Check for file exclusion/inclusion */ 178 ok = true; 179 if (fexclude || finclude) 180 ok &= file_matching(p->fts_path); 181 182 if (ok) 183 c += procfile(p->fts_path); 184 break; 185 } 186 } 187 188 fts_close(fts); 189 return (c); 190} 191 192/* 193 * Opens a file and processes it. Each file is processed line-by-line 194 * passing the lines to procline(). 195 */ 196int 197procfile(const char *fn) 198{ 199 struct parsec pc; 200 long long tail; 201 struct file *f; 202 struct stat sb; 203 struct str *ln; 204 mode_t s; 205 int c, last_outed, t; 206 bool doctx, printmatch, same_file; 207 208 if (strcmp(fn, "-") == 0) { 209 fn = label != NULL ? label : getstr(1); 210 f = grep_open(NULL); 211 } else { 212 if (!stat(fn, &sb)) { 213 /* Check if we need to process the file */ 214 s = sb.st_mode & S_IFMT; 215 if (s == S_IFDIR && dirbehave == DIR_SKIP) 216 return (0); 217 if ((s == S_IFIFO || s == S_IFCHR || s == S_IFBLK 218 || s == S_IFSOCK) && devbehave == DEV_SKIP) 219 return (0); 220 } 221 f = grep_open(fn); 222 } 223 if (f == NULL) { 224 file_err = true; 225 if (!sflag) 226 warn("%s", fn); 227 return (0); 228 } 229 230 /* Convenience */ 231 ln = &pc.ln; 232 pc.ln.file = grep_malloc(strlen(fn) + 1); 233 strcpy(pc.ln.file, fn); 234 pc.ln.line_no = 0; 235 pc.ln.len = 0; 236 pc.ln.off = -1; 237 pc.binary = f->binary; 238 tail = 0; 239 last_outed = 0; 240 same_file = false; 241 doctx = false; 242 printmatch = true; 243 if ((pc.binary && binbehave == BINFILE_BIN) || cflag || qflag || 244 lflag || Lflag) 245 printmatch = false; 246 if (printmatch && (Aflag != 0 || Bflag != 0)) 247 doctx = true; 248 mcount = mlimit; 249 250 for (c = 0; c == 0 || !(lflag || qflag); ) { 251 /* Reset match count and line start for every line processed */ 252 pc.matchidx = 0; 253 pc.lnstart = 0; 254 pc.ln.off += pc.ln.len + 1; 255 if ((pc.ln.dat = grep_fgetln(f, &pc.ln.len)) == NULL || 256 pc.ln.len == 0) { 257 if (pc.ln.line_no == 0 && matchall) 258 /* 259 * An empty file with an empty pattern and the 260 * -w flag does not match 261 */ 262 exit(matchall && wflag ? 1 : 0); 263 else 264 break; 265 } 266 267 if (pc.ln.len > 0 && pc.ln.dat[pc.ln.len - 1] == fileeol) 268 --pc.ln.len; 269 pc.ln.line_no++; 270 271 /* Return if we need to skip a binary file */ 272 if (pc.binary && binbehave == BINFILE_SKIP) { 273 grep_close(f); 274 free(pc.ln.file); 275 free(f); 276 return (0); 277 } 278 279 if ((t = procline(&pc)) == 0) 280 ++c; 281 282 /* Deal with any -B context or context separators */ 283 if (t == 0 && doctx) { 284 if (!first_match && (!same_file || last_outed > 0)) 285 printf("--\n"); 286 if (Bflag > 0) 287 printqueue(); 288 tail = Aflag; 289 } 290 /* Print the matching line, but only if not quiet/binary */ 291 if (t == 0 && printmatch) { 292 printline(&pc, ':'); 293 while (pc.matchidx >= MAX_LINE_MATCHES) { 294 /* Reset matchidx and try again */ 295 pc.matchidx = 0; 296 if (procline(&pc) == 0) 297 printline(&pc, ':'); 298 else 299 break; 300 } 301 first_match = false; 302 same_file = true; 303 last_outed = 0; 304 } 305 if (t != 0 && doctx) { 306 /* Deal with any -A context */ 307 if (tail > 0) { 308 printline(&pc, '-'); 309 tail--; 310 if (Bflag > 0) 311 clearqueue(); 312 } else { 313 /* 314 * Enqueue non-matching lines for -B context. 315 * If we're not actually doing -B context or if 316 * the enqueue resulted in a line being rotated 317 * out, then go ahead and increment last_outed 318 * to signify a gap between context/match. 319 */ 320 if (Bflag == 0 || (Bflag > 0 && enqueue(ln))) 321 ++last_outed; 322 } 323 } 324 325 /* Count the matches if we have a match limit */ 326 if (t == 0 && mflag) { 327 --mcount; 328 if (mflag && mcount <= 0) 329 break; 330 } 331 332 } 333 if (Bflag > 0) 334 clearqueue(); 335 grep_close(f); 336 337 if (cflag) { 338 if (!hflag) 339 printf("%s:", pc.ln.file); 340 printf("%u\n", c); 341 } 342 if (lflag && !qflag && c != 0) 343 printf("%s%c", fn, nullflag ? 0 : '\n'); 344 if (Lflag && !qflag && c == 0) 345 printf("%s%c", fn, nullflag ? 0 : '\n'); 346 if (c && !cflag && !lflag && !Lflag && 347 binbehave == BINFILE_BIN && f->binary && !qflag) 348 printf(getstr(8), fn); 349 350 free(pc.ln.file); 351 free(f); 352 return (c); 353} 354 355#define iswword(x) (iswalnum((x)) || (x) == L'_') 356 357/* 358 * Processes a line comparing it with the specified patterns. Each pattern 359 * is looped to be compared along with the full string, saving each and every 360 * match, which is necessary to colorize the output and to count the 361 * matches. The matching lines are passed to printline() to display the 362 * appropriate output. 363 */ 364static int 365procline(struct parsec *pc) 366{ 367 regmatch_t pmatch, lastmatch, chkmatch; 368 wchar_t wbegin, wend; 369 size_t st, nst; 370 unsigned int i; 371 int c = 0, r = 0, lastmatches = 0, leflags = eflags; 372 size_t startm = 0, matchidx; 373 unsigned int retry; 374 375 matchidx = pc->matchidx; 376 377 /* Special case: empty pattern with -w flag, check first character */ 378 if (matchall && wflag) { 379 if (pc->ln.len == 0) 380 return (0); 381 wend = L' '; 382 if (sscanf(&pc->ln.dat[0], "%lc", &wend) != 1 || iswword(wend)) 383 return (1); 384 else 385 return (0); 386 } else if (matchall) 387 return (0); 388 389 st = pc->lnstart; 390 nst = 0; 391 /* Initialize to avoid a false positive warning from GCC. */ 392 lastmatch.rm_so = lastmatch.rm_eo = 0; 393 394 /* Loop to process the whole line */ 395 while (st <= pc->ln.len) { 396 lastmatches = 0; 397 startm = matchidx; 398 retry = 0; 399 if (st > 0) 400 leflags |= REG_NOTBOL; 401 /* Loop to compare with all the patterns */ 402 for (i = 0; i < patterns; i++) { 403 pmatch.rm_so = st; 404 pmatch.rm_eo = pc->ln.len; 405#ifndef WITHOUT_FASTMATCH 406 if (fg_pattern[i].pattern) 407 r = fastexec(&fg_pattern[i], 408 pc->ln.dat, 1, &pmatch, leflags); 409 else 410#endif 411 r = regexec(&r_pattern[i], pc->ln.dat, 1, 412 &pmatch, leflags); 413 if (r != 0) 414 continue; 415 /* Check for full match */ 416 if (xflag && (pmatch.rm_so != 0 || 417 (size_t)pmatch.rm_eo != pc->ln.len)) 418 continue; 419 /* Check for whole word match */ 420#ifndef WITHOUT_FASTMATCH 421 if (wflag || fg_pattern[i].word) { 422#else 423 if (wflag) { 424#endif 425 wbegin = wend = L' '; 426 if (pmatch.rm_so != 0 && 427 sscanf(&pc->ln.dat[pmatch.rm_so - 1], 428 "%lc", &wbegin) != 1) 429 r = REG_NOMATCH; 430 else if ((size_t)pmatch.rm_eo != 431 pc->ln.len && 432 sscanf(&pc->ln.dat[pmatch.rm_eo], 433 "%lc", &wend) != 1) 434 r = REG_NOMATCH; 435 else if (iswword(wbegin) || 436 iswword(wend)) 437 r = REG_NOMATCH; 438 /* 439 * If we're doing whole word matching and we 440 * matched once, then we should try the pattern 441 * again after advancing just past the start of 442 * the earliest match. This allows the pattern 443 * to match later on in the line and possibly 444 * still match a whole word. 445 */ 446 if (r == REG_NOMATCH && 447 (retry == pc->lnstart || 448 pmatch.rm_so + 1 < retry)) 449 retry = pmatch.rm_so + 1; 450 if (r == REG_NOMATCH) 451 continue; 452 } 453 lastmatches++; 454 lastmatch = pmatch; 455 456 if (matchidx == 0) 457 c++; 458 459 /* 460 * Replace previous match if the new one is earlier 461 * and/or longer. This will lead to some amount of 462 * extra work if -o/--color are specified, but it's 463 * worth it from a correctness point of view. 464 */ 465 if (matchidx > startm) { 466 chkmatch = pc->matches[matchidx - 1]; 467 if (pmatch.rm_so < chkmatch.rm_so || 468 (pmatch.rm_so == chkmatch.rm_so && 469 (pmatch.rm_eo - pmatch.rm_so) > 470 (chkmatch.rm_eo - chkmatch.rm_so))) { 471 pc->matches[matchidx - 1] = pmatch; 472 nst = pmatch.rm_eo; 473 } 474 } else { 475 /* Advance as normal if not */ 476 pc->matches[matchidx++] = pmatch; 477 nst = pmatch.rm_eo; 478 } 479 /* avoid excessive matching - skip further patterns */ 480 if ((color == NULL && !oflag) || qflag || lflag || 481 matchidx >= MAX_LINE_MATCHES) { 482 pc->lnstart = nst; 483 lastmatches = 0; 484 break; 485 } 486 } 487 488 /* 489 * Advance to just past the start of the earliest match, try 490 * again just in case we still have a chance to match later in 491 * the string. 492 */ 493 if (lastmatches == 0 && retry > pc->lnstart) { 494 st = retry; 495 continue; 496 } 497 498 /* One pass if we are not recording matches */ 499 if (!wflag && ((color == NULL && !oflag) || qflag || lflag || Lflag)) 500 break; 501 502 /* If we didn't have any matches or REG_NOSUB set */ 503 if (lastmatches == 0 || (cflags & REG_NOSUB)) 504 nst = pc->ln.len; 505 506 if (lastmatches == 0) 507 /* No matches */ 508 break; 509 else if (st == nst && lastmatch.rm_so == lastmatch.rm_eo) 510 /* Zero-length match -- advance one more so we don't get stuck */ 511 nst++; 512 513 /* Advance st based on previous matches */ 514 st = nst; 515 pc->lnstart = st; 516 } 517 518 /* Reflect the new matchidx in the context */ 519 pc->matchidx = matchidx; 520 if (vflag) 521 c = !c; 522 return (c ? 0 : 1); 523} 524 525/* 526 * Safe malloc() for internal use. 527 */ 528void * 529grep_malloc(size_t size) 530{ 531 void *ptr; 532 533 if ((ptr = malloc(size)) == NULL) 534 err(2, "malloc"); 535 return (ptr); 536} 537 538/* 539 * Safe calloc() for internal use. 540 */ 541void * 542grep_calloc(size_t nmemb, size_t size) 543{ 544 void *ptr; 545 546 if ((ptr = calloc(nmemb, size)) == NULL) 547 err(2, "calloc"); 548 return (ptr); 549} 550 551/* 552 * Safe realloc() for internal use. 553 */ 554void * 555grep_realloc(void *ptr, size_t size) 556{ 557 558 if ((ptr = realloc(ptr, size)) == NULL) 559 err(2, "realloc"); 560 return (ptr); 561} 562 563/* 564 * Safe strdup() for internal use. 565 */ 566char * 567grep_strdup(const char *str) 568{ 569 char *ret; 570 571 if ((ret = strdup(str)) == NULL) 572 err(2, "strdup"); 573 return (ret); 574} 575 576/* 577 * Print an entire line as-is, there are no inline matches to consider. This is 578 * used for printing context. 579 */ 580void grep_printline(struct str *line, int sep) { 581 printline_metadata(line, sep); 582 fwrite(line->dat, line->len, 1, stdout); 583 putchar(fileeol); 584} 585 586static void 587printline_metadata(struct str *line, int sep) 588{ 589 bool printsep; 590 591 printsep = false; 592 if (!hflag) { 593 if (!nullflag) { 594 fputs(line->file, stdout); 595 printsep = true; 596 } else { 597 printf("%s", line->file); 598 putchar(0); 599 } 600 } 601 if (nflag) { 602 if (printsep) 603 putchar(sep); 604 printf("%d", line->line_no); 605 printsep = true; 606 } 607 if (bflag) { 608 if (printsep) 609 putchar(sep); 610 printf("%lld", (long long)line->off); 611 printsep = true; 612 } 613 if (printsep) 614 putchar(sep); 615} 616 617/* 618 * Prints a matching line according to the command line options. 619 */ 620static void 621printline(struct parsec *pc, int sep) 622{ 623 size_t a = 0; 624 size_t i, matchidx; 625 regmatch_t match; 626 627 /* If matchall, everything matches but don't actually print for -o */ 628 if (oflag && matchall) 629 return; 630 631 matchidx = pc->matchidx; 632 633 /* --color and -o */ 634 if ((oflag || color) && matchidx > 0) { 635 printline_metadata(&pc->ln, sep); 636 for (i = 0; i < matchidx; i++) { 637 match = pc->matches[i]; 638 /* Don't output zero length matches */ 639 if (match.rm_so == match.rm_eo) 640 continue; 641 if (!oflag) 642 fwrite(pc->ln.dat + a, match.rm_so - a, 1, 643 stdout); 644 if (color) 645 fprintf(stdout, "\33[%sm\33[K", color); 646 fwrite(pc->ln.dat + match.rm_so, 647 match.rm_eo - match.rm_so, 1, stdout); 648 if (color) 649 fprintf(stdout, "\33[m\33[K"); 650 a = match.rm_eo; 651 if (oflag) 652 putchar('\n'); 653 } 654 if (!oflag) { 655 if (pc->ln.len - a > 0) 656 fwrite(pc->ln.dat + a, pc->ln.len - a, 1, 657 stdout); 658 putchar('\n'); 659 } 660 } else 661 grep_printline(&pc->ln, sep); 662} 663