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

Annotation of mandoc/mansearch.c, Revision 1.28

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

CVSweb