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