[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.39

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