]> git.sesse.net Git - plocate/blob - plocate.cpp
Add debug output if io_uring initialization fails.
[plocate] / plocate.cpp
1 #include "db.h"
2 #include "dprintf.h"
3 #include "io_uring_engine.h"
4 #include "parse_trigrams.h"
5 #include "turbopfor.h"
6 #include "unique_sort.h"
7
8 #include <algorithm>
9 #include <assert.h>
10 #include <chrono>
11 #include <fcntl.h>
12 #include <fnmatch.h>
13 #include <functional>
14 #include <getopt.h>
15 #include <iosfwd>
16 #include <iterator>
17 #include <limits>
18 #include <memory>
19 #include <queue>
20 #include <regex.h>
21 #include <stdint.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <string>
26 #include <string_view>
27 #include <unistd.h>
28 #include <unordered_map>
29 #include <unordered_set>
30 #include <utility>
31 #include <vector>
32 #include <zstd.h>
33
34 using namespace std;
35 using namespace std::chrono;
36
37 #define DEFAULT_DBPATH "/var/lib/mlocate/plocate.db"
38
39 const char *dbpath = DEFAULT_DBPATH;
40 bool ignore_case = false;
41 bool only_count = false;
42 bool print_nul = false;
43 bool use_debug = false;
44 bool patterns_are_regex = false;
45 bool use_extended_regex = false;
46 int64_t limit_matches = numeric_limits<int64_t>::max();
47
48 class Serializer {
49 public:
50         bool ready_to_print(int seq) { return next_seq == seq; }
51         void print_delayed(int seq, const vector<string> msg);
52         void release_current();
53
54 private:
55         int next_seq = 0;
56         struct Element {
57                 int seq;
58                 vector<string> msg;
59
60                 bool operator<(const Element &other) const
61                 {
62                         return seq > other.seq;
63                 }
64         };
65         priority_queue<Element> pending;
66 };
67
68 void Serializer::print_delayed(int seq, const vector<string> msg)
69 {
70         pending.push(Element{ seq, move(msg) });
71 }
72
73 void Serializer::release_current()
74 {
75         ++next_seq;
76
77         // See if any delayed prints can now be dealt with.
78         while (!pending.empty() && pending.top().seq == next_seq) {
79                 if (limit_matches-- <= 0)
80                         return;
81                 for (const string &msg : pending.top().msg) {
82                         if (print_nul) {
83                                 printf("%s%c", msg.c_str(), 0);
84                         } else {
85                                 printf("%s\n", msg.c_str());
86                         }
87                 }
88                 pending.pop();
89                 ++next_seq;
90         }
91 }
92
93 struct Needle {
94         enum { STRSTR,
95                REGEX,
96                GLOB } type;
97         string str;  // Filled in no matter what.
98         regex_t re;  // For REGEX.
99 };
100
101 bool matches(const Needle &needle, const char *haystack)
102 {
103         if (needle.type == Needle::STRSTR) {
104                 return strstr(haystack, needle.str.c_str()) != nullptr;
105         } else if (needle.type == Needle::GLOB) {
106                 int flags = ignore_case ? FNM_CASEFOLD : 0;
107                 return fnmatch(needle.str.c_str(), haystack, flags) == 0;
108         } else {
109                 assert(needle.type == Needle::REGEX);
110                 return regexec(&needle.re, haystack, /*nmatch=*/0, /*pmatch=*/nullptr, /*flags=*/0) == 0;
111         }
112 }
113
114 bool has_access(const char *filename,
115                 unordered_map<string, bool> *access_rx_cache)
116 {
117         const char *end = strchr(filename + 1, '/');
118         while (end != nullptr) {
119                 string parent_path(filename, end);
120                 auto it = access_rx_cache->find(parent_path);
121                 bool ok;
122                 if (it == access_rx_cache->end()) {
123                         ok = access(parent_path.c_str(), R_OK | X_OK) == 0;
124                         access_rx_cache->emplace(move(parent_path), ok);
125                 } else {
126                         ok = it->second;
127                 }
128                 if (!ok) {
129                         return false;
130                 }
131                 end = strchr(end + 1, '/');
132         }
133
134         return true;
135 }
136
137 class Corpus {
138 public:
139         Corpus(int fd, IOUringEngine *engine);
140         ~Corpus();
141         void find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb);
142         void get_compressed_filename_block(uint32_t docid, function<void(string_view)> cb) const;
143         size_t get_num_filename_blocks() const;
144         off_t offset_for_block(uint32_t docid) const
145         {
146                 return hdr.filename_index_offset_bytes + docid * sizeof(uint64_t);
147         }
148
149 public:
150         const int fd;
151         IOUringEngine *const engine;
152
153         Header hdr;
154 };
155
156 Corpus::Corpus(int fd, IOUringEngine *engine)
157         : fd(fd), engine(engine)
158 {
159         // Enable to test cold-cache behavior (except for access()).
160         if (false) {
161                 off_t len = lseek(fd, 0, SEEK_END);
162                 if (len == -1) {
163                         perror("lseek");
164                         exit(1);
165                 }
166                 posix_fadvise(fd, 0, len, POSIX_FADV_DONTNEED);
167         }
168
169         complete_pread(fd, &hdr, sizeof(hdr), /*offset=*/0);
170         if (memcmp(hdr.magic, "\0plocate", 8) != 0) {
171                 fprintf(stderr, "plocate.db is corrupt or an old version; please rebuild it.\n");
172                 exit(1);
173         }
174         if (hdr.version != 0) {
175                 fprintf(stderr, "plocate.db has version %u, expected 0; please rebuild it.\n", hdr.version);
176                 exit(1);
177         }
178 }
179
180 Corpus::~Corpus()
181 {
182         close(fd);
183 }
184
185 void Corpus::find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb)
186 {
187         uint32_t bucket = hash_trigram(trgm, hdr.hashtable_size);
188         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) {
189                 const Trigram *trgmptr = reinterpret_cast<const Trigram *>(s.data());
190                 for (unsigned i = 0; i < hdr.extra_ht_slots + 1; ++i) {
191                         if (trgmptr[i].trgm == trgm) {
192                                 cb(trgmptr + i, trgmptr[i + 1].offset - trgmptr[i].offset);
193                                 return;
194                         }
195                 }
196
197                 // Not found.
198                 cb(nullptr, 0);
199         });
200 }
201
202 void Corpus::get_compressed_filename_block(uint32_t docid, function<void(string_view)> cb) const
203 {
204         // Read the file offset from this docid and the next one.
205         // This is always allowed, since we have a sentinel block at the end.
206         engine->submit_read(fd, sizeof(uint64_t) * 2, offset_for_block(docid), [this, cb{ move(cb) }](string_view s) {
207                 const uint64_t *ptr = reinterpret_cast<const uint64_t *>(s.data());
208                 off_t offset = ptr[0];
209                 size_t len = ptr[1] - ptr[0];
210                 engine->submit_read(fd, len, offset, cb);
211         });
212 }
213
214 size_t Corpus::get_num_filename_blocks() const
215 {
216         return hdr.num_docids;
217 }
218
219 uint64_t scan_file_block(const vector<Needle> &needles, string_view compressed,
220                          unordered_map<string, bool> *access_rx_cache, int seq,
221                          Serializer *serializer)
222 {
223         uint64_t matched = 0;
224
225         unsigned long long uncompressed_len = ZSTD_getFrameContentSize(compressed.data(), compressed.size());
226         if (uncompressed_len == ZSTD_CONTENTSIZE_UNKNOWN || uncompressed_len == ZSTD_CONTENTSIZE_ERROR) {
227                 fprintf(stderr, "ZSTD_getFrameContentSize() failed\n");
228                 exit(1);
229         }
230
231         string block;
232         block.resize(uncompressed_len + 1);
233
234         size_t err = ZSTD_decompress(&block[0], block.size(), compressed.data(),
235                                      compressed.size());
236         if (ZSTD_isError(err)) {
237                 fprintf(stderr, "ZSTD_decompress(): %s\n", ZSTD_getErrorName(err));
238                 exit(1);
239         }
240         block[block.size() - 1] = '\0';
241
242         bool immediate_print = (serializer == nullptr || serializer->ready_to_print(seq));
243         vector<string> delayed;
244
245         for (const char *filename = block.data();
246              filename != block.data() + block.size();
247              filename += strlen(filename) + 1) {
248                 bool found = true;
249                 for (const Needle &needle : needles) {
250                         if (!matches(needle, filename)) {
251                                 found = false;
252                                 break;
253                         }
254                 }
255                 if (found && has_access(filename, access_rx_cache)) {
256                         if (limit_matches-- <= 0)
257                                 break;
258                         ++matched;
259                         if (only_count)
260                                 continue;
261                         if (immediate_print) {
262                                 if (print_nul) {
263                                         printf("%s%c", filename, 0);
264                                 } else {
265                                         printf("%s\n", filename);
266                                 }
267                         } else {
268                                 delayed.push_back(filename);
269                         }
270                 }
271         }
272         if (serializer != nullptr && !only_count) {
273                 if (immediate_print) {
274                         serializer->release_current();
275                 } else {
276                         serializer->print_delayed(seq, move(delayed));
277                 }
278         }
279         return matched;
280 }
281
282 size_t scan_docids(const vector<Needle> &needles, const vector<uint32_t> &docids, const Corpus &corpus, IOUringEngine *engine)
283 {
284         Serializer docids_in_order;
285         unordered_map<string, bool> access_rx_cache;
286         uint64_t matched = 0;
287         for (size_t i = 0; i < docids.size(); ++i) {
288                 uint32_t docid = docids[i];
289                 corpus.get_compressed_filename_block(docid, [i, &matched, &needles, &access_rx_cache, &docids_in_order](string_view compressed) {
290                         matched += scan_file_block(needles, compressed, &access_rx_cache, i, &docids_in_order);
291                 });
292         }
293         engine->finish();
294         return matched;
295 }
296
297 // We do this sequentially, as it's faster than scattering
298 // a lot of I/O through io_uring and hoping the kernel will
299 // coalesce it plus readahead for us.
300 uint64_t scan_all_docids(const vector<Needle> &needles, int fd, const Corpus &corpus, IOUringEngine *engine)
301 {
302         unordered_map<string, bool> access_rx_cache;
303         uint32_t num_blocks = corpus.get_num_filename_blocks();
304         unique_ptr<uint64_t[]> offsets(new uint64_t[num_blocks + 1]);
305         complete_pread(fd, offsets.get(), (num_blocks + 1) * sizeof(uint64_t), corpus.offset_for_block(0));
306         string compressed;
307         uint64_t matched = 0;
308         for (uint32_t io_docid = 0; io_docid < num_blocks; io_docid += 32) {
309                 uint32_t last_docid = std::min(io_docid + 32, num_blocks);
310                 size_t io_len = offsets[last_docid] - offsets[io_docid];
311                 if (compressed.size() < io_len) {
312                         compressed.resize(io_len);
313                 }
314                 complete_pread(fd, &compressed[0], io_len, offsets[io_docid]);
315
316                 for (uint32_t docid = io_docid; docid < last_docid; ++docid) {
317                         size_t relative_offset = offsets[docid] - offsets[io_docid];
318                         size_t len = offsets[docid + 1] - offsets[docid];
319                         matched += scan_file_block(needles, { &compressed[relative_offset], len }, &access_rx_cache, 0, nullptr);
320                         if (limit_matches <= 0)
321                                 return matched;
322                 }
323         }
324         return matched;
325 }
326
327 // Takes the given posting list, unions it into the parts of the trigram disjunction
328 // already read; if the list is complete, intersects with “cur_candidates”.
329 //
330 // Returns true if the search should be aborted (we are done).
331 bool new_posting_list_read(TrigramDisjunction *td, vector<uint32_t> decoded, vector<uint32_t> *cur_candidates, vector<uint32_t> *tmp)
332 {
333         if (td->docids.empty()) {
334                 td->docids = move(decoded);
335         } else {
336                 tmp->clear();
337                 set_union(decoded.begin(), decoded.end(), td->docids.begin(), td->docids.end(), back_inserter(*tmp));
338                 swap(*tmp, td->docids);
339         }
340         if (--td->remaining_trigrams_to_read > 0) {
341                 // Need to wait for more.
342                 if (ignore_case) {
343                         dprintf("  ... %u reads left in OR group %u (%zu docids in list)\n",
344                                 td->remaining_trigrams_to_read, td->index, td->docids.size());
345                 }
346                 return false;
347         }
348         if (cur_candidates->empty()) {
349                 if (ignore_case) {
350                         dprintf("  ... all reads done for OR group %u (%zu docids)\n",
351                                 td->index, td->docids.size());
352                 }
353                 *cur_candidates = move(td->docids);
354         } else {
355                 tmp->clear();
356                 set_intersection(cur_candidates->begin(), cur_candidates->end(),
357                                  td->docids.begin(), td->docids.end(),
358                                  back_inserter(*tmp));
359                 swap(*cur_candidates, *tmp);
360                 if (ignore_case) {
361                         if (cur_candidates->empty()) {
362                                 dprintf("  ... all reads done for OR group %u (%zu docids), intersected (none left, search is done)\n",
363                                         td->index, td->docids.size());
364                                 return true;
365                         } else {
366                                 dprintf("  ... all reads done for OR group %u (%zu docids), intersected (%zu left)\n",
367                                         td->index, td->docids.size(), cur_candidates->size());
368                         }
369                 }
370         }
371         return false;
372 }
373
374 void do_search_file(const vector<Needle> &needles, const char *filename)
375 {
376         int fd = open(filename, O_RDONLY);
377         if (fd == -1) {
378                 perror(filename);
379                 exit(1);
380         }
381
382         // Drop privileges.
383         if (setgid(getgid()) != 0) {
384                 perror("setgid");
385                 exit(EXIT_FAILURE);
386         }
387
388         steady_clock::time_point start __attribute__((unused)) = steady_clock::now();
389         if (access("/", R_OK | X_OK)) {
390                 // We can't find anything, no need to bother...
391                 return;
392         }
393
394         IOUringEngine engine(/*slop_bytes=*/16);  // 16 slop bytes as described in turbopfor.h.
395         Corpus corpus(fd, &engine);
396         dprintf("Corpus init done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
397
398         vector<TrigramDisjunction> trigram_groups;
399         if (patterns_are_regex) {
400                 // We could parse the regex to find trigrams that have to be there
401                 // (there are actually known algorithms to deal with disjunctions
402                 // and such, too), but for now, we just go brute force.
403                 // Using locate with regexes is pretty niche.
404         } else {
405                 for (const Needle &needle : needles) {
406                         parse_trigrams(needle.str, ignore_case, &trigram_groups);
407                 }
408         }
409
410         unique_sort(
411                 &trigram_groups,
412                 [](const TrigramDisjunction &a, const TrigramDisjunction &b) { return a.trigram_alternatives < b.trigram_alternatives; },
413                 [](const TrigramDisjunction &a, const TrigramDisjunction &b) { return a.trigram_alternatives == b.trigram_alternatives; });
414
415         // Give them names for debugging.
416         unsigned td_index = 0;
417         for (TrigramDisjunction &td : trigram_groups) {
418                 td.index = td_index++;
419         }
420
421         // Collect which trigrams we need to look up in the hash table.
422         unordered_map<uint32_t, vector<TrigramDisjunction *>> trigrams_to_lookup;
423         for (TrigramDisjunction &td : trigram_groups) {
424                 for (uint32_t trgm : td.trigram_alternatives) {
425                         trigrams_to_lookup[trgm].push_back(&td);
426                 }
427         }
428         if (trigrams_to_lookup.empty()) {
429                 // Too short for trigram matching. Apply brute force.
430                 // (We could have searched through all trigrams that matched
431                 // the pattern and done a union of them, but that's a lot of
432                 // work for fairly unclear gain.)
433                 uint64_t matched = scan_all_docids(needles, fd, corpus, &engine);
434                 if (only_count) {
435                         printf("%zu\n", matched);
436                 }
437                 return;
438         }
439
440         // Look them all up on disk.
441         for (auto &[trgm, trigram_groups] : trigrams_to_lookup) {
442                 corpus.find_trigram(trgm, [trgm{ trgm }, trigram_groups{ &trigram_groups }](const Trigram *trgmptr, size_t len) {
443                         if (trgmptr == nullptr) {
444                                 dprintf("trigram %s isn't found\n", print_trigram(trgm).c_str());
445                                 for (TrigramDisjunction *td : *trigram_groups) {
446                                         --td->remaining_trigrams_to_read;
447                                         if (td->remaining_trigrams_to_read == 0 && td->read_trigrams.empty()) {
448                                                 dprintf("zero matches in %s, so we are done\n", print_td(*td).c_str());
449                                                 if (only_count) {
450                                                         printf("0\n");
451                                                 }
452                                                 exit(0);
453                                         }
454                                 }
455                                 return;
456                         }
457                         for (TrigramDisjunction *td : *trigram_groups) {
458                                 --td->remaining_trigrams_to_read;
459                                 td->max_num_docids += trgmptr->num_docids;
460                                 td->read_trigrams.emplace_back(*trgmptr, len);
461                         }
462                 });
463         }
464         engine.finish();
465         dprintf("Hashtable lookups done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
466
467         for (TrigramDisjunction &td : trigram_groups) {
468                 // Reset for reads.
469                 td.remaining_trigrams_to_read = td.read_trigrams.size();
470
471                 if (ignore_case) {  // If case-sensitive, they'll all be pretty obvious single-entry groups.
472                         dprintf("OR group %u (max_num_docids=%u): %s\n", td.index, td.max_num_docids, print_td(td).c_str());
473                 }
474         }
475
476         // TODO: For case-insensitive (ie. more than one alternative in each),
477         // prioritize the ones with fewer seeks?
478         sort(trigram_groups.begin(), trigram_groups.end(),
479              [&](const TrigramDisjunction &a, const TrigramDisjunction &b) {
480                      return a.max_num_docids < b.max_num_docids;
481              });
482
483         unordered_map<uint32_t, vector<TrigramDisjunction *>> uses_trigram;
484         for (TrigramDisjunction &td : trigram_groups) {
485                 for (uint32_t trgm : td.trigram_alternatives) {
486                         uses_trigram[trgm].push_back(&td);
487                 }
488         }
489
490         unordered_set<uint32_t> trigrams_submitted_read;
491         vector<uint32_t> cur_candidates, tmp, decoded;
492         bool done = false;
493         for (TrigramDisjunction &td : trigram_groups) {
494                 if (!cur_candidates.empty() && td.max_num_docids > cur_candidates.size() * 100) {
495                         dprintf("%s has up to %u entries, ignoring the rest (will "
496                                 "weed out false positives later)\n",
497                                 print_td(td).c_str(), td.max_num_docids);
498                         break;
499                 }
500
501                 for (auto &[trgmptr, len] : td.read_trigrams) {
502                         if (trigrams_submitted_read.count(trgmptr.trgm) != 0) {
503                                 continue;
504                         }
505                         trigrams_submitted_read.insert(trgmptr.trgm);
506                         // Only stay a certain amount ahead, so that we don't spend I/O
507                         // on reading the latter, large posting lists. We are unlikely
508                         // to need them anyway, even if they should come in first.
509                         if (engine.get_waiting_reads() >= 5) {
510                                 engine.finish();
511                                 if (done)
512                                         break;
513                         }
514                         engine.submit_read(fd, len, trgmptr.offset, [trgmptr{ trgmptr }, len{ len }, &done, &cur_candidates, &tmp, &decoded, &uses_trigram](string_view s) {
515                                 if (done)
516                                         return;
517
518                                 uint32_t trgm __attribute__((unused)) = trgmptr.trgm;
519                                 const unsigned char *pldata = reinterpret_cast<const unsigned char *>(s.data());
520                                 size_t num = trgmptr.num_docids;
521                                 decoded.resize(num);
522                                 decode_pfor_delta1_128(pldata, num, /*interleaved=*/true, &decoded[0]);
523
524                                 assert(uses_trigram.count(trgm) != 0);
525                                 bool was_empty = cur_candidates.empty();
526                                 if (ignore_case) {
527                                         dprintf("trigram %s (%zu bytes) decoded to %zu entries\n", print_trigram(trgm).c_str(), len, num);
528                                 }
529
530                                 for (TrigramDisjunction *td : uses_trigram[trgm]) {
531                                         done |= new_posting_list_read(td, decoded, &cur_candidates, &tmp);
532                                         if (done)
533                                                 break;
534                                 }
535                                 if (!ignore_case) {
536                                         if (was_empty) {
537                                                 dprintf("trigram %s (%zu bytes) decoded to %zu entries\n", print_trigram(trgm).c_str(), len, num);
538                                         } else if (cur_candidates.empty()) {
539                                                 dprintf("trigram %s (%zu bytes) decoded to %zu entries (none left, search is done)\n", print_trigram(trgm).c_str(), len, num);
540                                         } else {
541                                                 dprintf("trigram %s (%zu bytes) decoded to %zu entries (%zu left)\n", print_trigram(trgm).c_str(), len, num, cur_candidates.size());
542                                         }
543                                 }
544                         });
545                 }
546         }
547         engine.finish();
548         if (done) {
549                 return;
550         }
551         dprintf("Intersection done after %.1f ms. Doing final verification and printing:\n",
552                 1e3 * duration<float>(steady_clock::now() - start).count());
553
554         uint64_t matched = scan_docids(needles, cur_candidates, corpus, &engine);
555         dprintf("Done in %.1f ms, found %zu matches.\n",
556                 1e3 * duration<float>(steady_clock::now() - start).count(), matched);
557
558         if (only_count) {
559                 printf("%zu\n", matched);
560         }
561 }
562
563 string unescape_glob_to_plain_string(const string &needle)
564 {
565         string unescaped;
566         for (size_t i = 0; i < needle.size(); i += read_unigram(needle, i).second) {
567                 uint32_t ch = read_unigram(needle, i).first;
568                 assert(ch != WILDCARD_UNIGRAM);
569                 if (ch == PREMATURE_END_UNIGRAM) {
570                         fprintf(stderr, "Pattern '%s' ended prematurely\n", needle.c_str());
571                         exit(1);
572                 }
573                 unescaped.push_back(ch);
574         }
575         return unescaped;
576 }
577
578 regex_t compile_regex(const string &needle)
579 {
580         regex_t re;
581         int flags = REG_NOSUB;
582         if (ignore_case) {
583                 flags |= REG_ICASE;
584         }
585         if (use_extended_regex) {
586                 flags |= REG_EXTENDED;
587         }
588         int err = regcomp(&re, needle.c_str(), flags);
589         if (err != 0) {
590                 char errbuf[256];
591                 regerror(err, &re, errbuf, sizeof(errbuf));
592                 fprintf(stderr, "Error when compiling regex '%s': %s\n", needle.c_str(), errbuf);
593                 exit(1);
594         }
595         return re;
596 }
597
598 void usage()
599 {
600         printf(
601                 "Usage: plocate [OPTION]... PATTERN...\n"
602                 "\n"
603                 "  -c, --count            print number of matches instead of the matches\n"
604                 "  -d, --database DBPATH  search for files in DBPATH\n"
605                 "                         (default is " DEFAULT_DBPATH ")\n"
606                 "  -i, --ignore-case      search case-insensitively\n"
607                 "  -l, --limit LIMIT      stop after LIMIT matches\n"
608                 "  -0, --null             delimit matches by NUL instead of newline\n"
609                 "  -r, --regexp           interpret patterns as basic regexps (slow)\n"
610                 "      --regex            interpret patterns as extended regexps (slow)\n"
611                 "      --help             print this help\n"
612                 "      --version          print version information\n");
613 }
614
615 void version()
616 {
617         printf("plocate %s\n", PLOCATE_VERSION);
618         printf("Copyright 2020 Steinar H. Gunderson\n");
619         printf("License GPLv2+: GNU GPL version 2 or later <https://gnu.org/licenses/gpl.html>.\n");
620         printf("This is free software: you are free to change and redistribute it.\n");
621         printf("There is NO WARRANTY, to the extent permitted by law.\n");
622         exit(0);
623 }
624
625 int main(int argc, char **argv)
626 {
627         constexpr int EXTENDED_REGEX = 1000;
628         static const struct option long_options[] = {
629                 { "help", no_argument, 0, 'h' },
630                 { "count", no_argument, 0, 'c' },
631                 { "database", required_argument, 0, 'd' },
632                 { "ignore-case", no_argument, 0, 'i' },
633                 { "limit", required_argument, 0, 'l' },
634                 { "null", no_argument, 0, '0' },
635                 { "version", no_argument, 0, 'V' },
636                 { "regexp", no_argument, 0, 'r' },
637                 { "regex", no_argument, 0, EXTENDED_REGEX },
638                 { "debug", no_argument, 0, 'D' },  // Not documented.
639                 { 0, 0, 0, 0 }
640         };
641
642         setlocale(LC_ALL, "");
643         for (;;) {
644                 int option_index = 0;
645                 int c = getopt_long(argc, argv, "cd:hil:n:0VD", long_options, &option_index);
646                 if (c == -1) {
647                         break;
648                 }
649                 switch (c) {
650                 case 'c':
651                         only_count = true;
652                         break;
653                 case 'd':
654                         dbpath = strdup(optarg);
655                         break;
656                 case 'h':
657                         usage();
658                         exit(0);
659                 case 'i':
660                         ignore_case = true;
661                         break;
662                 case 'l':
663                 case 'n':
664                         limit_matches = atoll(optarg);
665                         if (limit_matches <= 0) {
666                                 fprintf(stderr, "Error: limit must be a strictly positive number.\n");
667                                 exit(1);
668                         }
669                         break;
670                 case '0':
671                         print_nul = true;
672                         break;
673                 case 'r':
674                         patterns_are_regex = true;
675                         break;
676                 case EXTENDED_REGEX:
677                         patterns_are_regex = true;
678                         use_extended_regex = true;
679                         break;
680                 case 'D':
681                         use_debug = true;
682                         break;
683                 case 'V':
684                         version();
685                         break;
686                 default:
687                         exit(1);
688                 }
689         }
690
691         if (use_debug) {
692                 // Debug information would leak information about which files exist,
693                 // so drop setgid before we open the file; one would either need to run
694                 // as root, or use a locally-built file.
695                 if (setgid(getgid()) != 0) {
696                         perror("setgid");
697                         exit(EXIT_FAILURE);
698                 }
699         }
700
701         vector<Needle> needles;
702         for (int i = optind; i < argc; ++i) {
703                 Needle needle;
704                 needle.str = argv[i];
705
706                 // See if there are any wildcard characters, which indicates we should treat it
707                 // as an (anchored) glob.
708                 bool any_wildcard = false;
709                 for (size_t i = 0; i < needle.str.size(); i += read_unigram(needle.str, i).second) {
710                         if (read_unigram(needle.str, i).first == WILDCARD_UNIGRAM) {
711                                 any_wildcard = true;
712                                 break;
713                         }
714                 }
715
716                 if (patterns_are_regex) {
717                         needle.type = Needle::REGEX;
718                         needle.re = compile_regex(needle.str);
719                 } else if (any_wildcard) {
720                         needle.type = Needle::GLOB;
721                 } else if (ignore_case) {
722                         // strcasestr() doesn't handle locales correctly (even though LSB
723                         // claims it should), but somehow, fnmatch() does, and it's about
724                         // the same speed as using a regex.
725                         needle.type = Needle::GLOB;
726                         needle.str = "*" + needle.str + "*";
727                 } else {
728                         needle.type = Needle::STRSTR;
729                         needle.str = unescape_glob_to_plain_string(needle.str);
730                 }
731                 needles.push_back(move(needle));
732         }
733         if (needles.empty()) {
734                 fprintf(stderr, "plocate: no pattern to search for specified\n");
735                 exit(0);
736         }
737         do_search_file(needles, dbpath);
738 }