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 $ */ 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$"); 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 57 static int linesqueued; 58 static int procline(struct str *l, int); 59 60 static int lasta; 61 static bool ctxover; 62 63 bool 64 file_matching(const char *fname) 65 { 66 char *fname_base, *fname_buf; 67 bool ret; 68 69 ret = finclude ? false : true; 70 fname_buf = strdup(fname); 71 if (fname_buf == NULL) 72 err(2, "strdup"); 73 fname_base = basename(fname_buf); 74 75 for (unsigned int i = 0; i < fpatterns; ++i) { 76 if (fnmatch(fpattern[i].pat, fname, 0) == 0 || 77 fnmatch(fpattern[i].pat, fname_base, 0) == 0) { 78 if (fpattern[i].mode == EXCL_PAT) { 79 ret = false; 80 break; 81 } else 82 ret = true; 83 } 84 } 85 free(fname_buf); 86 return (ret); 87 } 88 89 static inline bool 90 dir_matching(const char *dname) 91 { 92 bool ret; 93 94 ret = dinclude ? false : true; 95 96 for (unsigned int i = 0; i < dpatterns; ++i) { 97 if (dname != NULL && 98 fnmatch(dpattern[i].pat, dname, 0) == 0) { 99 if (dpattern[i].mode == EXCL_PAT) 100 return (false); 101 else 102 ret = true; 103 } 104 } 105 return (ret); 106 } 107 108 /* 109 * Processes a directory when a recursive search is performed with 110 * the -R option. Each appropriate file is passed to procfile(). 111 */ 112 int 113 grep_tree(char **argv) 114 { 115 FTS *fts; 116 FTSENT *p; 117 int c, fts_flags; 118 bool ok; 119 const char *wd[] = { ".", NULL }; 120 121 c = fts_flags = 0; 122 123 switch(linkbehave) { 124 case LINK_EXPLICIT: 125 fts_flags = FTS_COMFOLLOW; 126 break; 127 case LINK_SKIP: 128 fts_flags = FTS_PHYSICAL; 129 break; 130 default: 131 fts_flags = FTS_LOGICAL; 132 133 } 134 135 fts_flags |= FTS_NOSTAT | FTS_NOCHDIR; 136 137 fts = fts_open((argv[0] == NULL) ? 138 __DECONST(char * const *, wd) : argv, fts_flags, NULL); 139 if (fts == NULL) 140 err(2, "fts_open"); 141 while ((p = fts_read(fts)) != NULL) { 142 switch (p->fts_info) { 143 case FTS_DNR: 144 /* FALLTHROUGH */ 145 case FTS_ERR: 146 file_err = true; 147 if(!sflag) 148 warnx("%s: %s", p->fts_path, strerror(p->fts_errno)); 149 break; 150 case FTS_D: 151 /* FALLTHROUGH */ 152 case FTS_DP: 153 if (dexclude || dinclude) 154 if (!dir_matching(p->fts_name) || 155 !dir_matching(p->fts_path)) 156 fts_set(fts, p, FTS_SKIP); 157 break; 158 case FTS_DC: 159 /* Print a warning for recursive directory loop */ 160 warnx("warning: %s: recursive directory loop", 161 p->fts_path); 162 break; 163 default: 164 /* Check for file exclusion/inclusion */ 165 ok = true; 166 if (fexclude || finclude) 167 ok &= file_matching(p->fts_path); 168 169 if (ok) 170 c += procfile(p->fts_path); 171 break; 172 } 173 } 174 175 fts_close(fts); 176 return (c); 177 } 178 179 /* 180 * Opens a file and processes it. Each file is processed line-by-line 181 * passing the lines to procline(). 182 */ 183 int 184 procfile(const char *fn) 185 { 186 struct file *f; 187 struct stat sb; 188 struct str ln; 189 mode_t s; 190 int c, t; 191 192 mcount = mlimit; 193 194 if (strcmp(fn, "-") == 0) { 195 fn = label != NULL ? label : getstr(1); 196 f = grep_open(NULL); 197 } else { 198 if (!stat(fn, &sb)) { 199 /* Check if we need to process the file */ 200 s = sb.st_mode & S_IFMT; 201 if (s == S_IFDIR && dirbehave == DIR_SKIP) 202 return (0); 203 if ((s == S_IFIFO || s == S_IFCHR || s == S_IFBLK 204 || s == S_IFSOCK) && devbehave == DEV_SKIP) 205 return (0); 206 } 207 f = grep_open(fn); 208 } 209 if (f == NULL) { 210 file_err = true; 211 if (!sflag) 212 warn("%s", fn); 213 return (0); 214 } 215 216 ln.file = grep_malloc(strlen(fn) + 1); 217 strcpy(ln.file, fn); 218 ln.line_no = 0; 219 ln.len = 0; 220 ctxover = false; 221 linesqueued = 0; 222 tail = 0; 223 lasta = 0; 224 ln.off = -1; 225 226 for (c = 0; c == 0 || !(lflag || qflag); ) { 227 ln.off += ln.len + 1; 228 if ((ln.dat = grep_fgetln(f, &ln.len)) == NULL || ln.len == 0) { 229 if (ln.line_no == 0 && matchall) 230 exit(0); 231 else 232 break; 233 } 234 if (ln.len > 0 && ln.dat[ln.len - 1] == fileeol) 235 --ln.len; 236 ln.line_no++; 237 238 /* Return if we need to skip a binary file */ 239 if (f->binary && binbehave == BINFILE_SKIP) { 240 grep_close(f); 241 free(ln.file); 242 free(f); 243 return (0); 244 } 245 246 /* Process the file line-by-line, enqueue non-matching lines */ 247 if ((t = procline(&ln, f->binary)) == 0 && Bflag > 0) { 248 /* Except don't enqueue lines that appear in -A ctx */ 249 if (ln.line_no == 0 || lasta != ln.line_no) { 250 /* queue is maxed to Bflag number of lines */ 251 enqueue(&ln); 252 linesqueued++; 253 ctxover = false; 254 } else { 255 /* 256 * Indicate to procline() that we have ctx 257 * overlap and make sure queue is empty. 258 */ 259 if (!ctxover) 260 clearqueue(); 261 ctxover = true; 262 } 263 } 264 c += t; 265 if (mflag && mcount <= 0) 266 break; 267 } 268 if (Bflag > 0) 269 clearqueue(); 270 grep_close(f); 271 272 if (cflag) { 273 if (!hflag) 274 printf("%s:", ln.file); 275 printf("%u\n", c); 276 } 277 if (lflag && !qflag && c != 0) 278 printf("%s%c", fn, nullflag ? 0 : '\n'); 279 if (Lflag && !qflag && c == 0) 280 printf("%s%c", fn, nullflag ? 0 : '\n'); 281 if (c && !cflag && !lflag && !Lflag && 282 binbehave == BINFILE_BIN && f->binary && !qflag) 283 printf(getstr(8), fn); 284 285 free(ln.file); 286 free(f); 287 return (c); 288 } 289 290 #define iswword(x) (iswalnum((x)) || (x) == L'_') 291 292 /* 293 * Processes a line comparing it with the specified patterns. Each pattern 294 * is looped to be compared along with the full string, saving each and every 295 * match, which is necessary to colorize the output and to count the 296 * matches. The matching lines are passed to printline() to display the 297 * appropriate output. 298 */ 299 static int 300 procline(struct str *l, int nottext) 301 { 302 regmatch_t matches[MAX_LINE_MATCHES]; 303 regmatch_t pmatch, lastmatch; 304 size_t st = 0, nst = 0; 305 unsigned int i; 306 int c = 0, m = 0, r = 0, lastmatches = 0, leflags = eflags; 307 int startm = 0; 308 309 /* Initialize to avoid a false positive warning from GCC. */ 310 lastmatch.rm_so = lastmatch.rm_eo = 0; 311 312 /* Loop to process the whole line */ 313 while (st <= l->len) { 314 lastmatches = 0; 315 startm = m; 316 if (st > 0) 317 leflags |= REG_NOTBOL; 318 /* Loop to compare with all the patterns */ 319 for (i = 0; i < patterns; i++) { 320 pmatch.rm_so = st; 321 pmatch.rm_eo = l->len; 322 #ifndef WITHOUT_FASTMATCH 323 if (fg_pattern[i].pattern) 324 r = fastexec(&fg_pattern[i], 325 l->dat, 1, &pmatch, leflags); 326 else 327 #endif 328 r = regexec(&r_pattern[i], l->dat, 1, 329 &pmatch, leflags); 330 r = (r == 0) ? 0 : REG_NOMATCH; 331 if (r == REG_NOMATCH) 332 continue; 333 /* Check for full match */ 334 if (r == 0 && xflag) 335 if (pmatch.rm_so != 0 || 336 (size_t)pmatch.rm_eo != l->len) 337 r = REG_NOMATCH; 338 /* Check for whole word match */ 339 #ifndef WITHOUT_FASTMATCH 340 if (r == 0 && (wflag || fg_pattern[i].word)) { 341 #else 342 if (r == 0 && wflag) { 343 #endif 344 wchar_t wbegin, wend; 345 346 wbegin = wend = L' '; 347 if (pmatch.rm_so != 0 && 348 sscanf(&l->dat[pmatch.rm_so - 1], 349 "%lc", &wbegin) != 1) 350 r = REG_NOMATCH; 351 else if ((size_t)pmatch.rm_eo != 352 l->len && 353 sscanf(&l->dat[pmatch.rm_eo], 354 "%lc", &wend) != 1) 355 r = REG_NOMATCH; 356 else if (iswword(wbegin) || 357 iswword(wend)) 358 r = REG_NOMATCH; 359 } 360 if (r == 0) { 361 lastmatches++; 362 lastmatch = pmatch; 363 if (m == 0) 364 c++; 365 366 if (m < MAX_LINE_MATCHES) { 367 /* Replace previous match if the new one is earlier and/or longer */ 368 if (m > startm) { 369 if (pmatch.rm_so < matches[m-1].rm_so || 370 (pmatch.rm_so == matches[m-1].rm_so && (pmatch.rm_eo - pmatch.rm_so) > (matches[m-1].rm_eo - matches[m-1].rm_so))) { 371 matches[m-1] = pmatch; 372 nst = pmatch.rm_eo; 373 } 374 } else { 375 /* Advance as normal if not */ 376 matches[m++] = pmatch; 377 nst = pmatch.rm_eo; 378 } 379 } 380 381 /* matches - skip further patterns */ 382 if ((color == NULL && !oflag) || 383 qflag || lflag) 384 break; 385 } 386 } 387 388 if (vflag) { 389 c = !c; 390 break; 391 } 392 393 /* One pass if we are not recording matches */ 394 if (!wflag && ((color == NULL && !oflag) || qflag || lflag || Lflag)) 395 break; 396 397 /* If we didn't have any matches or REG_NOSUB set */ 398 if (lastmatches == 0 || (cflags & REG_NOSUB)) 399 nst = l->len; 400 401 if (lastmatches == 0) 402 /* No matches */ 403 break; 404 else if (st == nst && lastmatch.rm_so == lastmatch.rm_eo) 405 /* Zero-length match -- advance one more so we don't get stuck */ 406 nst++; 407 408 /* Advance st based on previous matches */ 409 st = nst; 410 } 411 412 413 /* Count the matches if we have a match limit */ 414 if (mflag) 415 mcount -= c; 416 417 if (c && binbehave == BINFILE_BIN && nottext) 418 return (c); /* Binary file */ 419 420 /* Dealing with the context */ 421 if ((tail || c) && !cflag && !qflag && !lflag && !Lflag) { 422 if (c) { 423 if (!first && !prev && !tail && (Bflag || Aflag) && 424 !ctxover) 425 printf("--\n"); 426 tail = Aflag; 427 if (Bflag > 0) { 428 printqueue(); 429 ctxover = false; 430 } 431 linesqueued = 0; 432 printline(l, ':', matches, m); 433 } else { 434 /* Print -A lines following matches */ 435 lasta = l->line_no; 436 printline(l, '-', matches, m); 437 tail--; 438 } 439 } 440 441 if (c) { 442 prev = true; 443 first = false; 444 } else 445 prev = false; 446 447 return (c); 448 } 449 450 /* 451 * Safe malloc() for internal use. 452 */ 453 void * 454 grep_malloc(size_t size) 455 { 456 void *ptr; 457 458 if ((ptr = malloc(size)) == NULL) 459 err(2, "malloc"); 460 return (ptr); 461 } 462 463 /* 464 * Safe calloc() for internal use. 465 */ 466 void * 467 grep_calloc(size_t nmemb, size_t size) 468 { 469 void *ptr; 470 471 if ((ptr = calloc(nmemb, size)) == NULL) 472 err(2, "calloc"); 473 return (ptr); 474 } 475 476 /* 477 * Safe realloc() for internal use. 478 */ 479 void * 480 grep_realloc(void *ptr, size_t size) 481 { 482 483 if ((ptr = realloc(ptr, size)) == NULL) 484 err(2, "realloc"); 485 return (ptr); 486 } 487 488 /* 489 * Safe strdup() for internal use. 490 */ 491 char * 492 grep_strdup(const char *str) 493 { 494 char *ret; 495 496 if ((ret = strdup(str)) == NULL) 497 err(2, "strdup"); 498 return (ret); 499 } 500 501 /* 502 * Prints a matching line according to the command line options. 503 */ 504 void 505 printline(struct str *line, int sep, regmatch_t *matches, int m) 506 { 507 size_t a = 0; 508 int i, n = 0; 509 510 /* If matchall, everything matches but don't actually print for -o */ 511 if (oflag && matchall) 512 return; 513 514 if (!hflag) { 515 if (!nullflag) { 516 fputs(line->file, stdout); 517 ++n; 518 } else { 519 printf("%s", line->file); 520 putchar(0); 521 } 522 } 523 if (nflag) { 524 if (n > 0) 525 putchar(sep); 526 printf("%d", line->line_no); 527 ++n; 528 } 529 if (bflag) { 530 if (n > 0) 531 putchar(sep); 532 printf("%lld", (long long)line->off); 533 ++n; 534 } 535 if (n) 536 putchar(sep); 537 /* --color and -o */ 538 if ((oflag || color) && m > 0) { 539 for (i = 0; i < m; i++) { 540 /* Don't output zero length matches */ 541 if (matches[i].rm_so == matches[i].rm_eo) 542 continue; 543 if (!oflag) 544 fwrite(line->dat + a, matches[i].rm_so - a, 1, 545 stdout); 546 if (color) 547 fprintf(stdout, "\33[%sm\33[K", color); 548 549 fwrite(line->dat + matches[i].rm_so, 550 matches[i].rm_eo - matches[i].rm_so, 1, 551 stdout); 552 if (color) 553 fprintf(stdout, "\33[m\33[K"); 554 a = matches[i].rm_eo; 555 if (oflag) 556 putchar('\n'); 557 } 558 if (!oflag) { 559 if (line->len - a > 0) 560 fwrite(line->dat + a, line->len - a, 1, stdout); 561 putchar('\n'); 562 } 563 } else { 564 fwrite(line->dat, line->len, 1, stdout); 565 putchar(fileeol); 566 } 567 } 568