1 /* $Id: mansearch.c,v 1.42 2014/08/09 14:24:53 schwarze Exp $ */
3 * Copyright (c) 2012 Kristaps Dzonsons <kristaps@bsd.lv>
4 * Copyright (c) 2013, 2014 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.
38 #include "compat_ohash.h"
41 #ifndef SQLITE_DETERMINISTIC
42 #define SQLITE_DETERMINISTIC 0
46 #include "mandoc_aux.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 fprintf(stderr, "%s\n", 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 fprintf(stderr, "%s\n", 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 fprintf(stderr, "%s\n", 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 char *desc; /* manual page description */
83 int form; /* 0 == catpage */
86 static void buildnames(struct manpage *, sqlite3 *,
87 sqlite3_stmt *, uint64_t,
88 const char *, int form);
89 static char *buildoutput(sqlite3 *, sqlite3_stmt *,
91 static void *hash_alloc(size_t, void *);
92 static void hash_free(void *, void *);
93 static void *hash_calloc(size_t, size_t, void *);
94 static struct expr *exprcomp(const struct mansearch *,
96 static void exprfree(struct expr *);
97 static struct expr *exprspec(struct expr *, uint64_t,
98 const char *, const char *);
99 static struct expr *exprterm(const struct mansearch *, char *, int);
100 static int manpage_compare(const void *, const void *);
101 static void sql_append(char **sql, size_t *sz,
102 const char *newstr, int count);
103 static void sql_match(sqlite3_context *context,
104 int argc, sqlite3_value **argv);
105 static void sql_regexp(sqlite3_context *context,
106 int argc, sqlite3_value **argv);
107 static char *sql_statement(const struct expr *);
111 mansearch_setup(int start)
113 static void *pagecache;
116 #define PC_PAGESIZE 1280
117 #define PC_NUMPAGES 256
120 if (NULL != pagecache) {
121 fprintf(stderr, "pagecache already enabled\n");
122 return((int)MANDOCLEVEL_BADARG);
125 pagecache = mmap(NULL, PC_PAGESIZE * PC_NUMPAGES,
126 PROT_READ | PROT_WRITE,
127 MAP_SHARED | MAP_ANON, -1, 0);
129 if (MAP_FAILED == pagecache) {
132 return((int)MANDOCLEVEL_SYSERR);
135 c = sqlite3_config(SQLITE_CONFIG_PAGECACHE,
136 pagecache, PC_PAGESIZE, PC_NUMPAGES);
139 return((int)MANDOCLEVEL_OK);
141 fprintf(stderr, "pagecache: %s\n", sqlite3_errstr(c));
143 } else if (NULL == pagecache) {
144 fprintf(stderr, "pagecache missing\n");
145 return((int)MANDOCLEVEL_BADARG);
148 if (-1 == munmap(pagecache, PC_PAGESIZE * PC_NUMPAGES)) {
151 return((int)MANDOCLEVEL_SYSERR);
155 return((int)MANDOCLEVEL_OK);
159 mansearch(const struct mansearch *search,
160 const struct manpaths *paths,
161 int argc, char *argv[],
163 struct manpage **res, size_t *sz)
165 int fd, rc, c, indexbit;
167 uint64_t outbit, iterbit;
170 struct manpage *mpage;
173 sqlite3_stmt *s, *s2;
175 struct ohash_info info;
178 size_t i, j, cur, maxres;
180 info.calloc = hash_calloc;
181 info.alloc = hash_alloc;
182 info.free = hash_free;
183 info.key_offset = offsetof(struct match, pageid);
185 *sz = cur = maxres = 0;
194 if (NULL == (e = exprcomp(search, argc, argv)))
198 if (NULL != outkey) {
199 for (indexbit = 0, iterbit = 1;
200 indexbit < mansearch_keymax;
201 indexbit++, iterbit <<= 1) {
202 if (0 == strcasecmp(outkey,
203 mansearch_keynames[indexbit])) {
211 * Save a descriptor to the current working directory.
212 * Since pathnames in the "paths" variable might be relative,
213 * and we'll be chdir()ing into them, we need to keep a handle
214 * on our current directory from which to start the chdir().
217 if (NULL == getcwd(buf, PATH_MAX)) {
220 } else if (-1 == (fd = open(buf, O_RDONLY, 0))) {
225 sql = sql_statement(e);
228 * Loop over the directories (containing databases) for us to
230 * Don't let missing/bad databases/directories phase us.
231 * In each, try to open the resident database and, if it opens,
232 * scan it for our match expression.
235 for (i = 0; i < paths->sz; i++) {
236 if (-1 == fchdir(fd)) {
240 } else if (-1 == chdir(paths->paths[i])) {
241 perror(paths->paths[i]);
245 c = sqlite3_open_v2(MANDOC_DB, &db,
246 SQLITE_OPEN_READONLY, NULL);
248 if (SQLITE_OK != c) {
255 * Define the SQL functions for substring
256 * and regular expression matching.
259 c = sqlite3_create_function(db, "match", 2,
260 SQLITE_UTF8 | SQLITE_DETERMINISTIC,
261 NULL, sql_match, NULL, NULL);
262 assert(SQLITE_OK == c);
263 c = sqlite3_create_function(db, "regexp", 2,
264 SQLITE_UTF8 | SQLITE_DETERMINISTIC,
265 NULL, sql_regexp, NULL, NULL);
266 assert(SQLITE_OK == c);
269 c = sqlite3_prepare_v2(db, sql, -1, &s, NULL);
271 fprintf(stderr, "%s\n", sqlite3_errmsg(db));
273 for (ep = e; NULL != ep; ep = ep->next) {
274 if (NULL == ep->substr) {
275 SQL_BIND_BLOB(db, s, j, ep->regexp);
277 SQL_BIND_TEXT(db, s, j, ep->substr);
278 if (0 == ((TYPE_Nd | TYPE_Nm) & ep->bits))
279 SQL_BIND_INT64(db, s, j, ep->bits);
282 memset(&htab, 0, sizeof(struct ohash));
283 ohash_init(&htab, 4, &info);
286 * Hash each entry on its [unique] document identifier.
287 * This is a uint64_t.
288 * Instead of using a hash function, simply convert the
289 * uint64_t to a uint32_t, the hash value's type.
290 * This gives good performance and preserves the
291 * distribution of buckets in the table.
293 while (SQLITE_ROW == (c = sqlite3_step(s))) {
294 pageid = sqlite3_column_int64(s, 2);
295 idx = ohash_lookup_memory(&htab,
296 (char *)&pageid, sizeof(uint64_t),
299 if (NULL != ohash_find(&htab, idx))
302 mp = mandoc_calloc(1, sizeof(struct match));
304 mp->form = sqlite3_column_int(s, 1);
305 if (TYPE_Nd == outbit)
306 mp->desc = mandoc_strdup((const char *)
307 sqlite3_column_text(s, 0));
308 ohash_insert(&htab, idx, mp);
311 if (SQLITE_DONE != c)
312 fprintf(stderr, "%s\n", sqlite3_errmsg(db));
316 c = sqlite3_prepare_v2(db,
317 "SELECT sec, arch, name, pageid FROM mlinks "
318 "WHERE pageid=? ORDER BY sec, arch, name",
321 fprintf(stderr, "%s\n", sqlite3_errmsg(db));
323 c = sqlite3_prepare_v2(db,
324 "SELECT bits, key, pageid FROM keys "
325 "WHERE pageid=? AND bits & ?",
328 fprintf(stderr, "%s\n", sqlite3_errmsg(db));
330 for (mp = ohash_first(&htab, &idx);
332 mp = ohash_next(&htab, &idx)) {
333 if (cur + 1 > maxres) {
335 *res = mandoc_reallocarray(*res,
336 maxres, sizeof(struct manpage));
340 mpage->form = mp->form;
341 buildnames(mpage, db, s, mp->pageid,
342 paths->paths[i], mp->form);
343 mpage->output = TYPE_Nd & outbit ?
345 buildoutput(db, s2, mp->pageid, outbit) : NULL;
352 sqlite3_finalize(s2);
356 qsort(*res, cur, sizeof(struct manpage), manpage_compare);
360 if (-1 == fchdir(fd))
371 manpage_compare(const void *vp1, const void *vp2)
373 const struct manpage *mp1, *mp2;
378 diff = mp1->sec - mp2->sec;
379 return(diff ? diff : strcasecmp(mp1->names, mp2->names));
383 buildnames(struct manpage *mpage, sqlite3 *db, sqlite3_stmt *s,
384 uint64_t pageid, const char *path, int form)
386 char *newnames, *prevsec, *prevarch;
387 const char *oldnames, *sep1, *name, *sec, *sep2, *arch, *fsec;
393 prevsec = prevarch = NULL;
395 SQL_BIND_INT64(db, s, i, pageid);
396 while (SQLITE_ROW == (c = sqlite3_step(s))) {
398 /* Decide whether we already have some names. */
400 if (NULL == mpage->names) {
404 oldnames = mpage->names;
408 /* Fetch the next name. */
410 sec = (const char *)sqlite3_column_text(s, 0);
411 arch = (const char *)sqlite3_column_text(s, 1);
412 name = (const char *)sqlite3_column_text(s, 2);
414 /* Remember the first section found. */
416 if (9 < mpage->sec && '1' <= *sec && '9' >= *sec)
417 mpage->sec = (*sec - '1') + 1;
419 /* If the section changed, append the old one. */
421 if (NULL != prevsec &&
422 (strcmp(sec, prevsec) ||
423 strcmp(arch, prevarch))) {
424 sep2 = '\0' == *prevarch ? "" : "/";
425 mandoc_asprintf(&newnames, "%s(%s%s%s)",
426 oldnames, prevsec, sep2, prevarch);
428 oldnames = mpage->names = newnames;
431 prevsec = prevarch = NULL;
434 /* Save the new section, to append it later. */
436 if (NULL == prevsec) {
437 prevsec = mandoc_strdup(sec);
438 prevarch = mandoc_strdup(arch);
441 /* Append the new name. */
443 mandoc_asprintf(&newnames, "%s%s%s",
444 oldnames, sep1, name);
446 mpage->names = newnames;
448 /* Also save the first file name encountered. */
450 if (NULL != mpage->file)
460 sep2 = '\0' == *arch ? "" : "/";
461 mandoc_asprintf(&mpage->file, "%s/%s%s%s%s/%s.%s",
462 path, sep1, sec, sep2, arch, name, fsec);
464 if (SQLITE_DONE != c)
465 fprintf(stderr, "%s\n", sqlite3_errmsg(db));
468 /* Append one final section to the names. */
470 if (NULL != prevsec) {
471 sep2 = '\0' == *prevarch ? "" : "/";
472 mandoc_asprintf(&newnames, "%s(%s%s%s)",
473 mpage->names, prevsec, sep2, prevarch);
475 mpage->names = newnames;
482 buildoutput(sqlite3 *db, sqlite3_stmt *s, uint64_t pageid, uint64_t outbit)
484 char *output, *newoutput;
485 const char *oldoutput, *sep1, *data;
491 SQL_BIND_INT64(db, s, i, pageid);
492 SQL_BIND_INT64(db, s, i, outbit);
493 while (SQLITE_ROW == (c = sqlite3_step(s))) {
494 if (NULL == output) {
501 data = (const char *)sqlite3_column_text(s, 1);
502 mandoc_asprintf(&newoutput, "%s%s%s",
503 oldoutput, sep1, data);
507 if (SQLITE_DONE != c)
508 fprintf(stderr, "%s\n", sqlite3_errmsg(db));
514 * Implement substring match as an application-defined SQL function.
515 * Using the SQL LIKE or GLOB operators instead would be a bad idea
516 * because that would require escaping metacharacters in the string
517 * being searched for.
520 sql_match(sqlite3_context *context, int argc, sqlite3_value **argv)
524 sqlite3_result_int(context, NULL != strcasestr(
525 (const char *)sqlite3_value_text(argv[1]),
526 (const char *)sqlite3_value_text(argv[0])));
530 * Implement regular expression match
531 * as an application-defined SQL function.
534 sql_regexp(sqlite3_context *context, int argc, sqlite3_value **argv)
538 sqlite3_result_int(context, !regexec(
539 (regex_t *)sqlite3_value_blob(argv[0]),
540 (const char *)sqlite3_value_text(argv[1]),
545 sql_append(char **sql, size_t *sz, const char *newstr, int count)
549 newsz = 1 < count ? (size_t)count : strlen(newstr);
550 *sql = mandoc_realloc(*sql, *sz + newsz + 1);
552 memset(*sql + *sz, *newstr, (size_t)count);
554 memcpy(*sql + *sz, newstr, newsz);
560 * Prepare the search SQL statement.
563 sql_statement(const struct expr *e)
570 "SELECT desc, form, pageid FROM mpages WHERE ");
573 for (needop = 0; NULL != e; e = e->next) {
575 sql_append(&sql, &sz, " AND ", 1);
577 sql_append(&sql, &sz, " OR ", 1);
579 sql_append(&sql, &sz, "(", e->open);
580 sql_append(&sql, &sz,
587 ? "pageid IN (SELECT pageid FROM names "
588 "WHERE name REGEXP ?)"
590 ? "pageid IN (SELECT pageid FROM names "
592 : "pageid IN (SELECT pageid FROM names "
593 "WHERE name MATCH ?)")
595 ? "pageid IN (SELECT pageid FROM keys "
596 "WHERE key REGEXP ? AND bits & ?)"
597 : "pageid IN (SELECT pageid FROM keys "
598 "WHERE key MATCH ? AND bits & ?)"), 1);
600 sql_append(&sql, &sz, ")", e->close);
608 * Compile a set of string tokens into an expression.
609 * Tokens in "argv" are assumed to be individual expression atoms (e.g.,
610 * "(", "foo=bar", etc.).
613 exprcomp(const struct mansearch *search, int argc, char *argv[])
616 int i, toopen, logic, igncase, toclose;
617 struct expr *first, *prev, *cur, *next;
620 logic = igncase = toclose = 0;
621 toopen = NULL != search->sec || NULL != search->arch;
623 for (i = 0; i < argc; i++) {
624 if (0 == strcmp("(", argv[i])) {
630 } else if (0 == strcmp(")", argv[i])) {
631 if (toopen || logic || igncase || NULL == cur)
637 } else if (0 == strcmp("-a", argv[i])) {
638 if (toopen || logic || igncase || NULL == cur)
642 } else if (0 == strcmp("-o", argv[i])) {
643 if (toopen || logic || igncase || NULL == cur)
647 } else if (0 == strcmp("-i", argv[i])) {
653 next = exprterm(search, argv[i], !igncase);
663 * Searching for descriptions must be split out
664 * because they are stored in the mpages table,
665 * not in the keys table.
668 for (mask = TYPE_Nm; mask <= TYPE_Nd; mask <<= 1) {
669 if (mask & cur->bits && ~mask & cur->bits) {
670 next = mandoc_calloc(1,
671 sizeof(struct expr));
672 memcpy(next, cur, sizeof(struct expr));
680 prev->and = (1 == logic);
681 prev->open += toopen;
685 toopen = logic = igncase = 0;
687 if (toopen || logic || igncase || toclose)
690 if (NULL != search->sec || NULL != search->arch)
692 if (NULL != search->arch)
693 cur = exprspec(cur, TYPE_arch, search->arch, "^(%s|any)$");
694 if (NULL != search->sec)
695 exprspec(cur, TYPE_sec, search->sec, "^%s$");
706 exprspec(struct expr *cur, uint64_t key, const char *value,
713 mandoc_asprintf(&cp, format, value);
714 cur->next = mandoc_calloc(1, sizeof(struct expr));
718 if (0 != (irc = regcomp(&cur->regexp, cp,
719 REG_EXTENDED | REG_NOSUB | REG_ICASE))) {
720 regerror(irc, &cur->regexp, errbuf, sizeof(errbuf));
721 fprintf(stderr, "regcomp: %s\n", errbuf);
729 exprterm(const struct mansearch *search, char *buf, int cs)
740 e = mandoc_calloc(1, sizeof(struct expr));
742 if (MANSEARCH_MAN & search->flags) {
743 e->bits = search->deftype;
750 * Look for an '=' or '~' operator,
751 * unless forced to some fixed macro keys.
754 if (MANSEARCH_WHATIS & search->flags)
757 val = strpbrk(buf, "=~");
760 e->bits = search->deftype;
765 * Regexp search is requested by !e->substr.
770 e->bits = search->deftype;
774 if (NULL != strstr(buf, "arch"))
778 /* Compile regular expressions. */
780 if (MANSEARCH_WHATIS & search->flags) {
782 mandoc_asprintf(&val, "[[:<:]]%s[[:>:]]", buf);
785 if (NULL == e->substr) {
786 irc = regcomp(&e->regexp, val,
787 REG_EXTENDED | REG_NOSUB | (cs ? 0 : REG_ICASE));
788 if (MANSEARCH_WHATIS & search->flags)
791 regerror(irc, &e->regexp, errbuf, sizeof(errbuf));
792 fprintf(stderr, "regcomp: %s\n", errbuf);
802 * Parse out all possible fields.
803 * If the field doesn't resolve, bail.
806 while (NULL != (key = strsep(&buf, ","))) {
809 for (i = 0, iterbit = 1;
810 i < mansearch_keymax;
811 i++, iterbit <<= 1) {
812 if (0 == strcasecmp(key,
813 mansearch_keynames[i])) {
818 if (i == mansearch_keymax) {
819 if (strcasecmp(key, "any")) {
831 exprfree(struct expr *p)
843 hash_calloc(size_t nmemb, size_t sz, void *arg)
846 return(mandoc_calloc(nmemb, sz));
850 hash_alloc(size_t sz, void *arg)
853 return(mandoc_malloc(sz));
857 hash_free(void *p, void *arg)