1 /* $OpenBSD: grep.c,v 1.57 2017/12/10 09:17:24 jmc Exp $ */ 2 3 /*- 4 * Copyright (c) 1999 James Howard and Dag-Erling Co�dan Sm�rgrav 5 * All rights reserved. 6 * 7 * Redistribution and use in source and binary forms, with or without 8 * modification, are permitted provided that the following conditions 9 * are met: 10 * 1. Redistributions of source code must retain the above copyright 11 * notice, this list of conditions and the following disclaimer. 12 * 2. Redistributions in binary form must reproduce the above copyright 13 * notice, this list of conditions and the following disclaimer in the 14 * documentation and/or other materials provided with the distribution. 15 * 16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND 17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 19 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE 20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 26 * SUCH DAMAGE. 27 */ 28 29 #include <sys/types.h> 30 #include <sys/stat.h> 31 #include <sys/queue.h> 32 33 #include <ctype.h> 34 #include <err.h> 35 #include <errno.h> 36 #include <getopt.h> 37 #include <regex.h> 38 #include <stdio.h> 39 #include <stdlib.h> 40 #include <string.h> 41 #include <unistd.h> 42 43 #include "grep.h" 44 45 /* Flags passed to regcomp() and regexec() */ 46 int cflags; 47 int eflags = REG_STARTEND; 48 49 int matchall; /* shortcut */ 50 int patterns, pattern_sz; 51 char **pattern; 52 regex_t *r_pattern; 53 fastgrep_t *fg_pattern; 54 55 /* For regex errors */ 56 char re_error[RE_ERROR_BUF + 1]; 57 58 /* Command-line flags */ 59 int Aflag; /* -A x: print x lines trailing each match */ 60 int Bflag; /* -B x: print x lines leading each match */ 61 int Eflag; /* -E: interpret pattern as extended regexp */ 62 int Fflag; /* -F: interpret pattern as list of fixed strings */ 63 int Hflag; /* -H: always print filename header */ 64 int Lflag; /* -L: only show names of files with no matches */ 65 int Rflag; /* -R: recursively search directory trees */ 66 #ifndef NOZ 67 int Zflag; /* -Z: decompress input before processing */ 68 #endif 69 int bflag; /* -b: show block numbers for each match */ 70 int cflag; /* -c: only show a count of matching lines */ 71 int hflag; /* -h: don't print filename headers */ 72 int iflag; /* -i: ignore case */ 73 int lflag; /* -l: only show names of files with matches */ 74 int mflag; /* -m x: stop reading the files after x matches */ 75 long long mcount; /* count for -m */ 76 long long mlimit; /* requested value for -m */ 77 int nflag; /* -n: show line numbers in front of matching lines */ 78 int oflag; /* -o: print each match */ 79 int qflag; /* -q: quiet mode (don't output anything) */ 80 int sflag; /* -s: silent mode (ignore errors) */ 81 int vflag; /* -v: only show non-matching lines */ 82 int wflag; /* -w: pattern must start and end on word boundaries */ 83 int xflag; /* -x: pattern must match entire line */ 84 int lbflag; /* --line-buffered */ 85 86 int binbehave = BIN_FILE_BIN; 87 88 enum { 89 BIN_OPT = CHAR_MAX + 1, 90 HELP_OPT, 91 MMAP_OPT, 92 LINEBUF_OPT 93 }; 94 95 /* Housekeeping */ 96 int first; /* flag whether or not this is our first match */ 97 int tail; /* lines left to print */ 98 int file_err; /* file reading error */ 99 100 struct patfile { 101 const char *pf_file; 102 SLIST_ENTRY(patfile) pf_next; 103 }; 104 SLIST_HEAD(, patfile) patfilelh; 105 106 extern char *__progname; 107 108 static void 109 usage(void) 110 { 111 fprintf(stderr, 112 #ifdef NOZ 113 "usage: %s [-abcEFGHhIiLlnoqRsUVvwx] [-A num] [-B num] [-C[num]]" 114 #else 115 "usage: %s [-abcEFGHhIiLlnoqRsUVvwxZ] [-A num] [-B num] [-C[num]]" 116 #endif 117 " [-e pattern]\n" 118 "\t[-f file] [-m num] [--binary-files=value] [--context[=num]]\n" 119 "\t[--line-buffered] [--max-count=num] [pattern] [file ...]\n", 120 __progname); 121 exit(2); 122 } 123 124 #ifdef NOZ 125 static const char optstr[] = "0123456789A:B:CEFGHILRUVabce:f:hilm:noqrsuvwxy"; 126 #else 127 static const char optstr[] = "0123456789A:B:CEFGHILRUVZabce:f:hilm:noqrsuvwxy"; 128 #endif 129 130 static const struct option long_options[] = 131 { 132 {"binary-files", required_argument, NULL, BIN_OPT}, 133 {"help", no_argument, NULL, HELP_OPT}, 134 {"mmap", no_argument, NULL, MMAP_OPT}, 135 {"line-buffered", no_argument, NULL, LINEBUF_OPT}, 136 {"after-context", required_argument, NULL, 'A'}, 137 {"before-context", required_argument, NULL, 'B'}, 138 {"context", optional_argument, NULL, 'C'}, 139 {"devices", required_argument, NULL, 'D'}, 140 {"extended-regexp", no_argument, NULL, 'E'}, 141 {"fixed-strings", no_argument, NULL, 'F'}, 142 {"basic-regexp", no_argument, NULL, 'G'}, 143 {"with-filename", no_argument, NULL, 'H'}, 144 {"binary", no_argument, NULL, 'U'}, 145 {"version", no_argument, NULL, 'V'}, 146 {"text", no_argument, NULL, 'a'}, 147 {"byte-offset", no_argument, NULL, 'b'}, 148 {"count", no_argument, NULL, 'c'}, 149 {"regexp", required_argument, NULL, 'e'}, 150 {"file", required_argument, NULL, 'f'}, 151 {"no-filename", no_argument, NULL, 'h'}, 152 {"ignore-case", no_argument, NULL, 'i'}, 153 {"files-without-match", no_argument, NULL, 'L'}, 154 {"files-with-matches", no_argument, NULL, 'l'}, 155 {"max-count", required_argument, NULL, 'm'}, 156 {"line-number", no_argument, NULL, 'n'}, 157 {"quiet", no_argument, NULL, 'q'}, 158 {"silent", no_argument, NULL, 'q'}, 159 {"recursive", no_argument, NULL, 'r'}, 160 {"no-messages", no_argument, NULL, 's'}, 161 {"revert-match", no_argument, NULL, 'v'}, 162 {"word-regexp", no_argument, NULL, 'w'}, 163 {"line-regexp", no_argument, NULL, 'x'}, 164 {"unix-byte-offsets", no_argument, NULL, 'u'}, 165 #ifndef NOZ 166 {"decompress", no_argument, NULL, 'Z'}, 167 #endif 168 {NULL, no_argument, NULL, 0} 169 }; 170 171 172 static void 173 add_pattern(char *pat, size_t len) 174 { 175 if (!xflag && (len == 0 || matchall)) { 176 matchall = 1; 177 return; 178 } 179 if (patterns == pattern_sz) { 180 pattern_sz *= 2; 181 pattern = grep_reallocarray(pattern, ++pattern_sz, sizeof(*pattern)); 182 } 183 if (len > 0 && pat[len - 1] == '\n') 184 --len; 185 /* pat may not be NUL-terminated */ 186 if (wflag && !Fflag) { 187 int bol = 0, eol = 0, extra; 188 if (pat[0] == '^') 189 bol = 1; 190 if (len > 0 && pat[len - 1] == '$') 191 eol = 1; 192 extra = Eflag ? 2 : 4; 193 pattern[patterns] = grep_malloc(len + 15 + extra); 194 snprintf(pattern[patterns], len + 15 + extra, 195 "%s[[:<:]]%s%.*s%s[[:>:]]%s", 196 bol ? "^" : "", 197 Eflag ? "(" : "\\(", 198 (int)len - bol - eol, pat + bol, 199 Eflag ? ")" : "\\)", 200 eol ? "$" : ""); 201 len += 14 + extra; 202 } else { 203 pattern[patterns] = grep_malloc(len + 1); 204 memcpy(pattern[patterns], pat, len); 205 pattern[patterns][len] = '\0'; 206 } 207 ++patterns; 208 } 209 210 static void 211 add_patterns(char *pats) 212 { 213 char *nl; 214 215 while ((nl = strchr(pats, '\n')) != NULL) { 216 add_pattern(pats, nl - pats); 217 pats = nl + 1; 218 } 219 add_pattern(pats, strlen(pats)); 220 } 221 222 static void 223 read_patterns(const char *fn) 224 { 225 FILE *f; 226 char *line; 227 size_t len; 228 229 if ((f = fopen(fn, "r")) == NULL) 230 err(2, "%s", fn); 231 while ((line = fgetln(f, &len)) != NULL) 232 add_pattern(line, *line == '\n' ? 0 : len); 233 if (ferror(f)) 234 err(2, "%s", fn); 235 fclose(f); 236 } 237 238 int 239 main(int argc, char *argv[]) 240 { 241 int c, lastc, prevoptind, newarg, i, needpattern, exprs, expr_sz; 242 struct patfile *patfile, *pf_next; 243 long l; 244 char **expr; 245 const char *errstr; 246 247 if (pledge("stdio rpath", NULL) == -1) 248 err(2, "pledge"); 249 250 SLIST_INIT(&patfilelh); 251 switch (__progname[0]) { 252 case 'e': 253 Eflag = 1; 254 break; 255 case 'f': 256 Fflag = 1; 257 break; 258 #ifndef NOZ 259 case 'z': 260 Zflag = 1; 261 switch(__progname[1]) { 262 case 'e': 263 Eflag = 1; 264 break; 265 case 'f': 266 Fflag = 1; 267 break; 268 } 269 break; 270 #endif 271 } 272 273 lastc = '\0'; 274 newarg = 1; 275 prevoptind = 1; 276 needpattern = 1; 277 expr_sz = exprs = 0; 278 expr = NULL; 279 while ((c = getopt_long(argc, argv, optstr, 280 long_options, NULL)) != -1) { 281 switch (c) { 282 case '0': case '1': case '2': case '3': case '4': 283 case '5': case '6': case '7': case '8': case '9': 284 if (newarg || !isdigit(lastc)) 285 Aflag = 0; 286 else if (Aflag > INT_MAX / 10) 287 errx(2, "context out of range"); 288 Aflag = Bflag = (Aflag * 10) + (c - '0'); 289 break; 290 case 'A': 291 case 'B': 292 l = strtonum(optarg, 1, INT_MAX, &errstr); 293 if (errstr != NULL) 294 errx(2, "context %s", errstr); 295 if (c == 'A') 296 Aflag = (int)l; 297 else 298 Bflag = (int)l; 299 break; 300 case 'C': 301 if (optarg == NULL) 302 Aflag = Bflag = 2; 303 else { 304 l = strtonum(optarg, 1, INT_MAX, &errstr); 305 if (errstr != NULL) 306 errx(2, "context %s", errstr); 307 Aflag = Bflag = (int)l; 308 } 309 break; 310 case 'E': 311 Fflag = 0; 312 Eflag = 1; 313 break; 314 case 'F': 315 Eflag = 0; 316 Fflag = 1; 317 break; 318 case 'G': 319 Eflag = Fflag = 0; 320 break; 321 case 'H': 322 Hflag = 1; 323 break; 324 case 'I': 325 binbehave = BIN_FILE_SKIP; 326 break; 327 case 'L': 328 lflag = 0; 329 Lflag = qflag = 1; 330 break; 331 case 'R': 332 case 'r': 333 Rflag = 1; 334 break; 335 case 'U': 336 binbehave = BIN_FILE_BIN; 337 break; 338 case 'V': 339 fprintf(stderr, "grep version %u.%u\n", VER_MAJ, VER_MIN); 340 exit(0); 341 break; 342 #ifndef NOZ 343 case 'Z': 344 Zflag = 1; 345 break; 346 #endif 347 case 'a': 348 binbehave = BIN_FILE_TEXT; 349 break; 350 case 'b': 351 bflag = 1; 352 break; 353 case 'c': 354 cflag = 1; 355 break; 356 case 'e': 357 /* defer adding of expressions until all arguments are parsed */ 358 if (exprs == expr_sz) { 359 expr_sz *= 2; 360 expr = grep_reallocarray(expr, ++expr_sz, 361 sizeof(*expr)); 362 } 363 needpattern = 0; 364 expr[exprs] = optarg; 365 ++exprs; 366 break; 367 case 'f': 368 patfile = grep_malloc(sizeof(*patfile)); 369 patfile->pf_file = optarg; 370 SLIST_INSERT_HEAD(&patfilelh, patfile, pf_next); 371 needpattern = 0; 372 break; 373 case 'h': 374 hflag = 1; 375 break; 376 case 'i': 377 case 'y': 378 iflag = 1; 379 cflags |= REG_ICASE; 380 break; 381 case 'l': 382 Lflag = 0; 383 lflag = qflag = 1; 384 break; 385 case 'm': 386 mflag = 1; 387 mlimit = mcount = strtonum(optarg, 0, LLONG_MAX, 388 &errstr); 389 if (errstr != NULL) 390 errx(2, "invalid max-count %s: %s", 391 optarg, errstr); 392 break; 393 case 'n': 394 nflag = 1; 395 break; 396 case 'o': 397 oflag = 1; 398 break; 399 case 'q': 400 qflag = 1; 401 break; 402 case 's': 403 sflag = 1; 404 break; 405 case 'v': 406 vflag = 1; 407 break; 408 case 'w': 409 wflag = 1; 410 break; 411 case 'x': 412 xflag = 1; 413 break; 414 case BIN_OPT: 415 if (strcmp("binary", optarg) == 0) 416 binbehave = BIN_FILE_BIN; 417 else if (strcmp("without-match", optarg) == 0) 418 binbehave = BIN_FILE_SKIP; 419 else if (strcmp("text", optarg) == 0) 420 binbehave = BIN_FILE_TEXT; 421 else 422 errx(2, "Unknown binary-files option"); 423 break; 424 case 'u': 425 case MMAP_OPT: 426 /* default, compatibility */ 427 break; 428 case LINEBUF_OPT: 429 lbflag = 1; 430 break; 431 case HELP_OPT: 432 default: 433 usage(); 434 } 435 lastc = c; 436 newarg = optind != prevoptind; 437 prevoptind = optind; 438 } 439 argc -= optind; 440 argv += optind; 441 442 for (i = 0; i < exprs; i++) 443 add_patterns(expr[i]); 444 free(expr); 445 expr = NULL; 446 447 for (patfile = SLIST_FIRST(&patfilelh); patfile != NULL; 448 patfile = pf_next) { 449 pf_next = SLIST_NEXT(patfile, pf_next); 450 read_patterns(patfile->pf_file); 451 free(patfile); 452 } 453 454 if (argc == 0 && needpattern) 455 usage(); 456 457 if (argc != 0 && needpattern) { 458 add_patterns(*argv); 459 --argc; 460 ++argv; 461 } 462 463 if (Rflag && argc == 0) 464 warnx("warning: recursive search of stdin"); 465 if (Eflag) 466 cflags |= REG_EXTENDED; 467 if (Fflag) 468 cflags |= REG_NOSPEC; 469 #ifdef SMALL 470 /* Sorry, this won't work */ 471 if (Fflag && wflag) 472 errx(1, "Can't use small fgrep with -w"); 473 #endif 474 fg_pattern = grep_calloc(patterns, sizeof(*fg_pattern)); 475 r_pattern = grep_calloc(patterns, sizeof(*r_pattern)); 476 for (i = 0; i < patterns; ++i) { 477 /* Check if cheating is allowed (always is for fgrep). */ 478 #ifndef SMALL 479 if (Fflag) { 480 fgrepcomp(&fg_pattern[i], pattern[i]); 481 } else 482 #endif 483 { 484 if (fastcomp(&fg_pattern[i], pattern[i])) { 485 /* Fall back to full regex library */ 486 c = regcomp(&r_pattern[i], pattern[i], cflags); 487 if (c != 0) { 488 regerror(c, &r_pattern[i], re_error, 489 RE_ERROR_BUF); 490 errx(2, "%s", re_error); 491 } 492 } 493 } 494 } 495 496 if (lbflag) 497 setvbuf(stdout, NULL, _IOLBF, 0); 498 499 if ((argc == 0 || argc == 1) && !Rflag && !Hflag) 500 hflag = 1; 501 502 if (argc == 0) 503 exit(!procfile(NULL)); 504 505 if (Rflag) 506 c = grep_tree(argv); 507 else 508 for (c = 0; argc--; ++argv) 509 c += procfile(*argv); 510 511 exit(c ? (file_err ? (qflag ? 0 : 2) : 0) : (file_err ? 2 : 1)); 512 } 513