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