]> git.sesse.net Git - plocate/blob - plocate.cpp
Quit on unknown option.
[plocate] / plocate.cpp
1 #include "db.h"
2 #include "io_uring_engine.h"
3 #include "vp4.h"
4
5 #include <algorithm>
6 #include <arpa/inet.h>
7 #include <chrono>
8 #include <endian.h>
9 #include <fcntl.h>
10 #include <functional>
11 #include <getopt.h>
12 #include <memory>
13 #include <stdio.h>
14 #include <string.h>
15 #include <string>
16 #include <unistd.h>
17 #include <unordered_map>
18 #include <vector>
19 #include <zstd.h>
20
21 using namespace std;
22 using namespace std::chrono;
23
24 #define dprintf(...)
25 //#define dprintf(...) fprintf(stderr, __VA_ARGS__);
26
27 const char *dbpath = "/var/lib/mlocate/plocate.db";
28 bool print_nul = false;
29
30 class Serializer {
31 public:
32         void do_or_wait(int seq, function<void()> cb);
33
34 private:
35         int next_seq = 0;
36         struct Element {
37                 int seq;
38                 function<void()> cb;
39
40                 bool operator<(const Element &other) const
41                 {
42                         return seq > other.seq;
43                 }
44         };
45         priority_queue<Element> pending;
46 };
47
48 void Serializer::do_or_wait(int seq, function<void()> cb)
49 {
50         if (seq != next_seq) {
51                 pending.emplace(Element{ seq, move(cb) });
52                 return;
53         }
54
55         cb();
56         ++next_seq;
57
58         while (!pending.empty() && pending.top().seq == next_seq) {
59                 pending.top().cb();
60                 pending.pop();
61                 ++next_seq;
62         }
63 }
64
65 static inline uint32_t read_unigram(const string &s, size_t idx)
66 {
67         if (idx < s.size()) {
68                 return (unsigned char)s[idx];
69         } else {
70                 return 0;
71         }
72 }
73
74 static inline uint32_t read_trigram(const string &s, size_t start)
75 {
76         return read_unigram(s, start) | (read_unigram(s, start + 1) << 8) |
77                 (read_unigram(s, start + 2) << 16);
78 }
79
80 bool has_access(const char *filename,
81                 unordered_map<string, bool> *access_rx_cache)
82 {
83         const char *end = strchr(filename + 1, '/');
84         while (end != nullptr) {
85                 string parent_path(filename, end);
86                 auto it = access_rx_cache->find(parent_path);
87                 bool ok;
88                 if (it == access_rx_cache->end()) {
89                         ok = access(parent_path.c_str(), R_OK | X_OK) == 0;
90                         access_rx_cache->emplace(move(parent_path), ok);
91                 } else {
92                         ok = it->second;
93                 }
94                 if (!ok) {
95                         return false;
96                 }
97                 end = strchr(end + 1, '/');
98         }
99
100         return true;
101 }
102
103 class Corpus {
104 public:
105         Corpus(int fd, IOUringEngine *engine);
106         ~Corpus();
107         void find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb);
108         void get_compressed_filename_block(uint32_t docid, function<void(string)> cb) const;
109         size_t get_num_filename_blocks() const;
110         off_t offset_for_block(uint32_t docid) const
111         {
112                 return hdr.filename_index_offset_bytes + docid * sizeof(uint64_t);
113         }
114
115 public:
116         const int fd;
117         IOUringEngine *const engine;
118
119         Header hdr;
120 };
121
122 Corpus::Corpus(int fd, IOUringEngine *engine)
123         : fd(fd), engine(engine)
124 {
125         // Enable to test cold-cache behavior (except for access()).
126         if (false) {
127                 off_t len = lseek(fd, 0, SEEK_END);
128                 if (len == -1) {
129                         perror("lseek");
130                         exit(1);
131                 }
132                 posix_fadvise(fd, 0, len, POSIX_FADV_DONTNEED);
133         }
134
135         complete_pread(fd, &hdr, sizeof(hdr), /*offset=*/0);
136         if (memcmp(hdr.magic, "\0plocate", 8) != 0) {
137                 fprintf(stderr, "plocate.db is corrupt or an old version; please rebuild it.\n");
138                 exit(1);
139         }
140         if (hdr.version != 0) {
141                 fprintf(stderr, "plocate.db has version %u, expected 0; please rebuild it.\n", hdr.version);
142                 exit(1);
143         }
144 }
145
146 Corpus::~Corpus()
147 {
148         close(fd);
149 }
150
151 void Corpus::find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb)
152 {
153         uint32_t bucket = hash_trigram(trgm, hdr.hashtable_size);
154         engine->submit_read(fd, sizeof(Trigram) * (hdr.extra_ht_slots + 2), hdr.hash_table_offset_bytes + sizeof(Trigram) * bucket, [this, trgm, bucket, cb{ move(cb) }](string s) {
155                 const Trigram *trgmptr = reinterpret_cast<const Trigram *>(s.data());
156                 for (unsigned i = 0; i < hdr.extra_ht_slots + 1; ++i) {
157                         if (trgmptr[i].trgm == trgm) {
158                                 cb(trgmptr + i, trgmptr[i + 1].offset - trgmptr[i].offset);
159                                 return;
160                         }
161                 }
162
163                 // Not found.
164                 cb(nullptr, 0);
165         });
166 }
167
168 void Corpus::get_compressed_filename_block(uint32_t docid, function<void(string)> cb) const
169 {
170         // Read the file offset from this docid and the next one.
171         // This is always allowed, since we have a sentinel block at the end.
172         engine->submit_read(fd, sizeof(uint64_t) * 2, offset_for_block(docid), [this, cb{ move(cb) }](string s) {
173                 const uint64_t *ptr = reinterpret_cast<const uint64_t *>(s.data());
174                 off_t offset = ptr[0];
175                 size_t len = ptr[1] - ptr[0];
176                 engine->submit_read(fd, len, offset, cb);
177         });
178 }
179
180 size_t Corpus::get_num_filename_blocks() const
181 {
182         // The beginning of the filename blocks is the end of the filename index blocks.
183         uint64_t end;
184         complete_pread(fd, &end, sizeof(end), hdr.filename_index_offset_bytes);
185
186         // Subtract the sentinel block.
187         return (end - hdr.filename_index_offset_bytes) / sizeof(uint64_t) - 1;
188 }
189
190 size_t scan_file_block(const vector<string> &needles, string_view compressed,
191                        unordered_map<string, bool> *access_rx_cache)
192 {
193         size_t matched = 0;
194
195         unsigned long long uncompressed_len = ZSTD_getFrameContentSize(compressed.data(), compressed.size());
196         if (uncompressed_len == ZSTD_CONTENTSIZE_UNKNOWN || uncompressed_len == ZSTD_CONTENTSIZE_ERROR) {
197                 fprintf(stderr, "ZSTD_getFrameContentSize() failed\n");
198                 exit(1);
199         }
200
201         string block;
202         block.resize(uncompressed_len + 1);
203
204         size_t err = ZSTD_decompress(&block[0], block.size(), compressed.data(),
205                                      compressed.size());
206         if (ZSTD_isError(err)) {
207                 fprintf(stderr, "ZSTD_decompress(): %s\n", ZSTD_getErrorName(err));
208                 exit(1);
209         }
210         block[block.size() - 1] = '\0';
211
212         for (const char *filename = block.data();
213              filename != block.data() + block.size();
214              filename += strlen(filename) + 1) {
215                 bool found = true;
216                 for (const string &needle : needles) {
217                         if (strstr(filename, needle.c_str()) == nullptr) {
218                                 found = false;
219                                 break;
220                         }
221                 }
222                 if (found && has_access(filename, access_rx_cache)) {
223                         ++matched;
224                         if (print_nul) {
225                                 printf("%s%c", filename, 0);
226                         } else {
227                                 printf("%s\n", filename);
228                         }
229                 }
230         }
231         return matched;
232 }
233
234 size_t scan_docids(const vector<string> &needles, const vector<uint32_t> &docids, const Corpus &corpus, IOUringEngine *engine)
235 {
236         Serializer docids_in_order;
237         unordered_map<string, bool> access_rx_cache;
238         size_t matched = 0;
239         for (size_t i = 0; i < docids.size(); ++i) {
240                 uint32_t docid = docids[i];
241                 corpus.get_compressed_filename_block(docid, [i, &matched, &needles, &access_rx_cache, &docids_in_order](string compressed) {
242                         docids_in_order.do_or_wait(i, [&matched, &needles, compressed{ move(compressed) }, &access_rx_cache] {
243                                 matched += scan_file_block(needles, compressed, &access_rx_cache);
244                         });
245                 });
246         }
247         engine->finish();
248         return matched;
249 }
250
251 // We do this sequentially, as it's faster than scattering
252 // a lot of I/O through io_uring and hoping the kernel will
253 // coalesce it plus readahead for us.
254 void scan_all_docids(const vector<string> &needles, int fd, const Corpus &corpus, IOUringEngine *engine)
255 {
256         unordered_map<string, bool> access_rx_cache;
257         uint32_t num_blocks = corpus.get_num_filename_blocks();
258         unique_ptr<uint64_t[]> offsets(new uint64_t[num_blocks + 1]);
259         complete_pread(fd, offsets.get(), (num_blocks + 1) * sizeof(uint64_t), corpus.offset_for_block(0));
260         string compressed;
261         for (uint32_t io_docid = 0; io_docid < num_blocks; io_docid += 32) {
262                 uint32_t last_docid = std::min(io_docid + 32, num_blocks);
263                 size_t io_len = offsets[last_docid] - offsets[io_docid];
264                 if (compressed.size() < io_len) {
265                         compressed.resize(io_len);
266                 }
267                 complete_pread(fd, &compressed[0], io_len, offsets[io_docid]);
268
269                 for (uint32_t docid = io_docid; docid < last_docid; ++docid) {
270                         size_t relative_offset = offsets[docid] - offsets[io_docid];
271                         size_t len = offsets[docid + 1] - offsets[docid];
272                         scan_file_block(needles, { &compressed[relative_offset], len }, &access_rx_cache);
273                 }
274         }
275 }
276
277 void do_search_file(const vector<string> &needles, const char *filename)
278 {
279         int fd = open(filename, O_RDONLY);
280         if (fd == -1) {
281                 perror(filename);
282                 exit(1);
283         }
284
285         // Drop privileges.
286         if (setgid(getgid()) != 0) {
287                 perror("setgid");
288                 exit(EXIT_FAILURE);
289         }
290
291         steady_clock::time_point start __attribute__((unused)) = steady_clock::now();
292         if (access("/", R_OK | X_OK)) {
293                 // We can't find anything, no need to bother...
294                 return;
295         }
296
297         IOUringEngine engine;
298         Corpus corpus(fd, &engine);
299         dprintf("Corpus init done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
300
301         vector<pair<Trigram, size_t>> trigrams;
302         for (const string &needle : needles) {
303                 if (needle.size() < 3) continue;
304                 for (size_t i = 0; i < needle.size() - 2; ++i) {
305                         uint32_t trgm = read_trigram(needle, i);
306                         corpus.find_trigram(trgm, [trgm, &trigrams](const Trigram *trgmptr, size_t len) {
307                                 if (trgmptr == nullptr) {
308                                         dprintf("trigram %06x isn't found, we abort the search\n", trgm);
309                                         return;
310                                 }
311                                 trigrams.emplace_back(*trgmptr, len);
312                         });
313                 }
314         }
315         engine.finish();
316         dprintf("Hashtable lookups done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
317
318         if (trigrams.empty()) {
319                 // Too short for trigram matching. Apply brute force.
320                 // (We could have searched through all trigrams that matched
321                 // the pattern and done a union of them, but that's a lot of
322                 // work for fairly unclear gain.)
323                 scan_all_docids(needles, fd, corpus, &engine);
324                 return;
325         }
326         sort(trigrams.begin(), trigrams.end());
327         {
328                 auto last = unique(trigrams.begin(), trigrams.end());
329                 trigrams.erase(last, trigrams.end());
330         }
331         sort(trigrams.begin(), trigrams.end(),
332              [&](const pair<Trigram, size_t> &a, const pair<Trigram, size_t> &b) {
333                      return a.first.num_docids < b.first.num_docids;
334              });
335
336         vector<uint32_t> in1, in2, out;
337         bool done = false;
338         for (auto [trgmptr, len] : trigrams) {
339                 if (!in1.empty() && trgmptr.num_docids > in1.size() * 100) {
340                         uint32_t trgm __attribute__((unused)) = trgmptr.trgm;
341                         dprintf("trigram '%c%c%c' (%zu bytes) has %u entries, ignoring the rest (will "
342                                 "weed out false positives later)\n",
343                                 trgm & 0xff, (trgm >> 8) & 0xff, (trgm >> 16) & 0xff,
344                                 len, trgmptr.num_docids);
345                         break;
346                 }
347
348                 // Only stay a certain amount ahead, so that we don't spend I/O
349                 // on reading the latter, large posting lists. We are unlikely
350                 // to need them anyway, even if they should come in first.
351                 if (engine.get_waiting_reads() >= 5) {
352                         engine.finish();
353                         if (done)
354                                 break;
355                 }
356                 engine.submit_read(fd, len, trgmptr.offset, [trgmptr, len, &done, &in1, &in2, &out](string s) {
357                         if (done)
358                                 return;
359                         uint32_t trgm __attribute__((unused)) = trgmptr.trgm;
360                         size_t num = trgmptr.num_docids;
361                         unsigned char *pldata = reinterpret_cast<unsigned char *>(s.data());
362                         if (in1.empty()) {
363                                 in1.resize(num + 128);
364                                 p4nd1dec128v32(pldata, num, &in1[0]);
365                                 in1.resize(num);
366                                 dprintf("trigram '%c%c%c' (%zu bytes) decoded to %zu entries\n", trgm & 0xff,
367                                         (trgm >> 8) & 0xff, (trgm >> 16) & 0xff, len, num);
368                         } else {
369                                 if (in2.size() < num + 128) {
370                                         in2.resize(num + 128);
371                                 }
372                                 p4nd1dec128v32(pldata, num, &in2[0]);
373
374                                 out.clear();
375                                 set_intersection(in1.begin(), in1.end(), in2.begin(), in2.begin() + num,
376                                                  back_inserter(out));
377                                 swap(in1, out);
378                                 dprintf("trigram '%c%c%c' (%zu bytes) decoded to %zu entries, %zu left\n",
379                                         trgm & 0xff, (trgm >> 8) & 0xff, (trgm >> 16) & 0xff,
380                                         len, num, in1.size());
381                                 if (in1.empty()) {
382                                         dprintf("no matches (intersection list is empty)\n");
383                                         done = true;
384                                 }
385                         }
386                 });
387         }
388         engine.finish();
389         if (done) {
390                 return;
391         }
392         dprintf("Intersection done after %.1f ms. Doing final verification and printing:\n",
393                 1e3 * duration<float>(steady_clock::now() - start).count());
394
395         size_t matched __attribute__((unused)) = scan_docids(needles, in1, corpus, &engine);
396         dprintf("Done in %.1f ms, found %zu matches.\n",
397                 1e3 * duration<float>(steady_clock::now() - start).count(), matched);
398 }
399
400 void usage()
401 {
402         // The help text comes from mlocate.
403         printf("Usage: plocate [OPTION]... PATTERN...\n");
404         printf("  -d, --database DBPATH  use DBPATH instead of default database (which is\n");
405         printf("                         %s)\n", dbpath);
406         printf("  -h, --help             print this help\n");
407         printf("  -0, --null             separate entries with NUL on output\n");
408 }
409
410 int main(int argc, char **argv)
411 {
412         static const struct option long_options[] = {
413                 { "help", no_argument, 0, 'h' },
414                 { "database", required_argument, 0, 'd' },
415                 { "null", no_argument, 0, '0' },
416                 { 0, 0, 0, 0 }
417         };
418
419         for (;;) {
420                 int option_index = 0;
421                 int c = getopt_long(argc, argv, "d:h0", long_options, &option_index);
422                 if (c == -1) {
423                         break;
424                 }
425                 switch (c) {
426                 case 'd':
427                         dbpath = strdup(optarg);
428                         break;
429                 case 'h':
430                         usage();
431                         exit(0);
432                 case '0':
433                         print_nul = true;
434                         break;
435                 default:
436                         exit(1);
437                 }
438         }
439
440         vector<string> needles;
441         for (int i = optind; i < argc; ++i) {
442                 needles.push_back(argv[i]);
443         }
444         if (needles.empty()) {
445                 fprintf(stderr, "plocate: no pattern to search for specified\n");
446                 exit(0);
447         }
448         do_search_file(needles, dbpath);
449 }