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

1.41    ! schwarze    1: /*     $OpenBSD: mansearch.c,v 1.40 2015/01/20 18:19:39 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:  *
                     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>
1.41    ! schwarze   26: #include <glob.h>
1.1       schwarze   27: #include <limits.h>
                     28: #include <regex.h>
                     29: #include <stdio.h>
                     30: #include <stdint.h>
                     31: #include <stddef.h>
                     32: #include <stdlib.h>
                     33: #include <string.h>
                     34: #include <unistd.h>
                     35:
                     36: #include <ohash.h>
                     37: #include <sqlite3.h>
                     38:
                     39: #include "mandoc.h"
1.14      schwarze   40: #include "mandoc_aux.h"
1.1       schwarze   41: #include "manpath.h"
                     42: #include "mansearch.h"
                     43:
1.11      schwarze   44: extern int mansearch_keymax;
                     45: extern const char *const mansearch_keynames[];
                     46:
1.1       schwarze   47: #define        SQL_BIND_TEXT(_db, _s, _i, _v) \
                     48:        do { if (SQLITE_OK != sqlite3_bind_text \
                     49:                ((_s), (_i)++, (_v), -1, SQLITE_STATIC)) \
                     50:                fprintf(stderr, "%s\n", sqlite3_errmsg((_db))); \
                     51:        } while (0)
                     52: #define        SQL_BIND_INT64(_db, _s, _i, _v) \
                     53:        do { if (SQLITE_OK != sqlite3_bind_int64 \
                     54:                ((_s), (_i)++, (_v))) \
                     55:                fprintf(stderr, "%s\n", sqlite3_errmsg((_db))); \
                     56:        } while (0)
                     57: #define        SQL_BIND_BLOB(_db, _s, _i, _v) \
                     58:        do { if (SQLITE_OK != sqlite3_bind_blob \
                     59:                ((_s), (_i)++, (&_v), sizeof(_v), SQLITE_STATIC)) \
                     60:                fprintf(stderr, "%s\n", sqlite3_errmsg((_db))); \
                     61:        } while (0)
                     62:
                     63: struct expr {
1.28      schwarze   64:        regex_t          regexp;  /* compiled regexp, if applicable */
                     65:        const char      *substr;  /* to search for, if applicable */
                     66:        struct expr     *next;    /* next in sequence */
1.24      schwarze   67:        uint64_t         bits;    /* type-mask */
1.28      schwarze   68:        int              equal;   /* equality, not subsring match */
1.4       schwarze   69:        int              open;    /* opening parentheses before */
                     70:        int              and;     /* logical AND before */
                     71:        int              close;   /* closing parentheses after */
1.1       schwarze   72: };
                     73:
                     74: struct match {
1.22      schwarze   75:        uint64_t         pageid; /* identifier in database */
1.37      schwarze   76:        uint64_t         bits; /* name type mask */
1.17      schwarze   77:        char            *desc; /* manual page description */
1.35      schwarze   78:        int              form; /* bit field: formatted, zipped? */
1.1       schwarze   79: };
                     80:
1.40      schwarze   81: static void             buildnames(const struct mansearch *,
                     82:                                struct manpage *, sqlite3 *,
1.10      schwarze   83:                                sqlite3_stmt *, uint64_t,
                     84:                                const char *, int form);
1.3       schwarze   85: static char            *buildoutput(sqlite3 *, sqlite3_stmt *,
                     86:                                 uint64_t, uint64_t);
1.1       schwarze   87: static void            *hash_alloc(size_t, void *);
1.27      espie      88: static void             hash_free(void *, void *);
                     89: static void            *hash_calloc(size_t, size_t, void *);
1.24      schwarze   90: static struct expr     *exprcomp(const struct mansearch *,
1.1       schwarze   91:                                int, char *[]);
                     92: static void             exprfree(struct expr *);
                     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.40      schwarze  338:                        buildnames(search, mpage, db, s, mp->pageid,
1.10      schwarze  339:                            paths->paths[i], mp->form);
1.40      schwarze  340:                        if (mpage->names != NULL) {
                    341:                                mpage->output = TYPE_Nd & outbit ?
                    342:                                    mp->desc : outbit ?
                    343:                                    buildoutput(db, s2, mp->pageid, outbit) :
                    344:                                    NULL;
                    345:                                cur++;
                    346:                        }
1.1       schwarze  347:                        free(mp);
                    348:                }
                    349:
                    350:                sqlite3_finalize(s);
1.3       schwarze  351:                sqlite3_finalize(s2);
1.1       schwarze  352:                sqlite3_close(db);
                    353:                ohash_delete(&htab);
1.36      schwarze  354:
                    355:                /*
                    356:                 * In man(1) mode, prefer matches in earlier trees
                    357:                 * over matches in later trees.
                    358:                 */
                    359:
                    360:                if (cur && search->firstmatch)
                    361:                        break;
1.1       schwarze  362:        }
1.29      schwarze  363:        qsort(*res, cur, sizeof(struct manpage), manpage_compare);
1.1       schwarze  364:        rc = 1;
                    365: out:
1.20      schwarze  366:        if (-1 != fd) {
                    367:                if (-1 == fchdir(fd))
                    368:                        perror(buf);
                    369:                close(fd);
                    370:        }
1.1       schwarze  371:        exprfree(e);
                    372:        free(sql);
                    373:        *sz = cur;
                    374:        return(rc);
1.2       schwarze  375: }
                    376:
1.33      schwarze  377: void
                    378: mansearch_free(struct manpage *res, size_t sz)
                    379: {
                    380:        size_t   i;
                    381:
                    382:        for (i = 0; i < sz; i++) {
                    383:                free(res[i].file);
                    384:                free(res[i].names);
                    385:                free(res[i].output);
                    386:        }
                    387:        free(res);
                    388: }
                    389:
1.29      schwarze  390: static int
                    391: manpage_compare(const void *vp1, const void *vp2)
                    392: {
                    393:        const struct manpage    *mp1, *mp2;
                    394:        int                      diff;
                    395:
                    396:        mp1 = vp1;
                    397:        mp2 = vp2;
1.37      schwarze  398:        return( (diff = mp2->bits - mp1->bits) ? diff :
                    399:                (diff = mp1->sec - mp2->sec) ? diff :
                    400:                strcasecmp(mp1->names, mp2->names));
1.29      schwarze  401: }
                    402:
1.8       schwarze  403: static void
1.40      schwarze  404: buildnames(const struct mansearch *search, struct manpage *mpage,
                    405:                sqlite3 *db, sqlite3_stmt *s,
1.22      schwarze  406:                uint64_t pageid, const char *path, int form)
1.2       schwarze  407: {
1.41    ! schwarze  408:        glob_t           globinfo;
        !           409:        char            *firstname, *newnames, *prevsec, *prevarch;
1.10      schwarze  410:        const char      *oldnames, *sep1, *name, *sec, *sep2, *arch, *fsec;
1.2       schwarze  411:        size_t           i;
1.41    ! schwarze  412:        int              c, globres;
1.2       schwarze  413:
1.16      schwarze  414:        mpage->file = NULL;
1.8       schwarze  415:        mpage->names = NULL;
1.41    ! schwarze  416:        firstname = prevsec = prevarch = NULL;
1.2       schwarze  417:        i = 1;
1.22      schwarze  418:        SQL_BIND_INT64(db, s, i, pageid);
1.2       schwarze  419:        while (SQLITE_ROW == (c = sqlite3_step(s))) {
1.8       schwarze  420:
1.13      schwarze  421:                /* Decide whether we already have some names. */
1.8       schwarze  422:
                    423:                if (NULL == mpage->names) {
1.2       schwarze  424:                        oldnames = "";
                    425:                        sep1 = "";
                    426:                } else {
1.8       schwarze  427:                        oldnames = mpage->names;
1.2       schwarze  428:                        sep1 = ", ";
                    429:                }
1.13      schwarze  430:
1.40      schwarze  431:                /* Fetch the next name, rejecting sec/arch mismatches. */
1.13      schwarze  432:
1.30      schwarze  433:                sec = (const char *)sqlite3_column_text(s, 0);
1.40      schwarze  434:                if (search->sec != NULL && strcasecmp(sec, search->sec))
                    435:                        continue;
1.30      schwarze  436:                arch = (const char *)sqlite3_column_text(s, 1);
1.40      schwarze  437:                if (search->arch != NULL && *arch != '\0' &&
                    438:                    strcasecmp(arch, search->arch))
                    439:                        continue;
1.30      schwarze  440:                name = (const char *)sqlite3_column_text(s, 2);
1.29      schwarze  441:
                    442:                /* Remember the first section found. */
                    443:
                    444:                if (9 < mpage->sec && '1' <= *sec && '9' >= *sec)
                    445:                        mpage->sec = (*sec - '1') + 1;
1.13      schwarze  446:
                    447:                /* If the section changed, append the old one. */
                    448:
                    449:                if (NULL != prevsec &&
                    450:                    (strcmp(sec, prevsec) ||
                    451:                     strcmp(arch, prevarch))) {
                    452:                        sep2 = '\0' == *prevarch ? "" : "/";
1.15      schwarze  453:                        mandoc_asprintf(&newnames, "%s(%s%s%s)",
                    454:                            oldnames, prevsec, sep2, prevarch);
1.13      schwarze  455:                        free(mpage->names);
                    456:                        oldnames = mpage->names = newnames;
                    457:                        free(prevsec);
                    458:                        free(prevarch);
                    459:                        prevsec = prevarch = NULL;
                    460:                }
                    461:
                    462:                /* Save the new section, to append it later. */
                    463:
                    464:                if (NULL == prevsec) {
                    465:                        prevsec = mandoc_strdup(sec);
                    466:                        prevarch = mandoc_strdup(arch);
                    467:                }
                    468:
                    469:                /* Append the new name. */
                    470:
1.15      schwarze  471:                mandoc_asprintf(&newnames, "%s%s%s",
                    472:                    oldnames, sep1, name);
1.8       schwarze  473:                free(mpage->names);
                    474:                mpage->names = newnames;
                    475:
                    476:                /* Also save the first file name encountered. */
                    477:
1.38      schwarze  478:                if (mpage->file != NULL)
1.8       schwarze  479:                        continue;
                    480:
1.35      schwarze  481:                if (form & FORM_SRC) {
1.10      schwarze  482:                        sep1 = "man";
                    483:                        fsec = sec;
                    484:                } else {
                    485:                        sep1 = "cat";
                    486:                        fsec = "0";
                    487:                }
1.38      schwarze  488:                sep2 = *arch == '\0' ? "" : "/";
                    489:                mandoc_asprintf(&mpage->file, "%s/%s%s%s%s/%s.%s",
                    490:                    path, sep1, sec, sep2, arch, name, fsec);
1.41    ! schwarze  491:                if (access(mpage->file, R_OK) != -1)
        !           492:                        continue;
        !           493:
        !           494:                /* Handle unusual file name extensions. */
        !           495:
        !           496:                if (firstname == NULL)
        !           497:                        firstname = mpage->file;
        !           498:                else
        !           499:                        free(mpage->file);
        !           500:                mandoc_asprintf(&mpage->file, "%s/%s%s%s%s/%s.*",
        !           501:                    path, sep1, sec, sep2, arch, name);
        !           502:                globres = glob(mpage->file, 0, NULL, &globinfo);
        !           503:                free(mpage->file);
        !           504:                mpage->file = globres ? NULL :
        !           505:                    mandoc_strdup(*globinfo.gl_pathv);
        !           506:                globfree(&globinfo);
1.2       schwarze  507:        }
1.38      schwarze  508:        if (c != SQLITE_DONE)
1.2       schwarze  509:                fprintf(stderr, "%s\n", sqlite3_errmsg(db));
                    510:        sqlite3_reset(s);
1.41    ! schwarze  511:
        !           512:        /* If none of the files is usable, use the first name. */
        !           513:
        !           514:        if (mpage->file == NULL)
        !           515:                mpage->file = firstname;
        !           516:        else if (mpage->file != firstname)
        !           517:                free(firstname);
1.13      schwarze  518:
                    519:        /* Append one final section to the names. */
                    520:
1.38      schwarze  521:        if (prevsec != NULL) {
                    522:                sep2 = *prevarch == '\0' ? "" : "/";
1.15      schwarze  523:                mandoc_asprintf(&newnames, "%s(%s%s%s)",
                    524:                    mpage->names, prevsec, sep2, prevarch);
1.13      schwarze  525:                free(mpage->names);
                    526:                mpage->names = newnames;
                    527:                free(prevsec);
                    528:                free(prevarch);
                    529:        }
1.3       schwarze  530: }
                    531:
                    532: static char *
1.22      schwarze  533: buildoutput(sqlite3 *db, sqlite3_stmt *s, uint64_t pageid, uint64_t outbit)
1.3       schwarze  534: {
                    535:        char            *output, *newoutput;
                    536:        const char      *oldoutput, *sep1, *data;
                    537:        size_t           i;
                    538:        int              c;
                    539:
                    540:        output = NULL;
                    541:        i = 1;
1.22      schwarze  542:        SQL_BIND_INT64(db, s, i, pageid);
1.3       schwarze  543:        SQL_BIND_INT64(db, s, i, outbit);
                    544:        while (SQLITE_ROW == (c = sqlite3_step(s))) {
                    545:                if (NULL == output) {
                    546:                        oldoutput = "";
                    547:                        sep1 = "";
                    548:                } else {
                    549:                        oldoutput = output;
                    550:                        sep1 = " # ";
                    551:                }
1.30      schwarze  552:                data = (const char *)sqlite3_column_text(s, 1);
1.15      schwarze  553:                mandoc_asprintf(&newoutput, "%s%s%s",
                    554:                    oldoutput, sep1, data);
1.3       schwarze  555:                free(output);
                    556:                output = newoutput;
                    557:        }
                    558:        if (SQLITE_DONE != c)
                    559:                fprintf(stderr, "%s\n", sqlite3_errmsg(db));
                    560:        sqlite3_reset(s);
                    561:        return(output);
1.1       schwarze  562: }
                    563:
                    564: /*
                    565:  * Implement substring match as an application-defined SQL function.
                    566:  * Using the SQL LIKE or GLOB operators instead would be a bad idea
                    567:  * because that would require escaping metacharacters in the string
                    568:  * being searched for.
                    569:  */
                    570: static void
                    571: sql_match(sqlite3_context *context, int argc, sqlite3_value **argv)
                    572: {
                    573:
                    574:        assert(2 == argc);
                    575:        sqlite3_result_int(context, NULL != strcasestr(
                    576:            (const char *)sqlite3_value_text(argv[1]),
                    577:            (const char *)sqlite3_value_text(argv[0])));
                    578: }
                    579:
                    580: /*
                    581:  * Implement regular expression match
                    582:  * as an application-defined SQL function.
                    583:  */
                    584: static void
                    585: sql_regexp(sqlite3_context *context, int argc, sqlite3_value **argv)
                    586: {
                    587:
                    588:        assert(2 == argc);
                    589:        sqlite3_result_int(context, !regexec(
                    590:            (regex_t *)sqlite3_value_blob(argv[0]),
                    591:            (const char *)sqlite3_value_text(argv[1]),
                    592:            0, NULL, 0));
                    593: }
                    594:
1.4       schwarze  595: static void
                    596: sql_append(char **sql, size_t *sz, const char *newstr, int count)
                    597: {
                    598:        size_t           newsz;
                    599:
                    600:        newsz = 1 < count ? (size_t)count : strlen(newstr);
                    601:        *sql = mandoc_realloc(*sql, *sz + newsz + 1);
                    602:        if (1 < count)
                    603:                memset(*sql + *sz, *newstr, (size_t)count);
                    604:        else
                    605:                memcpy(*sql + *sz, newstr, newsz);
                    606:        *sz += newsz;
                    607:        (*sql)[*sz] = '\0';
                    608: }
                    609:
1.1       schwarze  610: /*
                    611:  * Prepare the search SQL statement.
                    612:  */
                    613: static char *
1.6       schwarze  614: sql_statement(const struct expr *e)
1.1       schwarze  615: {
                    616:        char            *sql;
                    617:        size_t           sz;
1.4       schwarze  618:        int              needop;
1.1       schwarze  619:
1.37      schwarze  620:        sql = mandoc_strdup(e->equal ?
                    621:            "SELECT desc, form, pageid, bits "
                    622:                "FROM mpages NATURAL JOIN names WHERE " :
                    623:            "SELECT desc, form, pageid, 0 FROM mpages WHERE ");
1.1       schwarze  624:        sz = strlen(sql);
                    625:
1.4       schwarze  626:        for (needop = 0; NULL != e; e = e->next) {
                    627:                if (e->and)
                    628:                        sql_append(&sql, &sz, " AND ", 1);
                    629:                else if (needop)
                    630:                        sql_append(&sql, &sz, " OR ", 1);
                    631:                if (e->open)
                    632:                        sql_append(&sql, &sz, "(", e->open);
1.17      schwarze  633:                sql_append(&sql, &sz,
                    634:                    TYPE_Nd & e->bits
                    635:                    ? (NULL == e->substr
                    636:                        ? "desc REGEXP ?"
                    637:                        : "desc MATCH ?")
1.18      schwarze  638:                    : TYPE_Nm == e->bits
                    639:                    ? (NULL == e->substr
1.22      schwarze  640:                        ? "pageid IN (SELECT pageid FROM names "
1.18      schwarze  641:                          "WHERE name REGEXP ?)"
1.28      schwarze  642:                        : e->equal
1.37      schwarze  643:                        ? "name = ? "
1.22      schwarze  644:                        : "pageid IN (SELECT pageid FROM names "
1.18      schwarze  645:                          "WHERE name MATCH ?)")
1.17      schwarze  646:                    : (NULL == e->substr
1.22      schwarze  647:                        ? "pageid IN (SELECT pageid FROM keys "
1.17      schwarze  648:                          "WHERE key REGEXP ? AND bits & ?)"
1.22      schwarze  649:                        : "pageid IN (SELECT pageid FROM keys "
1.17      schwarze  650:                          "WHERE key MATCH ? AND bits & ?)"), 1);
1.4       schwarze  651:                if (e->close)
                    652:                        sql_append(&sql, &sz, ")", e->close);
                    653:                needop = 1;
1.1       schwarze  654:        }
                    655:
                    656:        return(sql);
                    657: }
                    658:
                    659: /*
                    660:  * Compile a set of string tokens into an expression.
                    661:  * Tokens in "argv" are assumed to be individual expression atoms (e.g.,
                    662:  * "(", "foo=bar", etc.).
                    663:  */
                    664: static struct expr *
                    665: exprcomp(const struct mansearch *search, int argc, char *argv[])
                    666: {
1.18      schwarze  667:        uint64_t         mask;
1.4       schwarze  668:        int              i, toopen, logic, igncase, toclose;
1.18      schwarze  669:        struct expr     *first, *prev, *cur, *next;
1.1       schwarze  670:
                    671:        first = cur = NULL;
1.40      schwarze  672:        logic = igncase = toopen = toclose = 0;
1.1       schwarze  673:
                    674:        for (i = 0; i < argc; i++) {
1.4       schwarze  675:                if (0 == strcmp("(", argv[i])) {
                    676:                        if (igncase)
                    677:                                goto fail;
                    678:                        toopen++;
                    679:                        toclose++;
                    680:                        continue;
                    681:                } else if (0 == strcmp(")", argv[i])) {
                    682:                        if (toopen || logic || igncase || NULL == cur)
                    683:                                goto fail;
                    684:                        cur->close++;
                    685:                        if (0 > --toclose)
                    686:                                goto fail;
                    687:                        continue;
                    688:                } else if (0 == strcmp("-a", argv[i])) {
                    689:                        if (toopen || logic || igncase || NULL == cur)
                    690:                                goto fail;
                    691:                        logic = 1;
                    692:                        continue;
                    693:                } else if (0 == strcmp("-o", argv[i])) {
                    694:                        if (toopen || logic || igncase || NULL == cur)
                    695:                                goto fail;
                    696:                        logic = 2;
                    697:                        continue;
                    698:                } else if (0 == strcmp("-i", argv[i])) {
                    699:                        if (igncase)
                    700:                                goto fail;
                    701:                        igncase = 1;
                    702:                        continue;
1.1       schwarze  703:                }
1.4       schwarze  704:                next = exprterm(search, argv[i], !igncase);
                    705:                if (NULL == next)
                    706:                        goto fail;
1.17      schwarze  707:                if (NULL == first)
                    708:                        first = next;
                    709:                else
1.1       schwarze  710:                        cur->next = next;
1.18      schwarze  711:                prev = cur = next;
1.17      schwarze  712:
                    713:                /*
                    714:                 * Searching for descriptions must be split out
                    715:                 * because they are stored in the mpages table,
                    716:                 * not in the keys table.
                    717:                 */
                    718:
1.18      schwarze  719:                for (mask = TYPE_Nm; mask <= TYPE_Nd; mask <<= 1) {
                    720:                        if (mask & cur->bits && ~mask & cur->bits) {
                    721:                                next = mandoc_calloc(1,
                    722:                                    sizeof(struct expr));
                    723:                                memcpy(next, cur, sizeof(struct expr));
                    724:                                prev->open = 1;
                    725:                                cur->bits = mask;
                    726:                                cur->next = next;
                    727:                                cur = next;
                    728:                                cur->bits &= ~mask;
                    729:                        }
                    730:                }
                    731:                prev->and = (1 == logic);
                    732:                prev->open += toopen;
                    733:                if (cur != prev)
1.17      schwarze  734:                        cur->close = 1;
1.18      schwarze  735:
1.4       schwarze  736:                toopen = logic = igncase = 0;
1.1       schwarze  737:        }
1.40      schwarze  738:        if ( ! (toopen || logic || igncase || toclose))
                    739:                return(first);
1.6       schwarze  740:
1.4       schwarze  741: fail:
                    742:        if (NULL != first)
                    743:                exprfree(first);
                    744:        return(NULL);
1.6       schwarze  745: }
                    746:
                    747: static struct expr *
1.1       schwarze  748: exprterm(const struct mansearch *search, char *buf, int cs)
                    749: {
1.6       schwarze  750:        char             errbuf[BUFSIZ];
1.1       schwarze  751:        struct expr     *e;
1.28      schwarze  752:        char            *key, *val;
1.11      schwarze  753:        uint64_t         iterbit;
                    754:        int              i, irc;
1.1       schwarze  755:
                    756:        if ('\0' == *buf)
                    757:                return(NULL);
                    758:
                    759:        e = mandoc_calloc(1, sizeof(struct expr));
                    760:
1.33      schwarze  761:        if (search->argmode == ARG_NAME) {
                    762:                e->bits = TYPE_Nm;
1.1       schwarze  763:                e->substr = buf;
1.28      schwarze  764:                e->equal = 1;
1.1       schwarze  765:                return(e);
                    766:        }
                    767:
                    768:        /*
1.33      schwarze  769:         * Separate macro keys from search string.
                    770:         * If needed, request regular expression handling
                    771:         * by setting e->substr to NULL.
1.1       schwarze  772:         */
                    773:
1.33      schwarze  774:        if (search->argmode == ARG_WORD) {
                    775:                e->bits = TYPE_Nm;
                    776:                e->substr = NULL;
                    777:                mandoc_asprintf(&val, "[[:<:]]%s[[:>:]]", buf);
                    778:                cs = 0;
                    779:        } else if ((val = strpbrk(buf, "=~")) == NULL) {
                    780:                e->bits = TYPE_Nm | TYPE_Nd;
1.1       schwarze  781:                e->substr = buf;
1.28      schwarze  782:        } else {
                    783:                if (val == buf)
1.33      schwarze  784:                        e->bits = TYPE_Nm | TYPE_Nd;
1.28      schwarze  785:                if ('=' == *val)
                    786:                        e->substr = val + 1;
                    787:                *val++ = '\0';
1.12      schwarze  788:                if (NULL != strstr(buf, "arch"))
                    789:                        cs = 0;
1.28      schwarze  790:        }
                    791:
                    792:        /* Compile regular expressions. */
                    793:
                    794:        if (NULL == e->substr) {
                    795:                irc = regcomp(&e->regexp, val,
                    796:                    REG_EXTENDED | REG_NOSUB | (cs ? 0 : REG_ICASE));
1.33      schwarze  797:                if (search->argmode == ARG_WORD)
1.28      schwarze  798:                        free(val);
                    799:                if (irc) {
1.6       schwarze  800:                        regerror(irc, &e->regexp, errbuf, sizeof(errbuf));
                    801:                        fprintf(stderr, "regcomp: %s\n", errbuf);
1.1       schwarze  802:                        free(e);
                    803:                        return(NULL);
                    804:                }
1.28      schwarze  805:        }
                    806:
                    807:        if (e->bits)
                    808:                return(e);
1.1       schwarze  809:
                    810:        /*
                    811:         * Parse out all possible fields.
                    812:         * If the field doesn't resolve, bail.
                    813:         */
                    814:
                    815:        while (NULL != (key = strsep(&buf, ","))) {
                    816:                if ('\0' == *key)
                    817:                        continue;
1.11      schwarze  818:                for (i = 0, iterbit = 1;
                    819:                     i < mansearch_keymax;
                    820:                     i++, iterbit <<= 1) {
                    821:                        if (0 == strcasecmp(key,
                    822:                            mansearch_keynames[i])) {
                    823:                                e->bits |= iterbit;
                    824:                                break;
                    825:                        }
                    826:                }
                    827:                if (i == mansearch_keymax) {
                    828:                        if (strcasecmp(key, "any")) {
                    829:                                free(e);
                    830:                                return(NULL);
                    831:                        }
                    832:                        e->bits |= ~0ULL;
1.1       schwarze  833:                }
                    834:        }
                    835:
                    836:        return(e);
                    837: }
                    838:
                    839: static void
                    840: exprfree(struct expr *p)
                    841: {
                    842:        struct expr     *pp;
                    843:
                    844:        while (NULL != p) {
                    845:                pp = p->next;
                    846:                free(p);
                    847:                p = pp;
                    848:        }
                    849: }
                    850:
                    851: static void *
1.27      espie     852: hash_calloc(size_t nmemb, size_t sz, void *arg)
1.1       schwarze  853: {
                    854:
1.27      espie     855:        return(mandoc_calloc(nmemb, sz));
1.1       schwarze  856: }
                    857:
                    858: static void *
                    859: hash_alloc(size_t sz, void *arg)
                    860: {
                    861:
                    862:        return(mandoc_malloc(sz));
                    863: }
                    864:
                    865: static void
1.27      espie     866: hash_free(void *p, void *arg)
1.1       schwarze  867: {
                    868:
                    869:        free(p);
                    870: }