grep.c 11 KB

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