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

Annotation of mandoc/mansearch.c, Revision 1.59

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

CVSweb