1 /* $Id: apropos_db.c,v 1.31 2012/03/24 01:46:25 kristaps Exp $ */
3 * Copyright (c) 2011, 2012 Kristaps Dzonsons <kristaps@bsd.lv>
4 * Copyright (c) 2011 Ingo Schwarze <schwarze@openbsd.org>
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
31 #if defined(__linux__)
34 #elif defined(__APPLE__)
35 # include <libkern/OSByteOrder.h>
42 #include "apropos_db.h"
52 free((_x)->matches); \
53 } while (/*CONSTCOND*/0)
56 int regex; /* is regex? */
57 int index; /* index in match array */
58 uint64_t mask; /* type-mask */
59 int and; /* is rhs of logical AND? */
60 char *v; /* search value */
61 regex_t re; /* compiled re, if regex */
62 struct expr *next; /* next in sequence */
72 struct res *node; /* record array for dir tree */
73 int len; /* length of record array */
76 static const struct type types[] = {
116 { UINT64_MAX, "any" },
120 static DB *btree_open(void);
121 static int btree_read(const DBT *, const DBT *,
122 const struct mchars *,
123 uint64_t *, recno_t *, char **);
124 static int expreval(const struct expr *, int *);
125 static void exprexec(const struct expr *,
126 const char *, uint64_t, struct res *);
127 static int exprmark(const struct expr *,
128 const char *, uint64_t, int *);
129 static struct expr *exprexpr(int, char *[], int *, int *, size_t *);
130 static struct expr *exprterm(char *, int);
131 static DB *index_open(void);
132 static int index_read(const DBT *, const DBT *, int,
133 const struct mchars *, struct res *);
134 static void norm_string(const char *,
135 const struct mchars *, char **);
136 static size_t norm_utf8(unsigned int, char[7]);
137 static int single_search(struct rectree *, const struct opts *,
138 const struct expr *, size_t terms,
139 struct mchars *, int);
142 * Open the keyword mandoc-db database.
150 memset(&info, 0, sizeof(BTREEINFO));
154 db = dbopen(MANDOC_DB, O_RDONLY, 0, DB_BTREE, &info);
162 * Read a keyword from the database and normalise it.
163 * Return 0 if the database is insane, else 1.
166 btree_read(const DBT *k, const DBT *v, const struct mchars *mc,
167 uint64_t *mask, recno_t *rec, char **buf)
171 /* Are our sizes sane? */
172 if (k->size < 2 || sizeof(vbuf) != v->size)
175 /* Is our string nil-terminated? */
176 if ('\0' != ((const char *)k->data)[(int)k->size - 1])
179 norm_string((const char *)k->data, mc, buf);
180 memcpy(vbuf, v->data, v->size);
181 *mask = betoh64(vbuf[0]);
182 *rec = betoh64(vbuf[1]);
187 * Take a Unicode codepoint and produce its UTF-8 encoding.
188 * This isn't the best way to do this, but it works.
189 * The magic numbers are from the UTF-8 packaging.
190 * They're not as scary as they seem: read the UTF-8 spec for details.
193 norm_utf8(unsigned int cp, char out[7])
199 if (cp <= 0x0000007F) {
202 } else if (cp <= 0x000007FF) {
204 out[0] = (cp >> 6 & 31) | 192;
205 out[1] = (cp & 63) | 128;
206 } else if (cp <= 0x0000FFFF) {
208 out[0] = (cp >> 12 & 15) | 224;
209 out[1] = (cp >> 6 & 63) | 128;
210 out[2] = (cp & 63) | 128;
211 } else if (cp <= 0x001FFFFF) {
213 out[0] = (cp >> 18 & 7) | 240;
214 out[1] = (cp >> 12 & 63) | 128;
215 out[2] = (cp >> 6 & 63) | 128;
216 out[3] = (cp & 63) | 128;
217 } else if (cp <= 0x03FFFFFF) {
219 out[0] = (cp >> 24 & 3) | 248;
220 out[1] = (cp >> 18 & 63) | 128;
221 out[2] = (cp >> 12 & 63) | 128;
222 out[3] = (cp >> 6 & 63) | 128;
223 out[4] = (cp & 63) | 128;
224 } else if (cp <= 0x7FFFFFFF) {
226 out[0] = (cp >> 30 & 1) | 252;
227 out[1] = (cp >> 24 & 63) | 128;
228 out[2] = (cp >> 18 & 63) | 128;
229 out[3] = (cp >> 12 & 63) | 128;
230 out[4] = (cp >> 6 & 63) | 128;
231 out[5] = (cp & 63) | 128;
240 * Normalise strings from the index and database.
241 * These strings are escaped as defined by mandoc_char(7) along with
242 * other goop in mandoc.h (e.g., soft hyphens).
243 * This function normalises these into a nice UTF-8 string.
244 * Returns 0 if the database is fucked.
247 norm_string(const char *val, const struct mchars *mc, char **buf)
251 const char *seq, *cpp;
254 static const char res[] = { '\\', '\t',
255 ASCII_NBRSP, ASCII_HYPH, '\0' };
257 /* Pre-allocate by the length of the input */
259 bsz = strlen(val) + 1;
260 *buf = mandoc_realloc(*buf, bsz);
263 while ('\0' != *val) {
265 * Halt on the first escape sequence.
266 * This also halts on the end of string, in which case
267 * we just copy, fallthrough, and exit the loop.
269 if ((sz = strcspn(val, res)) > 0) {
270 memcpy(&(*buf)[pos], val, sz);
275 if (ASCII_HYPH == *val) {
279 } else if ('\t' == *val || ASCII_NBRSP == *val) {
283 } else if ('\\' != *val)
286 /* Read past the slash. */
292 * Parse the escape sequence and see if it's a
293 * predefined character or special character.
296 esc = mandoc_escape(&val, &seq, &len);
297 if (ESCAPE_ERROR == esc)
301 * XXX - this just does UTF-8, but we need to know
302 * beforehand whether we should do text substitution.
306 case (ESCAPE_SPECIAL):
307 if (0 != (u = mchars_spec2cp(mc, seq, len)))
315 * If we have a Unicode codepoint, try to convert that
316 * to a UTF-8 byte string.
320 if (0 == (sz = norm_utf8(u, utfbuf)))
323 /* Copy the rendered glyph into the stream. */
328 *buf = mandoc_realloc(*buf, bsz);
330 memcpy(&(*buf)[pos], cpp, sz);
338 * Open the filename-index mandoc-db database.
339 * Returns NULL if opening failed.
346 db = dbopen(MANDOC_IDX, O_RDONLY, 0, DB_RECNO, NULL);
354 * Safely unpack from an index file record into the structure.
355 * Returns 1 if an entry was unpacked, 0 if the database is insane.
358 index_read(const DBT *key, const DBT *val, int index,
359 const struct mchars *mc, struct res *rec)
365 #define INDEX_BREAD(_dst) \
367 if (NULL == (np = memchr(cp, '\0', left))) \
369 norm_string(cp, mc, &(_dst)); \
370 left -= (np - cp) + 1; \
372 } while (/* CONSTCOND */ 0)
374 if (0 == (left = val->size))
378 assert(sizeof(recno_t) == key->size);
379 memcpy(&rec->rec, key->data, key->size);
382 if ('d' == (type = *cp++))
383 rec->type = RESTYPE_MDOC;
384 else if ('a' == type)
385 rec->type = RESTYPE_MAN;
386 else if ('c' == type)
387 rec->type = RESTYPE_CAT;
392 INDEX_BREAD(rec->file);
393 INDEX_BREAD(rec->cat);
394 INDEX_BREAD(rec->title);
395 INDEX_BREAD(rec->arch);
396 INDEX_BREAD(rec->desc);
401 * Search mandocdb databases in paths for expression "expr".
402 * Filter out by "opts".
403 * Call "res" with the results, which may be zero.
404 * Return 0 if there was a database error, else return 1.
407 apropos_search(int pathsz, char **paths, const struct opts *opts,
408 const struct expr *expr, size_t terms, void *arg,
409 size_t *sz, struct res **resp,
410 void (*res)(struct res *, size_t, void *))
416 memset(&tree, 0, sizeof(struct rectree));
424 * Main loop. Change into the directory containing manpage
425 * databases. Run our expession over each database in the set.
428 for (i = 0; i < pathsz; i++) {
431 if (single_search(&tree, opts, expr, terms, mc, i))
434 resfree(tree.node, tree.len);
439 (*res)(tree.node, tree.len, arg);
447 single_search(struct rectree *tree, const struct opts *opts,
448 const struct expr *expr, size_t terms,
449 struct mchars *mc, int vol)
467 memset(&r, 0, sizeof(struct res));
469 if (NULL == (btree = btree_open()))
472 if (NULL == (idx = index_open())) {
473 (*btree->close)(btree);
477 while (0 == (ch = (*btree->seq)(btree, &key, &val, R_NEXT))) {
478 if ( ! btree_read(&key, &val, mc, &mask, &rec, &buf))
482 * See if this keyword record matches any of the
483 * expressions we have stored.
485 if ( ! exprmark(expr, buf, mask, NULL))
489 * O(log n) scan for prior records. Since a record
490 * number is unbounded, this has decent performance over
491 * a complex hash function.
494 for (leaf = root; leaf >= 0; )
495 if (rec > rs[leaf].rec &&
498 else if (rec < rs[leaf].rec &&
505 * If we find a record, see if it has already evaluated
506 * to true. If it has, great, just keep going. If not,
507 * try to evaluate it now and continue anyway.
510 if (leaf >= 0 && rs[leaf].rec == rec) {
511 if (0 == rs[leaf].matched)
512 exprexec(expr, buf, mask, &rs[leaf]);
517 * We have a new file to examine.
518 * Extract the manpage's metadata from the index
519 * database, then begin partial evaluation.
523 key.size = sizeof(recno_t);
525 if (0 != (*idx->get)(idx, &key, &val, 0))
529 if ( ! index_read(&key, &val, vol, mc, &r))
532 /* XXX: this should be elsewhere, I guess? */
534 if (opts->cat && strcasecmp(opts->cat, r.cat))
537 if (opts->arch && *r.arch)
538 if (strcasecmp(opts->arch, r.arch))
541 tree->node = rs = mandoc_realloc
542 (rs, (tree->len + 1) * sizeof(struct res));
544 memcpy(&rs[tree->len], &r, sizeof(struct res));
545 memset(&r, 0, sizeof(struct res));
546 rs[tree->len].matches =
547 mandoc_calloc(terms, sizeof(int));
549 exprexec(expr, buf, mask, &rs[tree->len]);
551 /* Append to our tree. */
554 if (rec > rs[leaf].rec)
555 rs[leaf].rhs = tree->len;
557 rs[leaf].lhs = tree->len;
564 (*btree->close)(btree);
573 resfree(struct res *rec, size_t sz)
577 for (i = 0; i < sz; i++)
583 * Compile a list of straight-up terms.
584 * The arguments are re-written into ~[[:<:]]term[[:>:]], or "term"
585 * surrounded by word boundaries, then pumped through exprterm().
586 * Terms are case-insensitive.
587 * This emulates whatis(1) behaviour.
590 termcomp(int argc, char *argv[], size_t *tt)
594 struct expr *e, *next;
601 for (pos = argc - 1; pos >= 0; pos--) {
602 sz = strlen(argv[pos]) + 18;
603 buf = mandoc_realloc(buf, sz);
604 strlcpy(buf, "Nm~[[:<:]]", sz);
605 strlcat(buf, argv[pos], sz);
606 strlcat(buf, "[[:>:]]", sz);
607 if (NULL == (next = exprterm(buf, 0))) {
622 * Compile a sequence of logical expressions.
623 * See apropos.1 for a grammar of this sequence.
626 exprcomp(int argc, char *argv[], size_t *tt)
634 e = exprexpr(argc, argv, &pos, &lvl, tt);
636 if (0 == lvl && pos >= argc)
644 * Compile an array of tokens into an expression.
645 * An informal expression grammar is defined in apropos(1).
646 * Return NULL if we fail doing so. All memory will be cleaned up.
647 * Return the root of the expression sequence if alright.
650 exprexpr(int argc, char *argv[], int *pos, int *lvl, size_t *tt)
652 struct expr *e, *first, *next;
657 for ( ; *pos < argc; (*pos)++) {
661 * Close out a subexpression.
664 if (NULL != e && 0 == strcmp(")", argv[*pos])) {
671 * Small note: if we're just starting, don't let "-a"
672 * and "-o" be considered logical operators: they're
673 * just tokens unless pairwise joining, in which case we
674 * record their existence (or assume "OR").
678 if (NULL != e && 0 == strcmp("-a", argv[*pos]))
680 else if (NULL != e && 0 == strcmp("-o", argv[*pos]))
683 if (log > 0 && ++(*pos) >= argc)
687 * Now we parse the term part. This can begin with
688 * "-i", in which case the expression is case
692 if (0 == strcmp("(", argv[*pos])) {
695 next = mandoc_calloc(1, sizeof(struct expr));
696 next->subexpr = exprexpr(argc, argv, pos, lvl, tt);
697 if (NULL == next->subexpr) {
701 } else if (0 == strcmp("-i", argv[*pos])) {
702 if (++(*pos) >= argc)
704 next = exprterm(argv[*pos], 0);
706 next = exprterm(argv[*pos], 1);
711 next->and = log == 1;
712 next->index = (int)(*tt)++;
714 /* Append to our chain of expressions. */
732 * Parse a terminal expression with the grammar as defined in
734 * Return NULL if we fail the parse.
737 exprterm(char *buf, int cs)
744 memset(&e, 0, sizeof(struct expr));
746 /* Choose regex or substring match. */
748 if (NULL == (e.v = strpbrk(buf, "=~"))) {
752 e.regex = '~' == *e.v;
756 /* Determine the record types to search for. */
760 while (NULL != (key = strsep(&buf, ","))) {
762 while (types[i].mask &&
763 strcmp(types[i].name, key))
765 e.mask |= types[i].mask;
769 e.mask = TYPE_Nm | TYPE_Nd;
772 i = REG_EXTENDED | REG_NOSUB | (cs ? 0 : REG_ICASE);
773 if (regcomp(&e.re, e.v, i))
777 e.v = mandoc_strdup(e.v);
779 p = mandoc_calloc(1, sizeof(struct expr));
780 memcpy(p, &e, sizeof(struct expr));
785 exprfree(struct expr *p)
791 exprfree(p->subexpr);
802 exprmark(const struct expr *p, const char *cp,
803 uint64_t mask, int *ms)
806 for ( ; p; p = p->next) {
808 if (exprmark(p->subexpr, cp, mask, ms))
811 } else if ( ! (mask & p->mask))
815 if (regexec(&p->re, cp, 0, NULL, 0))
817 } else if (NULL == strcasestr(cp, p->v))
830 expreval(const struct expr *p, int *ms)
835 * AND has precedence over OR. Analysis is left-right, though
836 * it doesn't matter because there are no side-effects.
837 * Thus, step through pairwise ANDs and accumulate their Boolean
838 * evaluation. If we encounter a single true AND collection or
839 * standalone term, the whole expression is true (by definition
843 for (match = 0; p && ! match; p = p->next) {
844 /* Evaluate a subexpression, if applicable. */
845 if (p->subexpr && ! ms[p->index])
846 ms[p->index] = expreval(p->subexpr, ms);
848 match = ms[p->index];
849 for ( ; p->next && p->next->and; p = p->next) {
850 /* Evaluate a subexpression, if applicable. */
851 if (p->next->subexpr && ! ms[p->next->index])
853 expreval(p->next->subexpr, ms);
854 match = match && ms[p->next->index];
862 * First, update the array of terms for which this expression evaluates
864 * Second, logically evaluate all terms over the updated array of truth
866 * If this evaluates to true, mark the expression as satisfied.
869 exprexec(const struct expr *e, const char *cp,
870 uint64_t mask, struct res *r)
873 assert(0 == r->matched);
874 exprmark(e, cp, mask, r->matches);
875 r->matched = expreval(e, r->matches);