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

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