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