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