]> git.sesse.net Git - plocate/blob - plocate.cpp
Format everything with clang-format.
[plocate] / plocate.cpp
1 #include "vp4.h"
2
3 #include <algorithm>
4 #include <arpa/inet.h>
5 #include <chrono>
6 #include <endian.h>
7 #include <fcntl.h>
8 #include <stdio.h>
9 #include <string.h>
10 #include <string>
11 #include <sys/mman.h>
12 #include <unistd.h>
13 #include <unordered_map>
14 #include <vector>
15 #include <zstd.h>
16
17 #define P4NENC_BOUND(n) ((n + 127) / 128 + (n + 32) * sizeof(uint32_t))
18
19 using namespace std;
20 using namespace std::chrono;
21
22 #define dprintf(...)
23 //#define dprintf(...) fprintf(stderr, __VA_ARGS__);
24
25 static inline uint32_t read_unigram(const string &s, size_t idx)
26 {
27         if (idx < s.size()) {
28                 return (unsigned char)s[idx];
29         } else {
30                 return 0;
31         }
32 }
33
34 static inline uint32_t read_trigram(const string &s, size_t start)
35 {
36         return read_unigram(s, start) | (read_unigram(s, start + 1) << 8) |
37                 (read_unigram(s, start + 2) << 16);
38 }
39
40 bool has_access(const char *filename,
41                 unordered_map<string, bool> *access_rx_cache)
42 {
43         const char *end = strchr(filename + 1, '/');
44         while (end != nullptr) {
45                 string parent_path(filename, end);
46                 auto it = access_rx_cache->find(parent_path);
47                 bool ok;
48                 if (it == access_rx_cache->end()) {
49                         ok = access(parent_path.c_str(), R_OK | X_OK) == 0;
50                         access_rx_cache->emplace(move(parent_path), ok);
51                 } else {
52                         ok = it->second;
53                 }
54                 if (!ok) {
55                         return false;
56                 }
57                 end = strchr(end + 1, '/');
58         }
59
60         return true;
61 }
62
63 struct Trigram {
64         uint32_t trgm;
65         uint32_t num_docids;
66         uint64_t offset;
67 };
68
69 class Corpus {
70 public:
71         Corpus(int fd);
72         ~Corpus();
73         const Trigram *find_trigram(uint32_t trgm) const;
74         const unsigned char *
75         get_compressed_posting_list(const Trigram *trigram) const;
76         string_view get_compressed_filename_block(uint32_t docid) const;
77
78 private:
79         const int fd;
80         off_t len;
81         const char *data;
82         const uint64_t *filename_offsets;
83         const Trigram *trgm_begin, *trgm_end;
84 };
85
86 Corpus::Corpus(int fd)
87         : fd(fd)
88 {
89         len = lseek(fd, 0, SEEK_END);
90         if (len == -1) {
91                 perror("lseek");
92                 exit(1);
93         }
94         data = (char *)mmap(nullptr, len, PROT_READ, MAP_SHARED, fd, /*offset=*/0);
95         if (data == MAP_FAILED) {
96                 perror("mmap");
97                 exit(1);
98         }
99
100         uint64_t num_trigrams = *(const uint64_t *)data;
101         uint64_t filename_index_offset = *(const uint64_t *)(data + sizeof(uint64_t));
102         filename_offsets = (const uint64_t *)(data + filename_index_offset);
103
104         trgm_begin = (Trigram *)(data + sizeof(uint64_t) * 2);
105         trgm_end = trgm_begin + num_trigrams;
106 }
107
108 Corpus::~Corpus()
109 {
110         munmap((void *)data, len);
111         close(fd);
112 }
113
114 const Trigram *Corpus::find_trigram(uint32_t trgm) const
115 {
116         const Trigram *trgmptr = lower_bound(
117                 trgm_begin, trgm_end, trgm,
118                 [](const Trigram &trgm, uint32_t t) { return trgm.trgm < t; });
119         if (trgmptr == trgm_end || trgmptr->trgm != trgm) {
120                 return nullptr;
121         }
122         return trgmptr;
123 }
124
125 const unsigned char *
126 Corpus::get_compressed_posting_list(const Trigram *trgmptr) const
127 {
128         return reinterpret_cast<const unsigned char *>(data + trgmptr->offset);
129 }
130
131 string_view Corpus::get_compressed_filename_block(uint32_t docid) const
132 {
133         const char *compressed = (const char *)(data + filename_offsets[docid]);
134         size_t compressed_size =
135                 filename_offsets[docid + 1] -
136                 filename_offsets[docid];  // Allowed we have a sentinel block at the end.
137         return { compressed, compressed_size };
138 }
139
140 size_t scan_docid(const string &needle, uint32_t docid, const Corpus &corpus,
141                   unordered_map<string, bool> *access_rx_cache)
142 {
143         string_view compressed = corpus.get_compressed_filename_block(docid);
144         size_t matched = 0;
145
146         string block;
147         block.resize(ZSTD_getFrameContentSize(compressed.data(), compressed.size()) +
148                      1);
149
150         ZSTD_decompress(&block[0], block.size(), compressed.data(),
151                         compressed.size());
152         block[block.size() - 1] = '\0';
153
154         for (const char *filename = block.data();
155              filename != block.data() + block.size();
156              filename += strlen(filename) + 1) {
157                 if (strstr(filename, needle.c_str()) == nullptr) {
158                         continue;
159                 }
160                 if (has_access(filename, access_rx_cache)) {
161                         ++matched;
162                         printf("%s\n", filename);
163                 }
164         }
165         return matched;
166 }
167
168 void do_search_file(const string &needle, const char *filename)
169 {
170         int fd = open(filename, O_RDONLY);
171         if (fd == -1) {
172                 perror(filename);
173                 exit(1);
174         }
175
176         // Drop privileges.
177         if (setgid(getgid()) != 0) {
178                 perror("setgid");
179                 exit(EXIT_FAILURE);
180         }
181
182         // steady_clock::time_point start = steady_clock::now();
183         if (access("/", R_OK | X_OK)) {
184                 // We can't find anything, no need to bother...
185                 return;
186         }
187
188         Corpus corpus(fd);
189
190         vector<const Trigram *> trigrams;
191         for (size_t i = 0; i < needle.size() - 2; ++i) {
192                 uint32_t trgm = read_trigram(needle, i);
193                 const Trigram *trgmptr = corpus.find_trigram(trgm);
194                 if (trgmptr == nullptr) {
195                         dprintf("trigram %06x isn't found, we abort the search\n", trgm);
196                         return;
197                 }
198                 trigrams.push_back(trgmptr);
199         }
200         sort(trigrams.begin(), trigrams.end());
201         {
202                 auto last = unique(trigrams.begin(), trigrams.end());
203                 trigrams.erase(last, trigrams.end());
204         }
205         sort(trigrams.begin(), trigrams.end(),
206              [&](const Trigram *a, const Trigram *b) {
207                      return a->num_docids < b->num_docids;
208              });
209
210         vector<uint32_t> in1, in2, out;
211         for (const Trigram *trgmptr : trigrams) {
212                 // uint32_t trgm = trgmptr->trgm;
213                 size_t num = trgmptr->num_docids;
214                 const unsigned char *pldata = corpus.get_compressed_posting_list(trgmptr);
215                 if (in1.empty()) {
216                         in1.resize(num + 128);
217                         p4nd1dec128v32(const_cast<unsigned char *>(pldata), num, &in1[0]);
218                         in1.resize(num);
219                         dprintf("trigram '%c%c%c' decoded to %zu entries\n", trgm & 0xff,
220                                 (trgm >> 8) & 0xff, (trgm >> 16) & 0xff, num);
221                 } else {
222                         if (num > in1.size() * 100) {
223                                 dprintf("trigram '%c%c%c' has %zu entries, ignoring the rest (will "
224                                         "weed out false positives later)\n",
225                                         trgm & 0xff, (trgm >> 8) & 0xff, (trgm >> 16) & 0xff, num);
226                                 break;
227                         }
228
229                         if (in2.size() < num + 128) {
230                                 in2.resize(num + 128);
231                         }
232                         p4nd1dec128v32(const_cast<unsigned char *>(pldata), num, &in2[0]);
233
234                         out.clear();
235                         set_intersection(in1.begin(), in1.end(), in2.begin(), in2.begin() + num,
236                                          back_inserter(out));
237                         swap(in1, out);
238                         dprintf("trigram '%c%c%c' decoded to %zu entries, %zu left\n",
239                                 trgm & 0xff, (trgm >> 8) & 0xff, (trgm >> 16) & 0xff, num,
240                                 in1.size());
241                         if (in1.empty()) {
242                                 dprintf("no matches (intersection list is empty)\n");
243                                 break;
244                         }
245                 }
246         }
247         steady_clock::time_point end = steady_clock::now();
248
249         dprintf("Intersection took %.1f ms. Doing final verification and printing:\n",
250                 1e3 * duration<float>(end - start).count());
251
252         unordered_map<string, bool> access_rx_cache;
253
254         int matched = 0;
255         for (uint32_t docid : in1) {
256                 matched += scan_docid(needle, docid, corpus, &access_rx_cache);
257         }
258         end = steady_clock::now();
259         dprintf("Done in %.1f ms, found %d matches.\n",
260                 1e3 * duration<float>(end - start).count(), matched);
261 }
262
263 int main(int argc, char **argv)
264 {
265         do_search_file(argv[1], "/var/lib/mlocate/plocate.db");
266 }