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