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