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