grep: implement -w
[oweals/busybox.git] / findutils / grep.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini grep implementation for busybox using libc regex.
4  *
5  * Copyright (C) 1999,2000,2001 by Lineo, inc. and Mark Whitley
6  * Copyright (C) 1999,2000,2001 by Mark Whitley <markw@codepoet.org>
7  *
8  * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
9  */
10 /* BB_AUDIT SUSv3 defects - unsupported option -x.  */
11 /* BB_AUDIT GNU defects - always acts as -a.  */
12 /* http://www.opengroup.org/onlinepubs/007904975/utilities/grep.html */
13 /*
14  * 2004,2006 (C) Vladimir Oleynik <dzo@simtreas.ru> -
15  * correction "-e pattern1 -e pattern2" logic and more optimizations.
16  * precompiled regex
17  */
18 /*
19  * (C) 2006 Jac Goudsmit added -o option
20  */
21
22 #include "busybox.h"
23 #include "xregex.h"
24
25 /* options */
26 #define OPTSTR_GREP \
27         "lnqvscFiHhe:f:Lor" \
28         USE_FEATURE_GREP_CONTEXT("A:B:C:") \
29         USE_FEATURE_GREP_EGREP_ALIAS("E") \
30         USE_DESKTOP("w") \
31
32 enum {
33         OPTBIT_l,
34         OPTBIT_n,
35         OPTBIT_q,
36         OPTBIT_v,
37         OPTBIT_s,
38         OPTBIT_c,
39         OPTBIT_F,
40         OPTBIT_i,
41         OPTBIT_H,
42         OPTBIT_h,
43         OPTBIT_e,
44         OPTBIT_f,
45         OPTBIT_L,
46         OPTBIT_o,
47         OPTBIT_r,
48         USE_FEATURE_GREP_CONTEXT(OPTBIT_A ,)
49         USE_FEATURE_GREP_CONTEXT(OPTBIT_B ,)
50         USE_FEATURE_GREP_CONTEXT(OPTBIT_C ,)
51         USE_FEATURE_GREP_CONTEXT(OPTBIT_E ,)
52         USE_DESKTOP(             OPTBIT_w ,)
53         OPT_l = 1 << OPTBIT_l,
54         OPT_n = 1 << OPTBIT_n,
55         OPT_q = 1 << OPTBIT_q,
56         OPT_v = 1 << OPTBIT_v,
57         OPT_s = 1 << OPTBIT_s,
58         OPT_c = 1 << OPTBIT_c,
59         OPT_F = 1 << OPTBIT_F,
60         OPT_i = 1 << OPTBIT_i,
61         OPT_H = 1 << OPTBIT_H,
62         OPT_h = 1 << OPTBIT_h,
63         OPT_e = 1 << OPTBIT_e,
64         OPT_f = 1 << OPTBIT_f,
65         OPT_L = 1 << OPTBIT_L,
66         OPT_o = 1 << OPTBIT_o,
67         OPT_r = 1 << OPTBIT_r,
68         OPT_A = USE_FEATURE_GREP_CONTEXT((1 << OPTBIT_A)) + 0,
69         OPT_B = USE_FEATURE_GREP_CONTEXT((1 << OPTBIT_B)) + 0,
70         OPT_C = USE_FEATURE_GREP_CONTEXT((1 << OPTBIT_C)) + 0,
71         OPT_E = USE_FEATURE_GREP_CONTEXT((1 << OPTBIT_E)) + 0,
72         OPT_w = USE_DESKTOP(             (1 << OPTBIT_w)) + 0,
73 };
74
75 #define PRINT_FILES_WITH_MATCHES (option_mask32 & OPT_l)
76 #define PRINT_LINE_NUM (option_mask32 & OPT_n)
77 #define BE_QUIET (option_mask32 & OPT_q)
78 #define SUPPRESS_ERR_MSGS (option_mask32 & OPT_s)
79 #define PRINT_MATCH_COUNTS (option_mask32 & OPT_c)
80 #define FGREP_FLAG (option_mask32 & OPT_F)
81 #define PRINT_FILES_WITHOUT_MATCHES (option_mask32 & OPT_L)
82
83 typedef unsigned char byte_t;
84
85 static int reflags;
86 static byte_t invert_search;
87 static byte_t print_filename;
88 static byte_t open_errors;
89
90 #if ENABLE_FEATURE_GREP_CONTEXT
91 static int lines_before;
92 static int lines_after;
93 static char **before_buf;
94 static int last_line_printed;
95 #endif /* ENABLE_FEATURE_GREP_CONTEXT */
96
97 /* globals used internally */
98 static llist_t *pattern_head;   /* growable list of patterns to match */
99 static const char *cur_file;    /* the current file we are reading */
100
101 typedef struct grep_list_data_t {
102         char *pattern;
103         regex_t preg;
104 #define PATTERN_MEM_A 1
105 #define COMPILED 2
106         int flg_mem_alocated_compiled;
107 } grep_list_data_t;
108
109 static void print_line(const char *line, int linenum, char decoration)
110 {
111 #if ENABLE_FEATURE_GREP_CONTEXT
112         /* possibly print the little '--' separator */
113         if ((lines_before || lines_after) && last_line_printed &&
114                         last_line_printed < linenum - 1) {
115                 puts("--");
116         }
117         last_line_printed = linenum;
118 #endif
119         if (print_filename)
120                 printf("%s%c", cur_file, decoration);
121         if (PRINT_LINE_NUM)
122                 printf("%i%c", linenum, decoration);
123         /* Emulate weird GNU grep behavior with -ov */
124         if ((option_mask32 & (OPT_v+OPT_o)) != (OPT_v+OPT_o))
125                 puts(line);
126 }
127
128 static int grep_file(FILE *file)
129 {
130         char *line;
131         byte_t ret;
132         int linenum = 0;
133         int nmatches = 0;
134         regmatch_t regmatch;
135 #if ENABLE_FEATURE_GREP_CONTEXT
136         int print_n_lines_after = 0;
137         int curpos = 0; /* track where we are in the circular 'before' buffer */
138         int idx = 0; /* used for iteration through the circular buffer */
139 #endif /* ENABLE_FEATURE_GREP_CONTEXT */
140
141         while ((line = xmalloc_getline(file)) != NULL) {
142                 llist_t *pattern_ptr = pattern_head;
143                 grep_list_data_t * gl;
144
145                 linenum++;
146                 ret = 0;
147                 while (pattern_ptr) {
148                         gl = (grep_list_data_t *)pattern_ptr->data;
149                         if (FGREP_FLAG) {
150                                 ret = strstr(line, gl->pattern) != NULL;
151                         } else {
152                                 /*
153                                  * test for a postitive-assertion match (regexec returns success (0)
154                                  * and the user did not specify invert search), or a negative-assertion
155                                  * match (regexec returns failure (REG_NOMATCH) and the user specified
156                                  * invert search)
157                                  */
158                                 if (!(gl->flg_mem_alocated_compiled & COMPILED)) {
159                                         gl->flg_mem_alocated_compiled |= COMPILED;
160                                         xregcomp(&(gl->preg), gl->pattern, reflags);
161                                 }
162                                 regmatch.rm_so = 0;
163                                 regmatch.rm_eo = 0;
164                                 if (regexec(&(gl->preg), line, 1, &regmatch, 0) == 0) {
165                                         if (!(option_mask32 & OPT_w))
166                                                 ret = 1;
167                                         else {
168                                                 char c = ' ';
169                                                 if (regmatch.rm_so)
170                                                         c = line[regmatch.rm_so - 1];
171                                                 if (!isalnum(c) && c != '_') {
172                                                         c = line[regmatch.rm_eo];
173                                                         if (!c || (!isalnum(c) && c != '_'))
174                                                                 ret = 1;
175                                                 }
176                                         }
177                                 }
178                         }
179                         pattern_ptr = pattern_ptr->link;
180                 } /* while (pattern_ptr) */
181
182                 if (ret ^ invert_search) {
183                         if (PRINT_FILES_WITH_MATCHES || BE_QUIET)
184                                 free(line);
185
186                         /* if we found a match but were told to be quiet, stop here */
187                         if (BE_QUIET || PRINT_FILES_WITHOUT_MATCHES)
188                                 return -1;
189
190                         /* keep track of matches */
191                         nmatches++;
192
193                         /* if we're just printing filenames, we stop after the first match */
194                         if (PRINT_FILES_WITH_MATCHES)
195                                 break;
196
197                         /* print the matched line */
198                         if (PRINT_MATCH_COUNTS == 0) {
199 #if ENABLE_FEATURE_GREP_CONTEXT
200                                 int prevpos = (curpos == 0) ? lines_before - 1 : curpos - 1;
201
202                                 /* if we were told to print 'before' lines and there is at least
203                                  * one line in the circular buffer, print them */
204                                 if (lines_before && before_buf[prevpos] != NULL) {
205                                         int first_buf_entry_line_num = linenum - lines_before;
206
207                                         /* advance to the first entry in the circular buffer, and
208                                          * figure out the line number is of the first line in the
209                                          * buffer */
210                                         idx = curpos;
211                                         while (before_buf[idx] == NULL) {
212                                                 idx = (idx + 1) % lines_before;
213                                                 first_buf_entry_line_num++;
214                                         }
215
216                                         /* now print each line in the buffer, clearing them as we go */
217                                         while (before_buf[idx] != NULL) {
218                                                 print_line(before_buf[idx], first_buf_entry_line_num, '-');
219                                                 free(before_buf[idx]);
220                                                 before_buf[idx] = NULL;
221                                                 idx = (idx + 1) % lines_before;
222                                                 first_buf_entry_line_num++;
223                                         }
224                                 }
225
226                                 /* make a note that we need to print 'after' lines */
227                                 print_n_lines_after = lines_after;
228 #endif
229                                 if (option_mask32 & OPT_o) {
230                                         line[regmatch.rm_eo] = '\0';
231                                         print_line(line + regmatch.rm_so, linenum, ':');
232                                 } else {
233                                         print_line(line, linenum, ':');
234                                 }
235                         }
236                 }
237 #if ENABLE_FEATURE_GREP_CONTEXT
238                 else { /* no match */
239                         /* Add the line to the circular 'before' buffer */
240                         if (lines_before) {
241                                 free(before_buf[curpos]);
242                                 before_buf[curpos] = xstrdup(line);
243                                 curpos = (curpos + 1) % lines_before;
244                         }
245                 }
246
247                 /* if we need to print some context lines after the last match, do so */
248                 if (print_n_lines_after && (last_line_printed != linenum)) {
249                         print_line(line, linenum, '-');
250                         print_n_lines_after--;
251                 }
252 #endif /* ENABLE_FEATURE_GREP_CONTEXT */
253                 free(line);
254         }
255
256         /* special-case file post-processing for options where we don't print line
257          * matches, just filenames and possibly match counts */
258
259         /* grep -c: print [filename:]count, even if count is zero */
260         if (PRINT_MATCH_COUNTS) {
261                 if (print_filename)
262                         printf("%s:", cur_file);
263                 printf("%d\n", nmatches);
264         }
265
266         /* grep -l: print just the filename, but only if we grepped the line in the file  */
267         if (PRINT_FILES_WITH_MATCHES && nmatches > 0) {
268                 puts(cur_file);
269         }
270
271         /* grep -L: print just the filename, but only if we didn't grep the line in the file  */
272         if (PRINT_FILES_WITHOUT_MATCHES && nmatches == 0) {
273                 puts(cur_file);
274         }
275
276         return nmatches;
277 }
278
279 #if ENABLE_FEATURE_CLEAN_UP
280 #define new_grep_list_data(p, m) add_grep_list_data(p, m)
281 static char * add_grep_list_data(char *pattern, int flg_used_mem)
282 #else
283 #define new_grep_list_data(p, m) add_grep_list_data(p)
284 static char * add_grep_list_data(char *pattern)
285 #endif
286 {
287         grep_list_data_t *gl = xmalloc(sizeof(grep_list_data_t));
288         gl->pattern = pattern;
289 #if ENABLE_FEATURE_CLEAN_UP
290         gl->flg_mem_alocated_compiled = flg_used_mem;
291 #else
292         gl->flg_mem_alocated_compiled = 0;
293 #endif
294         return (char *)gl;
295 }
296
297
298 static void load_regexes_from_file(llist_t *fopt)
299 {
300         char *line;
301         FILE *f;
302
303         while (fopt) {
304                 llist_t *cur = fopt;
305                 char *ffile = cur->data;
306
307                 fopt = cur->link;
308                 free(cur);
309                 f = xfopen(ffile, "r");
310                 while ((line = xmalloc_getline(f)) != NULL) {
311                         llist_add_to(&pattern_head,
312                                 new_grep_list_data(line, PATTERN_MEM_A));
313                 }
314         }
315 }
316
317 static int file_action_grep(const char *filename, struct stat *statbuf, void* matched, int depth)
318 {
319         FILE *file = fopen(filename, "r");
320         if (file == NULL) {
321                 if (!SUPPRESS_ERR_MSGS)
322                         bb_perror_msg("%s", cur_file);
323                 open_errors = 1;
324                 return 0;
325         }
326         cur_file = filename;
327         *(int*)matched += grep_file(file);
328         fclose(file);
329         return 1;
330 }
331
332 static int grep_dir(const char *dir)
333 {
334         int matched = 0;
335         recursive_action(dir,
336                 /* recurse= */ 1,
337                 /* followLinks= */ 0,
338                 /* depthFirst= */ 1,
339                 /* fileAction= */ file_action_grep,
340                 /* dirAction= */ NULL,
341                 /* userData= */ &matched,
342                 /* depth= */ 0);
343         return matched;
344 }
345
346 int grep_main(int argc, char **argv);
347 int grep_main(int argc, char **argv)
348 {
349         FILE *file;
350         int matched;
351         llist_t *fopt = NULL;
352
353         /* do normal option parsing */
354 #if ENABLE_FEATURE_GREP_CONTEXT
355         char *slines_after;
356         char *slines_before;
357         char *Copt;
358
359         opt_complementary = "H-h:e::f::C-AB";
360         getopt32(argc, argv,
361                 OPTSTR_GREP,
362                 &pattern_head, &fopt,
363                 &slines_after, &slines_before, &Copt);
364
365         if (option_mask32 & OPT_C) {
366                 /* -C unsets prev -A and -B, but following -A or -B
367                    may override it */
368                 if (!(option_mask32 & OPT_A)) /* not overridden */
369                         slines_after = Copt;
370                 if (!(option_mask32 & OPT_B)) /* not overridden */
371                         slines_before = Copt;
372                 option_mask32 |= OPT_A|OPT_B; /* for parser */
373         }
374         if (option_mask32 & OPT_A) {
375                 lines_after = xatoi_u(slines_after);
376         }
377         if (option_mask32 & OPT_B) {
378                 lines_before = xatoi_u(slines_before);
379         }
380         /* sanity checks */
381         if (option_mask32 & (OPT_c|OPT_q|OPT_l|OPT_L)) {
382                 option_mask32 &= ~OPT_n;
383                 lines_before = 0;
384                 lines_after = 0;
385         } else if (lines_before > 0)
386                 before_buf = xzalloc(lines_before * sizeof(char *));
387 #else
388         /* with auto sanity checks */
389         opt_complementary = "H-h:e::f::c-n:q-n:l-n";
390         getopt32(argc, argv, OPTSTR_GREP,
391                 &pattern_head, &fopt);
392 #endif
393         invert_search = ((option_mask32 & OPT_v) != 0); /* 0 | 1 */
394
395         if (pattern_head != NULL) {
396                 /* convert char *argv[] to grep_list_data_t */
397                 llist_t *cur;
398
399                 for (cur = pattern_head; cur; cur = cur->link)
400                         cur->data = new_grep_list_data(cur->data, 0);
401         }
402         if (option_mask32 & OPT_f)
403                 load_regexes_from_file(fopt);
404
405         if (ENABLE_FEATURE_GREP_FGREP_ALIAS && applet_name[0] == 'f')
406                 option_mask32 |= OPT_F;
407
408         if (!(option_mask32 & (OPT_o | OPT_w)))
409                 reflags = REG_NOSUB;
410
411         if (ENABLE_FEATURE_GREP_EGREP_ALIAS &&
412                         (applet_name[0] == 'e' || (option_mask32 & OPT_E)))
413                 reflags |= REG_EXTENDED;
414
415         if (option_mask32 & OPT_i)
416                 reflags |= REG_ICASE;
417
418         argv += optind;
419         argc -= optind;
420
421         /* if we didn't get a pattern from a -e and no command file was specified,
422          * argv[optind] should be the pattern. no pattern, no worky */
423         if (pattern_head == NULL) {
424                 char *pattern;
425                 if (*argv == NULL)
426                         bb_show_usage();
427                 pattern = new_grep_list_data(*argv++, 0);
428                 llist_add_to(&pattern_head, pattern);
429                 argc--;
430         }
431
432         /* argv[(optind)..(argc-1)] should be names of file to grep through. If
433          * there is more than one file to grep, we will print the filenames. */
434         if (argc > 1)
435                 print_filename = 1;
436         /* -H / -h of course override */
437         if (option_mask32 & OPT_H)
438                 print_filename = 1;
439         if (option_mask32 & OPT_h)
440                 print_filename = 0;
441
442         /* If no files were specified, or '-' was specified, take input from
443          * stdin. Otherwise, we grep through all the files specified. */
444         if (argc == 0)
445                 argc++;
446         matched = 0;
447         while (argc--) {
448                 cur_file = *argv++;
449                 file = stdin;
450                 if (!cur_file || (*cur_file == '-' && !cur_file[1])) {
451                         cur_file = "(standard input)";
452                 } else {
453                         if (option_mask32 & OPT_r) {
454                                 struct stat st;
455                                 if (stat(cur_file, &st) == 0 && S_ISDIR(st.st_mode)) {
456                                         if (!(option_mask32 & OPT_h))
457                                                 print_filename = 1;
458                                         matched += grep_dir(cur_file);
459                                         goto grep_done;
460                                 }
461                         }
462                         /* else: fopen(dir) will succeed, but reading won't */
463                         file = fopen(cur_file, "r");
464                         if (file == NULL) {
465                                 if (!SUPPRESS_ERR_MSGS)
466                                         bb_perror_msg("%s", cur_file);
467                                 open_errors = 1;
468                                 continue;
469                         }
470                 }
471                 matched += grep_file(file);
472                 fclose_if_not_stdin(file);
473  grep_done:
474                 if (matched < 0) {
475                         /* we found a match but were told to be quiet, stop here and
476                         * return success */
477                         break;
478                 }
479         }
480
481         /* destroy all the elments in the pattern list */
482         if (ENABLE_FEATURE_CLEAN_UP) {
483                 while (pattern_head) {
484                         llist_t *pattern_head_ptr = pattern_head;
485                         grep_list_data_t *gl =
486                                 (grep_list_data_t *)pattern_head_ptr->data;
487
488                         pattern_head = pattern_head->link;
489                         if ((gl->flg_mem_alocated_compiled & PATTERN_MEM_A))
490                                 free(gl->pattern);
491                         if ((gl->flg_mem_alocated_compiled & COMPILED))
492                                 regfree(&(gl->preg));
493                         free(pattern_head_ptr);
494                 }
495         }
496         /* 0 = success, 1 = failed, 2 = error */
497         /* If the -q option is specified, the exit status shall be zero
498          * if an input line is selected, even if an error was detected.  */
499         if (BE_QUIET && matched)
500                 return 0;
501         if (open_errors)
502                 return 2;
503         return !matched; /* invert return value 0 = success, 1 = failed */
504 }