1 /* $Id: mansearch.c,v 1.55 2015/03/11 13:11:22 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 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.
21 #include <sys/types.h>
40 #include "compat_ohash.h"
43 #ifndef SQLITE_DETERMINISTIC
44 #define SQLITE_DETERMINISTIC 0
48 #include "mandoc_aux.h"
50 #include "mansearch.h"
52 extern int mansearch_keymax;
53 extern const char *const mansearch_keynames[];
55 #define SQL_BIND_TEXT(_db, _s, _i, _v) \
56 do { if (SQLITE_OK != sqlite3_bind_text \
57 ((_s), (_i)++, (_v), -1, SQLITE_STATIC)) \
58 fprintf(stderr, "%s\n", sqlite3_errmsg((_db))); \
60 #define SQL_BIND_INT64(_db, _s, _i, _v) \
61 do { if (SQLITE_OK != sqlite3_bind_int64 \
62 ((_s), (_i)++, (_v))) \
63 fprintf(stderr, "%s\n", sqlite3_errmsg((_db))); \
65 #define SQL_BIND_BLOB(_db, _s, _i, _v) \
66 do { if (SQLITE_OK != sqlite3_bind_blob \
67 ((_s), (_i)++, (&_v), sizeof(_v), SQLITE_STATIC)) \
68 fprintf(stderr, "%s\n", sqlite3_errmsg((_db))); \
72 regex_t regexp; /* compiled regexp, if applicable */
73 const char *substr; /* to search for, if applicable */
74 struct expr *next; /* next in sequence */
75 uint64_t bits; /* type-mask */
76 int equal; /* equality, not subsring match */
77 int open; /* opening parentheses before */
78 int and; /* logical AND before */
79 int close; /* closing parentheses after */
83 uint64_t pageid; /* identifier in database */
84 uint64_t bits; /* name type mask */
85 char *desc; /* manual page description */
86 int form; /* bit field: formatted, zipped? */
89 static void buildnames(const struct mansearch *,
90 struct manpage *, sqlite3 *,
91 sqlite3_stmt *, uint64_t,
92 const char *, int form);
93 static char *buildoutput(sqlite3 *, sqlite3_stmt *,
95 static void *hash_alloc(size_t, void *);
96 static void hash_free(void *, void *);
97 static void *hash_calloc(size_t, size_t, void *);
98 static struct expr *exprcomp(const struct mansearch *,
100 static void exprfree(struct expr *);
101 static struct expr *exprterm(const struct mansearch *, char *, int);
102 static int manpage_compare(const void *, const void *);
103 static void sql_append(char **sql, size_t *sz,
104 const char *newstr, int count);
105 static void sql_match(sqlite3_context *context,
106 int argc, sqlite3_value **argv);
107 static void sql_regexp(sqlite3_context *context,
108 int argc, sqlite3_value **argv);
109 static char *sql_statement(const struct expr *);
113 mansearch_setup(int start)
115 static void *pagecache;
118 #define PC_PAGESIZE 1280
119 #define PC_NUMPAGES 256
122 if (NULL != pagecache) {
123 fprintf(stderr, "pagecache already enabled\n");
124 return((int)MANDOCLEVEL_BADARG);
127 pagecache = mmap(NULL, PC_PAGESIZE * PC_NUMPAGES,
128 PROT_READ | PROT_WRITE,
129 MAP_SHARED | MAP_ANON, -1, 0);
131 if (MAP_FAILED == pagecache) {
134 return((int)MANDOCLEVEL_SYSERR);
137 c = sqlite3_config(SQLITE_CONFIG_PAGECACHE,
138 pagecache, PC_PAGESIZE, PC_NUMPAGES);
141 return((int)MANDOCLEVEL_OK);
143 fprintf(stderr, "pagecache: %s\n", sqlite3_errstr(c));
145 } else if (NULL == pagecache) {
146 fprintf(stderr, "pagecache missing\n");
147 return((int)MANDOCLEVEL_BADARG);
150 if (-1 == munmap(pagecache, PC_PAGESIZE * PC_NUMPAGES)) {
153 return((int)MANDOCLEVEL_SYSERR);
157 return((int)MANDOCLEVEL_OK);
161 mansearch(const struct mansearch *search,
162 const struct manpaths *paths,
163 int argc, char *argv[],
164 struct manpage **res, size_t *sz)
166 int fd, rc, c, indexbit;
168 uint64_t outbit, iterbit;
171 struct manpage *mpage;
174 sqlite3_stmt *s, *s2;
176 struct ohash_info info;
179 size_t i, j, cur, maxres;
181 info.calloc = hash_calloc;
182 info.alloc = hash_alloc;
183 info.free = hash_free;
184 info.key_offset = offsetof(struct match, pageid);
186 *sz = cur = maxres = 0;
195 if (NULL == (e = exprcomp(search, argc, argv)))
198 if (NULL != search->outkey) {
200 for (indexbit = 0, iterbit = 1;
201 indexbit < mansearch_keymax;
202 indexbit++, iterbit <<= 1) {
203 if (0 == strcasecmp(search->outkey,
204 mansearch_keynames[indexbit])) {
213 * Save a descriptor to the current working directory.
214 * Since pathnames in the "paths" variable might be relative,
215 * and we'll be chdir()ing into them, we need to keep a handle
216 * on our current directory from which to start the chdir().
219 if (NULL == getcwd(buf, PATH_MAX)) {
222 } else if (-1 == (fd = open(buf, O_RDONLY, 0))) {
227 sql = sql_statement(e);
230 * Loop over the directories (containing databases) for us to
232 * Don't let missing/bad databases/directories phase us.
233 * In each, try to open the resident database and, if it opens,
234 * scan it for our match expression.
237 for (i = 0; i < paths->sz; i++) {
238 if (-1 == fchdir(fd)) {
242 } else if (-1 == chdir(paths->paths[i])) {
243 perror(paths->paths[i]);
247 c = sqlite3_open_v2(MANDOC_DB, &db,
248 SQLITE_OPEN_READONLY, NULL);
250 if (SQLITE_OK != c) {
251 fprintf(stderr, "%s/%s: %s\n",
252 paths->paths[i], MANDOC_DB, strerror(errno));
258 * Define the SQL functions for substring
259 * and regular expression matching.
262 c = sqlite3_create_function(db, "match", 2,
263 SQLITE_UTF8 | SQLITE_DETERMINISTIC,
264 NULL, sql_match, NULL, NULL);
265 assert(SQLITE_OK == c);
266 c = sqlite3_create_function(db, "regexp", 2,
267 SQLITE_UTF8 | SQLITE_DETERMINISTIC,
268 NULL, sql_regexp, NULL, NULL);
269 assert(SQLITE_OK == c);
272 c = sqlite3_prepare_v2(db, sql, -1, &s, NULL);
274 fprintf(stderr, "%s\n", sqlite3_errmsg(db));
276 for (ep = e; NULL != ep; ep = ep->next) {
277 if (NULL == ep->substr) {
278 SQL_BIND_BLOB(db, s, j, ep->regexp);
280 SQL_BIND_TEXT(db, s, j, ep->substr);
281 if (0 == ((TYPE_Nd | TYPE_Nm) & ep->bits))
282 SQL_BIND_INT64(db, s, j, ep->bits);
285 memset(&htab, 0, sizeof(struct ohash));
286 ohash_init(&htab, 4, &info);
289 * Hash each entry on its [unique] document identifier.
290 * This is a uint64_t.
291 * Instead of using a hash function, simply convert the
292 * uint64_t to a uint32_t, the hash value's type.
293 * This gives good performance and preserves the
294 * distribution of buckets in the table.
296 while (SQLITE_ROW == (c = sqlite3_step(s))) {
297 pageid = sqlite3_column_int64(s, 2);
298 idx = ohash_lookup_memory(&htab,
299 (char *)&pageid, sizeof(uint64_t),
302 if (NULL != ohash_find(&htab, idx))
305 mp = mandoc_calloc(1, sizeof(struct match));
307 mp->form = sqlite3_column_int(s, 1);
308 mp->bits = sqlite3_column_int64(s, 3);
309 if (TYPE_Nd == outbit)
310 mp->desc = mandoc_strdup((const char *)
311 sqlite3_column_text(s, 0));
312 ohash_insert(&htab, idx, mp);
315 if (SQLITE_DONE != c)
316 fprintf(stderr, "%s\n", sqlite3_errmsg(db));
320 c = sqlite3_prepare_v2(db,
321 "SELECT sec, arch, name, pageid FROM mlinks "
322 "WHERE pageid=? ORDER BY sec, arch, name",
325 fprintf(stderr, "%s\n", sqlite3_errmsg(db));
327 c = sqlite3_prepare_v2(db,
328 "SELECT bits, key, pageid FROM keys "
329 "WHERE pageid=? AND bits & ?",
332 fprintf(stderr, "%s\n", sqlite3_errmsg(db));
334 for (mp = ohash_first(&htab, &idx);
336 mp = ohash_next(&htab, &idx)) {
337 if (cur + 1 > maxres) {
339 *res = mandoc_reallocarray(*res,
340 maxres, sizeof(struct manpage));
344 mpage->bits = mp->bits;
346 mpage->form = mp->form;
347 buildnames(search, mpage, db, s, mp->pageid,
348 paths->paths[i], mp->form);
349 if (mpage->names != NULL) {
350 mpage->output = TYPE_Nd & outbit ?
352 buildoutput(db, s2, mp->pageid, outbit) :
360 sqlite3_finalize(s2);
365 * In man(1) mode, prefer matches in earlier trees
366 * over matches in later trees.
369 if (cur && search->firstmatch)
372 qsort(*res, cur, sizeof(struct manpage), manpage_compare);
376 if (-1 == fchdir(fd))
387 mansearch_free(struct manpage *res, size_t sz)
391 for (i = 0; i < sz; i++) {
400 manpage_compare(const void *vp1, const void *vp2)
402 const struct manpage *mp1, *mp2;
407 return( (diff = mp2->bits - mp1->bits) ? diff :
408 (diff = mp1->sec - mp2->sec) ? diff :
409 strcasecmp(mp1->names, mp2->names));
413 buildnames(const struct mansearch *search, struct manpage *mpage,
414 sqlite3 *db, sqlite3_stmt *s,
415 uint64_t pageid, const char *path, int form)
418 char *firstname, *newnames, *prevsec, *prevarch;
419 const char *oldnames, *sep1, *name, *sec, *sep2, *arch, *fsec;
425 firstname = prevsec = prevarch = NULL;
427 SQL_BIND_INT64(db, s, i, pageid);
428 while (SQLITE_ROW == (c = sqlite3_step(s))) {
430 /* Decide whether we already have some names. */
432 if (NULL == mpage->names) {
436 oldnames = mpage->names;
440 /* Fetch the next name, rejecting sec/arch mismatches. */
442 sec = (const char *)sqlite3_column_text(s, 0);
443 if (search->sec != NULL && strcasecmp(sec, search->sec))
445 arch = (const char *)sqlite3_column_text(s, 1);
446 if (search->arch != NULL && *arch != '\0' &&
447 strcasecmp(arch, search->arch))
449 name = (const char *)sqlite3_column_text(s, 2);
451 /* Remember the first section found. */
453 if (9 < mpage->sec && '1' <= *sec && '9' >= *sec)
454 mpage->sec = (*sec - '1') + 1;
456 /* If the section changed, append the old one. */
458 if (NULL != prevsec &&
459 (strcmp(sec, prevsec) ||
460 strcmp(arch, prevarch))) {
461 sep2 = '\0' == *prevarch ? "" : "/";
462 mandoc_asprintf(&newnames, "%s(%s%s%s)",
463 oldnames, prevsec, sep2, prevarch);
465 oldnames = mpage->names = newnames;
468 prevsec = prevarch = NULL;
471 /* Save the new section, to append it later. */
473 if (NULL == prevsec) {
474 prevsec = mandoc_strdup(sec);
475 prevarch = mandoc_strdup(arch);
478 /* Append the new name. */
480 mandoc_asprintf(&newnames, "%s%s%s",
481 oldnames, sep1, name);
483 mpage->names = newnames;
485 /* Also save the first file name encountered. */
487 if (mpage->file != NULL)
490 if (form & FORM_SRC) {
497 sep2 = *arch == '\0' ? "" : "/";
498 mandoc_asprintf(&mpage->file, "%s/%s%s%s%s/%s.%s",
499 path, sep1, sec, sep2, arch, name, fsec);
500 if (access(mpage->file, R_OK) != -1)
503 /* Handle unusual file name extensions. */
505 if (firstname == NULL)
506 firstname = mpage->file;
509 mandoc_asprintf(&mpage->file, "%s/%s%s%s%s/%s.*",
510 path, sep1, sec, sep2, arch, name);
511 globres = glob(mpage->file, 0, NULL, &globinfo);
513 mpage->file = globres ? NULL :
514 mandoc_strdup(*globinfo.gl_pathv);
517 if (c != SQLITE_DONE)
518 fprintf(stderr, "%s\n", sqlite3_errmsg(db));
521 /* If none of the files is usable, use the first name. */
523 if (mpage->file == NULL)
524 mpage->file = firstname;
525 else if (mpage->file != firstname)
528 /* Append one final section to the names. */
530 if (prevsec != NULL) {
531 sep2 = *prevarch == '\0' ? "" : "/";
532 mandoc_asprintf(&newnames, "%s(%s%s%s)",
533 mpage->names, prevsec, sep2, prevarch);
535 mpage->names = newnames;
542 buildoutput(sqlite3 *db, sqlite3_stmt *s, uint64_t pageid, uint64_t outbit)
544 char *output, *newoutput;
545 const char *oldoutput, *sep1, *data;
551 SQL_BIND_INT64(db, s, i, pageid);
552 SQL_BIND_INT64(db, s, i, outbit);
553 while (SQLITE_ROW == (c = sqlite3_step(s))) {
554 if (NULL == output) {
561 data = (const char *)sqlite3_column_text(s, 1);
562 mandoc_asprintf(&newoutput, "%s%s%s",
563 oldoutput, sep1, data);
567 if (SQLITE_DONE != c)
568 fprintf(stderr, "%s\n", sqlite3_errmsg(db));
574 * Implement substring match as an application-defined SQL function.
575 * Using the SQL LIKE or GLOB operators instead would be a bad idea
576 * because that would require escaping metacharacters in the string
577 * being searched for.
580 sql_match(sqlite3_context *context, int argc, sqlite3_value **argv)
584 sqlite3_result_int(context, NULL != strcasestr(
585 (const char *)sqlite3_value_text(argv[1]),
586 (const char *)sqlite3_value_text(argv[0])));
590 * Implement regular expression match
591 * as an application-defined SQL function.
594 sql_regexp(sqlite3_context *context, int argc, sqlite3_value **argv)
598 sqlite3_result_int(context, !regexec(
599 (regex_t *)sqlite3_value_blob(argv[0]),
600 (const char *)sqlite3_value_text(argv[1]),
605 sql_append(char **sql, size_t *sz, const char *newstr, int count)
609 newsz = 1 < count ? (size_t)count : strlen(newstr);
610 *sql = mandoc_realloc(*sql, *sz + newsz + 1);
612 memset(*sql + *sz, *newstr, (size_t)count);
614 memcpy(*sql + *sz, newstr, newsz);
620 * Prepare the search SQL statement.
623 sql_statement(const struct expr *e)
629 sql = mandoc_strdup(e->equal ?
630 "SELECT desc, form, pageid, bits "
631 "FROM mpages NATURAL JOIN names WHERE " :
632 "SELECT desc, form, pageid, 0 FROM mpages WHERE ");
635 for (needop = 0; NULL != e; e = e->next) {
637 sql_append(&sql, &sz, " AND ", 1);
639 sql_append(&sql, &sz, " OR ", 1);
641 sql_append(&sql, &sz, "(", e->open);
642 sql_append(&sql, &sz,
649 ? "pageid IN (SELECT pageid FROM names "
650 "WHERE name REGEXP ?)"
653 : "pageid IN (SELECT pageid FROM names "
654 "WHERE name MATCH ?)")
656 ? "pageid IN (SELECT pageid FROM keys "
657 "WHERE key REGEXP ? AND bits & ?)"
658 : "pageid IN (SELECT pageid FROM keys "
659 "WHERE key MATCH ? AND bits & ?)"), 1);
661 sql_append(&sql, &sz, ")", e->close);
669 * Compile a set of string tokens into an expression.
670 * Tokens in "argv" are assumed to be individual expression atoms (e.g.,
671 * "(", "foo=bar", etc.).
674 exprcomp(const struct mansearch *search, int argc, char *argv[])
677 int i, toopen, logic, igncase, toclose;
678 struct expr *first, *prev, *cur, *next;
681 logic = igncase = toopen = toclose = 0;
683 for (i = 0; i < argc; i++) {
684 if (0 == strcmp("(", argv[i])) {
690 } else if (0 == strcmp(")", argv[i])) {
691 if (toopen || logic || igncase || NULL == cur)
697 } else if (0 == strcmp("-a", argv[i])) {
698 if (toopen || logic || igncase || NULL == cur)
702 } else if (0 == strcmp("-o", argv[i])) {
703 if (toopen || logic || igncase || NULL == cur)
707 } else if (0 == strcmp("-i", argv[i])) {
713 next = exprterm(search, argv[i], !igncase);
723 * Searching for descriptions must be split out
724 * because they are stored in the mpages table,
725 * not in the keys table.
728 for (mask = TYPE_Nm; mask <= TYPE_Nd; mask <<= 1) {
729 if (mask & cur->bits && ~mask & cur->bits) {
730 next = mandoc_calloc(1,
731 sizeof(struct expr));
732 memcpy(next, cur, sizeof(struct expr));
740 prev->and = (1 == logic);
741 prev->open += toopen;
745 toopen = logic = igncase = 0;
747 if ( ! (toopen || logic || igncase || toclose))
757 exprterm(const struct mansearch *search, char *buf, int cs)
768 e = mandoc_calloc(1, sizeof(struct expr));
770 if (search->argmode == ARG_NAME) {
778 * Separate macro keys from search string.
779 * If needed, request regular expression handling
780 * by setting e->substr to NULL.
783 if (search->argmode == ARG_WORD) {
786 mandoc_asprintf(&val, "[[:<:]]%s[[:>:]]", buf);
788 } else if ((val = strpbrk(buf, "=~")) == NULL) {
789 e->bits = TYPE_Nm | TYPE_Nd;
793 e->bits = TYPE_Nm | TYPE_Nd;
797 if (NULL != strstr(buf, "arch"))
801 /* Compile regular expressions. */
803 if (NULL == e->substr) {
804 irc = regcomp(&e->regexp, val,
805 REG_EXTENDED | REG_NOSUB | (cs ? 0 : REG_ICASE));
806 if (search->argmode == ARG_WORD)
809 regerror(irc, &e->regexp, errbuf, sizeof(errbuf));
810 fprintf(stderr, "regcomp: %s\n", errbuf);
820 * Parse out all possible fields.
821 * If the field doesn't resolve, bail.
824 while (NULL != (key = strsep(&buf, ","))) {
827 for (i = 0, iterbit = 1;
828 i < mansearch_keymax;
829 i++, iterbit <<= 1) {
830 if (0 == strcasecmp(key,
831 mansearch_keynames[i])) {
836 if (i == mansearch_keymax) {
837 if (strcasecmp(key, "any")) {
849 exprfree(struct expr *p)
861 hash_calloc(size_t nmemb, size_t sz, void *arg)
864 return(mandoc_calloc(nmemb, sz));
868 hash_alloc(size_t sz, void *arg)
871 return(mandoc_malloc(sz));
875 hash_free(void *p, void *arg)