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