1 /* grep.c - show lines matching regular expressions
2  *
3  * Copyright 2013 CE Strake <strake888 at gmail.com>
4  *
5  * See http://pubs.opengroup.org/onlinepubs/9699919799/utilities/grep.html
6  *
7  * Posix doesn't even specify -r, documenting deviations from it is silly.
8 * echo hello | grep -w ''
9 * echo '' | grep -w ''
10 * echo hello | grep -f </dev/null
11 *
12 
13 USE_GREP(NEWTOY(grep, "(line-buffered)(color):;(exclude-dir)*S(exclude)*M(include)*ZzEFHIab(byte-offset)h(no-filename)ino(only-matching)rRsvwcl(files-with-matches)q(quiet)(silent)e*f*C#B#A#m#x[!wx][!EFw]", TOYFLAG_BIN|TOYFLAG_ARGFAIL(2)|TOYFLAG_LINEBUF))
14 USE_EGREP(OLDTOY(egrep, grep, TOYFLAG_BIN|TOYFLAG_ARGFAIL(2)|TOYFLAG_LINEBUF))
15 USE_FGREP(OLDTOY(fgrep, grep, TOYFLAG_BIN|TOYFLAG_ARGFAIL(2)|TOYFLAG_LINEBUF))
16 
17 config GREP
18   bool "grep"
19   default y
20   help
21     usage: grep [-EFrivwcloqsHbhn] [-ABC NUM] [-m MAX] [-e REGEX]... [-MS PATTERN]... [-f REGFILE] [FILE]...
22 
23     Show lines matching regular expressions. If no -e, first argument is
24     regular expression to match. With no files (or "-" filename) read stdin.
25     Returns 0 if matched, 1 if no match found, 2 for command errors.
26 
27     -e  Regex to match. (May be repeated.)
28     -f  File listing regular expressions to match.
29 
30     file search:
31     -r  Recurse into subdirectories (defaults FILE to ".")
32     -R  Recurse into subdirectories and symlinks to directories
33     -M  Match filename pattern (--include)
34     -S  Skip filename pattern (--exclude)
35     --exclude-dir=PATTERN  Skip directory pattern
36     -I  Ignore binary files
37 
38     match type:
39     -A  Show NUM lines after     -B  Show NUM lines before match
40     -C  NUM lines context (A+B)  -E  extended regex syntax
41     -F  fixed (literal match)    -a  always text (not binary)
42     -i  case insensitive         -m  match MAX many lines
43     -v  invert match             -w  whole word (implies -E)
44     -x  whole line               -z  input NUL terminated
45 
46     display modes: (default: matched line)
47     -c  count of matching lines  -l  show only matching filenames
48     -o  only matching part       -q  quiet (errors only)
49     -s  silent (no error msg)    -Z  output NUL terminated
50 
51     output prefix (default: filename if checking more than 1 file)
52     -H  force filename           -b  byte offset of match
53     -h  hide filename            -n  line number of match
54 
55 config EGREP
56   bool
57   default y
58   depends on GREP
59 
60 config FGREP
61   bool
62   default y
63   depends on GREP
64 */
65 
66 #define FOR_grep
67 #include "toys.h"
68 
69 GLOBALS(
70   long m, A, B, C;
71   struct arg_list *f, *e, *M, *S, *exclude_dir;
72   char *color;
73 
74   char *purple, *cyan, *red, *green, *grey;
75   struct double_list *reg;
76   char indelim, outdelim;
77   int found, tried;
78 )
79 
80 struct reg {
81   struct reg *next, *prev;
82   int rc;
83   regex_t r;
84   regmatch_t m;
85 };
86 
numdash(long num,char dash)87 static void numdash(long num, char dash)
88 {
89   printf("%s%ld%s%c", TT.green, num, TT.cyan, dash);
90 }
91 
92 // Emit line with various potential prefixes and delimiter
outline(char * line,char dash,char * name,long lcount,long bcount,unsigned trim)93 static void outline(char *line, char dash, char *name, long lcount, long bcount,
94   unsigned trim)
95 {
96   if (!trim && FLAG(o)) return;
97   if (name && FLAG(H)) printf("%s%s%s%c", TT.purple, name, TT.cyan, dash);
98   if (FLAG(c)) {
99     printf("%s%ld", TT.grey, lcount);
100     xputc(TT.outdelim);
101   } else if (lcount && FLAG(n)) numdash(lcount, dash);
102   if (bcount && FLAG(b)) numdash(bcount-1, dash);
103   if (line) {
104     if (FLAG(color)) xputsn(FLAG(o) ? TT.red : TT.grey);
105     // support embedded NUL bytes in output
106     xputsl(line, trim);
107     xputc(TT.outdelim);
108   }
109 }
110 
111 // Show matches in one file
do_grep(int fd,char * name)112 static void do_grep(int fd, char *name)
113 {
114   long lcount = 0, mcount = 0, offset = 0, after = 0, before = 0;
115   struct double_list *dlb = 0;
116   char *bars = 0;
117   FILE *file;
118   int bin = 0;
119 
120   if (!FLAG(r)) TT.tried++;
121   if (!fd) name = "(standard input)";
122 
123   // Only run binary file check on lseekable files.
124   if (!FLAG(a) && !lseek(fd, 0, SEEK_CUR)) {
125     char buf[256];
126     int len, i = 0;
127     wchar_t wc;
128 
129     // If the first 256 bytes don't parse as utf8, call it binary.
130     if (0<(len = read(fd, buf, 256))) {
131       lseek(fd, -len, SEEK_CUR);
132       while (i<len) {
133         bin = utf8towc(&wc, buf+i, len-i);
134         if (bin == -2) i = len;
135         if (bin<1) break;
136         i += bin;
137       }
138       bin = i!=len;
139     }
140     if (bin && FLAG(I)) return;
141   }
142 
143   if (!(file = fdopen(fd, "r"))) return perror_msg("%s", name);
144 
145   // Loop through lines of input
146   for (;;) {
147     char *line = 0, *start;
148     struct reg *shoe;
149     size_t ulen;
150     long len;
151     int matched = 0, rc = 1;
152 
153     // get next line, check and trim delimiter
154     lcount++;
155     errno = 0;
156     ulen = len = getdelim(&line, &ulen, TT.indelim, file);
157     if (len == -1 && errno) perror_msg("%s", name);
158     if (len<1) break;
159     if (line[ulen-1] == TT.indelim) line[--ulen] = 0;
160 
161     // Prepare for next line
162     start = line;
163     if (TT.reg) for (shoe = (void *)TT.reg; shoe; shoe = shoe->next)
164       shoe->rc = 0;
165 
166     // Loop to handle multiple matches in same line
167     do {
168       regmatch_t *mm = (void *)toybuf;
169 
170       // Handle "fixed" (literal) matches
171       if (FLAG(F)) {
172         struct arg_list *seek, fseek;
173         char *s = 0;
174 
175         for (seek = TT.e; seek; seek = seek->next) {
176           if (FLAG(x)) {
177             if (!(FLAG(i) ? strcasecmp : strcmp)(seek->arg, line)) s = line;
178           } else if (!*seek->arg) {
179             // No need to set fseek.next because this will match every line.
180             seek = &fseek;
181             fseek.arg = s = line;
182           } else if (FLAG(i)) s = strcasestr(start, seek->arg);
183           else s = strstr(start, seek->arg);
184 
185           if (s) break;
186         }
187 
188         if (s) {
189           rc = 0;
190           mm->rm_so = (s-start);
191           mm->rm_eo = (s-start)+strlen(seek->arg);
192         } else rc = 1;
193 
194       // Handle regex matches
195       } else {
196         int baseline = mm->rm_eo;
197 
198         mm->rm_so = mm->rm_eo = INT_MAX;
199         rc = 1;
200         for (shoe = (void *)TT.reg; shoe; shoe = shoe->next) {
201 
202           // Do we need to re-check this regex?
203           if (!shoe->rc) {
204             shoe->m.rm_so -= baseline;
205             shoe->m.rm_eo -= baseline;
206             if (!matched || shoe->m.rm_so<0)
207               shoe->rc = regexec0(&shoe->r, start, ulen-(start-line), 1,
208                                   &shoe->m, start==line ? 0 : REG_NOTBOL);
209           }
210 
211           // If we got a match, is it a _better_ match?
212           if (!shoe->rc && (shoe->m.rm_so < mm->rm_so ||
213               (shoe->m.rm_so == mm->rm_so && shoe->m.rm_eo >= mm->rm_eo)))
214           {
215             mm = &shoe->m;
216             rc = 0;
217           }
218         }
219       }
220 
221       if (!rc && FLAG(o) && !mm->rm_eo && ulen>start-line) {
222         start++;
223         continue;
224       }
225 
226       if (!rc && FLAG(x) && (mm->rm_so || ulen-(start-line)!=mm->rm_eo)) rc = 1;
227 
228       if (!rc && FLAG(w)) {
229         char c = 0;
230 
231         if ((start+mm->rm_so)!=line) {
232           c = start[mm->rm_so-1];
233           if (!isalnum(c) && c != '_') c = 0;
234         }
235         if (!c) {
236           c = start[mm->rm_eo];
237           if (!isalnum(c) && c != '_') c = 0;
238         }
239         if (c) {
240           start += mm->rm_so+1;
241           continue;
242         }
243       }
244 
245       if (FLAG(v)) {
246         if (FLAG(o)) {
247           if (rc) mm->rm_eo = ulen-(start-line);
248           else if (!mm->rm_so) {
249             start += mm->rm_eo;
250             continue;
251           } else mm->rm_eo = mm->rm_so;
252         } else {
253           if (!rc) break;
254           mm->rm_eo = ulen-(start-line);
255         }
256         mm->rm_so = 0;
257       } else if (rc) break;
258 
259       // At least one line we didn't print since match while -ABC active
260       if (bars) {
261         xputs(bars);
262         bars = 0;
263       }
264       matched++;
265       TT.found = 1;
266       if (FLAG(q)) {
267         toys.exitval = 0;
268         xexit();
269       }
270       if (FLAG(l)) {
271         xprintf("%s%c", name, TT.outdelim);
272         free(line);
273         fclose(file);
274         return;
275       }
276 
277       if (!FLAG(c)) {
278         long bcount = 1 + offset + (start-line) + (FLAG(o) ? mm->rm_so : 0);
279 
280         if (bin) printf("Binary file %s matches\n", name);
281         else if (FLAG(o))
282           outline(start+mm->rm_so, ':', name, lcount, bcount,
283                   mm->rm_eo-mm->rm_so);
284         else {
285           while (dlb) {
286             struct double_list *dl = dlist_pop(&dlb);
287             unsigned *uu = (void *)(dl->data+(strlen(dl->data)|3)+1);
288 
289             outline(dl->data, '-', name, lcount-before, uu[0]+1, uu[1]);
290             free(dl->data);
291             free(dl);
292             before--;
293           }
294 
295           if (matched==1)
296             outline(FLAG(color) ? 0 : line, ':', name, lcount, bcount, ulen);
297           if (FLAG(color)) {
298             xputsn(TT.grey);
299             if (mm->rm_so) xputsl(line, mm->rm_so);
300             xputsn(TT.red);
301             xputsl(line+mm->rm_so, mm->rm_eo-mm->rm_so);
302           }
303 
304           if (TT.A) after = TT.A+1;
305         }
306       }
307 
308       start += mm->rm_eo;
309       if (mm->rm_so == mm->rm_eo) break;
310       if (!FLAG(o) && FLAG(color)) break;
311     } while (*start);
312     offset += len;
313 
314     if (matched) {
315       // Finish off pending line color fragment.
316       if (FLAG(color) && !FLAG(o)) {
317         xputsn(TT.grey);
318         if (ulen > start-line) xputsl(start, ulen-(start-line));
319         xputc(TT.outdelim);
320       }
321       mcount++;
322     } else {
323       int discard = (after || TT.B);
324 
325       if (after && --after) {
326         outline(line, '-', name, lcount, 0, ulen);
327         discard = 0;
328       }
329       if (discard && TT.B) {
330         unsigned *uu, ul = (ulen|3)+1;
331 
332         line = xrealloc(line, ul+8);
333         uu = (void *)(line+ul);
334         uu[0] = offset-len;
335         uu[1] = ulen;
336         dlist_add(&dlb, line);
337         line = 0;
338         if (++before>TT.B) {
339           struct double_list *dl;
340 
341           dl = dlist_pop(&dlb);
342           free(dl->data);
343           free(dl);
344           before--;
345         } else discard = 0;
346       }
347       // If we discarded a line while displaying context, show bars before next
348       // line (but don't show them now in case that was last match in file)
349       if (discard && mcount) bars = "--";
350     }
351     free(line);
352 
353     if (FLAG(m) && mcount >= TT.m) break;
354   }
355 
356   if (FLAG(c)) outline(0, ':', name, mcount, 0, 1);
357 
358   // loopfiles will also close the fd, but this frees an (opaque) struct.
359   fclose(file);
360   while (dlb) {
361     struct double_list *dl = dlist_pop(&dlb);
362 
363     free(dl->data);
364     free(dl);
365   }
366 }
367 
parse_regex(void)368 static void parse_regex(void)
369 {
370   struct arg_list *al, *new, *list = NULL;
371   char *s, *ss;
372 
373   // Add all -f lines to -e list. (Yes, this is leaking allocation context for
374   // exit to free. Not supporting nofork for this command any time soon.)
375   al = TT.f ? TT.f : TT.e;
376   while (al) {
377     if (TT.f) {
378       if (!*(s = ss = xreadfile(al->arg, 0, 0))) {
379         free(ss);
380         s = 0;
381       }
382     } else s = ss = al->arg;
383 
384     // Advance, when we run out of -f switch to -e.
385     al = al->next;
386     if (!al && TT.f) {
387       TT.f = 0;
388       al = TT.e;
389     }
390     if (!s) continue;
391 
392     // Split lines at \n, add individual lines to new list.
393     do {
394       ss = FLAG(z) ? 0 : strchr(s, '\n');
395       if (ss) *(ss++) = 0;
396       new = xmalloc(sizeof(struct arg_list));
397       new->next = list;
398       new->arg = s;
399       list = new;
400       s = ss;
401     } while (ss && *s);
402   }
403   TT.e = list;
404 
405   if (!FLAG(F)) {
406     // Convert regex list
407     for (al = TT.e; al; al = al->next) {
408       struct reg *shoe;
409 
410       if (FLAG(o) && !*al->arg) continue;
411       dlist_add_nomalloc(&TT.reg, (void *)(shoe = xmalloc(sizeof(struct reg))));
412       xregcomp(&shoe->r, al->arg,
413                (REG_EXTENDED*!!FLAG(E))|(REG_ICASE*!!FLAG(i)));
414     }
415     dlist_terminate(TT.reg);
416   }
417 }
418 
do_grep_r(struct dirtree * new)419 static int do_grep_r(struct dirtree *new)
420 {
421   struct arg_list *al;
422   char *name;
423 
424   if (!new->parent) TT.tried++;
425   if (!dirtree_notdotdot(new)) return 0;
426   if (S_ISDIR(new->st.st_mode)) {
427     for (al = TT.exclude_dir; al; al = al->next)
428       if (!fnmatch(al->arg, new->name, 0)) return 0;
429     return DIRTREE_RECURSE|(FLAG(R)?DIRTREE_SYMFOLLOW:0);
430   }
431   if (TT.S || TT.M) {
432     for (al = TT.S; al; al = al->next)
433       if (!fnmatch(al->arg, new->name, 0)) return 0;
434 
435     if (TT.M) {
436       for (al = TT.M; al; al = al->next)
437         if (!fnmatch(al->arg, new->name, 0)) break;
438 
439       if (!al) return 0;
440     }
441   }
442 
443   // "grep -r onefile" doesn't show filenames, but "grep -r onedir" should.
444   if (new->parent && !FLAG(h)) toys.optflags |= FLAG_H;
445 
446   name = dirtree_path(new, 0);
447   do_grep(openat(dirtree_parentfd(new), new->name, 0), name);
448   free(name);
449 
450   return 0;
451 }
452 
grep_main(void)453 void grep_main(void)
454 {
455   char **ss = toys.optargs;
456 
457   if (FLAG(color) && (!TT.color || !strcmp(TT.color, "auto")) && !isatty(1))
458     toys.optflags &= ~FLAG_color;
459 
460   if (FLAG(color)) {
461     TT.purple = "\033[35m";
462     TT.cyan = "\033[36m";
463     TT.red = "\033[1;31m";
464     TT.green = "\033[32m";
465     TT.grey = "\033[0m";
466   } else TT.purple = TT.cyan = TT.red = TT.green = TT.grey = "";
467 
468   if (FLAG(R)) toys.optflags |= FLAG_r;
469 
470   // Grep exits with 2 for errors
471   toys.exitval = 2;
472 
473   if (!TT.A) TT.A = TT.C;
474   if (!TT.B) TT.B = TT.C;
475 
476   TT.indelim = '\n' * !FLAG(z);
477   TT.outdelim = '\n' * !FLAG(Z);
478 
479   // Handle egrep and fgrep
480   if (*toys.which->name == 'e') toys.optflags |= FLAG_E;
481   if (*toys.which->name == 'f') toys.optflags |= FLAG_F;
482 
483   if (!TT.e && !TT.f) {
484     if (!*ss) error_exit("no REGEX");
485     TT.e = xzalloc(sizeof(struct arg_list));
486     TT.e->arg = *(ss++);
487     toys.optc--;
488   }
489 
490   parse_regex();
491 
492   if (!FLAG(h) && toys.optc>1) toys.optflags |= FLAG_H;
493 
494   if (FLAG(s)) {
495     close(2);
496     xopen_stdio("/dev/null", O_RDWR);
497   }
498 
499   if (FLAG(r)) {
500     // Iterate through -r arguments. Use "." as default if none provided.
501     for (ss = *ss ? ss : (char *[]){".", 0}; *ss; ss++) {
502       if (!strcmp(*ss, "-")) do_grep(0, *ss);
503       else dirtree_read(*ss, do_grep_r);
504     }
505   } else loopfiles_rw(ss, O_RDONLY|WARN_ONLY, 0, do_grep);
506   if (TT.tried >= toys.optc || (FLAG(q)&&TT.found)) toys.exitval = !TT.found;
507 }
508