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