[BACK]Return to mansearch.c CVS log [TXT][DIR] Up to [local] / src / usr.bin / mandoc

Annotation of src/usr.bin/mandoc/mansearch.c, Revision 1.46

1.46    ! schwarze    1: /*     $OpenBSD: mansearch.c,v 1.45 2015/10/06 18:30:44 schwarze Exp $ */
1.1       schwarze    2: /*
                      3:  * Copyright (c) 2012 Kristaps Dzonsons <kristaps@bsd.lv>
1.40      schwarze    4:  * Copyright (c) 2013, 2014, 2015 Ingo Schwarze <schwarze@openbsd.org>
1.1       schwarze    5:  *
                      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.
                      9:  *
1.43      schwarze   10:  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
1.1       schwarze   11:  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
1.43      schwarze   12:  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR
1.1       schwarze   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.
                     17:  */
1.33      schwarze   18:
1.19      schwarze   19: #include <sys/mman.h>
1.33      schwarze   20: #include <sys/types.h>
                     21:
1.1       schwarze   22: #include <assert.h>
1.46    ! schwarze   23: #include <err.h>
1.39      schwarze   24: #include <errno.h>
1.1       schwarze   25: #include <fcntl.h>
                     26: #include <getopt.h>
1.41      schwarze   27: #include <glob.h>
1.1       schwarze   28: #include <limits.h>
                     29: #include <regex.h>
                     30: #include <stdio.h>
                     31: #include <stdint.h>
                     32: #include <stddef.h>
                     33: #include <stdlib.h>
                     34: #include <string.h>
                     35: #include <unistd.h>
                     36:
                     37: #include <ohash.h>
                     38: #include <sqlite3.h>
                     39:
                     40: #include "mandoc.h"
1.14      schwarze   41: #include "mandoc_aux.h"
1.43      schwarze   42: #include "manconf.h"
1.1       schwarze   43: #include "mansearch.h"
                     44:
1.11      schwarze   45: extern int mansearch_keymax;
                     46: extern const char *const mansearch_keynames[];
                     47:
1.1       schwarze   48: #define        SQL_BIND_TEXT(_db, _s, _i, _v) \
                     49:        do { if (SQLITE_OK != sqlite3_bind_text \
                     50:                ((_s), (_i)++, (_v), -1, SQLITE_STATIC)) \
1.46    ! schwarze   51:                warnx("%s", sqlite3_errmsg((_db))); \
1.1       schwarze   52:        } while (0)
                     53: #define        SQL_BIND_INT64(_db, _s, _i, _v) \
                     54:        do { if (SQLITE_OK != sqlite3_bind_int64 \
                     55:                ((_s), (_i)++, (_v))) \
1.46    ! schwarze   56:                warnx("%s", sqlite3_errmsg((_db))); \
1.1       schwarze   57:        } while (0)
                     58: #define        SQL_BIND_BLOB(_db, _s, _i, _v) \
                     59:        do { if (SQLITE_OK != sqlite3_bind_blob \
                     60:                ((_s), (_i)++, (&_v), sizeof(_v), SQLITE_STATIC)) \
1.46    ! schwarze   61:                warnx("%s", sqlite3_errmsg((_db))); \
1.1       schwarze   62:        } while (0)
                     63:
                     64: struct expr {
1.28      schwarze   65:        regex_t          regexp;  /* compiled regexp, if applicable */
                     66:        const char      *substr;  /* to search for, if applicable */
                     67:        struct expr     *next;    /* next in sequence */
1.24      schwarze   68:        uint64_t         bits;    /* type-mask */
1.28      schwarze   69:        int              equal;   /* equality, not subsring match */
1.4       schwarze   70:        int              open;    /* opening parentheses before */
                     71:        int              and;     /* logical AND before */
                     72:        int              close;   /* closing parentheses after */
1.1       schwarze   73: };
                     74:
                     75: struct match {
1.22      schwarze   76:        uint64_t         pageid; /* identifier in database */
1.37      schwarze   77:        uint64_t         bits; /* name type mask */
1.17      schwarze   78:        char            *desc; /* manual page description */
1.35      schwarze   79:        int              form; /* bit field: formatted, zipped? */
1.1       schwarze   80: };
                     81:
1.40      schwarze   82: static void             buildnames(const struct mansearch *,
                     83:                                struct manpage *, sqlite3 *,
1.10      schwarze   84:                                sqlite3_stmt *, uint64_t,
                     85:                                const char *, int form);
1.3       schwarze   86: static char            *buildoutput(sqlite3 *, sqlite3_stmt *,
                     87:                                 uint64_t, uint64_t);
1.1       schwarze   88: static void            *hash_alloc(size_t, void *);
1.27      espie      89: static void             hash_free(void *, void *);
                     90: static void            *hash_calloc(size_t, size_t, void *);
1.24      schwarze   91: static struct expr     *exprcomp(const struct mansearch *,
1.1       schwarze   92:                                int, char *[]);
                     93: static void             exprfree(struct expr *);
                     94: static struct expr     *exprterm(const struct mansearch *, char *, int);
1.29      schwarze   95: static int              manpage_compare(const void *, const void *);
1.4       schwarze   96: static void             sql_append(char **sql, size_t *sz,
                     97:                                const char *newstr, int count);
1.1       schwarze   98: static void             sql_match(sqlite3_context *context,
                     99:                                int argc, sqlite3_value **argv);
                    100: static void             sql_regexp(sqlite3_context *context,
                    101:                                int argc, sqlite3_value **argv);
1.6       schwarze  102: static char            *sql_statement(const struct expr *);
1.19      schwarze  103:
1.24      schwarze  104:
1.19      schwarze  105: int
                    106: mansearch_setup(int start)
                    107: {
                    108:        static void     *pagecache;
                    109:        int              c;
                    110:
                    111: #define        PC_PAGESIZE     1280
                    112: #define        PC_NUMPAGES     256
                    113:
                    114:        if (start) {
                    115:                if (NULL != pagecache) {
1.46    ! schwarze  116:                        warnx("pagecache already enabled");
1.45      schwarze  117:                        return (int)MANDOCLEVEL_BADARG;
1.19      schwarze  118:                }
                    119:
                    120:                pagecache = mmap(NULL, PC_PAGESIZE * PC_NUMPAGES,
1.31      schwarze  121:                    PROT_READ | PROT_WRITE,
                    122:                    MAP_SHARED | MAP_ANON, -1, 0);
1.19      schwarze  123:
                    124:                if (MAP_FAILED == pagecache) {
                    125:                        perror("mmap");
                    126:                        pagecache = NULL;
1.45      schwarze  127:                        return (int)MANDOCLEVEL_SYSERR;
1.19      schwarze  128:                }
                    129:
                    130:                c = sqlite3_config(SQLITE_CONFIG_PAGECACHE,
                    131:                    pagecache, PC_PAGESIZE, PC_NUMPAGES);
                    132:
                    133:                if (SQLITE_OK == c)
1.45      schwarze  134:                        return (int)MANDOCLEVEL_OK;
1.19      schwarze  135:
1.46    ! schwarze  136:                warnx("pagecache: %s", sqlite3_errstr(c));
1.19      schwarze  137:
                    138:        } else if (NULL == pagecache) {
1.46    ! schwarze  139:                warnx("pagecache missing");
1.45      schwarze  140:                return (int)MANDOCLEVEL_BADARG;
1.19      schwarze  141:        }
                    142:
                    143:        if (-1 == munmap(pagecache, PC_PAGESIZE * PC_NUMPAGES)) {
                    144:                perror("munmap");
                    145:                pagecache = NULL;
1.45      schwarze  146:                return (int)MANDOCLEVEL_SYSERR;
1.19      schwarze  147:        }
                    148:
                    149:        pagecache = NULL;
1.45      schwarze  150:        return (int)MANDOCLEVEL_OK;
1.19      schwarze  151: }
1.1       schwarze  152:
                    153: int
                    154: mansearch(const struct mansearch *search,
1.3       schwarze  155:                const struct manpaths *paths,
                    156:                int argc, char *argv[],
1.1       schwarze  157:                struct manpage **res, size_t *sz)
                    158: {
1.22      schwarze  159:        int64_t          pageid;
1.11      schwarze  160:        uint64_t         outbit, iterbit;
1.1       schwarze  161:        char             buf[PATH_MAX];
1.2       schwarze  162:        char            *sql;
1.1       schwarze  163:        struct manpage  *mpage;
                    164:        struct expr     *e, *ep;
                    165:        sqlite3         *db;
1.3       schwarze  166:        sqlite3_stmt    *s, *s2;
1.1       schwarze  167:        struct match    *mp;
                    168:        struct ohash_info info;
                    169:        struct ohash     htab;
                    170:        unsigned int     idx;
                    171:        size_t           i, j, cur, maxres;
1.44      schwarze  172:        int              c, chdir_status, getcwd_status, indexbit;
                    173:
                    174:        if (argc == 0 || (e = exprcomp(search, argc, argv)) == NULL) {
                    175:                *sz = 0;
1.45      schwarze  176:                return 0;
1.44      schwarze  177:        }
1.1       schwarze  178:
1.27      espie     179:        info.calloc = hash_calloc;
1.1       schwarze  180:        info.alloc = hash_alloc;
1.27      espie     181:        info.free = hash_free;
1.22      schwarze  182:        info.key_offset = offsetof(struct match, pageid);
1.1       schwarze  183:
1.44      schwarze  184:        cur = maxres = 0;
1.1       schwarze  185:        *res = NULL;
                    186:
1.33      schwarze  187:        if (NULL != search->outkey) {
1.42      schwarze  188:                outbit = TYPE_Nd;
1.11      schwarze  189:                for (indexbit = 0, iterbit = 1;
                    190:                     indexbit < mansearch_keymax;
                    191:                     indexbit++, iterbit <<= 1) {
1.33      schwarze  192:                        if (0 == strcasecmp(search->outkey,
1.11      schwarze  193:                            mansearch_keynames[indexbit])) {
                    194:                                outbit = iterbit;
1.3       schwarze  195:                                break;
                    196:                        }
                    197:                }
1.42      schwarze  198:        } else
                    199:                outbit = 0;
1.3       schwarze  200:
1.1       schwarze  201:        /*
1.44      schwarze  202:         * Remember the original working directory, if possible.
                    203:         * This will be needed if the second or a later directory
                    204:         * is given as a relative path.
                    205:         * Do not error out if the current directory is not
                    206:         * searchable: Maybe it won't be needed after all.
1.1       schwarze  207:         */
                    208:
1.44      schwarze  209:        if (getcwd(buf, PATH_MAX) == NULL) {
                    210:                getcwd_status = 0;
                    211:                (void)strlcpy(buf, strerror(errno), sizeof(buf));
                    212:        } else
                    213:                getcwd_status = 1;
1.1       schwarze  214:
1.6       schwarze  215:        sql = sql_statement(e);
1.1       schwarze  216:
                    217:        /*
                    218:         * Loop over the directories (containing databases) for us to
                    219:         * search.
                    220:         * Don't let missing/bad databases/directories phase us.
                    221:         * In each, try to open the resident database and, if it opens,
                    222:         * scan it for our match expression.
                    223:         */
                    224:
1.44      schwarze  225:        chdir_status = 0;
1.1       schwarze  226:        for (i = 0; i < paths->sz; i++) {
1.44      schwarze  227:                if (chdir_status && paths->paths[i][0] != '/') {
                    228:                        if ( ! getcwd_status) {
1.46    ! schwarze  229:                                warnx("%s: getcwd: %s", paths->paths[i], buf);
1.44      schwarze  230:                                continue;
                    231:                        } else if (chdir(buf) == -1) {
                    232:                                perror(buf);
                    233:                                continue;
                    234:                        }
                    235:                }
                    236:                if (chdir(paths->paths[i]) == -1) {
1.1       schwarze  237:                        perror(paths->paths[i]);
                    238:                        continue;
1.24      schwarze  239:                }
1.44      schwarze  240:                chdir_status = 1;
1.1       schwarze  241:
1.24      schwarze  242:                c = sqlite3_open_v2(MANDOC_DB, &db,
                    243:                    SQLITE_OPEN_READONLY, NULL);
1.1       schwarze  244:
                    245:                if (SQLITE_OK != c) {
1.46    ! schwarze  246:                        warn("%s/%s", paths->paths[i], MANDOC_DB);
1.1       schwarze  247:                        sqlite3_close(db);
                    248:                        continue;
                    249:                }
                    250:
                    251:                /*
                    252:                 * Define the SQL functions for substring
                    253:                 * and regular expression matching.
                    254:                 */
                    255:
                    256:                c = sqlite3_create_function(db, "match", 2,
1.21      schwarze  257:                    SQLITE_UTF8 | SQLITE_DETERMINISTIC,
                    258:                    NULL, sql_match, NULL, NULL);
1.1       schwarze  259:                assert(SQLITE_OK == c);
                    260:                c = sqlite3_create_function(db, "regexp", 2,
1.21      schwarze  261:                    SQLITE_UTF8 | SQLITE_DETERMINISTIC,
                    262:                    NULL, sql_regexp, NULL, NULL);
1.1       schwarze  263:                assert(SQLITE_OK == c);
                    264:
                    265:                j = 1;
                    266:                c = sqlite3_prepare_v2(db, sql, -1, &s, NULL);
                    267:                if (SQLITE_OK != c)
1.46    ! schwarze  268:                        warnx("%s", sqlite3_errmsg(db));
1.1       schwarze  269:
                    270:                for (ep = e; NULL != ep; ep = ep->next) {
                    271:                        if (NULL == ep->substr) {
                    272:                                SQL_BIND_BLOB(db, s, j, ep->regexp);
                    273:                        } else
                    274:                                SQL_BIND_TEXT(db, s, j, ep->substr);
1.18      schwarze  275:                        if (0 == ((TYPE_Nd | TYPE_Nm) & ep->bits))
1.17      schwarze  276:                                SQL_BIND_INT64(db, s, j, ep->bits);
1.1       schwarze  277:                }
                    278:
                    279:                memset(&htab, 0, sizeof(struct ohash));
                    280:                ohash_init(&htab, 4, &info);
                    281:
                    282:                /*
                    283:                 * Hash each entry on its [unique] document identifier.
                    284:                 * This is a uint64_t.
                    285:                 * Instead of using a hash function, simply convert the
                    286:                 * uint64_t to a uint32_t, the hash value's type.
                    287:                 * This gives good performance and preserves the
                    288:                 * distribution of buckets in the table.
                    289:                 */
                    290:                while (SQLITE_ROW == (c = sqlite3_step(s))) {
1.22      schwarze  291:                        pageid = sqlite3_column_int64(s, 2);
1.24      schwarze  292:                        idx = ohash_lookup_memory(&htab,
                    293:                            (char *)&pageid, sizeof(uint64_t),
                    294:                            (uint32_t)pageid);
1.1       schwarze  295:
                    296:                        if (NULL != ohash_find(&htab, idx))
                    297:                                continue;
                    298:
                    299:                        mp = mandoc_calloc(1, sizeof(struct match));
1.22      schwarze  300:                        mp->pageid = pageid;
1.17      schwarze  301:                        mp->form = sqlite3_column_int(s, 1);
1.37      schwarze  302:                        mp->bits = sqlite3_column_int64(s, 3);
1.17      schwarze  303:                        if (TYPE_Nd == outbit)
1.30      schwarze  304:                                mp->desc = mandoc_strdup((const char *)
1.17      schwarze  305:                                    sqlite3_column_text(s, 0));
1.1       schwarze  306:                        ohash_insert(&htab, idx, mp);
                    307:                }
                    308:
                    309:                if (SQLITE_DONE != c)
1.46    ! schwarze  310:                        warnx("%s", sqlite3_errmsg(db));
1.1       schwarze  311:
                    312:                sqlite3_finalize(s);
                    313:
1.24      schwarze  314:                c = sqlite3_prepare_v2(db,
1.25      schwarze  315:                    "SELECT sec, arch, name, pageid FROM mlinks "
                    316:                    "WHERE pageid=? ORDER BY sec, arch, name",
1.1       schwarze  317:                    -1, &s, NULL);
                    318:                if (SQLITE_OK != c)
1.46    ! schwarze  319:                        warnx("%s", sqlite3_errmsg(db));
1.1       schwarze  320:
1.3       schwarze  321:                c = sqlite3_prepare_v2(db,
1.25      schwarze  322:                    "SELECT bits, key, pageid FROM keys "
                    323:                    "WHERE pageid=? AND bits & ?",
1.3       schwarze  324:                    -1, &s2, NULL);
                    325:                if (SQLITE_OK != c)
1.46    ! schwarze  326:                        warnx("%s", sqlite3_errmsg(db));
1.3       schwarze  327:
1.1       schwarze  328:                for (mp = ohash_first(&htab, &idx);
                    329:                                NULL != mp;
                    330:                                mp = ohash_next(&htab, &idx)) {
                    331:                        if (cur + 1 > maxres) {
                    332:                                maxres += 1024;
1.26      schwarze  333:                                *res = mandoc_reallocarray(*res,
                    334:                                    maxres, sizeof(struct manpage));
1.1       schwarze  335:                        }
                    336:                        mpage = *res + cur;
1.34      schwarze  337:                        mpage->ipath = i;
1.37      schwarze  338:                        mpage->bits = mp->bits;
1.29      schwarze  339:                        mpage->sec = 10;
1.1       schwarze  340:                        mpage->form = mp->form;
1.40      schwarze  341:                        buildnames(search, mpage, db, s, mp->pageid,
1.10      schwarze  342:                            paths->paths[i], mp->form);
1.40      schwarze  343:                        if (mpage->names != NULL) {
                    344:                                mpage->output = TYPE_Nd & outbit ?
                    345:                                    mp->desc : outbit ?
                    346:                                    buildoutput(db, s2, mp->pageid, outbit) :
                    347:                                    NULL;
                    348:                                cur++;
                    349:                        }
1.1       schwarze  350:                        free(mp);
                    351:                }
                    352:
                    353:                sqlite3_finalize(s);
1.3       schwarze  354:                sqlite3_finalize(s2);
1.1       schwarze  355:                sqlite3_close(db);
                    356:                ohash_delete(&htab);
1.36      schwarze  357:
                    358:                /*
                    359:                 * In man(1) mode, prefer matches in earlier trees
                    360:                 * over matches in later trees.
                    361:                 */
                    362:
                    363:                if (cur && search->firstmatch)
                    364:                        break;
1.1       schwarze  365:        }
1.29      schwarze  366:        qsort(*res, cur, sizeof(struct manpage), manpage_compare);
1.44      schwarze  367:        if (chdir_status && getcwd_status && chdir(buf) == -1)
                    368:                perror(buf);
1.1       schwarze  369:        exprfree(e);
                    370:        free(sql);
                    371:        *sz = cur;
1.45      schwarze  372:        return 1;
1.2       schwarze  373: }
                    374:
1.33      schwarze  375: void
                    376: mansearch_free(struct manpage *res, size_t sz)
                    377: {
                    378:        size_t   i;
                    379:
                    380:        for (i = 0; i < sz; i++) {
                    381:                free(res[i].file);
                    382:                free(res[i].names);
                    383:                free(res[i].output);
                    384:        }
                    385:        free(res);
                    386: }
                    387:
1.29      schwarze  388: static int
                    389: manpage_compare(const void *vp1, const void *vp2)
                    390: {
                    391:        const struct manpage    *mp1, *mp2;
                    392:        int                      diff;
                    393:
                    394:        mp1 = vp1;
                    395:        mp2 = vp2;
1.45      schwarze  396:        return (diff = mp2->bits - mp1->bits) ? diff :
                    397:            (diff = mp1->sec - mp2->sec) ? diff :
                    398:            strcasecmp(mp1->names, mp2->names);
1.29      schwarze  399: }
                    400:
1.8       schwarze  401: static void
1.40      schwarze  402: buildnames(const struct mansearch *search, struct manpage *mpage,
                    403:                sqlite3 *db, sqlite3_stmt *s,
1.22      schwarze  404:                uint64_t pageid, const char *path, int form)
1.2       schwarze  405: {
1.41      schwarze  406:        glob_t           globinfo;
                    407:        char            *firstname, *newnames, *prevsec, *prevarch;
1.10      schwarze  408:        const char      *oldnames, *sep1, *name, *sec, *sep2, *arch, *fsec;
1.2       schwarze  409:        size_t           i;
1.41      schwarze  410:        int              c, globres;
1.2       schwarze  411:
1.16      schwarze  412:        mpage->file = NULL;
1.8       schwarze  413:        mpage->names = NULL;
1.41      schwarze  414:        firstname = prevsec = prevarch = NULL;
1.2       schwarze  415:        i = 1;
1.22      schwarze  416:        SQL_BIND_INT64(db, s, i, pageid);
1.2       schwarze  417:        while (SQLITE_ROW == (c = sqlite3_step(s))) {
1.8       schwarze  418:
1.13      schwarze  419:                /* Decide whether we already have some names. */
1.8       schwarze  420:
                    421:                if (NULL == mpage->names) {
1.2       schwarze  422:                        oldnames = "";
                    423:                        sep1 = "";
                    424:                } else {
1.8       schwarze  425:                        oldnames = mpage->names;
1.2       schwarze  426:                        sep1 = ", ";
                    427:                }
1.13      schwarze  428:
1.40      schwarze  429:                /* Fetch the next name, rejecting sec/arch mismatches. */
1.13      schwarze  430:
1.30      schwarze  431:                sec = (const char *)sqlite3_column_text(s, 0);
1.40      schwarze  432:                if (search->sec != NULL && strcasecmp(sec, search->sec))
                    433:                        continue;
1.30      schwarze  434:                arch = (const char *)sqlite3_column_text(s, 1);
1.40      schwarze  435:                if (search->arch != NULL && *arch != '\0' &&
                    436:                    strcasecmp(arch, search->arch))
                    437:                        continue;
1.30      schwarze  438:                name = (const char *)sqlite3_column_text(s, 2);
1.29      schwarze  439:
                    440:                /* Remember the first section found. */
                    441:
                    442:                if (9 < mpage->sec && '1' <= *sec && '9' >= *sec)
                    443:                        mpage->sec = (*sec - '1') + 1;
1.13      schwarze  444:
                    445:                /* If the section changed, append the old one. */
                    446:
                    447:                if (NULL != prevsec &&
                    448:                    (strcmp(sec, prevsec) ||
                    449:                     strcmp(arch, prevarch))) {
                    450:                        sep2 = '\0' == *prevarch ? "" : "/";
1.15      schwarze  451:                        mandoc_asprintf(&newnames, "%s(%s%s%s)",
                    452:                            oldnames, prevsec, sep2, prevarch);
1.13      schwarze  453:                        free(mpage->names);
                    454:                        oldnames = mpage->names = newnames;
                    455:                        free(prevsec);
                    456:                        free(prevarch);
                    457:                        prevsec = prevarch = NULL;
                    458:                }
                    459:
                    460:                /* Save the new section, to append it later. */
                    461:
                    462:                if (NULL == prevsec) {
                    463:                        prevsec = mandoc_strdup(sec);
                    464:                        prevarch = mandoc_strdup(arch);
                    465:                }
                    466:
                    467:                /* Append the new name. */
                    468:
1.15      schwarze  469:                mandoc_asprintf(&newnames, "%s%s%s",
                    470:                    oldnames, sep1, name);
1.8       schwarze  471:                free(mpage->names);
                    472:                mpage->names = newnames;
                    473:
                    474:                /* Also save the first file name encountered. */
                    475:
1.38      schwarze  476:                if (mpage->file != NULL)
1.8       schwarze  477:                        continue;
                    478:
1.35      schwarze  479:                if (form & FORM_SRC) {
1.10      schwarze  480:                        sep1 = "man";
                    481:                        fsec = sec;
                    482:                } else {
                    483:                        sep1 = "cat";
                    484:                        fsec = "0";
                    485:                }
1.38      schwarze  486:                sep2 = *arch == '\0' ? "" : "/";
                    487:                mandoc_asprintf(&mpage->file, "%s/%s%s%s%s/%s.%s",
                    488:                    path, sep1, sec, sep2, arch, name, fsec);
1.41      schwarze  489:                if (access(mpage->file, R_OK) != -1)
                    490:                        continue;
                    491:
                    492:                /* Handle unusual file name extensions. */
                    493:
                    494:                if (firstname == NULL)
                    495:                        firstname = mpage->file;
                    496:                else
                    497:                        free(mpage->file);
                    498:                mandoc_asprintf(&mpage->file, "%s/%s%s%s%s/%s.*",
                    499:                    path, sep1, sec, sep2, arch, name);
                    500:                globres = glob(mpage->file, 0, NULL, &globinfo);
                    501:                free(mpage->file);
                    502:                mpage->file = globres ? NULL :
                    503:                    mandoc_strdup(*globinfo.gl_pathv);
                    504:                globfree(&globinfo);
1.2       schwarze  505:        }
1.38      schwarze  506:        if (c != SQLITE_DONE)
1.46    ! schwarze  507:                warnx("%s", sqlite3_errmsg(db));
1.2       schwarze  508:        sqlite3_reset(s);
1.41      schwarze  509:
                    510:        /* If none of the files is usable, use the first name. */
                    511:
                    512:        if (mpage->file == NULL)
                    513:                mpage->file = firstname;
                    514:        else if (mpage->file != firstname)
                    515:                free(firstname);
1.13      schwarze  516:
                    517:        /* Append one final section to the names. */
                    518:
1.38      schwarze  519:        if (prevsec != NULL) {
                    520:                sep2 = *prevarch == '\0' ? "" : "/";
1.15      schwarze  521:                mandoc_asprintf(&newnames, "%s(%s%s%s)",
                    522:                    mpage->names, prevsec, sep2, prevarch);
1.13      schwarze  523:                free(mpage->names);
                    524:                mpage->names = newnames;
                    525:                free(prevsec);
                    526:                free(prevarch);
                    527:        }
1.3       schwarze  528: }
                    529:
                    530: static char *
1.22      schwarze  531: buildoutput(sqlite3 *db, sqlite3_stmt *s, uint64_t pageid, uint64_t outbit)
1.3       schwarze  532: {
                    533:        char            *output, *newoutput;
                    534:        const char      *oldoutput, *sep1, *data;
                    535:        size_t           i;
                    536:        int              c;
                    537:
                    538:        output = NULL;
                    539:        i = 1;
1.22      schwarze  540:        SQL_BIND_INT64(db, s, i, pageid);
1.3       schwarze  541:        SQL_BIND_INT64(db, s, i, outbit);
                    542:        while (SQLITE_ROW == (c = sqlite3_step(s))) {
                    543:                if (NULL == output) {
                    544:                        oldoutput = "";
                    545:                        sep1 = "";
                    546:                } else {
                    547:                        oldoutput = output;
                    548:                        sep1 = " # ";
                    549:                }
1.30      schwarze  550:                data = (const char *)sqlite3_column_text(s, 1);
1.15      schwarze  551:                mandoc_asprintf(&newoutput, "%s%s%s",
                    552:                    oldoutput, sep1, data);
1.3       schwarze  553:                free(output);
                    554:                output = newoutput;
                    555:        }
                    556:        if (SQLITE_DONE != c)
1.46    ! schwarze  557:                warnx("%s", sqlite3_errmsg(db));
1.3       schwarze  558:        sqlite3_reset(s);
1.45      schwarze  559:        return output;
1.1       schwarze  560: }
                    561:
                    562: /*
                    563:  * Implement substring match as an application-defined SQL function.
                    564:  * Using the SQL LIKE or GLOB operators instead would be a bad idea
                    565:  * because that would require escaping metacharacters in the string
                    566:  * being searched for.
                    567:  */
                    568: static void
                    569: sql_match(sqlite3_context *context, int argc, sqlite3_value **argv)
                    570: {
                    571:
                    572:        assert(2 == argc);
                    573:        sqlite3_result_int(context, NULL != strcasestr(
                    574:            (const char *)sqlite3_value_text(argv[1]),
                    575:            (const char *)sqlite3_value_text(argv[0])));
                    576: }
                    577:
                    578: /*
                    579:  * Implement regular expression match
                    580:  * as an application-defined SQL function.
                    581:  */
                    582: static void
                    583: sql_regexp(sqlite3_context *context, int argc, sqlite3_value **argv)
                    584: {
                    585:
                    586:        assert(2 == argc);
                    587:        sqlite3_result_int(context, !regexec(
                    588:            (regex_t *)sqlite3_value_blob(argv[0]),
                    589:            (const char *)sqlite3_value_text(argv[1]),
                    590:            0, NULL, 0));
                    591: }
                    592:
1.4       schwarze  593: static void
                    594: sql_append(char **sql, size_t *sz, const char *newstr, int count)
                    595: {
                    596:        size_t           newsz;
                    597:
                    598:        newsz = 1 < count ? (size_t)count : strlen(newstr);
                    599:        *sql = mandoc_realloc(*sql, *sz + newsz + 1);
                    600:        if (1 < count)
                    601:                memset(*sql + *sz, *newstr, (size_t)count);
                    602:        else
                    603:                memcpy(*sql + *sz, newstr, newsz);
                    604:        *sz += newsz;
                    605:        (*sql)[*sz] = '\0';
                    606: }
                    607:
1.1       schwarze  608: /*
                    609:  * Prepare the search SQL statement.
                    610:  */
                    611: static char *
1.6       schwarze  612: sql_statement(const struct expr *e)
1.1       schwarze  613: {
                    614:        char            *sql;
                    615:        size_t           sz;
1.4       schwarze  616:        int              needop;
1.1       schwarze  617:
1.37      schwarze  618:        sql = mandoc_strdup(e->equal ?
                    619:            "SELECT desc, form, pageid, bits "
                    620:                "FROM mpages NATURAL JOIN names WHERE " :
                    621:            "SELECT desc, form, pageid, 0 FROM mpages WHERE ");
1.1       schwarze  622:        sz = strlen(sql);
                    623:
1.4       schwarze  624:        for (needop = 0; NULL != e; e = e->next) {
                    625:                if (e->and)
                    626:                        sql_append(&sql, &sz, " AND ", 1);
                    627:                else if (needop)
                    628:                        sql_append(&sql, &sz, " OR ", 1);
                    629:                if (e->open)
                    630:                        sql_append(&sql, &sz, "(", e->open);
1.17      schwarze  631:                sql_append(&sql, &sz,
                    632:                    TYPE_Nd & e->bits
                    633:                    ? (NULL == e->substr
                    634:                        ? "desc REGEXP ?"
                    635:                        : "desc MATCH ?")
1.18      schwarze  636:                    : TYPE_Nm == e->bits
                    637:                    ? (NULL == e->substr
1.22      schwarze  638:                        ? "pageid IN (SELECT pageid FROM names "
1.18      schwarze  639:                          "WHERE name REGEXP ?)"
1.28      schwarze  640:                        : e->equal
1.37      schwarze  641:                        ? "name = ? "
1.22      schwarze  642:                        : "pageid IN (SELECT pageid FROM names "
1.18      schwarze  643:                          "WHERE name MATCH ?)")
1.17      schwarze  644:                    : (NULL == e->substr
1.22      schwarze  645:                        ? "pageid IN (SELECT pageid FROM keys "
1.17      schwarze  646:                          "WHERE key REGEXP ? AND bits & ?)"
1.22      schwarze  647:                        : "pageid IN (SELECT pageid FROM keys "
1.17      schwarze  648:                          "WHERE key MATCH ? AND bits & ?)"), 1);
1.4       schwarze  649:                if (e->close)
                    650:                        sql_append(&sql, &sz, ")", e->close);
                    651:                needop = 1;
1.1       schwarze  652:        }
                    653:
1.45      schwarze  654:        return sql;
1.1       schwarze  655: }
                    656:
                    657: /*
                    658:  * Compile a set of string tokens into an expression.
                    659:  * Tokens in "argv" are assumed to be individual expression atoms (e.g.,
                    660:  * "(", "foo=bar", etc.).
                    661:  */
                    662: static struct expr *
                    663: exprcomp(const struct mansearch *search, int argc, char *argv[])
                    664: {
1.18      schwarze  665:        uint64_t         mask;
1.4       schwarze  666:        int              i, toopen, logic, igncase, toclose;
1.18      schwarze  667:        struct expr     *first, *prev, *cur, *next;
1.1       schwarze  668:
                    669:        first = cur = NULL;
1.40      schwarze  670:        logic = igncase = toopen = toclose = 0;
1.1       schwarze  671:
                    672:        for (i = 0; i < argc; i++) {
1.4       schwarze  673:                if (0 == strcmp("(", argv[i])) {
                    674:                        if (igncase)
                    675:                                goto fail;
                    676:                        toopen++;
                    677:                        toclose++;
                    678:                        continue;
                    679:                } else if (0 == strcmp(")", argv[i])) {
                    680:                        if (toopen || logic || igncase || NULL == cur)
                    681:                                goto fail;
                    682:                        cur->close++;
                    683:                        if (0 > --toclose)
                    684:                                goto fail;
                    685:                        continue;
                    686:                } else if (0 == strcmp("-a", argv[i])) {
                    687:                        if (toopen || logic || igncase || NULL == cur)
                    688:                                goto fail;
                    689:                        logic = 1;
                    690:                        continue;
                    691:                } else if (0 == strcmp("-o", argv[i])) {
                    692:                        if (toopen || logic || igncase || NULL == cur)
                    693:                                goto fail;
                    694:                        logic = 2;
                    695:                        continue;
                    696:                } else if (0 == strcmp("-i", argv[i])) {
                    697:                        if (igncase)
                    698:                                goto fail;
                    699:                        igncase = 1;
                    700:                        continue;
1.1       schwarze  701:                }
1.4       schwarze  702:                next = exprterm(search, argv[i], !igncase);
                    703:                if (NULL == next)
                    704:                        goto fail;
1.17      schwarze  705:                if (NULL == first)
                    706:                        first = next;
                    707:                else
1.1       schwarze  708:                        cur->next = next;
1.18      schwarze  709:                prev = cur = next;
1.17      schwarze  710:
                    711:                /*
                    712:                 * Searching for descriptions must be split out
                    713:                 * because they are stored in the mpages table,
                    714:                 * not in the keys table.
                    715:                 */
                    716:
1.18      schwarze  717:                for (mask = TYPE_Nm; mask <= TYPE_Nd; mask <<= 1) {
                    718:                        if (mask & cur->bits && ~mask & cur->bits) {
                    719:                                next = mandoc_calloc(1,
                    720:                                    sizeof(struct expr));
                    721:                                memcpy(next, cur, sizeof(struct expr));
                    722:                                prev->open = 1;
                    723:                                cur->bits = mask;
                    724:                                cur->next = next;
                    725:                                cur = next;
                    726:                                cur->bits &= ~mask;
                    727:                        }
                    728:                }
                    729:                prev->and = (1 == logic);
                    730:                prev->open += toopen;
                    731:                if (cur != prev)
1.17      schwarze  732:                        cur->close = 1;
1.18      schwarze  733:
1.4       schwarze  734:                toopen = logic = igncase = 0;
1.1       schwarze  735:        }
1.40      schwarze  736:        if ( ! (toopen || logic || igncase || toclose))
1.45      schwarze  737:                return first;
1.6       schwarze  738:
1.4       schwarze  739: fail:
                    740:        if (NULL != first)
                    741:                exprfree(first);
1.45      schwarze  742:        return NULL;
1.6       schwarze  743: }
                    744:
                    745: static struct expr *
1.1       schwarze  746: exprterm(const struct mansearch *search, char *buf, int cs)
                    747: {
1.6       schwarze  748:        char             errbuf[BUFSIZ];
1.1       schwarze  749:        struct expr     *e;
1.28      schwarze  750:        char            *key, *val;
1.11      schwarze  751:        uint64_t         iterbit;
                    752:        int              i, irc;
1.1       schwarze  753:
                    754:        if ('\0' == *buf)
1.45      schwarze  755:                return NULL;
1.1       schwarze  756:
                    757:        e = mandoc_calloc(1, sizeof(struct expr));
                    758:
1.33      schwarze  759:        if (search->argmode == ARG_NAME) {
                    760:                e->bits = TYPE_Nm;
1.1       schwarze  761:                e->substr = buf;
1.28      schwarze  762:                e->equal = 1;
1.45      schwarze  763:                return e;
1.1       schwarze  764:        }
                    765:
                    766:        /*
1.33      schwarze  767:         * Separate macro keys from search string.
                    768:         * If needed, request regular expression handling
                    769:         * by setting e->substr to NULL.
1.1       schwarze  770:         */
                    771:
1.33      schwarze  772:        if (search->argmode == ARG_WORD) {
                    773:                e->bits = TYPE_Nm;
                    774:                e->substr = NULL;
                    775:                mandoc_asprintf(&val, "[[:<:]]%s[[:>:]]", buf);
                    776:                cs = 0;
                    777:        } else if ((val = strpbrk(buf, "=~")) == NULL) {
                    778:                e->bits = TYPE_Nm | TYPE_Nd;
1.1       schwarze  779:                e->substr = buf;
1.28      schwarze  780:        } else {
                    781:                if (val == buf)
1.33      schwarze  782:                        e->bits = TYPE_Nm | TYPE_Nd;
1.28      schwarze  783:                if ('=' == *val)
                    784:                        e->substr = val + 1;
                    785:                *val++ = '\0';
1.12      schwarze  786:                if (NULL != strstr(buf, "arch"))
                    787:                        cs = 0;
1.28      schwarze  788:        }
                    789:
                    790:        /* Compile regular expressions. */
                    791:
                    792:        if (NULL == e->substr) {
                    793:                irc = regcomp(&e->regexp, val,
                    794:                    REG_EXTENDED | REG_NOSUB | (cs ? 0 : REG_ICASE));
1.33      schwarze  795:                if (search->argmode == ARG_WORD)
1.28      schwarze  796:                        free(val);
                    797:                if (irc) {
1.6       schwarze  798:                        regerror(irc, &e->regexp, errbuf, sizeof(errbuf));
1.46    ! schwarze  799:                        warnx("regcomp: %s", errbuf);
1.1       schwarze  800:                        free(e);
1.45      schwarze  801:                        return NULL;
1.1       schwarze  802:                }
1.28      schwarze  803:        }
                    804:
                    805:        if (e->bits)
1.45      schwarze  806:                return e;
1.1       schwarze  807:
                    808:        /*
                    809:         * Parse out all possible fields.
                    810:         * If the field doesn't resolve, bail.
                    811:         */
                    812:
                    813:        while (NULL != (key = strsep(&buf, ","))) {
                    814:                if ('\0' == *key)
                    815:                        continue;
1.11      schwarze  816:                for (i = 0, iterbit = 1;
                    817:                     i < mansearch_keymax;
                    818:                     i++, iterbit <<= 1) {
                    819:                        if (0 == strcasecmp(key,
                    820:                            mansearch_keynames[i])) {
                    821:                                e->bits |= iterbit;
                    822:                                break;
                    823:                        }
                    824:                }
                    825:                if (i == mansearch_keymax) {
                    826:                        if (strcasecmp(key, "any")) {
                    827:                                free(e);
1.45      schwarze  828:                                return NULL;
1.11      schwarze  829:                        }
                    830:                        e->bits |= ~0ULL;
1.1       schwarze  831:                }
                    832:        }
                    833:
1.45      schwarze  834:        return e;
1.1       schwarze  835: }
                    836:
                    837: static void
                    838: exprfree(struct expr *p)
                    839: {
                    840:        struct expr     *pp;
                    841:
                    842:        while (NULL != p) {
                    843:                pp = p->next;
                    844:                free(p);
                    845:                p = pp;
                    846:        }
                    847: }
                    848:
                    849: static void *
1.27      espie     850: hash_calloc(size_t nmemb, size_t sz, void *arg)
1.1       schwarze  851: {
                    852:
1.45      schwarze  853:        return mandoc_calloc(nmemb, sz);
1.1       schwarze  854: }
                    855:
                    856: static void *
                    857: hash_alloc(size_t sz, void *arg)
                    858: {
                    859:
1.45      schwarze  860:        return mandoc_malloc(sz);
1.1       schwarze  861: }
                    862:
                    863: static void
1.27      espie     864: hash_free(void *p, void *arg)
1.1       schwarze  865: {
                    866:
                    867:        free(p);
                    868: }