Debian Codegraph @

src/pdfgrep.cc

raw symbols SCIP
1 /***************************************************************************
2 * Copyright (C) 2010-2023 by Hans-Peter Deifel *
3 * [email protected] *
4 * *
5 * This program is free software; you can redistribute it and/or modify *
6 * it under the terms of the GNU General Public License as published by *
7 * the Free Software Foundation; either version 2 of the License, or *
8 * (at your option) any later version. *
9 * *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
14 * *
15 * You should have received a copy of the GNU General Public License *
16 * along with this program; if not, write to the *
17 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, *
18 * Boston, MA 02110-1301 USA. *
19 ***************************************************************************/
20
21 #include "config.h"
22
23 #include <cstdio>
24 #include <cstdlib>
25 #include <cstring>
26 #include <cctype>
27 #include <sys/types.h>
28 #include <getopt.h>
29 #include <cstdarg>
30 #include <unistd.h>
31 #include <cmath>
32 #include <fnmatch.h>
33 #include <cerrno>
34 #include <dirent.h>
35 #include <sys/stat.h>
36 #include <sys/types.h>
37 #include <climits>
38 #include <vector>
39 #include <iostream>
40 #include <sstream>
41 #include <fstream>
42 #include <locale>
43 #include <gcrypt.h>
44
45 #include <cpp/poppler-document.h>
46 #include <cpp/poppler-page.h>
47 #include <cpp/poppler-version.h>
48
49
50 #ifdef HAVE_UNAC
51 #include <unac.h>
52 #endif
53
54 #include <memory>
55
56 #include "pdfgrep.h"
57 #include "output.h"
58 #include "exclude.h"
59 #include "regengine.h"
60 #include "search.h"
61 #include "cache.h"
62 #include "intervals.h"
63
64 using namespace std;
65
66 /* set this to 1 if any match was found. Used for the exit status */
67 bool found_something = false;
68
69
70 // Options
71
72 enum {
73 HELP_OPTION,
74 COLOR_OPTION,
75 EXCLUDE_OPTION,
76 INCLUDE_OPTION,
77 PASSWORD,
78 DEBUG_OPTION,
79 PREFIX_SEP_OPTION,
80 WARN_EMPTY_OPTION,
81 UNAC_OPTION,
82 CACHE_OPTION,
83 PAGE_RANGE_OPTION,
84 PAGENUM_OPTION,
85 };
86
87 struct option long_options[] =
88 {
89 // name, has_arg, *flag, val
90 {"ignore-case", no_argument, nullptr, 'i'},
91 {"perl-regexp", no_argument, nullptr, 'P'},
92 {"page-number", optional_argument, nullptr, PAGENUM_OPTION},
93 {"with-filename", no_argument, nullptr, 'H'},
94 {"no-filename", no_argument, nullptr, 'h'},
95 {"count", no_argument, nullptr, 'c'},
96 {"color", required_argument, nullptr, COLOR_OPTION},
97 {"recursive", no_argument, nullptr, 'r'},
98 {"dereference-recursive", no_argument, nullptr, 'R'},
99 {"exclude", required_argument, nullptr, EXCLUDE_OPTION},
100 {"include", required_argument, nullptr, INCLUDE_OPTION},
101 {"help", no_argument, nullptr, HELP_OPTION},
102 {"version", no_argument, nullptr, 'V'},
103 {"page-count", no_argument, nullptr, 'p'},
104 {"quiet", no_argument, nullptr, 'q'},
105 {"password", required_argument, nullptr, PASSWORD},
106 {"max-count", required_argument, nullptr, 'm'},
107 {"debug", no_argument, nullptr, DEBUG_OPTION},
108 {"only-matching", no_argument, nullptr, 'o'},
109 {"null", no_argument, nullptr, 'Z'},
110 {"match-prefix-separator", required_argument, nullptr, PREFIX_SEP_OPTION},
111 {"warn-empty", no_argument, nullptr, WARN_EMPTY_OPTION},
112 {"unac", no_argument, nullptr, UNAC_OPTION},
113 {"fixed-strings", no_argument, nullptr, 'F'},
114 {"cache", no_argument, nullptr, CACHE_OPTION},
115 {"after-context", required_argument, nullptr, 'A'},
116 {"before-context", required_argument, nullptr, 'B'},
117 {"context", required_argument, nullptr, 'C'},
118 {"page-range", required_argument, nullptr, PAGE_RANGE_OPTION},
119 {"regexp", required_argument, nullptr, 'e'},
120 {"file", required_argument, nullptr, 'f'},
121 {"files-with-matches", no_argument, nullptr, 'l'},
122 {"files-without-match", no_argument, nullptr, 'L'},
123 {nullptr, 0, nullptr, 0}
124 };
125
126 #ifdef HAVE_UNAC
127 /* convenience layer over libunac. */
128 string simple_unac(const Options &opts, const string str)
129 {
130 if (!opts.use_unac) {
131 return str;
132 }
133
134 char *res = NULL;
135 size_t reslen = 0;
136
137 if (unac_string("UTF-8", str.c_str(), str.size(), &res, &reslen) != 0) {
138 perror("pdfgrep: Failed to remove accents: ");
139 return str;
140 }
141
142 return res;
143 }
144 #endif
145
146 /* parses a color pair like "foo=bar" to "foo" and "bar" */
147 static void parse_env_color_pair(char* pair, char** name, char** value)
148 {
149 *name = pair;
150 int i = 0;
151 while (pair[i] != '\0' && pair[i] != '=') {
152 i++;
153 }
154 if (pair[i] == '=') {
155 /* value starts one char after '=' */
156 *value = pair+i+1;
157 /* and replace '=' by '\0' */
158 pair[i] = '\0';
159 } else { /* if pair[i] == '\0' */
160 /* let value point to the '\0' */
161 *value = pair+i;
162 }
163 }
164
165
166 /* set colors of output according to content of environment-varaible env_var.
167 the content of env_var has to be like the GREP_COLORS variable for grep
168 see man 1 grep for further details of GREP_COLORS */
169 static void read_colors_from_env(Colorconf &colors, const char* env_var)
170 {
171 /* create a copy of var to edit it with strtok */
172 if (getenv(env_var) == nullptr) {
173 return;
174 }
175 char* colors_list = strdup(getenv(env_var));
176 if (colors_list == nullptr) {
177 /* if var is not set */
178 return;
179 }
180 /* save original length _before_ editing it with strtok */
181 int colors_list_len = strlen(colors_list);
182 int i = 0;
183 char* cur_color_pair;
184 char *cur_name, *cur_value;
185 /* read all color=value pairs */
186 while (i < colors_list_len && (cur_color_pair = strtok(colors_list+i, ":")) != nullptr) {
187 /* set index i to next color pair */
188 i += strlen(cur_color_pair); /* skip token content */
189 i += 1; /* skip delemiter */
190 /* get name and value of color pair */
191 parse_env_color_pair(cur_color_pair, &cur_name, &cur_value);
192
193 #define PARSE_COLOR(GREP_NAME, GLOBAL_VAR) \
194 if (!strcmp(cur_name, GREP_NAME)) { \
195 free(GLOBAL_VAR); /* free old value */ \
196 GLOBAL_VAR = strdup(cur_value); /* set to new color */ \
197 }
198
199 /* now check for known settings and set global colors */
200 PARSE_COLOR("mt", colors.highlight)
201 else PARSE_COLOR("ms", colors.highlight)
202 else PARSE_COLOR("mc", colors.highlight)
203 else PARSE_COLOR("fn", colors.filename)
204 else PARSE_COLOR("ln", colors.pagenum)
205 else PARSE_COLOR("se", colors.separator)
206
207 #undef PARSE_COLOR
208
209 }
210 /* free our copy of the environment var */
211 free(colors_list);
212 }
213
214 static void set_default_colors(Colorconf &colors)
215 {
216 // The grep(1) manpage documents the default value of GREP_COLORS to be
217 // ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=36
218 // which corresponds to these values below:
219
220 colors.filename = strdup("35");
221 colors.pagenum = strdup("32");
222 colors.highlight = strdup("01;31");
223 colors.separator = strdup("36");
224 }
225
226 static void init_colors(Colorconf &colors)
227 {
228 set_default_colors(colors);
229 }
230
231 static void print_usage(char *self)
232 {
233 cout << "Usage: " << self << " [OPTION]... PATTERN FILE..." << endl;
234 cout << endl << "See '" << self << " --help' for more information" << endl;
235 }
236
237 static void print_help(char *self)
238 {
239 cout << "Usage: " << self << " [OPTION]... PATTERN FILE..." << endl << endl
240 << "Search for PATTERN in each FILE." << endl
241 << "PATTERN is, by default, an extended regular expression." << endl
242 << endl
243 << "Commonly used options:" << endl
244 << " -i, --ignore-case Ignore case distinctions" << endl
245 << " -P, --perl-regexp Use Perl compatible regular expressions (PCRE)" << endl
246 << " -H, --with-filename Print the file name for each match" << endl
247 << " -h, --no-filename Suppress the prefixing of file name on output" << endl
248 << " -n, --page-number Print page number with output lines" << endl
249 << " -c, --count Print only a count of matches per file" << endl
250 << " --color WHEN Use colors for highlighting;" << endl
251 << " WHEN can be `always', `never' or `auto'" << endl
252 << " -p, --page-count Print only a count of matches per page" << endl
253 << " -m, --max-count NUM Stop reading after NUM matching lines (per file)" << endl
254 << " -q, --quiet Suppress normal output" << endl
255 << " -r, --recursive Search directories recursively" << endl
256 << " -R, --dereference-recursive Likewise, but follow all symlinks" << endl
257 << " --cache Use cache for faster operation" << endl
258 << " --help Print this help" << endl
259 << " -V, --version Show version information" << endl << endl
260 << "The above list is only a selection of commonly used options. Please refer" << endl
261 << "to the man page for a complete list." << endl;
262 }
263
264 static void print_version()
265 {
266 cout << "This is " << PACKAGE << " version " << VERSION << "." << endl << endl;
267 cout << "Using poppler version " << poppler::version_string().c_str() << endl;
268 #ifdef HAVE_UNAC
269 cout << "Using libunac version " << unac_version() << endl;
270 #endif
271 #ifdef HAVE_LIBPCRE
272 auto pcre_version = make_unique<char[]>(pcre2_config(PCRE2_CONFIG_VERSION, nullptr));
273 pcre2_config(PCRE2_CONFIG_VERSION, pcre_version.get());
274 cout << "Using libpcre2 version " << pcre_version.get() << endl;
275 #endif
276 #ifdef PDFGREP_GIT_HEAD
277 cout << "Built from git-commit " << PDFGREP_GIT_HEAD << endl;
278 #endif
279 }
280
281 static bool is_dir(const string &filename)
282 {
283 struct stat st;
284
285 return stat(filename.c_str(), &st) == 0 && S_ISDIR(st.st_mode);
286 }
287
288 static int sha1_file(const std::string &filename, unsigned char *sha1out)
289 {
290 std::ifstream file(filename);
291 std::stringstream content;
292 if (!(content << file.rdbuf())) {
293 return -1;
294 }
295 std::string str(content.str());
296
297 gcry_md_hash_buffer( GCRY_MD_SHA1, sha1out, str.c_str(), str.size());
298 return 0;
299 }
300
301 /** Perform search in `path`
302 *
303 * - filename is the basename of the file without the directory part
304 *
305 * TODO Return bool
306 */
307 static int do_search_in_document(const Options &opts, const string &path, const string &filename,
308 Regengine &re, bool check_excludes = true)
309 {
310 if (check_excludes &&
311 (!is_excluded(opts.includes, filename) || is_excluded(opts.excludes, filename))) {
312 return 0;
313 }
314
315 unique_ptr<Cache> cache;
316
317 if (opts.use_cache) {
318 unsigned char sha1sum[20];
319 std::string cache_file(opts.cache_directory);
320 if (sha1_file(path, sha1sum) != 0) {
321 err() << "Could not compute checksum for " << path << endl;
322 return 1;
323 }
324 char translate[] = "0123456789abcdef";
325 for (unsigned char c : sha1sum) {
326 cache_file += translate[c & 0xf];
327 cache_file += translate[(c >> 4 ) & 0xf];
328 }
329
330 cache = make_unique<Cache>(cache_file);
331 }
332
333 unique_ptr<poppler::document> doc;
334
335 if (opts.passwords.empty()) {
336 err() << "Internal error, password vector empty!" << endl;
337 abort();
338 }
339
340 for (string const &password : opts.passwords) {
341 // FIXME This logic doesn't seem to make sens. What if only the
342 // first password is correct?
343 doc = unique_ptr<poppler::document>(
344 poppler::document::load_from_file(path, string(password),
345 string(password))
346 );
347 }
348
349 if (doc == nullptr || doc->is_locked()) {
350 err() << "Could not open " << path.c_str() << endl;
351 return 1;
352 }
353
354 int matches = search_document(opts, move(doc), move(cache), path, re);
355 if (matches > 0) {
356 found_something = true;
357 if (opts.quiet) {
358 exit(EXIT_SUCCESS); // FIXME: Handle this with return value
359 }
360 }
361
362 return 0;
363 }
364
365 static int do_search_in_directory(const Options &opts, const string &filename, Regengine &re)
366 {
367 DIR *ptrDir = nullptr;
368
369 ptrDir = opendir(filename.c_str());
370 if (ptrDir == nullptr) {
371 err() << filename.c_str() << ": " << strerror(errno) << endl;
372 return 1;
373 }
374
375 while(true) {
376 string path(filename);
377 errno = 0;
378 struct dirent *ptrDirent = readdir(ptrDir); //not sorted, in order as `ls -f`
379 if (ptrDirent == nullptr) {
380 break;
381 }
382
383 if (strcmp(ptrDirent->d_name, ".") == 0 || strcmp(ptrDirent->d_name, "..") == 0) {
384 continue;
385 }
386
387 path += "/";
388 path += ptrDirent->d_name;
389
390 struct stat st;
391 int statret;
392
393 if (opts.recursive == Recursion::FOLLOW_SYMLINKS) {
394 statret = stat(path.c_str(), &st);
395 } else {
396 statret = lstat(path.c_str(), &st);
397 }
398
399 if (statret != 0) {
400 err() << filename.c_str() << ": " << strerror(errno) << endl;
401 continue;
402 }
403
404 if (S_ISLNK(st.st_mode)) {
405 continue;
406 }
407
408 if (S_ISDIR(st.st_mode)) {
409 do_search_in_directory(opts, path, re);
410 } else {
411 do_search_in_document(opts, path, ptrDirent->d_name, re);
412 }
413 }
414
415 closedir(ptrDir);
416
417 return 0;
418 }
419
420 static bool parse_int(const char *str, int *i)
421 {
422 char *endptr;
423 errno = 0;
424 unsigned long int d = strtoul(str, &endptr, 10);
425 if (errno != 0 || (long)d > INT_MAX || (long)d < INT_MIN
426 || *endptr != '\0') {
427 return false;
428 }
429
430 *i = d;
431 return true;
432 }
433
434 bool read_pattern_file(string const &filename, vector<string> &patterns)
435 {
436 ifstream file(filename);
437
438 if (!file.is_open()) {
439 err() << filename << ": " << strerror(errno) << endl;
440 return false;
441 }
442
443 string line;
444 while (getline(file, line)) {
445 patterns.push_back(line);
446 }
447
448 if (file.bad()) {
449 err() << filename << ": " << strerror(errno) << endl;
450 return false;
451 }
452
453 return true;
454 }
455
456 #if POPPLER_VERSION_MAJOR > 0 || POPPLER_VERSION_MINOR >= 29
457 static void handle_poppler_errors(const string &msg, void *_opts)
458 {
459 auto *opts = static_cast<Options*>(_opts);
460 if (opts->debug) {
461 err() << msg << endl;
462 }
463 }
464 #endif
465
466 int main(int argc, char** argv)
467 {
468 Options options;
469 init_colors(options.outconf.colors);
470
471 try {
472 // Set locale to user-preference. If this locale is an UTF-8 locale, the
473 // regex-functions regcomp/regexec become unicode aware, which means
474 // e.g. that '.' will match a unicode character, not a single byte.
475 locale::global(locale(""));
476 } catch (const runtime_error &e) {
477 // Fall back to the "C" locale.
478 locale::global(locale::classic());
479 err() << "Failed to set user locale: \"" << e.what()
480 << "\". Falling back to default" << endl;
481 }
482
483 enum re_engine_type {
484 RE_POSIX = 0,
485 RE_PCRE = 1,
486 RE_FIXED = 2
487 };
488
489 int re_engine = RE_POSIX;
490
491 // either -H or -h was set
492 bool explicit_filename_option = false;
493
494 enum {
495 COLOR_ALWAYS,
496 COLOR_AUTO,
497 COLOR_NEVER
498 } use_colors = COLOR_AUTO;
499
500 // patterns specified with --regex or --file
501 vector<string> patterns;
502 bool patterns_specified = false;
503
504 while (true) {
505 int c = getopt_long(argc, argv, "icA:B:C:nrRhHVPpqm:FoZe:f:lL",
506 long_options, nullptr);
507
508 if (c == -1) {
509 break;
510 }
511
512 switch (c) {
513 case HELP_OPTION:
514 print_help(argv[0]);
515 exit(EXIT_SUCCESS);
516 case 'V':
517 print_version();
518 exit(EXIT_SUCCESS);
519 case 'n':
520 options.outconf.pagenum = true;
521 break;
522 case PAGENUM_OPTION:
523 options.outconf.pagenum = true;
524 if (optarg == nullptr || !strcmp(optarg, "index")) {
525 options.outconf.pagenum_type = PagenumType::INDEX;
526 } else if (!strcmp(optarg, "label")) {
527 options.outconf.pagenum_type = PagenumType::LABEL;
528 } else {
529 err() << "Invalid argument '" << optarg
530 << "' for --page-number"
531 << "Candidates are: index, label"
532 << endl;
533 exit(EXIT_ERROR);
534 }
535 break;
536 case 'r':
537 options.recursive = Recursion::DONT_FOLLOW_SYMLINKS;
538 break;
539 case 'R':
540 options.recursive = Recursion::FOLLOW_SYMLINKS;
541 break;
542 case 'h':
543 options.outconf.filename = false;
544 explicit_filename_option = true;
545 break;
546 case 'H':
547 options.outconf.filename = true;
548 explicit_filename_option = true;
549 break;
550 case 'i':
551 options.ignore_case = true;
552 break;
553 case 'c':
554 options.count = true;
555 break;
556 case COLOR_OPTION:
557 if (strcmp("always", optarg) == 0) {
558 use_colors = COLOR_ALWAYS;
559 } else if (strcmp("never", optarg) == 0) {
560 use_colors = COLOR_NEVER;
561 } else if (strcmp("auto", optarg) == 0) {
562 use_colors = COLOR_AUTO;
563 } else {
564 err() << "Invalid argument '" << optarg << "' for --color. "
565 << "Candidates are: always, never or auto" << endl;
566 exit(EXIT_ERROR);
567 }
568 break;
569 case EXCLUDE_OPTION:
570 exclude_add(options.excludes, optarg);
571 break;
572 case INCLUDE_OPTION:
573 exclude_add(options.includes, optarg);
574 break;
575 case 'P':
576 #ifndef HAVE_LIBPCRE
577 err() << "PCRE support disabled at compile time!" << endl;
578 exit(EXIT_ERROR);
579 #else
580 re_engine |= RE_PCRE;
581 #endif
582 break;
583 case 'p':
584 options.pagecount = true;
585 options.outconf.pagenum = true;
586 break;
587
588 case 'q':
589 options.quiet = true;
590 break;
591
592 case PASSWORD:
593 options.passwords.emplace_back(string(optarg));
594 break;
595
596 case 'm':
597 if (!parse_int(optarg, &options.max_count)) {
598 err() << "Could not parse number: " << optarg << "." << endl;
599 exit(EXIT_ERROR);
600 } else if (options.max_count <= 0) {
601 err() << "--max-count must be positive." << endl;
602 exit(EXIT_ERROR);
603 }
604 break;
605 case DEBUG_OPTION:
606 options.debug = true;
607 break;
608
609 case UNAC_OPTION:
610 #ifndef HAVE_UNAC
611 err() << "UNAC support disabled at compile time!" << endl;
612 exit(EXIT_ERROR);
613 #else
614 options.use_unac = true;
615 #endif
616 break;
617 case 'F':
618 re_engine |= RE_FIXED;
619 break;
620
621 case CACHE_OPTION:
622 options.use_cache = true;
623 break;
624
625 case 'o':
626 options.outconf.only_matching = true;
627 break;
628
629 case 'Z': // --null
630 options.outconf.null_byte_sep = true;
631 break;
632
633 case PREFIX_SEP_OPTION:
634 options.outconf.prefix_sep = string(optarg);
635 break;
636
637 case WARN_EMPTY_OPTION:
638 options.warn_empty = true;
639 break;
640
641 case 'A':
642 if (!parse_int(optarg, &options.outconf.context_after)) {
643 err() << "Could not parse number: " << optarg << "." << endl;
644 exit(EXIT_ERROR);
645 } else if (options.outconf.context_after < 0) {
646 err() << "--after-context must be positive." << endl;
647 exit(EXIT_ERROR);
648 }
649 options.outconf.context_mode = true;
650 break;
651
652 case 'B':
653 if (!parse_int(optarg, &options.outconf.context_before)) {
654 err() << "Could not parse number: " << optarg << "." << endl;
655 exit(EXIT_ERROR);
656 } else if (options.outconf.context_before < 0) {
657 err() << "--before-context must be positive." << endl;
658 exit(EXIT_ERROR);
659 }
660 options.outconf.context_mode = true;
661 break;
662
663 case 'C':
664 if (!parse_int(optarg, &options.outconf.context_after)) {
665 err() << "Could not parse number: " << optarg << "." << endl;
666 exit(EXIT_ERROR);
667 } else if (options.outconf.context_after < 0) {
668 err() << "--after-context must be positive." << endl;
669 exit(EXIT_ERROR);
670 }
671 options.outconf.context_before = options.outconf.context_after;
672 options.outconf.context_mode = true;
673 break;
674
675 case PAGE_RANGE_OPTION:
676 options.page_range = IntervalContainer::fromString(optarg);
677 break;
678
679 case 'e':
680 patterns_specified = true;
681 patterns.emplace_back(string(optarg));
682 break;
683
684 case 'f':
685 patterns_specified = true;
686 if (!read_pattern_file(string(optarg), patterns)) {
687 exit(EXIT_ERROR);
688 }
689 break;
690
691 case 'l':
692 options.only_filenames = OnlyFilenames::WITH_MATCHES;
693 break;
694
695 case 'L':
696 options.only_filenames = OnlyFilenames::WITHOUT_MATCH;
697 break;
698
699 /* In these two cases, getopt already prints an
700 * error message
701 */
702 case '?': // unknown option
703 case ':': // missing argument
704 exit(EXIT_ERROR);
705 break;
706 default:
707 break;
708 }
709 }
710
711 int remaining_args = argc - optind;
712 int required_args = 0;
713 if (!patterns_specified) {
714 required_args++;
715 }
716 if (options.recursive == Recursion::NONE) {
717 required_args++;
718 }
719
720 if (remaining_args < required_args) {
721 print_usage(argv[0]);
722 exit(EXIT_ERROR);
723 }
724
725 unique_ptr<Regengine> re;
726 if (re_engine == (RE_FIXED | RE_PCRE)) {
727 err() << "--pcre and --fixed cannot be used together" << endl;
728 exit(EXIT_ERROR);
729 }
730
731 auto make_regengine = [&](const string pattern) -> unique_ptr<Regengine> {
732 #ifdef HAVE_UNAC
733 const string new_pattern = simple_unac(options, pattern);
734 #else
735 const string new_pattern = pattern;
736 #endif
737 #ifdef HAVE_LIBPCRE
738 if (re_engine == RE_PCRE) {
739 return make_unique<PCRERegex>(new_pattern, options.ignore_case);
740 }
741 #endif // HAVE_LIBPCRE
742 if (re_engine == RE_FIXED) {
743 return make_unique<FixedString>(new_pattern, options.ignore_case);
744 }
745
746 // RE_POSIX
747 return make_unique<PosixRegex>(new_pattern, options.ignore_case);
748 };
749
750 if (patterns.empty()) {
751 re = make_regengine(argv[optind++]);
752 } else {
753 auto patt_list = std::make_unique<PatternList>();
754 for (auto const &p : patterns) {
755 patt_list->add_pattern(make_regengine(p));
756 }
757 re = move(patt_list);
758 }
759
760 #if POPPLER_VERSION_MAJOR > 0 || POPPLER_VERSION_MINOR >= 29
761 // set poppler error output function
762 poppler::set_debug_error_function(handle_poppler_errors, &options);
763 #endif
764
765 bool color_tty = isatty(STDOUT_FILENO) != 0
766 && getenv("TERM") != nullptr
767 && strcmp(getenv("TERM"), "dumb") != 0;
768
769 options.outconf.color =
770 use_colors == COLOR_ALWAYS
771 || (use_colors == COLOR_AUTO && color_tty);
772
773 if (options.outconf.color) {
774 read_colors_from_env(options.outconf.colors, "GREP_COLORS");
775 }
776
777 if (!explicit_filename_option) {
778 if ((argc - optind) == 1 && !is_dir(argv[optind])) {
779 options.outconf.filename = false;
780 } else {
781 options.outconf.filename = true;
782 }
783 }
784
785 if (options.outconf.only_matching && (options.outconf.context_before > 0
786 || options.outconf.context_after > 0)) {
787 err() << "warning: --only-matching and context options can't be used together."
788 << " Ignoring context option." << endl;
789
790 options.outconf.context_mode = false;
791 }
792
793 if (options.count && options.outconf.pagenum) {
794 err() << "warning: --count and --page-number can't be used together."
795 << " Ignoring --page-number." << endl;
796
797 options.outconf.pagenum = false;
798 }
799
800 // TODO Warn about --files-{with-matches,without-match} and other output
801 // options
802
803 if (excludes_empty(options.includes)) {
804 exclude_add(options.includes, "*.[Pp][Dd][Ff]");
805 }
806
807 // If no password has been specified on the command line, insert the
808 // empty string aka "no password" into the passwords array.
809 if (options.passwords.empty()) {
810 options.passwords.emplace_back("");
811 }
812
813 if (options.use_cache) {
814 if (find_cache_directory(options.cache_directory) != 0) {
815 err() << "warning: Failed to initialize cache directory."
816 << " no cache is used!" << endl;
817 options.use_cache = false;
818 } else {
819 char *limitstr = getenv("PDFGREP_CACHE_LIMIT");
820 unsigned int limit = (limitstr != nullptr) ? strtoul(limitstr, nullptr, 10) : 200;
821 limit_cachesize(options.cache_directory.c_str(), limit);
822 }
823 }
824
825 bool error = false;
826
827 for (int i = optind; i < argc; i++) {
828 const string filename(argv[i]);
829
830 if (!is_dir(filename)) {
831 if (do_search_in_document(options, filename, filename, *re, false) != 0) {
832 error = true;
833 }
834 } else if (options.recursive != Recursion::NONE) {
835 if (do_search_in_directory(options, filename, *re) != 0) {
836 error = true;
837 }
838 } else {
839 err() << filename << " is a directory. Did you mean to use '--recursive'?" << endl;
840 error = true;
841 }
842 }
843
844 if (argc == optind && options.recursive != Recursion::NONE) {
845 do_search_in_directory(options, ".", *re);
846 }
847
848 if (error) {
849 exit(EXIT_ERROR);
850 } else if (found_something) {
851 exit(EXIT_SUCCESS);
852 } else {
853 exit(EXIT_NOT_FOUND);
854 }
855 }
856
857 /* vim: set noet: */