]> git.sesse.net Git - plocate/blob - plocate.cpp
7cc4f5a4eb2587f4bb685aaa83155e8951f06dd2
[plocate] / plocate.cpp
1 #include "access_rx_cache.h"
2 #include "complete_pread.h"
3 #include "db.h"
4 #include "dprintf.h"
5 #include "io_uring_engine.h"
6 #include "needle.h"
7 #include "parse_trigrams.h"
8 #include "serializer.h"
9 #include "turbopfor.h"
10 #include "unique_sort.h"
11
12 #include <algorithm>
13 #include <assert.h>
14 #include <atomic>
15 #include <chrono>
16 #include <condition_variable>
17 #include <deque>
18 #include <fcntl.h>
19 #include <functional>
20 #include <getopt.h>
21 #include <inttypes.h>
22 #include <iterator>
23 #include <limits>
24 #include <locale.h>
25 #include <memory>
26 #include <mutex>
27 #include <regex.h>
28 #include <stdint.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <string>
33 #include <string_view>
34 #include <sys/types.h>
35 #include <sys/wait.h>
36 #include <thread>
37 #include <tuple>
38 #include <unistd.h>
39 #include <unordered_map>
40 #include <unordered_set>
41 #include <utility>
42 #include <vector>
43 #include <zstd.h>
44
45 using namespace std;
46 using namespace std::chrono;
47
48 bool ignore_case = false;
49 bool only_count = false;
50 bool print_nul = false;
51 bool use_debug = false;
52 bool flush_cache = false;
53 bool patterns_are_regex = false;
54 bool use_extended_regex = false;
55 bool match_basename = false;
56 bool check_existence = false;
57 int64_t limit_matches = numeric_limits<int64_t>::max();
58 int64_t limit_left = numeric_limits<int64_t>::max();
59 bool stdout_is_tty = false;
60 static bool in_forked_child = false;
61
62 steady_clock::time_point start;
63 ZSTD_DDict *ddict = nullptr;
64
65 class Corpus {
66 public:
67         Corpus(int fd, IOUringEngine *engine);
68         ~Corpus();
69         void find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb);
70         void get_compressed_filename_block(uint32_t docid, function<void(string_view)> cb) const;
71         size_t get_num_filename_blocks() const;
72         off_t offset_for_block(uint32_t docid) const
73         {
74                 return hdr.filename_index_offset_bytes + docid * sizeof(uint64_t);
75         }
76         const Header &get_hdr() const { return hdr; }
77
78 public:
79         const int fd;
80         IOUringEngine *const engine;
81
82         Header hdr;
83 };
84
85 Corpus::Corpus(int fd, IOUringEngine *engine)
86         : fd(fd), engine(engine)
87 {
88         if (flush_cache) {
89                 off_t len = lseek(fd, 0, SEEK_END);
90                 if (len == -1) {
91                         perror("lseek");
92                         exit(1);
93                 }
94                 posix_fadvise(fd, 0, len, POSIX_FADV_DONTNEED);
95         }
96
97         complete_pread(fd, &hdr, sizeof(hdr), /*offset=*/0);
98         if (memcmp(hdr.magic, "\0plocate", 8) != 0) {
99                 fprintf(stderr, "plocate.db is corrupt or an old version; please rebuild it.\n");
100                 exit(1);
101         }
102         if (hdr.version != 0 && hdr.version != 1) {
103                 fprintf(stderr, "plocate.db has version %u, expected 0 or 1; please rebuild it.\n", hdr.version);
104                 exit(1);
105         }
106         if (hdr.version == 0) {
107                 // These will be junk data.
108                 hdr.zstd_dictionary_offset_bytes = 0;
109                 hdr.zstd_dictionary_length_bytes = 0;
110         }
111         if (hdr.max_version < 2) {
112                 // This too. (We ignore the other max_version 2 fields.)
113                 hdr.check_visibility = true;
114         }
115 }
116
117 Corpus::~Corpus()
118 {
119         close(fd);
120 }
121
122 void Corpus::find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb)
123 {
124         uint32_t bucket = hash_trigram(trgm, hdr.hashtable_size);
125         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) {
126                 const Trigram *trgmptr = reinterpret_cast<const Trigram *>(s.data());
127                 for (unsigned i = 0; i < hdr.extra_ht_slots + 1; ++i) {
128                         if (trgmptr[i].trgm == trgm) {
129                                 cb(trgmptr + i, trgmptr[i + 1].offset - trgmptr[i].offset);
130                                 return;
131                         }
132                 }
133
134                 // Not found.
135                 cb(nullptr, 0);
136         });
137 }
138
139 void Corpus::get_compressed_filename_block(uint32_t docid, function<void(string_view)> cb) const
140 {
141         // Read the file offset from this docid and the next one.
142         // This is always allowed, since we have a sentinel block at the end.
143         engine->submit_read(fd, sizeof(uint64_t) * 2, offset_for_block(docid), [this, cb{ move(cb) }](string_view s) {
144                 const uint64_t *ptr = reinterpret_cast<const uint64_t *>(s.data());
145                 off_t offset = ptr[0];
146                 size_t len = ptr[1] - ptr[0];
147                 engine->submit_read(fd, len, offset, cb);
148         });
149 }
150
151 size_t Corpus::get_num_filename_blocks() const
152 {
153         return hdr.num_docids;
154 }
155
156 template<class T>
157 void stat_if_needed(const char *filename, bool access_ok, IOUringEngine *engine, T cb)
158 {
159         if (!access_ok || !check_existence) {
160                 // Doesn't have access or doesn't care about existence, so no need to stat.
161                 cb(access_ok);
162         } else if (engine == nullptr || !engine->get_supports_stat()) {
163                 // Do a synchronous stat.
164                 struct stat buf;
165                 bool ok = lstat(filename, &buf) == 0;
166                 cb(ok);
167         } else {
168                 engine->submit_stat(filename, cb);
169         }
170 }
171
172 void scan_file_block(const vector<Needle> &needles, string_view compressed,
173                      IOUringEngine *engine, AccessRXCache *access_rx_cache, uint64_t seq, ResultReceiver *serializer,
174                      atomic<uint64_t> *matched)
175 {
176         unsigned long long uncompressed_len = ZSTD_getFrameContentSize(compressed.data(), compressed.size());
177         if (uncompressed_len == ZSTD_CONTENTSIZE_UNKNOWN || uncompressed_len == ZSTD_CONTENTSIZE_ERROR) {
178                 fprintf(stderr, "ZSTD_getFrameContentSize() failed\n");
179                 exit(1);
180         }
181
182         string block;
183         block.resize(uncompressed_len + 1);
184
185         static thread_local ZSTD_DCtx *ctx = ZSTD_createDCtx();  // Reused across calls.
186         size_t err;
187
188         if (ddict != nullptr) {
189                 err = ZSTD_decompress_usingDDict(ctx, &block[0], block.size(), compressed.data(),
190                                                  compressed.size(), ddict);
191         } else {
192                 err = ZSTD_decompressDCtx(ctx, &block[0], block.size(), compressed.data(),
193                                           compressed.size());
194         }
195         if (ZSTD_isError(err)) {
196                 fprintf(stderr, "ZSTD_decompress(): %s\n", ZSTD_getErrorName(err));
197                 exit(1);
198         }
199         block[block.size() - 1] = '\0';
200
201         auto test_candidate = [&](const char *filename, uint64_t local_seq, uint64_t next_seq) {
202                 access_rx_cache->check_access(filename, /*allow_async=*/true, [matched, engine, serializer, local_seq, next_seq, filename{ strdup(filename) }](bool ok) {
203                         stat_if_needed(filename, ok, engine, [matched, serializer, local_seq, next_seq, filename](bool ok) {
204                                 if (ok) {
205                                         ++*matched;
206                                         serializer->print(local_seq, next_seq - local_seq, filename);
207                                 } else {
208                                         serializer->print(local_seq, next_seq - local_seq, "");
209                                 }
210                                 free(filename);
211                         });
212                 });
213         };
214
215         // We need to know the next sequence number before inserting into Serializer,
216         // so always buffer one candidate.
217         const char *pending_candidate = nullptr;
218
219         uint64_t local_seq = seq << 32;
220         for (const char *filename = block.data();
221              filename != block.data() + block.size();
222              filename += strlen(filename) + 1) {
223                 const char *haystack = filename;
224                 if (match_basename) {
225                         haystack = strrchr(filename, '/');
226                         if (haystack == nullptr) {
227                                 haystack = filename;
228                         } else {
229                                 ++haystack;
230                         }
231                 }
232
233                 bool found = true;
234                 for (const Needle &needle : needles) {
235                         if (!matches(needle, haystack)) {
236                                 found = false;
237                                 break;
238                         }
239                 }
240                 if (found) {
241                         if (pending_candidate != nullptr) {
242                                 test_candidate(pending_candidate, local_seq, local_seq + 1);
243                                 ++local_seq;
244                         }
245                         pending_candidate = filename;
246                 }
247         }
248         if (pending_candidate == nullptr) {
249                 serializer->print(seq << 32, 1ULL << 32, "");
250         } else {
251                 test_candidate(pending_candidate, local_seq, (seq + 1) << 32);
252         }
253 }
254
255 size_t scan_docids(const vector<Needle> &needles, const vector<uint32_t> &docids, const Corpus &corpus, IOUringEngine *engine)
256 {
257         Serializer docids_in_order;
258         AccessRXCache access_rx_cache(engine, corpus.get_hdr().check_visibility);
259         atomic<uint64_t> matched{ 0 };
260         for (size_t i = 0; i < docids.size(); ++i) {
261                 uint32_t docid = docids[i];
262                 corpus.get_compressed_filename_block(docid, [i, &matched, &needles, &access_rx_cache, engine, &docids_in_order](string_view compressed) {
263                         scan_file_block(needles, compressed, engine, &access_rx_cache, i, &docids_in_order, &matched);
264                 });
265         }
266         engine->finish();
267         return matched;
268 }
269
270 struct WorkerThread {
271         thread t;
272
273         // We use a result queue instead of synchronizing Serializer,
274         // since a lock on it becomes a huge choke point if there are
275         // lots of threads.
276         mutex result_mu;
277         struct Result {
278                 uint64_t seq;
279                 uint64_t skip;
280                 string msg;
281         };
282         vector<Result> results;
283 };
284
285 class WorkerThreadReceiver : public ResultReceiver {
286 public:
287         WorkerThreadReceiver(WorkerThread *wt)
288                 : wt(wt) {}
289
290         void print(uint64_t seq, uint64_t skip, const string msg) override
291         {
292                 lock_guard<mutex> lock(wt->result_mu);
293                 if (msg.empty() && !wt->results.empty() && wt->results.back().seq + wt->results.back().skip == seq) {
294                         wt->results.back().skip += skip;
295                 } else {
296                         wt->results.emplace_back(WorkerThread::Result{ seq, skip, move(msg) });
297                 }
298         }
299
300 private:
301         WorkerThread *wt;
302 };
303
304 void deliver_results(WorkerThread *wt, Serializer *serializer)
305 {
306         vector<WorkerThread::Result> results;
307         {
308                 lock_guard<mutex> lock(wt->result_mu);
309                 results = move(wt->results);
310         }
311         for (const WorkerThread::Result &result : results) {
312                 serializer->print(result.seq, result.skip, move(result.msg));
313         }
314 }
315
316 // We do this sequentially, as it's faster than scattering
317 // a lot of I/O through io_uring and hoping the kernel will
318 // coalesce it plus readahead for us. Since we assume that
319 // we will primarily be CPU-bound, we'll be firing up one
320 // worker thread for each spare core (the last one will
321 // only be doing I/O). access() is still synchronous.
322 uint64_t scan_all_docids(const vector<Needle> &needles, int fd, const Corpus &corpus)
323 {
324         {
325                 const Header &hdr = corpus.get_hdr();
326                 if (hdr.zstd_dictionary_length_bytes > 0) {
327                         string dictionary;
328                         dictionary.resize(hdr.zstd_dictionary_length_bytes);
329                         complete_pread(fd, &dictionary[0], hdr.zstd_dictionary_length_bytes, hdr.zstd_dictionary_offset_bytes);
330                         ddict = ZSTD_createDDict(dictionary.data(), dictionary.size());
331                 }
332         }
333
334         AccessRXCache access_rx_cache(nullptr, corpus.get_hdr().check_visibility);
335         Serializer serializer;
336         uint32_t num_blocks = corpus.get_num_filename_blocks();
337         unique_ptr<uint64_t[]> offsets(new uint64_t[num_blocks + 1]);
338         complete_pread(fd, offsets.get(), (num_blocks + 1) * sizeof(uint64_t), corpus.offset_for_block(0));
339         atomic<uint64_t> matched{ 0 };
340
341         mutex mu;
342         condition_variable queue_added, queue_removed;
343         deque<tuple<int, int, string>> work_queue;  // Under mu.
344         bool done = false;  // Under mu.
345
346         unsigned num_threads = max<int>(sysconf(_SC_NPROCESSORS_ONLN) - 1, 1);
347         dprintf("Using %u worker threads for linear scan.\n", num_threads);
348         unique_ptr<WorkerThread[]> threads(new WorkerThread[num_threads]);
349         for (unsigned i = 0; i < num_threads; ++i) {
350                 threads[i].t = thread([&threads, &mu, &queue_added, &queue_removed, &work_queue, &done, &offsets, &needles, &access_rx_cache, engine{ corpus.engine }, &matched, i] {
351                         // regcomp() takes a lock on the regex, so each thread will need its own.
352                         const vector<Needle> *use_needles = &needles;
353                         vector<Needle> recompiled_needles;
354                         if (i != 0 && patterns_are_regex) {
355                                 recompiled_needles = needles;
356                                 for (Needle &needle : recompiled_needles) {
357                                         needle.re = compile_regex(needle.str);
358                                 }
359                                 use_needles = &recompiled_needles;
360                         }
361
362                         WorkerThreadReceiver receiver(&threads[i]);
363                         for (;;) {
364                                 uint32_t io_docid, last_docid;
365                                 string compressed;
366
367                                 {
368                                         unique_lock<mutex> lock(mu);
369                                         queue_added.wait(lock, [&work_queue, &done] { return !work_queue.empty() || done; });
370                                         if (done && work_queue.empty()) {
371                                                 return;
372                                         }
373                                         tie(io_docid, last_docid, compressed) = move(work_queue.front());
374                                         work_queue.pop_front();
375                                         queue_removed.notify_all();
376                                 }
377
378                                 for (uint32_t docid = io_docid; docid < last_docid; ++docid) {
379                                         size_t relative_offset = offsets[docid] - offsets[io_docid];
380                                         size_t len = offsets[docid + 1] - offsets[docid];
381                                         scan_file_block(*use_needles, { &compressed[relative_offset], len }, engine, &access_rx_cache, docid, &receiver, &matched);
382                                 }
383                         }
384                 });
385         }
386
387         string compressed;
388         for (uint32_t io_docid = 0; io_docid < num_blocks; io_docid += 32) {
389                 uint32_t last_docid = std::min(io_docid + 32, num_blocks);
390                 size_t io_len = offsets[last_docid] - offsets[io_docid];
391                 if (compressed.size() < io_len) {
392                         compressed.resize(io_len);
393                 }
394                 complete_pread(fd, &compressed[0], io_len, offsets[io_docid]);
395
396                 {
397                         unique_lock<mutex> lock(mu);
398                         queue_removed.wait(lock, [&work_queue] { return work_queue.size() < 256; });  // Allow ~2MB of data queued up.
399                         work_queue.emplace_back(io_docid, last_docid, move(compressed));
400                         queue_added.notify_one();  // Avoid the thundering herd.
401                 }
402
403                 // Pick up some results, so that we are sure that we won't just overload.
404                 // (Seemingly, going through all of these causes slowness with many threads,
405                 // but taking only one is OK.)
406                 unsigned i = io_docid / 32;
407                 deliver_results(&threads[i % num_threads], &serializer);
408         }
409         {
410                 lock_guard<mutex> lock(mu);
411                 done = true;
412                 queue_added.notify_all();
413         }
414         for (unsigned i = 0; i < num_threads; ++i) {
415                 threads[i].t.join();
416                 deliver_results(&threads[i], &serializer);
417         }
418         return matched;
419 }
420
421 // Takes the given posting list, unions it into the parts of the trigram disjunction
422 // already read; if the list is complete, intersects with “cur_candidates”.
423 //
424 // Returns true if the search should be aborted (we are done).
425 bool new_posting_list_read(TrigramDisjunction *td, vector<uint32_t> decoded, vector<uint32_t> *cur_candidates, vector<uint32_t> *tmp)
426 {
427         if (td->docids.empty()) {
428                 td->docids = move(decoded);
429         } else {
430                 tmp->clear();
431                 set_union(decoded.begin(), decoded.end(), td->docids.begin(), td->docids.end(), back_inserter(*tmp));
432                 swap(*tmp, td->docids);
433         }
434         if (--td->remaining_trigrams_to_read > 0) {
435                 // Need to wait for more.
436                 if (ignore_case) {
437                         dprintf("  ... %u reads left in OR group %u (%zu docids in list)\n",
438                                 td->remaining_trigrams_to_read, td->index, td->docids.size());
439                 }
440                 return false;
441         }
442         if (cur_candidates->empty()) {
443                 if (ignore_case) {
444                         dprintf("  ... all reads done for OR group %u (%zu docids)\n",
445                                 td->index, td->docids.size());
446                 }
447                 *cur_candidates = move(td->docids);
448         } else {
449                 tmp->clear();
450                 set_intersection(cur_candidates->begin(), cur_candidates->end(),
451                                  td->docids.begin(), td->docids.end(),
452                                  back_inserter(*tmp));
453                 swap(*cur_candidates, *tmp);
454                 if (ignore_case) {
455                         if (cur_candidates->empty()) {
456                                 dprintf("  ... all reads done for OR group %u (%zu docids), intersected (none left, search is done)\n",
457                                         td->index, td->docids.size());
458                                 return true;
459                         } else {
460                                 dprintf("  ... all reads done for OR group %u (%zu docids), intersected (%zu left)\n",
461                                         td->index, td->docids.size(), cur_candidates->size());
462                         }
463                 }
464         }
465         return false;
466 }
467
468 uint64_t do_search_file(const vector<Needle> &needles, const std::string &filename)
469 {
470         int fd = open(filename.c_str(), O_RDONLY);
471         if (fd == -1) {
472                 perror(filename.c_str());
473                 exit(1);
474         }
475
476         // Drop privileges.
477         if (setgid(getgid()) != 0) {
478                 perror("setgid");
479                 exit(EXIT_FAILURE);
480         }
481
482         start = steady_clock::now();
483         if (access("/", R_OK | X_OK)) {
484                 // We can't find anything, no need to bother...
485                 return 0;
486         }
487
488         IOUringEngine engine(/*slop_bytes=*/16);  // 16 slop bytes as described in turbopfor.h.
489         Corpus corpus(fd, &engine);
490         dprintf("Corpus init done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
491
492         vector<TrigramDisjunction> trigram_groups;
493         if (patterns_are_regex) {
494                 // We could parse the regex to find trigrams that have to be there
495                 // (there are actually known algorithms to deal with disjunctions
496                 // and such, too), but for now, we just go brute force.
497                 // Using locate with regexes is pretty niche.
498         } else {
499                 for (const Needle &needle : needles) {
500                         parse_trigrams(needle.str, ignore_case, &trigram_groups);
501                 }
502         }
503
504         unique_sort(
505                 &trigram_groups,
506                 [](const TrigramDisjunction &a, const TrigramDisjunction &b) { return a.trigram_alternatives < b.trigram_alternatives; },
507                 [](const TrigramDisjunction &a, const TrigramDisjunction &b) { return a.trigram_alternatives == b.trigram_alternatives; });
508
509         // Give them names for debugging.
510         unsigned td_index = 0;
511         for (TrigramDisjunction &td : trigram_groups) {
512                 td.index = td_index++;
513         }
514
515         // Collect which trigrams we need to look up in the hash table.
516         unordered_map<uint32_t, vector<TrigramDisjunction *>> trigrams_to_lookup;
517         for (TrigramDisjunction &td : trigram_groups) {
518                 for (uint32_t trgm : td.trigram_alternatives) {
519                         trigrams_to_lookup[trgm].push_back(&td);
520                 }
521         }
522         if (trigrams_to_lookup.empty()) {
523                 // Too short for trigram matching. Apply brute force.
524                 // (We could have searched through all trigrams that matched
525                 // the pattern and done a union of them, but that's a lot of
526                 // work for fairly unclear gain.)
527                 uint64_t matched = scan_all_docids(needles, fd, corpus);
528                 dprintf("Done in %.1f ms, found %" PRId64 " matches.\n",
529                         1e3 * duration<float>(steady_clock::now() - start).count(), matched);
530                 return matched;
531         }
532
533         // Sneak in fetching the dictionary, if present. It's not necessarily clear
534         // exactly where it would be cheapest to get it, but it needs to be present
535         // before we can decode any of the posting lists. Most likely, it's
536         // in the same filesystem block as the header anyway, so it should be
537         // present in the cache.
538         {
539                 const Header &hdr = corpus.get_hdr();
540                 if (hdr.zstd_dictionary_length_bytes > 0) {
541                         engine.submit_read(fd, hdr.zstd_dictionary_length_bytes, hdr.zstd_dictionary_offset_bytes, [](string_view s) {
542                                 ddict = ZSTD_createDDict(s.data(), s.size());
543                                 dprintf("Dictionary initialized after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
544                         });
545                 }
546         }
547
548         // Look them all up on disk.
549         bool should_early_exit = false;
550         for (auto &[trgm, trigram_groups] : trigrams_to_lookup) {
551                 corpus.find_trigram(trgm, [trgm{ trgm }, trigram_groups{ &trigram_groups }, &should_early_exit](const Trigram *trgmptr, size_t len) {
552                         if (trgmptr == nullptr) {
553                                 dprintf("trigram %s isn't found\n", print_trigram(trgm).c_str());
554                                 for (TrigramDisjunction *td : *trigram_groups) {
555                                         --td->remaining_trigrams_to_read;
556
557                                         // If we now know this trigram group doesn't match anything at all,
558                                         // we can do early exit; however, if we're in a forked child,
559                                         // that would confuse the parent process (since we don't write
560                                         // our count to the pipe), so we wait until we're back in to the
561                                         // regular (non-async) context. This is a fairly rare case anyway,
562                                         // and the gains from dropping the remaining trigram reads are limited.
563                                         if (td->remaining_trigrams_to_read == 0 && td->read_trigrams.empty()) {
564                                                 if (in_forked_child) {
565                                                         should_early_exit = true;
566                                                 } else {
567                                                         dprintf("zero matches in %s, so we are done\n", print_td(*td).c_str());
568                                                         if (only_count) {
569                                                                 printf("0\n");
570                                                         }
571                                                         exit(0);
572                                                 }
573                                         }
574                                 }
575                                 return;
576                         }
577                         for (TrigramDisjunction *td : *trigram_groups) {
578                                 --td->remaining_trigrams_to_read;
579                                 td->max_num_docids += trgmptr->num_docids;
580                                 td->read_trigrams.emplace_back(*trgmptr, len);
581                         }
582                 });
583         }
584         engine.finish();
585         dprintf("Hashtable lookups done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
586
587         if (should_early_exit) {
588                 return 0;
589         }
590
591         for (TrigramDisjunction &td : trigram_groups) {
592                 // Reset for reads.
593                 td.remaining_trigrams_to_read = td.read_trigrams.size();
594
595                 if (ignore_case) {  // If case-sensitive, they'll all be pretty obvious single-entry groups.
596                         dprintf("OR group %u (max_num_docids=%u): %s\n", td.index, td.max_num_docids, print_td(td).c_str());
597                 }
598         }
599
600         // TODO: For case-insensitive (ie. more than one alternative in each),
601         // prioritize the ones with fewer seeks?
602         sort(trigram_groups.begin(), trigram_groups.end(),
603              [&](const TrigramDisjunction &a, const TrigramDisjunction &b) {
604                      return a.max_num_docids < b.max_num_docids;
605              });
606
607         unordered_map<uint32_t, vector<TrigramDisjunction *>> uses_trigram;
608         for (TrigramDisjunction &td : trigram_groups) {
609                 for (uint32_t trgm : td.trigram_alternatives) {
610                         uses_trigram[trgm].push_back(&td);
611                 }
612         }
613
614         unordered_set<uint32_t> trigrams_submitted_read;
615         vector<uint32_t> cur_candidates, tmp, decoded;
616         bool done = false;
617         for (TrigramDisjunction &td : trigram_groups) {
618                 if (!cur_candidates.empty() && td.max_num_docids > cur_candidates.size() * 100) {
619                         dprintf("%s has up to %u entries, ignoring the rest (will "
620                                 "weed out false positives later)\n",
621                                 print_td(td).c_str(), td.max_num_docids);
622                         break;
623                 }
624
625                 for (auto &[trgmptr, len] : td.read_trigrams) {
626                         if (trigrams_submitted_read.count(trgmptr.trgm) != 0) {
627                                 continue;
628                         }
629                         trigrams_submitted_read.insert(trgmptr.trgm);
630                         // Only stay a certain amount ahead, so that we don't spend I/O
631                         // on reading the latter, large posting lists. We are unlikely
632                         // to need them anyway, even if they should come in first.
633                         if (engine.get_waiting_reads() >= 5) {
634                                 engine.finish();
635                                 if (done)
636                                         break;
637                         }
638                         engine.submit_read(fd, len, trgmptr.offset, [trgmptr{ trgmptr }, len{ len }, &done, &cur_candidates, &tmp, &decoded, &uses_trigram](string_view s) {
639                                 if (done)
640                                         return;
641
642                                 uint32_t trgm = trgmptr.trgm;
643                                 const unsigned char *pldata = reinterpret_cast<const unsigned char *>(s.data());
644                                 size_t num = trgmptr.num_docids;
645                                 decoded.resize(num);
646                                 decode_pfor_delta1_128(pldata, num, /*interleaved=*/true, &decoded[0]);
647
648                                 assert(uses_trigram.count(trgm) != 0);
649                                 bool was_empty = cur_candidates.empty();
650                                 if (ignore_case) {
651                                         dprintf("trigram %s (%zu bytes) decoded to %zu entries\n", print_trigram(trgm).c_str(), len, num);
652                                 }
653
654                                 for (TrigramDisjunction *td : uses_trigram[trgm]) {
655                                         done |= new_posting_list_read(td, decoded, &cur_candidates, &tmp);
656                                         if (done)
657                                                 break;
658                                 }
659                                 if (!ignore_case) {
660                                         if (was_empty) {
661                                                 dprintf("trigram %s (%zu bytes) decoded to %zu entries\n", print_trigram(trgm).c_str(), len, num);
662                                         } else if (cur_candidates.empty()) {
663                                                 dprintf("trigram %s (%zu bytes) decoded to %zu entries (none left, search is done)\n", print_trigram(trgm).c_str(), len, num);
664                                         } else {
665                                                 dprintf("trigram %s (%zu bytes) decoded to %zu entries (%zu left)\n", print_trigram(trgm).c_str(), len, num, cur_candidates.size());
666                                         }
667                                 }
668                         });
669                 }
670         }
671         engine.finish();
672         if (done) {
673                 return 0;
674         }
675         dprintf("Intersection done after %.1f ms. Doing final verification and printing:\n",
676                 1e3 * duration<float>(steady_clock::now() - start).count());
677
678         uint64_t matched = scan_docids(needles, cur_candidates, corpus, &engine);
679         dprintf("Done in %.1f ms, found %" PRId64 " matches.\n",
680                 1e3 * duration<float>(steady_clock::now() - start).count(), matched);
681         return matched;
682 }
683
684 // Run do_search_file() in a child process.
685 //
686 // The reason for this is that we're not robust against malicious input, so we need
687 // to drop privileges after opening the file. (Otherwise, we could fall prey to an attack
688 // where a user does locate -d badfile.db:/var/lib/plocate/plocate.db, badfile.db contains
689 // a buffer overflow that takes over the process, and then uses the elevated privileges
690 // to print out otherwise inaccessible paths.) We solve this by forking and treating the
691 // child process as untrusted after it has dropped its privileges (which it does before
692 // reading any data from the file); it returns a single 64-bit number over a pipe,
693 // and that's it. The parent keeps its privileges, and can then fork out new children
694 // without fear of being taken over. (The child keeps stdout for outputting results.)
695 //
696 // The count is returned over the pipe, because it's needed both for --limit and --count.
697 uint64_t do_search_file_in_child(const vector<Needle> &needles, const std::string &filename)
698 {
699         int pipefd[2];
700         if (pipe(pipefd) == -1) {
701                 perror("pipe");
702                 exit(EXIT_FAILURE);
703         }
704
705         pid_t child_pid = fork();
706         switch (child_pid) {
707         case 0: {
708                 // Child.
709                 close(pipefd[0]);
710                 in_forked_child = true;
711                 uint64_t matched = do_search_file(needles, filename);
712                 int ret;
713                 do {
714                         ret = write(pipefd[1], &matched, sizeof(matched));
715                 } while (ret == -1 && errno == EINTR);
716                 if (ret != sizeof(matched)) {
717                         perror("write");
718                         _exit(EXIT_FAILURE);
719                 }
720                 fflush(stdout);
721                 _exit(EXIT_SUCCESS);
722         }
723         case -1:
724                 // Error.
725                 perror("fork");
726                 exit(EXIT_FAILURE);
727         default:
728                 // Parent.
729                 close(pipefd[1]);
730                 break;
731         }
732
733         // Wait for the child to finish.
734         int wstatus;
735         pid_t err;
736         do {
737                 err = waitpid(child_pid, &wstatus, 0);
738         } while (err == -1 && errno == EINTR);
739         if (err == -1) {
740                 perror("waitpid");
741                 exit(EXIT_FAILURE);
742         }
743         if (WIFEXITED(wstatus)) {
744                 if (WEXITSTATUS(wstatus) != 0) {
745                         // The child has probably already printed out its error, so just propagate the exit status.
746                         exit(WEXITSTATUS(wstatus));
747                 }
748                 // Success!
749         } else if (!WIFEXITED(wstatus)) {
750                 fprintf(stderr, "FATAL: Child died unexpectedly while processing %s\n", filename.c_str());
751                 exit(1);
752         }
753
754         // Now get the number of matches from the child.
755         uint64_t matched;
756         int ret;
757         do {
758                 ret = read(pipefd[0], &matched, sizeof(matched));
759         } while (ret == -1 && errno == EINTR);
760         if (ret == -1) {
761                 perror("read");
762                 exit(EXIT_FAILURE);
763         } else if (ret != sizeof(matched)) {
764                 fprintf(stderr, "FATAL: Short read through pipe (got %d bytes)\n", ret);
765                 exit(EXIT_FAILURE);
766         }
767         close(pipefd[0]);
768         return matched;
769 }
770
771 // Parses a colon-separated list of strings and appends them onto the given vector.
772 // Backslash escapes whatever comes after it.
773 void parse_dbpaths(const char *ptr, vector<string> *output)
774 {
775         string str;
776         while (*ptr != '\0') {
777                 if (*ptr == '\\') {
778                         if (ptr[1] == '\0') {
779                                 fprintf(stderr, "ERROR: Escape character at the end of string\n");
780                                 exit(EXIT_FAILURE);
781                         }
782                         // Escape.
783                         str.push_back(ptr[1]);
784                         ptr += 2;
785                         continue;
786                 }
787                 if (*ptr == ':') {
788                         // Separator.
789                         output->push_back(move(str));
790                         ++ptr;
791                         continue;
792                 }
793                 str.push_back(*ptr++);
794         }
795         output->push_back(move(str));
796 }
797
798 void usage()
799 {
800         printf(
801                 "Usage: plocate [OPTION]... PATTERN...\n"
802                 "\n"
803                 "  -b, --basename         search only the file name portion of path names\n"
804                 "  -c, --count            print number of matches instead of the matches\n"
805                 "  -d, --database DBPATH  search for files in DBPATH\n"
806                 "                         (default is " DBFILE ")\n"
807                 "  -i, --ignore-case      search case-insensitively\n"
808                 "  -l, --limit LIMIT      stop after LIMIT matches\n"
809                 "  -0, --null             delimit matches by NUL instead of newline\n"
810                 "  -r, --regexp           interpret patterns as basic regexps (slow)\n"
811                 "      --regex            interpret patterns as extended regexps (slow)\n"
812                 "  -w, --wholename        search the entire path name (default; see -b)\n"
813                 "      --help             print this help\n"
814                 "      --version          print version information\n");
815 }
816
817 void version()
818 {
819         printf("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
820         printf("Copyright 2020 Steinar H. Gunderson\n");
821         printf("License GPLv2+: GNU GPL version 2 or later <https://gnu.org/licenses/gpl.html>.\n");
822         printf("This is free software: you are free to change and redistribute it.\n");
823         printf("There is NO WARRANTY, to the extent permitted by law.\n");
824         exit(0);
825 }
826
827 int main(int argc, char **argv)
828 {
829         vector<string> dbpaths;
830
831         constexpr int EXTENDED_REGEX = 1000;
832         constexpr int FLUSH_CACHE = 1001;
833         static const struct option long_options[] = {
834                 { "help", no_argument, 0, 'h' },
835                 { "count", no_argument, 0, 'c' },
836                 { "basename", no_argument, 0, 'b' },
837                 { "database", required_argument, 0, 'd' },
838                 { "existing", no_argument, 0, 'e' },
839                 { "ignore-case", no_argument, 0, 'i' },
840                 { "limit", required_argument, 0, 'l' },
841                 { "null", no_argument, 0, '0' },
842                 { "version", no_argument, 0, 'V' },
843                 { "regexp", no_argument, 0, 'r' },
844                 { "regex", no_argument, 0, EXTENDED_REGEX },
845                 { "wholename", no_argument, 0, 'w' },
846                 { "debug", no_argument, 0, 'D' },  // Not documented.
847                 // Enable to test cold-cache behavior (except for access()). Not documented.
848                 { "flush-cache", no_argument, 0, FLUSH_CACHE },
849                 { 0, 0, 0, 0 }
850         };
851
852         setlocale(LC_ALL, "");
853         for (;;) {
854                 int option_index = 0;
855                 int c = getopt_long(argc, argv, "bcd:ehil:n:0rwVD", long_options, &option_index);
856                 if (c == -1) {
857                         break;
858                 }
859                 switch (c) {
860                 case 'b':
861                         match_basename = true;
862                         break;
863                 case 'c':
864                         only_count = true;
865                         break;
866                 case 'd':
867                         parse_dbpaths(optarg, &dbpaths);
868                         break;
869                 case 'e':
870                         check_existence = true;
871                         break;
872                 case 'h':
873                         usage();
874                         exit(0);
875                 case 'i':
876                         ignore_case = true;
877                         break;
878                 case 'l':
879                 case 'n':
880                         limit_matches = limit_left = atoll(optarg);
881                         if (limit_matches <= 0) {
882                                 fprintf(stderr, "Error: limit must be a strictly positive number.\n");
883                                 exit(1);
884                         }
885                         break;
886                 case '0':
887                         print_nul = true;
888                         break;
889                 case 'r':
890                         patterns_are_regex = true;
891                         break;
892                 case EXTENDED_REGEX:
893                         patterns_are_regex = true;
894                         use_extended_regex = true;
895                         break;
896                 case 'w':
897                         match_basename = false;  // No-op unless -b is given first.
898                         break;
899                 case 'D':
900                         use_debug = true;
901                         break;
902                 case FLUSH_CACHE:
903                         flush_cache = true;
904                         break;
905                 case 'V':
906                         version();
907                         break;
908                 default:
909                         exit(1);
910                 }
911         }
912
913         if (use_debug || flush_cache) {
914                 // Debug information would leak information about which files exist,
915                 // so drop setgid before we open the file; one would either need to run
916                 // as root, or use a locally-built file. Doing the same thing for
917                 // flush_cache is mostly paranoia, in an attempt to prevent random users
918                 // from making plocate slow for everyone else.
919                 if (setgid(getgid()) != 0) {
920                         perror("setgid");
921                         exit(EXIT_FAILURE);
922                 }
923         }
924
925         if (!print_nul) {
926                 stdout_is_tty = isatty(1);
927         }
928
929         vector<Needle> needles;
930         for (int i = optind; i < argc; ++i) {
931                 Needle needle;
932                 needle.str = argv[i];
933
934                 // See if there are any wildcard characters, which indicates we should treat it
935                 // as an (anchored) glob.
936                 bool any_wildcard = false;
937                 for (size_t i = 0; i < needle.str.size(); i += read_unigram(needle.str, i).second) {
938                         if (read_unigram(needle.str, i).first == WILDCARD_UNIGRAM) {
939                                 any_wildcard = true;
940                                 break;
941                         }
942                 }
943
944                 if (patterns_are_regex) {
945                         needle.type = Needle::REGEX;
946                         needle.re = compile_regex(needle.str);
947                 } else if (any_wildcard) {
948                         needle.type = Needle::GLOB;
949                 } else if (ignore_case) {
950                         // strcasestr() doesn't handle locales correctly (even though LSB
951                         // claims it should), but somehow, fnmatch() does, and it's about
952                         // the same speed as using a regex.
953                         needle.type = Needle::GLOB;
954                         needle.str = "*" + needle.str + "*";
955                 } else {
956                         needle.type = Needle::STRSTR;
957                         needle.str = unescape_glob_to_plain_string(needle.str);
958                 }
959                 needles.push_back(move(needle));
960         }
961         if (needles.empty()) {
962                 fprintf(stderr, "plocate: no pattern to search for specified\n");
963                 exit(0);
964         }
965
966         if (dbpaths.empty()) {
967                 // No -d given, so use our default. Note that this happens
968                 // even if LOCATE_PATH exists, to match mlocate behavior.
969                 dbpaths.push_back(DBFILE);
970         }
971
972         const char *locate_path = getenv("LOCATE_PATH");
973         if (locate_path != nullptr) {
974                 parse_dbpaths(locate_path, &dbpaths);
975         }
976
977         uint64_t matched = 0;
978         for (size_t i = 0; i < dbpaths.size(); ++i) {
979                 uint64_t this_matched;
980                 if (i != dbpaths.size() - 1) {
981                         this_matched = do_search_file_in_child(needles, dbpaths[i]);
982                 } else {
983                         this_matched = do_search_file(needles, dbpaths[i]);
984                 }
985                 matched += this_matched;
986                 limit_left -= this_matched;
987         }
988         if (only_count) {
989                 printf("%" PRId64 "\n", matched);
990         }
991 }