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