[BACK]Return to mansearch.c CVS log [TXT][DIR] Up to [cvsweb.bsd.lv] / mandoc

Annotation of mandoc/mansearch.c, Revision 1.39

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

CVSweb