- new bb_opt_complementally syntax, use [-:?] only - 'free' chars
[platform/upstream/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, 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  * Apr 2004 by Vladimir Oleynik <dzo@simtreas.ru> -
15  * correction "-e pattern1 -e pattern2" logic and more optimizations.
16 */
17
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <getopt.h>
21 #include <string.h>
22 #include <errno.h>
23 #include "busybox.h"
24 #include "xregex.h"
25
26
27 /* options */
28 static unsigned long opt;
29 #define GREP_OPTS "lnqvscFiHhe:f:L"
30 #define GREP_OPT_l (1<<0)
31 #define PRINT_FILES_WITH_MATCHES (opt & GREP_OPT_l)
32 #define GREP_OPT_n (1<<1)
33 #define PRINT_LINE_NUM (opt & GREP_OPT_n)
34 #define GREP_OPT_q (1<<2)
35 #define BE_QUIET (opt & GREP_OPT_q)
36 #define GREP_OPT_v (1<<3)
37 typedef char invert_search_t;
38 static invert_search_t invert_search;
39 #define GREP_OPT_s (1<<4)
40 #define SUPPRESS_ERR_MSGS (opt & GREP_OPT_s)
41 #define GREP_OPT_c (1<<5)
42 #define PRINT_MATCH_COUNTS (opt & GREP_OPT_c)
43 #define GREP_OPT_F (1<<6)
44 #define FGREP_FLAG (opt & GREP_OPT_F)
45 #define GREP_OPT_i (1<<7)
46 #define GREP_OPT_H (1<<8)
47 #define GREP_OPT_h (1<<9)
48 #define GREP_OPT_e (1<<10)
49 #define GREP_OPT_f (1<<11)
50 #define GREP_OPT_L (1<<12)
51 #define PRINT_FILES_WITHOUT_MATCHES ((opt & GREP_OPT_L) != 0)
52 #if ENABLE_FEATURE_GREP_CONTEXT
53 #define GREP_OPT_CONTEXT "A:B:C"
54 #define GREP_OPT_A (1<<13)
55 #define GREP_OPT_B (1<<14)
56 #define GREP_OPT_C (1<<15)
57 #define GREP_OPT_E (1<<16)
58 #else
59 #define GREP_OPT_CONTEXT ""
60 #define GREP_OPT_A (0)
61 #define GREP_OPT_B (0)
62 #define GREP_OPT_C (0)
63 #define GREP_OPT_E (1<<13)
64 #endif
65 #if ENABLE_FEATURE_GREP_EGREP_ALIAS
66 # define OPT_EGREP "E"
67 #else
68 # define OPT_EGREP ""
69 #endif
70
71 static int reflags;
72 static int print_filename;
73
74 #if ENABLE_FEATURE_GREP_CONTEXT
75 static int lines_before;
76 static int lines_after;
77 static char **before_buf;
78 static int last_line_printed;
79 #endif /* ENABLE_FEATURE_GREP_CONTEXT */
80
81 /* globals used internally */
82 static llist_t *pattern_head;   /* growable list of patterns to match */
83 static char *cur_file;          /* the current file we are reading */
84
85
86 static void print_line(const char *line, int linenum, char decoration)
87 {
88 #if ENABLE_FEATURE_GREP_CONTEXT
89         /* possibly print the little '--' separator */
90         if ((lines_before || lines_after) && last_line_printed &&
91                         last_line_printed < linenum - 1) {
92                 puts("--");
93         }
94         last_line_printed = linenum;
95 #endif
96         if (print_filename > 0)
97                 printf("%s%c", cur_file, decoration);
98         if (PRINT_LINE_NUM)
99                 printf("%i%c", linenum, decoration);
100         puts(line);
101 }
102
103
104 static int grep_file(FILE *file)
105 {
106         char *line;
107         invert_search_t ret;
108         int linenum = 0;
109         int nmatches = 0;
110 #if ENABLE_FEATURE_GREP_CONTEXT
111         int print_n_lines_after = 0;
112         int curpos = 0; /* track where we are in the circular 'before' buffer */
113         int idx = 0; /* used for iteration through the circular buffer */
114 #endif /* ENABLE_FEATURE_GREP_CONTEXT */
115
116         while ((line = bb_get_chomped_line_from_file(file)) != NULL) {
117                 llist_t *pattern_ptr = pattern_head;
118
119                 linenum++;
120                 ret = 0;
121                 while (pattern_ptr) {
122                         if (FGREP_FLAG) {
123                                 ret = strstr(line, pattern_ptr->data) != NULL;
124                         } else {
125                                 /*
126                                  * test for a postitive-assertion match (regexec returns success (0)
127                                  * and the user did not specify invert search), or a negative-assertion
128                                  * match (regexec returns failure (REG_NOMATCH) and the user specified
129                                  * invert search)
130                                  */
131                                 regex_t regex;
132                                 xregcomp(&regex, pattern_ptr->data, reflags);
133                                 ret |= regexec(&regex, line, 0, NULL, 0) == 0;
134                                 regfree(&regex);
135                         }
136                         pattern_ptr = pattern_ptr->link;
137                 } /* while (pattern_ptr) */
138
139                 if ((ret ^ invert_search)) {
140
141                         if (PRINT_FILES_WITH_MATCHES || BE_QUIET)
142                                 free(line);
143
144                         /* if we found a match but were told to be quiet, stop here */
145                         if (BE_QUIET || PRINT_FILES_WITHOUT_MATCHES)
146                                 return -1;
147
148                                 /* keep track of matches */
149                                 nmatches++;
150
151                                 /* if we're just printing filenames, we stop after the first match */
152                                 if (PRINT_FILES_WITH_MATCHES)
153                                         break;
154
155                                 /* print the matched line */
156                                 if (PRINT_MATCH_COUNTS == 0) {
157 #if ENABLE_FEATURE_GREP_CONTEXT
158                                         int prevpos = (curpos == 0) ? lines_before - 1 : curpos - 1;
159
160                                         /* if we were told to print 'before' lines and there is at least
161                                          * one line in the circular buffer, print them */
162                                         if (lines_before && before_buf[prevpos] != NULL) {
163                                                 int first_buf_entry_line_num = linenum - lines_before;
164
165                                                 /* advance to the first entry in the circular buffer, and
166                                                  * figure out the line number is of the first line in the
167                                                  * buffer */
168                                                 idx = curpos;
169                                                 while (before_buf[idx] == NULL) {
170                                                         idx = (idx + 1) % lines_before;
171                                                         first_buf_entry_line_num++;
172                                                 }
173
174                                                 /* now print each line in the buffer, clearing them as we go */
175                                                 while (before_buf[idx] != NULL) {
176                                                         print_line(before_buf[idx], first_buf_entry_line_num, '-');
177                                                         free(before_buf[idx]);
178                                                         before_buf[idx] = NULL;
179                                                         idx = (idx + 1) % lines_before;
180                                                         first_buf_entry_line_num++;
181                                                 }
182                                         }
183
184                                         /* make a note that we need to print 'after' lines */
185                                         print_n_lines_after = lines_after;
186 #endif
187                                         print_line(line, linenum, ':');
188                                 }
189                         }
190 #if ENABLE_FEATURE_GREP_CONTEXT
191                         else { /* no match */
192                                 /* Add the line to the circular 'before' buffer */
193                                 if(lines_before) {
194                                         free(before_buf[curpos]);
195                                         before_buf[curpos] = bb_xstrdup(line);
196                                         curpos = (curpos + 1) % lines_before;
197                                 }
198                         }
199
200                         /* if we need to print some context lines after the last match, do so */
201                         if (print_n_lines_after && (last_line_printed != linenum)) {
202                                 print_line(line, linenum, '-');
203                                 print_n_lines_after--;
204                         }
205 #endif /* ENABLE_FEATURE_GREP_CONTEXT */
206                 free(line);
207         }
208
209
210         /* special-case file post-processing for options where we don't print line
211          * matches, just filenames and possibly match counts */
212
213         /* grep -c: print [filename:]count, even if count is zero */
214         if (PRINT_MATCH_COUNTS) {
215                 if (print_filename > 0)
216                         printf("%s:", cur_file);
217                     printf("%d\n", nmatches);
218         }
219
220         /* grep -l: print just the filename, but only if we grepped the line in the file  */
221         if (PRINT_FILES_WITH_MATCHES && nmatches > 0) {
222                 puts(cur_file);
223         }
224
225         /* grep -L: print just the filename, but only if we didn't grep the line in the file  */
226         if (PRINT_FILES_WITHOUT_MATCHES && nmatches == 0) {
227                 puts(cur_file);
228         }
229
230         return nmatches;
231 }
232
233 static void load_regexes_from_file(llist_t *fopt)
234 {
235         char *line;
236         FILE *f;
237
238         while(fopt) {
239                 llist_t *cur = fopt;
240                 char *ffile = cur->data;
241
242                 fopt = cur->link;
243                 free(cur);
244                 f = bb_xfopen(ffile, "r");
245                 while ((line = bb_get_chomped_line_from_file(f)) != NULL) {
246                         pattern_head = llist_add_to(pattern_head, line);
247                 }
248         }
249 }
250
251
252 extern int grep_main(int argc, char **argv)
253 {
254         FILE *file;
255         int matched;
256         llist_t *fopt = NULL;
257         int error_open_count = 0;
258
259         /* do normal option parsing */
260 #if ENABLE_FEATURE_GREP_CONTEXT
261   {
262         char *junk;
263         char *slines_after;
264         char *slines_before;
265         char *Copt;
266
267         bb_opt_complementally = "H-h:e::f::C-AB";
268         opt = bb_getopt_ulflags(argc, argv,
269                 GREP_OPTS GREP_OPT_CONTEXT OPT_EGREP,
270                 &pattern_head, &fopt,
271                 &slines_after, &slines_before, &Copt);
272
273         if(opt & GREP_OPT_C) {
274                 /* C option unseted A and B options, but next -A or -B
275                    may be ovewrite own option */
276                 if(!(opt & GREP_OPT_A))         /* not overwtited */
277                         slines_after = Copt;
278                 if(!(opt & GREP_OPT_B))         /* not overwtited */
279                         slines_before = Copt;
280                 opt |= GREP_OPT_A|GREP_OPT_B;   /* set for parse now */
281         }
282         if(opt & GREP_OPT_A) {
283                 lines_after = strtoul(slines_after, &junk, 10);
284                 if(*junk != '\0')
285                         bb_error_msg_and_die("invalid context length argument");
286         }
287         if(opt & GREP_OPT_B) {
288                 lines_before = strtoul(slines_before, &junk, 10);
289                 if(*junk != '\0')
290                         bb_error_msg_and_die("invalid context length argument");
291         }
292         /* sanity checks after parse may be invalid numbers ;-) */
293         if ((opt & (GREP_OPT_c|GREP_OPT_q|GREP_OPT_l|GREP_OPT_L))) {
294                 opt &= ~GREP_OPT_n;
295                 lines_before = 0;
296                 lines_after = 0;
297         } else if(lines_before > 0)
298                 before_buf = (char **)xcalloc(lines_before, sizeof(char *));
299         }
300 #else
301         /* with auto sanity checks */
302         bb_opt_complementally = "H-h:e::f::c-n:q-n:l-n";
303         opt = bb_getopt_ulflags(argc, argv, GREP_OPTS OPT_EGREP,
304                 &pattern_head, &fopt);
305 #endif
306         invert_search = (opt & GREP_OPT_v) != 0;        /* 0 | 1 */
307
308         if(opt & GREP_OPT_H)
309                 print_filename++;
310         if(opt & GREP_OPT_h)
311                 print_filename--;
312         if(opt & GREP_OPT_f)
313                 load_regexes_from_file(fopt);
314
315         if(ENABLE_FEATURE_GREP_FGREP_ALIAS && bb_applet_name[0] == 'f')
316                 opt |= GREP_OPT_F;
317
318         if(ENABLE_FEATURE_GREP_EGREP_ALIAS &&
319                         (bb_applet_name[0] == 'e' || (opt & GREP_OPT_E)))
320                 reflags = REG_EXTENDED | REG_NOSUB;
321         else
322                 reflags = REG_NOSUB;
323
324         if(opt & GREP_OPT_i)
325                 reflags |= REG_ICASE;
326
327         argv += optind;
328         argc -= optind;
329
330         /* if we didn't get a pattern from a -e and no command file was specified,
331          * argv[optind] should be the pattern. no pattern, no worky */
332         if (pattern_head == NULL) {
333                 if (*argv == NULL)
334                         bb_show_usage();
335                 else {
336                         pattern_head = llist_add_to(pattern_head, *argv++);
337                         argc--;
338                 }
339         }
340
341         /* argv[(optind)..(argc-1)] should be names of file to grep through. If
342          * there is more than one file to grep, we will print the filenames */
343         if (argc > 1) {
344                 print_filename++;
345
346         /* If no files were specified, or '-' was specified, take input from
347          * stdin. Otherwise, we grep through all the files specified. */
348         } else if (argc == 0) {
349                 argc++;
350         }
351         matched = 0;
352         while (argc--) {
353                 cur_file = *argv++;
354                 if(!cur_file || (*cur_file == '-' && !cur_file[1])) {
355                         cur_file = "(standard input)";
356                         file = stdin;
357                 } else {
358                         file = fopen(cur_file, "r");
359                 }
360                 if (file == NULL) {
361                         if (!SUPPRESS_ERR_MSGS)
362                                 bb_perror_msg("%s", cur_file);
363                         error_open_count++;
364                 } else {
365                         matched += grep_file(file);
366                         if(matched < 0) {
367                                 /* we found a match but were told to be quiet, stop here and
368                                 * return success */
369                                 break;
370                         }
371                         fclose(file);
372                 }
373         }
374
375         /* destroy all the elments in the pattern list */
376         if (ENABLE_FEATURE_CLEAN_UP)
377         while (pattern_head) {
378                 llist_t *pattern_head_ptr = pattern_head;
379
380                 pattern_head = pattern_head->link;
381                 free(pattern_head_ptr);
382         }
383
384         /* 0 = success, 1 = failed, 2 = error */
385         /* If the -q option is specified, the exit status shall be zero
386          * if an input line is selected, even if an error was detected.  */
387         if(BE_QUIET && matched)
388                 return 0;
389         if(error_open_count)
390                 return 2;
391         return !matched; /* invert return value 0 = success, 1 = failed */
392 }