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

Annotation of mandoc/mansearch.c, Revision 1.50

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

CVSweb