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