]> git.sesse.net Git - plocate/blob - plocate.cpp
Add a --version option.
[plocate] / plocate.cpp
1 #include "db.h"
2 #include "io_uring_engine.h"
3 #include "parse_trigrams.h"
4 #include "unique_sort.h"
5
6 #include <algorithm>
7 #include <assert.h>
8 #include <chrono>
9 #include <fcntl.h>
10 #include <fnmatch.h>
11 #include <functional>
12 #include <getopt.h>
13 #include <iosfwd>
14 #include <iterator>
15 #include <limits>
16 #include <memory>
17 #include <queue>
18 #include <regex.h>
19 #include <stdint.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <string>
24 #include <string_view>
25 #include <unistd.h>
26 #include <unordered_map>
27 #include <unordered_set>
28 #include <utility>
29 #include <vector>
30 #include <zstd.h>
31
32 using namespace std;
33 using namespace std::chrono;
34
35 #define dprintf(...) \
36         do { \
37                 if (use_debug) { \
38                         fprintf(stderr, __VA_ARGS__); \
39                 } \
40         } while (false)
41
42 #include "turbopfor.h"
43
44 const char *dbpath = "/var/lib/mlocate/plocate.db";
45 bool ignore_case = false;
46 bool only_count = false;
47 bool print_nul = false;
48 bool use_debug = false;
49 int64_t limit_matches = numeric_limits<int64_t>::max();
50
51 class Serializer {
52 public:
53         bool ready_to_print(int seq) { return next_seq == seq; }
54         void print_delayed(int seq, const vector<string> msg);
55         void release_current();
56
57 private:
58         int next_seq = 0;
59         struct Element {
60                 int seq;
61                 vector<string> msg;
62
63                 bool operator<(const Element &other) const
64                 {
65                         return seq > other.seq;
66                 }
67         };
68         priority_queue<Element> pending;
69 };
70
71 void Serializer::print_delayed(int seq, const vector<string> msg)
72 {
73         pending.push(Element{ seq, move(msg) });
74 }
75
76 void Serializer::release_current()
77 {
78         ++next_seq;
79
80         // See if any delayed prints can now be dealt with.
81         while (!pending.empty() && pending.top().seq == next_seq) {
82                 if (limit_matches-- <= 0)
83                         return;
84                 for (const string &msg : pending.top().msg) {
85                         if (print_nul) {
86                                 printf("%s%c", msg.c_str(), 0);
87                         } else {
88                                 printf("%s\n", msg.c_str());
89                         }
90                 }
91                 pending.pop();
92                 ++next_seq;
93         }
94 }
95
96 struct Needle {
97         enum { STRSTR,
98                REGEX,  // Not currently used.
99                GLOB } type;
100         string str;  // Filled in no matter what.
101         regex_t re;  // For REGEX.
102 };
103
104 bool matches(const Needle &needle, const char *haystack)
105 {
106         if (needle.type == Needle::STRSTR) {
107                 return strstr(haystack, needle.str.c_str()) != nullptr;
108         } else if (needle.type == Needle::GLOB) {
109                 int flags = ignore_case ? FNM_CASEFOLD : 0;
110                 return fnmatch(needle.str.c_str(), haystack, flags) == 0;
111         } else {
112                 assert(needle.type == Needle::REGEX);
113                 return regexec(&needle.re, haystack, /*nmatch=*/0, /*pmatch=*/nullptr, /*flags=*/0) == 0;
114         }
115 }
116
117 bool has_access(const char *filename,
118                 unordered_map<string, bool> *access_rx_cache)
119 {
120         const char *end = strchr(filename + 1, '/');
121         while (end != nullptr) {
122                 string parent_path(filename, end);
123                 auto it = access_rx_cache->find(parent_path);
124                 bool ok;
125                 if (it == access_rx_cache->end()) {
126                         ok = access(parent_path.c_str(), R_OK | X_OK) == 0;
127                         access_rx_cache->emplace(move(parent_path), ok);
128                 } else {
129                         ok = it->second;
130                 }
131                 if (!ok) {
132                         return false;
133                 }
134                 end = strchr(end + 1, '/');
135         }
136
137         return true;
138 }
139
140 class Corpus {
141 public:
142         Corpus(int fd, IOUringEngine *engine);
143         ~Corpus();
144         void find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb);
145         void get_compressed_filename_block(uint32_t docid, function<void(string_view)> cb) const;
146         size_t get_num_filename_blocks() const;
147         off_t offset_for_block(uint32_t docid) const
148         {
149                 return hdr.filename_index_offset_bytes + docid * sizeof(uint64_t);
150         }
151
152 public:
153         const int fd;
154         IOUringEngine *const engine;
155
156         Header hdr;
157 };
158
159 Corpus::Corpus(int fd, IOUringEngine *engine)
160         : fd(fd), engine(engine)
161 {
162         // Enable to test cold-cache behavior (except for access()).
163         if (false) {
164                 off_t len = lseek(fd, 0, SEEK_END);
165                 if (len == -1) {
166                         perror("lseek");
167                         exit(1);
168                 }
169                 posix_fadvise(fd, 0, len, POSIX_FADV_DONTNEED);
170         }
171
172         complete_pread(fd, &hdr, sizeof(hdr), /*offset=*/0);
173         if (memcmp(hdr.magic, "\0plocate", 8) != 0) {
174                 fprintf(stderr, "plocate.db is corrupt or an old version; please rebuild it.\n");
175                 exit(1);
176         }
177         if (hdr.version != 0) {
178                 fprintf(stderr, "plocate.db has version %u, expected 0; please rebuild it.\n", hdr.version);
179                 exit(1);
180         }
181 }
182
183 Corpus::~Corpus()
184 {
185         close(fd);
186 }
187
188 void Corpus::find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb)
189 {
190         uint32_t bucket = hash_trigram(trgm, hdr.hashtable_size);
191         engine->submit_read(fd, sizeof(Trigram) * (hdr.extra_ht_slots + 2), hdr.hash_table_offset_bytes + sizeof(Trigram) * bucket, [this, trgm, cb{ move(cb) }](string_view s) {
192                 const Trigram *trgmptr = reinterpret_cast<const Trigram *>(s.data());
193                 for (unsigned i = 0; i < hdr.extra_ht_slots + 1; ++i) {
194                         if (trgmptr[i].trgm == trgm) {
195                                 cb(trgmptr + i, trgmptr[i + 1].offset - trgmptr[i].offset);
196                                 return;
197                         }
198                 }
199
200                 // Not found.
201                 cb(nullptr, 0);
202         });
203 }
204
205 void Corpus::get_compressed_filename_block(uint32_t docid, function<void(string_view)> cb) const
206 {
207         // Read the file offset from this docid and the next one.
208         // This is always allowed, since we have a sentinel block at the end.
209         engine->submit_read(fd, sizeof(uint64_t) * 2, offset_for_block(docid), [this, cb{ move(cb) }](string_view s) {
210                 const uint64_t *ptr = reinterpret_cast<const uint64_t *>(s.data());
211                 off_t offset = ptr[0];
212                 size_t len = ptr[1] - ptr[0];
213                 engine->submit_read(fd, len, offset, cb);
214         });
215 }
216
217 size_t Corpus::get_num_filename_blocks() const
218 {
219         return hdr.num_docids;
220 }
221
222 uint64_t scan_file_block(const vector<Needle> &needles, string_view compressed,
223                          unordered_map<string, bool> *access_rx_cache, int seq,
224                          Serializer *serializer)
225 {
226         uint64_t matched = 0;
227
228         unsigned long long uncompressed_len = ZSTD_getFrameContentSize(compressed.data(), compressed.size());
229         if (uncompressed_len == ZSTD_CONTENTSIZE_UNKNOWN || uncompressed_len == ZSTD_CONTENTSIZE_ERROR) {
230                 fprintf(stderr, "ZSTD_getFrameContentSize() failed\n");
231                 exit(1);
232         }
233
234         string block;
235         block.resize(uncompressed_len + 1);
236
237         size_t err = ZSTD_decompress(&block[0], block.size(), compressed.data(),
238                                      compressed.size());
239         if (ZSTD_isError(err)) {
240                 fprintf(stderr, "ZSTD_decompress(): %s\n", ZSTD_getErrorName(err));
241                 exit(1);
242         }
243         block[block.size() - 1] = '\0';
244
245         bool immediate_print = (serializer == nullptr || serializer->ready_to_print(seq));
246         vector<string> delayed;
247
248         for (const char *filename = block.data();
249              filename != block.data() + block.size();
250              filename += strlen(filename) + 1) {
251                 bool found = true;
252                 for (const Needle &needle : needles) {
253                         if (!matches(needle, filename)) {
254                                 found = false;
255                                 break;
256                         }
257                 }
258                 if (found && has_access(filename, access_rx_cache)) {
259                         if (limit_matches-- <= 0)
260                                 break;
261                         ++matched;
262                         if (only_count)
263                                 continue;
264                         if (immediate_print) {
265                                 if (print_nul) {
266                                         printf("%s%c", filename, 0);
267                                 } else {
268                                         printf("%s\n", filename);
269                                 }
270                         } else {
271                                 delayed.push_back(filename);
272                         }
273                 }
274         }
275         if (serializer != nullptr && !only_count) {
276                 if (immediate_print) {
277                         serializer->release_current();
278                 } else {
279                         serializer->print_delayed(seq, move(delayed));
280                 }
281         }
282         return matched;
283 }
284
285 size_t scan_docids(const vector<Needle> &needles, const vector<uint32_t> &docids, const Corpus &corpus, IOUringEngine *engine)
286 {
287         Serializer docids_in_order;
288         unordered_map<string, bool> access_rx_cache;
289         uint64_t matched = 0;
290         for (size_t i = 0; i < docids.size(); ++i) {
291                 uint32_t docid = docids[i];
292                 corpus.get_compressed_filename_block(docid, [i, &matched, &needles, &access_rx_cache, &docids_in_order](string_view compressed) {
293                         matched += scan_file_block(needles, compressed, &access_rx_cache, i, &docids_in_order);
294                 });
295         }
296         engine->finish();
297         return matched;
298 }
299
300 // We do this sequentially, as it's faster than scattering
301 // a lot of I/O through io_uring and hoping the kernel will
302 // coalesce it plus readahead for us.
303 uint64_t scan_all_docids(const vector<Needle> &needles, int fd, const Corpus &corpus, IOUringEngine *engine)
304 {
305         unordered_map<string, bool> access_rx_cache;
306         uint32_t num_blocks = corpus.get_num_filename_blocks();
307         unique_ptr<uint64_t[]> offsets(new uint64_t[num_blocks + 1]);
308         complete_pread(fd, offsets.get(), (num_blocks + 1) * sizeof(uint64_t), corpus.offset_for_block(0));
309         string compressed;
310         uint64_t matched = 0;
311         for (uint32_t io_docid = 0; io_docid < num_blocks; io_docid += 32) {
312                 uint32_t last_docid = std::min(io_docid + 32, num_blocks);
313                 size_t io_len = offsets[last_docid] - offsets[io_docid];
314                 if (compressed.size() < io_len) {
315                         compressed.resize(io_len);
316                 }
317                 complete_pread(fd, &compressed[0], io_len, offsets[io_docid]);
318
319                 for (uint32_t docid = io_docid; docid < last_docid; ++docid) {
320                         size_t relative_offset = offsets[docid] - offsets[io_docid];
321                         size_t len = offsets[docid + 1] - offsets[docid];
322                         matched += scan_file_block(needles, { &compressed[relative_offset], len }, &access_rx_cache, 0, nullptr);
323                         if (limit_matches <= 0)
324                                 return matched;
325                 }
326         }
327         return matched;
328 }
329
330 // Takes the given posting list, unions it into the parts of the trigram disjunction
331 // already read; if the list is complete, intersects with “cur_candidates”.
332 //
333 // Returns true if the search should be aborted (we are done).
334 bool new_posting_list_read(TrigramDisjunction *td, vector<uint32_t> decoded, vector<uint32_t> *cur_candidates, vector<uint32_t> *tmp)
335 {
336         if (td->docids.empty()) {
337                 td->docids = move(decoded);
338         } else {
339                 tmp->clear();
340                 set_union(decoded.begin(), decoded.end(), td->docids.begin(), td->docids.end(), back_inserter(*tmp));
341                 swap(*tmp, td->docids);
342         }
343         if (--td->remaining_trigrams_to_read > 0) {
344                 // Need to wait for more.
345                 if (ignore_case) {
346                         dprintf("  ... %u reads left in OR group %u (%zu docids in list)\n",
347                                 td->remaining_trigrams_to_read, td->index, td->docids.size());
348                 }
349                 return false;
350         }
351         if (cur_candidates->empty()) {
352                 if (ignore_case) {
353                         dprintf("  ... all reads done for OR group %u (%zu docids)\n",
354                                 td->index, td->docids.size());
355                 }
356                 *cur_candidates = move(td->docids);
357         } else {
358                 tmp->clear();
359                 set_intersection(cur_candidates->begin(), cur_candidates->end(),
360                                  td->docids.begin(), td->docids.end(),
361                                  back_inserter(*tmp));
362                 swap(*cur_candidates, *tmp);
363                 if (ignore_case) {
364                         if (cur_candidates->empty()) {
365                                 dprintf("  ... all reads done for OR group %u (%zu docids), intersected (none left, search is done)\n",
366                                         td->index, td->docids.size());
367                                 return true;
368                         } else {
369                                 dprintf("  ... all reads done for OR group %u (%zu docids), intersected (%zu left)\n",
370                                         td->index, td->docids.size(), cur_candidates->size());
371                         }
372                 }
373         }
374         return false;
375 }
376
377 void do_search_file(const vector<Needle> &needles, const char *filename)
378 {
379         int fd = open(filename, O_RDONLY);
380         if (fd == -1) {
381                 perror(filename);
382                 exit(1);
383         }
384
385         // Drop privileges.
386         if (setgid(getgid()) != 0) {
387                 perror("setgid");
388                 exit(EXIT_FAILURE);
389         }
390
391         steady_clock::time_point start __attribute__((unused)) = steady_clock::now();
392         if (access("/", R_OK | X_OK)) {
393                 // We can't find anything, no need to bother...
394                 return;
395         }
396
397         IOUringEngine engine(/*slop_bytes=*/16);  // 16 slop bytes as described in turbopfor.h.
398         Corpus corpus(fd, &engine);
399         dprintf("Corpus init done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
400
401         vector<TrigramDisjunction> trigram_groups;
402         for (const Needle &needle : needles) {
403                 if (needle.str.size() < 3)
404                         continue;
405                 parse_trigrams(needle.str, ignore_case, &trigram_groups);
406         }
407         unique_sort(
408                 &trigram_groups,
409                 [](const TrigramDisjunction &a, const TrigramDisjunction &b) { return a.trigram_alternatives < b.trigram_alternatives; },
410                 [](const TrigramDisjunction &a, const TrigramDisjunction &b) { return a.trigram_alternatives == b.trigram_alternatives; });
411
412         // Give them names for debugging.
413         unsigned td_index = 0;
414         for (TrigramDisjunction &td : trigram_groups) {
415                 td.index = td_index++;
416         }
417
418         // Collect which trigrams we need to look up in the hash table.
419         unordered_map<uint32_t, vector<TrigramDisjunction *>> trigrams_to_lookup;
420         for (TrigramDisjunction &td : trigram_groups) {
421                 for (uint32_t trgm : td.trigram_alternatives) {
422                         trigrams_to_lookup[trgm].push_back(&td);
423                 }
424         }
425         if (trigrams_to_lookup.empty()) {
426                 // Too short for trigram matching. Apply brute force.
427                 // (We could have searched through all trigrams that matched
428                 // the pattern and done a union of them, but that's a lot of
429                 // work for fairly unclear gain.)
430                 uint64_t matched = scan_all_docids(needles, fd, corpus, &engine);
431                 if (only_count) {
432                         printf("%zu\n", matched);
433                 }
434                 return;
435         }
436
437         // Look them all up on disk.
438         for (auto &[trgm, trigram_groups] : trigrams_to_lookup) {
439                 corpus.find_trigram(trgm, [trgm{ trgm }, trigram_groups{ &trigram_groups }](const Trigram *trgmptr, size_t len) {
440                         if (trgmptr == nullptr) {
441                                 dprintf("trigram %s isn't found\n", print_trigram(trgm).c_str());
442                                 for (TrigramDisjunction *td : *trigram_groups) {
443                                         --td->remaining_trigrams_to_read;
444                                         if (td->remaining_trigrams_to_read == 0 && td->read_trigrams.empty()) {
445                                                 dprintf("zero matches in %s, so we are done\n", print_td(*td).c_str());
446                                                 if (only_count) {
447                                                         printf("0\n");
448                                                 }
449                                                 exit(0);
450                                         }
451                                 }
452                                 return;
453                         }
454                         for (TrigramDisjunction *td : *trigram_groups) {
455                                 --td->remaining_trigrams_to_read;
456                                 td->max_num_docids += trgmptr->num_docids;
457                                 td->read_trigrams.emplace_back(*trgmptr, len);
458                         }
459                 });
460         }
461         engine.finish();
462         dprintf("Hashtable lookups done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
463
464         for (TrigramDisjunction &td : trigram_groups) {
465                 // Reset for reads.
466                 td.remaining_trigrams_to_read = td.read_trigrams.size();
467
468                 if (ignore_case) {  // If case-sensitive, they'll all be pretty obvious single-entry groups.
469                         dprintf("OR group %u (max_num_docids=%u): %s\n", td.index, td.max_num_docids, print_td(td).c_str());
470                 }
471         }
472
473         // TODO: For case-insensitive (ie. more than one alternative in each),
474         // prioritize the ones with fewer seeks?
475         sort(trigram_groups.begin(), trigram_groups.end(),
476              [&](const TrigramDisjunction &a, const TrigramDisjunction &b) {
477                      return a.max_num_docids < b.max_num_docids;
478              });
479
480         unordered_map<uint32_t, vector<TrigramDisjunction *>> uses_trigram;
481         for (TrigramDisjunction &td : trigram_groups) {
482                 for (uint32_t trgm : td.trigram_alternatives) {
483                         uses_trigram[trgm].push_back(&td);
484                 }
485         }
486
487         unordered_set<uint32_t> trigrams_submitted_read;
488         vector<uint32_t> cur_candidates, tmp, decoded;
489         bool done = false;
490         for (TrigramDisjunction &td : trigram_groups) {
491                 if (!cur_candidates.empty() && td.max_num_docids > cur_candidates.size() * 100) {
492                         dprintf("%s has up to %u entries, ignoring the rest (will "
493                                 "weed out false positives later)\n",
494                                 print_td(td).c_str(), td.max_num_docids);
495                         break;
496                 }
497
498                 for (auto &[trgmptr, len] : td.read_trigrams) {
499                         if (trigrams_submitted_read.count(trgmptr.trgm) != 0) {
500                                 continue;
501                         }
502                         trigrams_submitted_read.insert(trgmptr.trgm);
503                         // Only stay a certain amount ahead, so that we don't spend I/O
504                         // on reading the latter, large posting lists. We are unlikely
505                         // to need them anyway, even if they should come in first.
506                         if (engine.get_waiting_reads() >= 5) {
507                                 engine.finish();
508                                 if (done)
509                                         break;
510                         }
511                         engine.submit_read(fd, len, trgmptr.offset, [trgmptr{ trgmptr }, len{ len }, &done, &cur_candidates, &tmp, &decoded, &uses_trigram](string_view s) {
512                                 if (done)
513                                         return;
514
515                                 uint32_t trgm __attribute__((unused)) = trgmptr.trgm;
516                                 const unsigned char *pldata = reinterpret_cast<const unsigned char *>(s.data());
517                                 size_t num = trgmptr.num_docids;
518                                 decoded.resize(num);
519                                 decode_pfor_delta1_128(pldata, num, /*interleaved=*/true, &decoded[0]);
520
521                                 assert(uses_trigram.count(trgm) != 0);
522                                 bool was_empty = cur_candidates.empty();
523                                 if (ignore_case) {
524                                         dprintf("trigram %s (%zu bytes) decoded to %zu entries\n", print_trigram(trgm).c_str(), len, num);
525                                 }
526
527                                 for (TrigramDisjunction *td : uses_trigram[trgm]) {
528                                         done |= new_posting_list_read(td, decoded, &cur_candidates, &tmp);
529                                         if (done)
530                                                 break;
531                                 }
532                                 if (!ignore_case) {
533                                         if (was_empty) {
534                                                 dprintf("trigram %s (%zu bytes) decoded to %zu entries\n", print_trigram(trgm).c_str(), len, num);
535                                         } else if (cur_candidates.empty()) {
536                                                 dprintf("trigram %s (%zu bytes) decoded to %zu entries (none left, search is done)\n", print_trigram(trgm).c_str(), len, num);
537                                         } else {
538                                                 dprintf("trigram %s (%zu bytes) decoded to %zu entries (%zu left)\n", print_trigram(trgm).c_str(), len, num, cur_candidates.size());
539                                         }
540                                 }
541                         });
542                 }
543         }
544         engine.finish();
545         if (done) {
546                 return;
547         }
548         dprintf("Intersection done after %.1f ms. Doing final verification and printing:\n",
549                 1e3 * duration<float>(steady_clock::now() - start).count());
550
551         uint64_t matched = scan_docids(needles, cur_candidates, corpus, &engine);
552         dprintf("Done in %.1f ms, found %zu matches.\n",
553                 1e3 * duration<float>(steady_clock::now() - start).count(), matched);
554
555         if (only_count) {
556                 printf("%zu\n", matched);
557         }
558 }
559
560 string unescape_glob_to_plain_string(const string &needle)
561 {
562         string unescaped;
563         for (size_t i = 0; i < needle.size(); i += read_unigram(needle, i).second) {
564                 uint32_t ch = read_unigram(needle, i).first;
565                 assert(ch != WILDCARD_UNIGRAM);
566                 if (ch == PREMATURE_END_UNIGRAM) {
567                         fprintf(stderr, "Pattern '%s' ended prematurely\n", needle.c_str());
568                         exit(1);
569                 }
570                 unescaped.push_back(ch);
571         }
572         return unescaped;
573 }
574
575 void usage()
576 {
577         // The help text comes from mlocate.
578         printf("Usage: plocate [OPTION]... PATTERN...\n");
579         printf("\n");
580         printf("  -c, --count            only print number of found entries\n");
581         printf("  -d, --database DBPATH  use DBPATH instead of default database (which is\n");
582         printf("                         %s)\n", dbpath);
583         printf("  -h, --help             print this help\n");
584         printf("  -i, --ignore-case      ignore case distinctions when matching patterns\n");
585         printf("  -l, --limit, -n LIMIT  limit output (or counting) to LIMIT entries\n");
586         printf("  -0, --null             separate entries with NUL on output\n");
587         printf("  -V, --version          print version information\n");
588 }
589
590 void version()
591 {
592         printf("plocate %s\n", PLOCATE_VERSION);
593         printf("Copyright 2020 Steinar H. Gunderson\n");
594         printf("License GPLv2+: GNU GPL version 2 or later <https://gnu.org/licenses/gpl.html>.\n");
595         printf("This is free software: you are free to change and redistribute it.\n");
596         printf("There is NO WARRANTY, to the extent permitted by law.\n");
597         exit(0);
598 }
599
600 int main(int argc, char **argv)
601 {
602         static const struct option long_options[] = {
603                 { "help", no_argument, 0, 'h' },
604                 { "count", no_argument, 0, 'c' },
605                 { "database", required_argument, 0, 'd' },
606                 { "ignore-case", no_argument, 0, 'i' },
607                 { "limit", required_argument, 0, 'l' },
608                 { "null", no_argument, 0, '0' },
609                 { "version", no_argument, 0, 'V' },
610                 { "debug", no_argument, 0, 'D' },  // Not documented.
611                 { 0, 0, 0, 0 }
612         };
613
614         setlocale(LC_ALL, "");
615         for (;;) {
616                 int option_index = 0;
617                 int c = getopt_long(argc, argv, "cd:hil:n:0VD", long_options, &option_index);
618                 if (c == -1) {
619                         break;
620                 }
621                 switch (c) {
622                 case 'c':
623                         only_count = true;
624                         break;
625                 case 'd':
626                         dbpath = strdup(optarg);
627                         break;
628                 case 'h':
629                         usage();
630                         exit(0);
631                 case 'i':
632                         ignore_case = true;
633                         break;
634                 case 'l':
635                 case 'n':
636                         limit_matches = atoll(optarg);
637                         break;
638                 case '0':
639                         print_nul = true;
640                         break;
641                 case 'D':
642                         use_debug = true;
643                         break;
644                 case 'V':
645                         version();
646                         break;
647                 default:
648                         exit(1);
649                 }
650         }
651
652         if (use_debug) {
653                 // Debug information would leak information about which files exist,
654                 // so drop setgid before we open the file; one would either need to run
655                 // as root, or use a locally-built file.
656                 if (setgid(getgid()) != 0) {
657                         perror("setgid");
658                         exit(EXIT_FAILURE);
659                 }
660         }
661
662         vector<Needle> needles;
663         for (int i = optind; i < argc; ++i) {
664                 Needle needle;
665                 needle.str = argv[i];
666
667                 // See if there are any wildcard characters, which indicates we should treat it
668                 // as an (anchored) glob.
669                 bool any_wildcard = false;
670                 for (size_t i = 0; i < needle.str.size(); i += read_unigram(needle.str, i).second) {
671                         if (read_unigram(needle.str, i).first == WILDCARD_UNIGRAM) {
672                                 any_wildcard = true;
673                                 break;
674                         }
675                 }
676
677                 if (any_wildcard) {
678                         needle.type = Needle::GLOB;
679                 } else if (ignore_case) {
680                         // strcasestr() doesn't handle locales correctly (even though LSB
681                         // claims it should), but somehow, fnmatch() does, and it's about
682                         // the same speed as using a regex.
683                         needle.type = Needle::GLOB;
684                         needle.str = "*" + needle.str + "*";
685                 } else {
686                         needle.type = Needle::STRSTR;
687                         needle.str = unescape_glob_to_plain_string(needle.str);
688                 }
689                 needles.push_back(move(needle));
690         }
691         if (needles.empty()) {
692                 fprintf(stderr, "plocate: no pattern to search for specified\n");
693                 exit(0);
694         }
695         do_search_file(needles, dbpath);
696 }