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

Annotation of mandoc/db.c, Revision 1.2

1.2     ! kristaps    1: /*     $Id: db.c,v 1.1 2011/11/09 01:24:23 kristaps Exp $ */
1.1       kristaps    2: /*
                      3:  * Copyright (c) 2011 Kristaps Dzonsons <kristaps@bsd.lv>
                      4:  *
                      5:  * Permission to use, copy, modify, and distribute this software for any
                      6:  * purpose with or without fee is hereby granted, provided that the above
                      7:  * copyright notice and this permission notice appear in all copies.
                      8:  *
                      9:  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
                     10:  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
                     11:  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
                     12:  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
                     13:  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
                     14:  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
                     15:  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
                     16:  */
                     17: #include <assert.h>
                     18: #include <fcntl.h>
                     19: #include <regex.h>
                     20: #include <stdarg.h>
                     21: #include <stdlib.h>
                     22: #include <string.h>
                     23:
                     24: #ifdef __linux__
                     25: # include <db_185.h>
                     26: #else
                     27: # include <db.h>
                     28: #endif
                     29:
                     30: #include "apropos.h"
                     31: #include "mandoc.h"
                     32:
1.2     ! kristaps   33: enum   match {
        !            34:        MATCH_REGEX,
        !            35:        MATCH_REGEXCASE,
        !            36:        MATCH_STR,
        !            37:        MATCH_STRCASE
        !            38: };
        !            39:
        !            40: struct expr {
        !            41:        enum match       match;
        !            42:        int              mask;
        !            43:        char            *v;
        !            44:        regex_t          re;
        !            45: };
        !            46:
        !            47: struct type {
        !            48:        int              mask;
        !            49:        const char      *name;
        !            50: };
        !            51:
        !            52: static const struct type types[] = {
        !            53:        { TYPE_NAME, "name" },
        !            54:        { TYPE_FUNCTION, "func" },
        !            55:        { TYPE_UTILITY, "utility" },
        !            56:        { TYPE_INCLUDES, "incl" },
        !            57:        { TYPE_VARIABLE, "var" },
        !            58:        { TYPE_STANDARD, "stand" },
        !            59:        { TYPE_AUTHOR, "auth" },
        !            60:        { TYPE_CONFIG, "conf" },
        !            61:        { TYPE_DESC, "desc" },
        !            62:        { TYPE_XREF, "xref" },
        !            63:        { TYPE_PATH, "path" },
        !            64:        { TYPE_ENV, "env" },
        !            65:        { TYPE_ERR, "err" },
        !            66:        { INT_MAX, "all" },
        !            67:        { 0, NULL }
        !            68: };
        !            69:
1.1       kristaps   70: static DB      *btree_open(void);
                     71: static int      btree_read(const DBT *, const struct mchars *, char **);
1.2     ! kristaps   72: static int      exprexec(const struct expr *, char *);
1.1       kristaps   73: static DB      *index_open(void);
                     74: static int      index_read(const DBT *, const DBT *,
                     75:                        const struct mchars *, struct rec *);
                     76: static void     norm_string(const char *,
                     77:                        const struct mchars *, char **);
                     78: static size_t   norm_utf8(unsigned int, char[7]);
                     79:
                     80: /*
                     81:  * Open the keyword mandoc-db database.
                     82:  */
                     83: static DB *
                     84: btree_open(void)
                     85: {
                     86:        BTREEINFO        info;
                     87:        DB              *db;
                     88:
                     89:        memset(&info, 0, sizeof(BTREEINFO));
                     90:        info.flags = R_DUP;
                     91:
                     92:        db = dbopen("mandoc.db", O_RDONLY, 0, DB_BTREE, &info);
                     93:        if (NULL != db)
                     94:                return(db);
                     95:
                     96:        return(NULL);
                     97: }
                     98:
                     99: /*
                    100:  * Read a keyword from the database and normalise it.
                    101:  * Return 0 if the database is insane, else 1.
                    102:  */
                    103: static int
                    104: btree_read(const DBT *v, const struct mchars *mc, char **buf)
                    105: {
                    106:
                    107:        /* Sanity: are we nil-terminated? */
                    108:
                    109:        assert(v->size > 0);
                    110:        if ('\0' != ((char *)v->data)[(int)v->size - 1])
                    111:                return(0);
                    112:
                    113:        norm_string((char *)v->data, mc, buf);
                    114:        return(1);
                    115: }
                    116:
                    117: /*
                    118:  * Take a Unicode codepoint and produce its UTF-8 encoding.
                    119:  * This isn't the best way to do this, but it works.
                    120:  * The magic numbers are from the UTF-8 packaging.
                    121:  * They're not as scary as they seem: read the UTF-8 spec for details.
                    122:  */
                    123: static size_t
                    124: norm_utf8(unsigned int cp, char out[7])
                    125: {
                    126:        size_t           rc;
                    127:
                    128:        rc = 0;
                    129:
                    130:        if (cp <= 0x0000007F) {
                    131:                rc = 1;
                    132:                out[0] = (char)cp;
                    133:        } else if (cp <= 0x000007FF) {
                    134:                rc = 2;
                    135:                out[0] = (cp >> 6  & 31) | 192;
                    136:                out[1] = (cp       & 63) | 128;
                    137:        } else if (cp <= 0x0000FFFF) {
                    138:                rc = 3;
                    139:                out[0] = (cp >> 12 & 15) | 224;
                    140:                out[1] = (cp >> 6  & 63) | 128;
                    141:                out[2] = (cp       & 63) | 128;
                    142:        } else if (cp <= 0x001FFFFF) {
                    143:                rc = 4;
                    144:                out[0] = (cp >> 18 & 7) | 240;
                    145:                out[1] = (cp >> 12 & 63) | 128;
                    146:                out[2] = (cp >> 6  & 63) | 128;
                    147:                out[3] = (cp       & 63) | 128;
                    148:        } else if (cp <= 0x03FFFFFF) {
                    149:                rc = 5;
                    150:                out[0] = (cp >> 24 & 3) | 248;
                    151:                out[1] = (cp >> 18 & 63) | 128;
                    152:                out[2] = (cp >> 12 & 63) | 128;
                    153:                out[3] = (cp >> 6  & 63) | 128;
                    154:                out[4] = (cp       & 63) | 128;
                    155:        } else if (cp <= 0x7FFFFFFF) {
                    156:                rc = 6;
                    157:                out[0] = (cp >> 30 & 1) | 252;
                    158:                out[1] = (cp >> 24 & 63) | 128;
                    159:                out[2] = (cp >> 18 & 63) | 128;
                    160:                out[3] = (cp >> 12 & 63) | 128;
                    161:                out[4] = (cp >> 6  & 63) | 128;
                    162:                out[5] = (cp       & 63) | 128;
                    163:        } else
                    164:                return(0);
                    165:
                    166:        out[rc] = '\0';
                    167:        return(rc);
                    168: }
                    169:
                    170: /*
                    171:  * Normalise strings from the index and database.
                    172:  * These strings are escaped as defined by mandoc_char(7) along with
                    173:  * other goop in mandoc.h (e.g., soft hyphens).
                    174:  * This function normalises these into a nice UTF-8 string.
                    175:  * Returns 0 if the database is fucked.
                    176:  */
                    177: static void
                    178: norm_string(const char *val, const struct mchars *mc, char **buf)
                    179: {
                    180:        size_t            sz, bsz;
                    181:        char              utfbuf[7];
                    182:        const char       *seq, *cpp;
                    183:        int               len, u, pos;
                    184:        enum mandoc_esc   esc;
                    185:        static const char res[] = { '\\', '\t',
                    186:                                ASCII_NBRSP, ASCII_HYPH, '\0' };
                    187:
                    188:        /* Pre-allocate by the length of the input */
                    189:
                    190:        bsz = strlen(val) + 1;
                    191:        *buf = mandoc_realloc(*buf, bsz);
                    192:        pos = 0;
                    193:
                    194:        while ('\0' != *val) {
                    195:                /*
                    196:                 * Halt on the first escape sequence.
                    197:                 * This also halts on the end of string, in which case
                    198:                 * we just copy, fallthrough, and exit the loop.
                    199:                 */
                    200:                if ((sz = strcspn(val, res)) > 0) {
                    201:                        memcpy(&(*buf)[pos], val, sz);
                    202:                        pos += (int)sz;
                    203:                        val += (int)sz;
                    204:                }
                    205:
                    206:                if (ASCII_HYPH == *val) {
                    207:                        (*buf)[pos++] = '-';
                    208:                        val++;
                    209:                        continue;
                    210:                } else if ('\t' == *val || ASCII_NBRSP == *val) {
                    211:                        (*buf)[pos++] = ' ';
                    212:                        val++;
                    213:                        continue;
                    214:                } else if ('\\' != *val)
                    215:                        break;
                    216:
                    217:                /* Read past the slash. */
                    218:
                    219:                val++;
                    220:                u = 0;
                    221:
                    222:                /*
                    223:                 * Parse the escape sequence and see if it's a
                    224:                 * predefined character or special character.
                    225:                 */
                    226:
                    227:                esc = mandoc_escape(&val, &seq, &len);
                    228:                if (ESCAPE_ERROR == esc)
                    229:                        break;
                    230:
                    231:                /*
                    232:                 * XXX - this just does UTF-8, but we need to know
                    233:                 * beforehand whether we should do text substitution.
                    234:                 */
                    235:
                    236:                switch (esc) {
                    237:                case (ESCAPE_SPECIAL):
                    238:                        if (0 != (u = mchars_spec2cp(mc, seq, len)))
                    239:                                break;
                    240:                        /* FALLTHROUGH */
                    241:                default:
                    242:                        continue;
                    243:                }
                    244:
                    245:                /*
                    246:                 * If we have a Unicode codepoint, try to convert that
                    247:                 * to a UTF-8 byte string.
                    248:                 */
                    249:
                    250:                cpp = utfbuf;
                    251:                if (0 == (sz = norm_utf8(u, utfbuf)))
                    252:                        continue;
                    253:
                    254:                /* Copy the rendered glyph into the stream. */
                    255:
                    256:                sz = strlen(cpp);
                    257:                bsz += sz;
                    258:
                    259:                *buf = mandoc_realloc(*buf, bsz);
                    260:
                    261:                memcpy(&(*buf)[pos], cpp, sz);
                    262:                pos += (int)sz;
                    263:        }
                    264:
                    265:        (*buf)[pos] = '\0';
                    266: }
                    267:
                    268: /*
                    269:  * Open the filename-index mandoc-db database.
                    270:  * Returns NULL if opening failed.
                    271:  */
                    272: static DB *
                    273: index_open(void)
                    274: {
                    275:        DB              *db;
                    276:
                    277:        db = dbopen("mandoc.index", O_RDONLY, 0, DB_RECNO, NULL);
                    278:        if (NULL != db)
                    279:                return(db);
                    280:
                    281:        return(NULL);
                    282: }
                    283:
                    284: /*
                    285:  * Safely unpack from an index file record into the structure.
                    286:  * Returns 1 if an entry was unpacked, 0 if the database is insane.
                    287:  */
                    288: static int
                    289: index_read(const DBT *key, const DBT *val,
                    290:                const struct mchars *mc, struct rec *rec)
                    291: {
                    292:        size_t           left;
                    293:        char            *np, *cp;
                    294:
                    295: #define        INDEX_BREAD(_dst) \
                    296:        do { \
                    297:                if (NULL == (np = memchr(cp, '\0', left))) \
                    298:                        return(0); \
                    299:                norm_string(cp, mc, &(_dst)); \
                    300:                left -= (np - cp) + 1; \
                    301:                cp = np + 1; \
                    302:        } while (/* CONSTCOND */ 0)
                    303:
                    304:        left = val->size;
                    305:        cp = (char *)val->data;
                    306:
                    307:        rec->rec = *(recno_t *)key->data;
                    308:
                    309:        INDEX_BREAD(rec->file);
                    310:        INDEX_BREAD(rec->cat);
                    311:        INDEX_BREAD(rec->title);
                    312:        INDEX_BREAD(rec->arch);
                    313:        INDEX_BREAD(rec->desc);
                    314:        return(1);
                    315: }
                    316:
                    317: /*
1.2     ! kristaps  318:  * Search the mandocdb database for the expression "expr".
1.1       kristaps  319:  * Filter out by "opts".
                    320:  * Call "res" with the results, which may be zero.
                    321:  */
                    322: void
1.2     ! kristaps  323: apropos_search(const struct opts *opts, const struct expr *expr,
        !           324:                void *arg, void (*res)(struct rec *, size_t, void *))
1.1       kristaps  325: {
                    326:        int              i, len, root, leaf;
                    327:        DBT              key, val;
                    328:        DB              *btree, *idx;
                    329:        struct mchars   *mc;
                    330:        int              ch;
                    331:        char            *buf;
                    332:        recno_t          rec;
                    333:        struct rec      *recs;
                    334:        struct rec       srec;
                    335:
                    336:        root    = -1;
                    337:        leaf    = -1;
                    338:        btree   = NULL;
                    339:        idx     = NULL;
                    340:        mc      = NULL;
                    341:        buf     = NULL;
                    342:        recs    = NULL;
                    343:        len     = 0;
                    344:
                    345:        memset(&srec, 0, sizeof(struct rec));
                    346:
                    347:        /* XXX: error out with bad regexp? */
                    348:
                    349:        mc = mchars_alloc();
                    350:
                    351:        /* XXX: return fact that we've errored? */
                    352:
                    353:        if (NULL == (btree = btree_open()))
                    354:                goto out;
                    355:        if (NULL == (idx = index_open()))
                    356:                goto out;
                    357:
                    358:        while (0 == (ch = (*btree->seq)(btree, &key, &val, R_NEXT))) {
                    359:                /*
                    360:                 * Low-water mark for key and value.
                    361:                 * The key must have something in it, and the value must
                    362:                 * have the correct tags/recno mix.
                    363:                 */
                    364:                if (key.size < 2 || 8 != val.size)
                    365:                        break;
                    366:                if ( ! btree_read(&key, mc, &buf))
                    367:                        break;
1.2     ! kristaps  368:
        !           369:                if ( ! exprexec(expr, buf))
1.1       kristaps  370:                        continue;
                    371:
                    372:                memcpy(&rec, val.data + 4, sizeof(recno_t));
                    373:
                    374:                /*
                    375:                 * O(log n) scan for prior records.  Since a record
                    376:                 * number is unbounded, this has decent performance over
                    377:                 * a complex hash function.
                    378:                 */
                    379:
                    380:                for (leaf = root; leaf >= 0; )
                    381:                        if (rec > recs[leaf].rec && recs[leaf].rhs >= 0)
                    382:                                leaf = recs[leaf].rhs;
                    383:                        else if (rec < recs[leaf].rec && recs[leaf].lhs >= 0)
                    384:                                leaf = recs[leaf].lhs;
                    385:                        else
                    386:                                break;
                    387:
                    388:                if (leaf >= 0 && recs[leaf].rec == rec)
                    389:                        continue;
                    390:
                    391:                /*
                    392:                 * Now we actually extract the manpage's metadata from
                    393:                 * the index database.
                    394:                 */
                    395:
                    396:                key.data = &rec;
                    397:                key.size = sizeof(recno_t);
                    398:
                    399:                if (0 != (*idx->get)(idx, &key, &val, 0))
                    400:                        break;
                    401:
                    402:                srec.lhs = srec.rhs = -1;
                    403:                if ( ! index_read(&key, &val, mc, &srec))
                    404:                        break;
                    405:
                    406:                if (opts->cat && strcasecmp(opts->cat, srec.cat))
                    407:                        continue;
                    408:                if (opts->arch && strcasecmp(opts->arch, srec.arch))
                    409:                        continue;
                    410:
                    411:                recs = mandoc_realloc
                    412:                        (recs, (len + 1) * sizeof(struct rec));
                    413:
                    414:                memcpy(&recs[len], &srec, sizeof(struct rec));
                    415:
                    416:                /* Append to our tree. */
                    417:
                    418:                if (leaf >= 0) {
                    419:                        if (rec > recs[leaf].rec)
                    420:                                recs[leaf].rhs = len;
                    421:                        else
                    422:                                recs[leaf].lhs = len;
                    423:                } else
                    424:                        root = len;
                    425:
                    426:                memset(&srec, 0, sizeof(struct rec));
                    427:                len++;
                    428:        }
                    429:
                    430:        if (1 == ch)
                    431:                (*res)(recs, len, arg);
                    432:
                    433:        /* XXX: else?  corrupt database error? */
                    434: out:
                    435:        for (i = 0; i < len; i++) {
                    436:                free(recs[i].file);
                    437:                free(recs[i].cat);
                    438:                free(recs[i].title);
                    439:                free(recs[i].arch);
                    440:                free(recs[i].desc);
                    441:        }
                    442:
                    443:        free(srec.file);
                    444:        free(srec.cat);
                    445:        free(srec.title);
                    446:        free(srec.arch);
                    447:        free(srec.desc);
                    448:
                    449:        if (mc)
                    450:                mchars_free(mc);
                    451:        if (btree)
                    452:                (*btree->close)(btree);
                    453:        if (idx)
                    454:                (*idx->close)(idx);
                    455:
                    456:        free(buf);
                    457:        free(recs);
1.2     ! kristaps  458: }
        !           459:
        !           460: struct expr *
        !           461: exprcomp(int cs, char *argv[], int argc)
        !           462: {
        !           463:        struct expr     *p;
        !           464:        struct expr      e;
        !           465:        int              i, ch;
        !           466:
        !           467:        if (3 != argc)
        !           468:                return(NULL);
        !           469:
        !           470:        if (0 == strcmp("-eq", argv[0]))
        !           471:                e.match = cs ? MATCH_STRCASE : MATCH_STR;
        !           472:        else if (0 == strcmp("-ieq", argv[0]))
        !           473:                e.match = MATCH_STRCASE;
        !           474:        else if (0 == strcmp("-re", argv[0]))
        !           475:                e.match = cs ? MATCH_REGEXCASE : MATCH_REGEX;
        !           476:        else if (0 == strcmp("-ire", argv[0]))
        !           477:                e.match = MATCH_REGEXCASE;
        !           478:        else
        !           479:                return(NULL);
        !           480:
        !           481:        for (i = 0; 0 != types[i].mask; i++)
        !           482:                if (0 == strcmp(types[i].name, argv[1]))
        !           483:                        break;
        !           484:
        !           485:        if (0 == (e.mask = types[i].mask))
        !           486:                return(NULL);
        !           487:
        !           488:        e.v = mandoc_strdup(argv[2]);
        !           489:
        !           490:        if (MATCH_REGEX == e.match || MATCH_REGEXCASE == e.match) {
        !           491:                ch = REG_EXTENDED | REG_NOSUB;
        !           492:                if (MATCH_REGEXCASE == e.match)
        !           493:                        ch |= REG_ICASE;
        !           494:                if (regcomp(&e.re, e.v, ch))
        !           495:                        return(NULL);
        !           496:        }
        !           497:
        !           498:        p = mandoc_calloc(1, sizeof(struct expr));
        !           499:        memcpy(p, &e, sizeof(struct expr));
        !           500:        return(p);
        !           501: }
        !           502:
        !           503: void
        !           504: exprfree(struct expr *p)
        !           505: {
        !           506:
        !           507:        if (NULL == p)
        !           508:                return;
        !           509:
        !           510:        if (MATCH_REGEX == p->match)
        !           511:                regfree(&p->re);
        !           512:
        !           513:        free(p->v);
        !           514:        free(p);
        !           515: }
        !           516:
        !           517: static int
        !           518: exprexec(const struct expr *p, char *cp)
        !           519: {
        !           520:
        !           521:        if (MATCH_STR == p->match)
        !           522:                return(0 == strcmp(p->v, cp));
        !           523:        else if (MATCH_STRCASE == p->match)
        !           524:                return(0 == strcasecmp(p->v, cp));
        !           525:
        !           526:        assert(MATCH_REGEX == p->match);
        !           527:        return(0 == regexec(&p->re, cp, 0, NULL, 0));
1.1       kristaps  528: }

CVSweb