1 /* $Id: mansearch.c,v 1.65 2016/07/09 15:24:19 schwarze Exp $ */
3 * Copyright (c) 2012 Kristaps Dzonsons <kristaps@bsd.lv>
4 * Copyright (c) 2013, 2014, 2015 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 AUTHORS DISCLAIM ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS 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.
21 #include <sys/types.h>
40 #ifndef SQLITE_DETERMINISTIC
41 #define SQLITE_DETERMINISTIC 0
45 #include "mandoc_aux.h"
46 #include "mandoc_ohash.h"
48 #include "mansearch.h"
50 extern int mansearch_keymax;
51 extern const char *const mansearch_keynames[];
53 #define SQL_BIND_TEXT(_db, _s, _i, _v) \
54 do { if (SQLITE_OK != sqlite3_bind_text \
55 ((_s), (_i)++, (_v), -1, SQLITE_STATIC)) \
56 errx((int)MANDOCLEVEL_SYSERR, "%s", sqlite3_errmsg((_db))); \
58 #define SQL_BIND_INT64(_db, _s, _i, _v) \
59 do { if (SQLITE_OK != sqlite3_bind_int64 \
60 ((_s), (_i)++, (_v))) \
61 errx((int)MANDOCLEVEL_SYSERR, "%s", sqlite3_errmsg((_db))); \
63 #define SQL_BIND_BLOB(_db, _s, _i, _v) \
64 do { if (SQLITE_OK != sqlite3_bind_blob \
65 ((_s), (_i)++, (&_v), sizeof(_v), SQLITE_STATIC)) \
66 errx((int)MANDOCLEVEL_SYSERR, "%s", sqlite3_errmsg((_db))); \
70 regex_t regexp; /* compiled regexp, if applicable */
71 const char *substr; /* to search for, if applicable */
72 struct expr *next; /* next in sequence */
73 uint64_t bits; /* type-mask */
74 int equal; /* equality, not subsring match */
75 int open; /* opening parentheses before */
76 int and; /* logical AND before */
77 int close; /* closing parentheses after */
81 uint64_t pageid; /* identifier in database */
82 uint64_t bits; /* name type mask */
83 char *desc; /* manual page description */
84 int form; /* bit field: formatted, zipped? */
87 static void buildnames(const struct mansearch *,
88 struct manpage *, sqlite3 *,
89 sqlite3_stmt *, uint64_t,
90 const char *, int form);
91 static char *buildoutput(sqlite3 *, sqlite3_stmt *,
93 static struct expr *exprcomp(const struct mansearch *,
95 static void exprfree(struct expr *);
96 static struct expr *exprterm(const struct mansearch *, char *, int);
97 static int manpage_compare(const void *, const void *);
98 static void sql_append(char **sql, size_t *sz,
99 const char *newstr, int count);
100 static void sql_match(sqlite3_context *context,
101 int argc, sqlite3_value **argv);
102 static void sql_regexp(sqlite3_context *context,
103 int argc, sqlite3_value **argv);
104 static char *sql_statement(const struct expr *);
108 mansearch_setup(int start)
110 static void *pagecache;
113 #define PC_PAGESIZE 1280
114 #define PC_NUMPAGES 256
117 if (NULL != pagecache) {
118 warnx("pagecache already enabled");
119 return (int)MANDOCLEVEL_BADARG;
122 pagecache = mmap(NULL, PC_PAGESIZE * PC_NUMPAGES,
123 PROT_READ | PROT_WRITE,
124 MAP_SHARED | MAP_ANON, -1, 0);
126 if (MAP_FAILED == pagecache) {
129 return (int)MANDOCLEVEL_SYSERR;
132 c = sqlite3_config(SQLITE_CONFIG_PAGECACHE,
133 pagecache, PC_PAGESIZE, PC_NUMPAGES);
136 return (int)MANDOCLEVEL_OK;
138 warnx("pagecache: %s", sqlite3_errstr(c));
140 } else if (NULL == pagecache) {
141 warnx("pagecache missing");
142 return (int)MANDOCLEVEL_BADARG;
145 if (-1 == munmap(pagecache, PC_PAGESIZE * PC_NUMPAGES)) {
148 return (int)MANDOCLEVEL_SYSERR;
152 return (int)MANDOCLEVEL_OK;
156 mansearch(const struct mansearch *search,
157 const struct manpaths *paths,
158 int argc, char *argv[],
159 struct manpage **res, size_t *sz)
162 uint64_t outbit, iterbit;
165 struct manpage *mpage;
168 sqlite3_stmt *s, *s2;
172 size_t i, j, cur, maxres;
173 int c, chdir_status, getcwd_status, indexbit;
175 if (argc == 0 || (e = exprcomp(search, argc, argv)) == NULL) {
183 if (NULL != search->outkey) {
185 for (indexbit = 0, iterbit = 1;
186 indexbit < mansearch_keymax;
187 indexbit++, iterbit <<= 1) {
188 if (0 == strcasecmp(search->outkey,
189 mansearch_keynames[indexbit])) {
198 * Remember the original working directory, if possible.
199 * This will be needed if the second or a later directory
200 * is given as a relative path.
201 * Do not error out if the current directory is not
202 * searchable: Maybe it won't be needed after all.
205 if (getcwd(buf, PATH_MAX) == NULL) {
207 (void)strlcpy(buf, strerror(errno), sizeof(buf));
211 sql = sql_statement(e);
214 * Loop over the directories (containing databases) for us to
216 * Don't let missing/bad databases/directories phase us.
217 * In each, try to open the resident database and, if it opens,
218 * scan it for our match expression.
222 for (i = 0; i < paths->sz; i++) {
223 if (chdir_status && paths->paths[i][0] != '/') {
224 if ( ! getcwd_status) {
225 warnx("%s: getcwd: %s", paths->paths[i], buf);
227 } else if (chdir(buf) == -1) {
232 if (chdir(paths->paths[i]) == -1) {
233 warn("%s", paths->paths[i]);
238 c = sqlite3_open_v2(MANDOC_DB, &db,
239 SQLITE_OPEN_READONLY, NULL);
241 if (SQLITE_OK != c) {
242 warn("%s/%s", paths->paths[i], MANDOC_DB);
248 * Define the SQL functions for substring
249 * and regular expression matching.
252 c = sqlite3_create_function(db, "match", 2,
253 SQLITE_UTF8 | SQLITE_DETERMINISTIC,
254 NULL, sql_match, NULL, NULL);
255 assert(SQLITE_OK == c);
256 c = sqlite3_create_function(db, "regexp", 2,
257 SQLITE_UTF8 | SQLITE_DETERMINISTIC,
258 NULL, sql_regexp, NULL, NULL);
259 assert(SQLITE_OK == c);
262 c = sqlite3_prepare_v2(db, sql, -1, &s, NULL);
264 errx((int)MANDOCLEVEL_SYSERR,
265 "%s", sqlite3_errmsg(db));
267 for (ep = e; NULL != ep; ep = ep->next) {
268 if (NULL == ep->substr) {
269 SQL_BIND_BLOB(db, s, j, ep->regexp);
271 SQL_BIND_TEXT(db, s, j, ep->substr);
272 if (0 == ((TYPE_Nd | TYPE_Nm) & ep->bits))
273 SQL_BIND_INT64(db, s, j, ep->bits);
276 mandoc_ohash_init(&htab, 4, offsetof(struct match, pageid));
279 * Hash each entry on its [unique] document identifier.
280 * This is a uint64_t.
281 * Instead of using a hash function, simply convert the
282 * uint64_t to a uint32_t, the hash value's type.
283 * This gives good performance and preserves the
284 * distribution of buckets in the table.
286 while (SQLITE_ROW == (c = sqlite3_step(s))) {
287 pageid = sqlite3_column_int64(s, 2);
288 idx = ohash_lookup_memory(&htab,
289 (char *)&pageid, sizeof(uint64_t),
292 if (NULL != ohash_find(&htab, idx))
295 mp = mandoc_calloc(1, sizeof(struct match));
297 mp->form = sqlite3_column_int(s, 1);
298 mp->bits = sqlite3_column_int64(s, 3);
299 if (TYPE_Nd == outbit)
300 mp->desc = mandoc_strdup((const char *)
301 sqlite3_column_text(s, 0));
302 ohash_insert(&htab, idx, mp);
305 if (SQLITE_DONE != c)
306 warnx("%s", sqlite3_errmsg(db));
310 c = sqlite3_prepare_v2(db,
311 "SELECT sec, arch, name, pageid FROM mlinks "
312 "WHERE pageid=? ORDER BY sec, arch, name",
315 errx((int)MANDOCLEVEL_SYSERR,
316 "%s", sqlite3_errmsg(db));
318 c = sqlite3_prepare_v2(db,
319 "SELECT bits, key, pageid FROM keys "
320 "WHERE pageid=? AND bits & ?",
323 errx((int)MANDOCLEVEL_SYSERR,
324 "%s", sqlite3_errmsg(db));
326 for (mp = ohash_first(&htab, &idx);
328 mp = ohash_next(&htab, &idx)) {
329 if (cur + 1 > maxres) {
331 *res = mandoc_reallocarray(*res,
332 maxres, sizeof(struct manpage));
336 mpage->bits = mp->bits;
338 mpage->form = mp->form;
339 buildnames(search, mpage, db, s, mp->pageid,
340 paths->paths[i], mp->form);
341 if (mpage->names != NULL) {
342 mpage->output = TYPE_Nd & outbit ?
344 buildoutput(db, s2, mp->pageid, outbit) :
352 sqlite3_finalize(s2);
357 * In man(1) mode, prefer matches in earlier trees
358 * over matches in later trees.
361 if (cur && search->firstmatch)
364 qsort(*res, cur, sizeof(struct manpage), manpage_compare);
365 if (chdir_status && getcwd_status && chdir(buf) == -1)
374 mansearch_free(struct manpage *res, size_t sz)
378 for (i = 0; i < sz; i++) {
387 manpage_compare(const void *vp1, const void *vp2)
389 const struct manpage *mp1, *mp2;
394 return (diff = mp2->bits - mp1->bits) ? diff :
395 (diff = mp1->sec - mp2->sec) ? diff :
396 strcasecmp(mp1->names, mp2->names);
400 buildnames(const struct mansearch *search, struct manpage *mpage,
401 sqlite3 *db, sqlite3_stmt *s,
402 uint64_t pageid, const char *path, int form)
405 char *firstname, *newnames, *prevsec, *prevarch;
406 const char *oldnames, *sep1, *name, *sec, *sep2, *arch, *fsec;
412 firstname = prevsec = prevarch = NULL;
414 SQL_BIND_INT64(db, s, i, pageid);
415 while (SQLITE_ROW == (c = sqlite3_step(s))) {
417 /* Decide whether we already have some names. */
419 if (NULL == mpage->names) {
423 oldnames = mpage->names;
427 /* Fetch the next name, rejecting sec/arch mismatches. */
429 sec = (const char *)sqlite3_column_text(s, 0);
430 if (search->sec != NULL && strcasecmp(sec, search->sec))
432 arch = (const char *)sqlite3_column_text(s, 1);
433 if (search->arch != NULL && *arch != '\0' &&
434 strcasecmp(arch, search->arch))
436 name = (const char *)sqlite3_column_text(s, 2);
438 /* Remember the first section found. */
440 if (9 < mpage->sec && '1' <= *sec && '9' >= *sec)
441 mpage->sec = (*sec - '1') + 1;
443 /* If the section changed, append the old one. */
445 if (NULL != prevsec &&
446 (strcmp(sec, prevsec) ||
447 strcmp(arch, prevarch))) {
448 sep2 = '\0' == *prevarch ? "" : "/";
449 mandoc_asprintf(&newnames, "%s(%s%s%s)",
450 oldnames, prevsec, sep2, prevarch);
452 oldnames = mpage->names = newnames;
455 prevsec = prevarch = NULL;
458 /* Save the new section, to append it later. */
460 if (NULL == prevsec) {
461 prevsec = mandoc_strdup(sec);
462 prevarch = mandoc_strdup(arch);
465 /* Append the new name. */
467 mandoc_asprintf(&newnames, "%s%s%s",
468 oldnames, sep1, name);
470 mpage->names = newnames;
472 /* Also save the first file name encountered. */
474 if (mpage->file != NULL)
477 if (form & FORM_SRC) {
484 sep2 = *arch == '\0' ? "" : "/";
485 mandoc_asprintf(&mpage->file, "%s/%s%s%s%s/%s.%s",
486 path, sep1, sec, sep2, arch, name, fsec);
487 if (access(mpage->file, R_OK) != -1)
490 /* Handle unusual file name extensions. */
492 if (firstname == NULL)
493 firstname = mpage->file;
496 mandoc_asprintf(&mpage->file, "%s/%s%s%s%s/%s.*",
497 path, sep1, sec, sep2, arch, name);
498 globres = glob(mpage->file, 0, NULL, &globinfo);
500 mpage->file = globres ? NULL :
501 mandoc_strdup(*globinfo.gl_pathv);
504 if (c != SQLITE_DONE)
505 warnx("%s", sqlite3_errmsg(db));
508 /* If none of the files is usable, use the first name. */
510 if (mpage->file == NULL)
511 mpage->file = firstname;
512 else if (mpage->file != firstname)
515 /* Append one final section to the names. */
517 if (prevsec != NULL) {
518 sep2 = *prevarch == '\0' ? "" : "/";
519 mandoc_asprintf(&newnames, "%s(%s%s%s)",
520 mpage->names, prevsec, sep2, prevarch);
522 mpage->names = newnames;
529 buildoutput(sqlite3 *db, sqlite3_stmt *s, uint64_t pageid, uint64_t outbit)
531 char *output, *newoutput;
532 const char *oldoutput, *sep1, *data;
538 SQL_BIND_INT64(db, s, i, pageid);
539 SQL_BIND_INT64(db, s, i, outbit);
540 while (SQLITE_ROW == (c = sqlite3_step(s))) {
541 if (NULL == output) {
548 data = (const char *)sqlite3_column_text(s, 1);
549 mandoc_asprintf(&newoutput, "%s%s%s",
550 oldoutput, sep1, data);
554 if (SQLITE_DONE != c)
555 warnx("%s", sqlite3_errmsg(db));
561 * Implement substring match as an application-defined SQL function.
562 * Using the SQL LIKE or GLOB operators instead would be a bad idea
563 * because that would require escaping metacharacters in the string
564 * being searched for.
567 sql_match(sqlite3_context *context, int argc, sqlite3_value **argv)
571 sqlite3_result_int(context, NULL != strcasestr(
572 (const char *)sqlite3_value_text(argv[1]),
573 (const char *)sqlite3_value_text(argv[0])));
577 * Implement regular expression match
578 * as an application-defined SQL function.
581 sql_regexp(sqlite3_context *context, int argc, sqlite3_value **argv)
585 sqlite3_result_int(context, !regexec(
586 (regex_t *)sqlite3_value_blob(argv[0]),
587 (const char *)sqlite3_value_text(argv[1]),
592 sql_append(char **sql, size_t *sz, const char *newstr, int count)
596 newsz = 1 < count ? (size_t)count : strlen(newstr);
597 *sql = mandoc_realloc(*sql, *sz + newsz + 1);
599 memset(*sql + *sz, *newstr, (size_t)count);
601 memcpy(*sql + *sz, newstr, newsz);
607 * Prepare the search SQL statement.
610 sql_statement(const struct expr *e)
616 sql = mandoc_strdup(e->equal ?
617 "SELECT desc, form, pageid, bits "
618 "FROM mpages NATURAL JOIN names WHERE " :
619 "SELECT desc, form, pageid, 0 FROM mpages WHERE ");
622 for (needop = 0; NULL != e; e = e->next) {
624 sql_append(&sql, &sz, " AND ", 1);
626 sql_append(&sql, &sz, " OR ", 1);
628 sql_append(&sql, &sz, "(", e->open);
629 sql_append(&sql, &sz,
636 ? "pageid IN (SELECT pageid FROM names "
637 "WHERE name REGEXP ?)"
640 : "pageid IN (SELECT pageid FROM names "
641 "WHERE name MATCH ?)")
643 ? "pageid IN (SELECT pageid FROM keys "
644 "WHERE key REGEXP ? AND bits & ?)"
645 : "pageid IN (SELECT pageid FROM keys "
646 "WHERE key MATCH ? AND bits & ?)"), 1);
648 sql_append(&sql, &sz, ")", e->close);
656 * Compile a set of string tokens into an expression.
657 * Tokens in "argv" are assumed to be individual expression atoms (e.g.,
658 * "(", "foo=bar", etc.).
661 exprcomp(const struct mansearch *search, int argc, char *argv[])
664 int i, toopen, logic, igncase, toclose;
665 struct expr *first, *prev, *cur, *next;
668 logic = igncase = toopen = toclose = 0;
670 for (i = 0; i < argc; i++) {
671 if (0 == strcmp("(", argv[i])) {
677 } else if (0 == strcmp(")", argv[i])) {
678 if (toopen || logic || igncase || NULL == cur)
684 } else if (0 == strcmp("-a", argv[i])) {
685 if (toopen || logic || igncase || NULL == cur)
689 } else if (0 == strcmp("-o", argv[i])) {
690 if (toopen || logic || igncase || NULL == cur)
694 } else if (0 == strcmp("-i", argv[i])) {
700 next = exprterm(search, argv[i], !igncase);
710 * Searching for descriptions must be split out
711 * because they are stored in the mpages table,
712 * not in the keys table.
715 for (mask = TYPE_Nm; mask <= TYPE_Nd; mask <<= 1) {
716 if (mask & cur->bits && ~mask & cur->bits) {
717 next = mandoc_calloc(1,
718 sizeof(struct expr));
719 memcpy(next, cur, sizeof(struct expr));
727 prev->and = (1 == logic);
728 prev->open += toopen;
732 toopen = logic = igncase = 0;
734 if ( ! (toopen || logic || igncase || toclose))
744 exprterm(const struct mansearch *search, char *buf, int cs)
755 e = mandoc_calloc(1, sizeof(struct expr));
757 if (search->argmode == ARG_NAME) {
765 * Separate macro keys from search string.
766 * If needed, request regular expression handling
767 * by setting e->substr to NULL.
770 if (search->argmode == ARG_WORD) {
774 mandoc_asprintf(&val, "[[:<:]]%s[[:>:]]", buf);
776 mandoc_asprintf(&val, "\\<%s\\>", buf);
778 mandoc_asprintf(&val,
779 "(^|[^a-zA-Z01-9_])%s([^a-zA-Z01-9_]|$)", buf);
782 } else if ((val = strpbrk(buf, "=~")) == NULL) {
783 e->bits = TYPE_Nm | TYPE_Nd;
787 e->bits = TYPE_Nm | TYPE_Nd;
791 if (NULL != strstr(buf, "arch"))
795 /* Compile regular expressions. */
797 if (NULL == e->substr) {
798 irc = regcomp(&e->regexp, val,
799 REG_EXTENDED | REG_NOSUB | (cs ? 0 : REG_ICASE));
800 if (search->argmode == ARG_WORD)
803 regerror(irc, &e->regexp, errbuf, sizeof(errbuf));
804 warnx("regcomp: %s", errbuf);
814 * Parse out all possible fields.
815 * If the field doesn't resolve, bail.
818 while (NULL != (key = strsep(&buf, ","))) {
821 for (i = 0, iterbit = 1;
822 i < mansearch_keymax;
823 i++, iterbit <<= 1) {
824 if (0 == strcasecmp(key,
825 mansearch_keynames[i])) {
830 if (i == mansearch_keymax) {
831 if (strcasecmp(key, "any")) {
843 exprfree(struct expr *p)