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

Annotation of mandoc/apropos_db.c, Revision 1.2

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

CVSweb