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

Annotation of mandoc/mansearch.c, Revision 1.62

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

CVSweb