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