grep.c 12 KB

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