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

Annotation of mandoc/mandocdb.c, Revision 1.68

1.68    ! schwarze    1: /*     $Id: mandocdb.c,v 1.67 2013/06/07 04:51:26 schwarze Exp $ */
1.1       kristaps    2: /*
1.48      schwarze    3:  * Copyright (c) 2011, 2012 Kristaps Dzonsons <kristaps@bsd.lv>
1.56      schwarze    4:  * Copyright (c) 2011, 2012, 2013 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.50      kristaps   22: #include <sys/stat.h>
1.1       kristaps   23:
                     24: #include <assert.h>
1.43      kristaps   25: #include <ctype.h>
1.63      schwarze   26: #include <errno.h>
1.1       kristaps   27: #include <fcntl.h>
1.50      kristaps   28: #include <fts.h>
1.1       kristaps   29: #include <getopt.h>
1.58      schwarze   30: #include <limits.h>
1.50      kristaps   31: #include <stddef.h>
1.59      schwarze   32: #include <stdio.h>
1.1       kristaps   33: #include <stdint.h>
                     34: #include <stdlib.h>
                     35: #include <string.h>
1.17      schwarze   36: #include <unistd.h>
1.1       kristaps   37:
1.53      kristaps   38: #ifdef HAVE_OHASH
1.50      kristaps   39: #include <ohash.h>
1.53      kristaps   40: #else
                     41: #include "compat_ohash.h"
                     42: #endif
1.50      kristaps   43: #include <sqlite3.h>
1.1       kristaps   44:
1.50      kristaps   45: #include "mdoc.h"
1.1       kristaps   46: #include "man.h"
                     47: #include "mandoc.h"
1.10      kristaps   48: #include "manpath.h"
1.55      kristaps   49: #include "mansearch.h"
1.1       kristaps   50:
1.52      kristaps   51: #define        SQL_EXEC(_v) \
                     52:        if (SQLITE_OK != sqlite3_exec(db, (_v), NULL, NULL, NULL)) \
                     53:                fprintf(stderr, "%s\n", sqlite3_errmsg(db))
                     54: #define        SQL_BIND_TEXT(_s, _i, _v) \
                     55:        if (SQLITE_OK != sqlite3_bind_text \
                     56:                ((_s), (_i)++, (_v), -1, SQLITE_STATIC)) \
                     57:                fprintf(stderr, "%s\n", sqlite3_errmsg(db))
                     58: #define        SQL_BIND_INT(_s, _i, _v) \
                     59:        if (SQLITE_OK != sqlite3_bind_int \
                     60:                ((_s), (_i)++, (_v))) \
                     61:                fprintf(stderr, "%s\n", sqlite3_errmsg(db))
                     62: #define        SQL_BIND_INT64(_s, _i, _v) \
                     63:        if (SQLITE_OK != sqlite3_bind_int64 \
                     64:                ((_s), (_i)++, (_v))) \
                     65:                fprintf(stderr, "%s\n", sqlite3_errmsg(db))
                     66: #define SQL_STEP(_s) \
                     67:        if (SQLITE_DONE != sqlite3_step((_s))) \
                     68:                fprintf(stderr, "%s\n", sqlite3_errmsg(db))
                     69:
1.50      kristaps   70: enum   op {
                     71:        OP_DEFAULT = 0, /* new dbs from dir list or default config */
                     72:        OP_CONFFILE, /* new databases from custom config file */
                     73:        OP_UPDATE, /* delete/add entries in existing database */
                     74:        OP_DELETE, /* delete entries from existing database */
                     75:        OP_TEST /* change no databases, report potential problems */
1.38      schwarze   76: };
                     77:
1.50      kristaps   78: enum   form {
                     79:        FORM_SRC, /* format is -man or -mdoc */
                     80:        FORM_CAT, /* format is cat */
                     81:        FORM_NONE /* format is unknown */
                     82: };
1.38      schwarze   83:
1.50      kristaps   84: struct str {
                     85:        char            *utf8; /* key in UTF-8 form */
                     86:        const struct of *of; /* if set, the owning parse */
                     87:        uint64_t         mask; /* bitmask in sequence */
1.51      kristaps   88:        char             key[]; /* the string itself */
1.38      schwarze   89: };
                     90:
1.50      kristaps   91: struct id {
                     92:        ino_t            ino;
                     93:        dev_t            dev;
                     94: };
1.5       kristaps   95:
1.3       kristaps   96: struct of {
1.50      kristaps   97:        struct id        id; /* used for hashing routine */
                     98:        struct of       *next; /* next in ofs */
                     99:        enum form        dform; /* path-cued form */
                    100:        enum form        sform; /* suffix-cued form */
1.58      schwarze  101:        char             file[PATH_MAX]; /* filename rel. to manpath */
1.66      schwarze  102:        char            *desc; /* parsed description */
                    103:        char            *name; /* name (from filename) (not empty) */
                    104:        char            *sec; /* suffix-cued section (or empty) */
                    105:        char            *dsec; /* path-cued section (or empty) */
                    106:        char            *arch; /* path-cued arch. (or empty) */
1.3       kristaps  107: };
                    108:
1.50      kristaps  109: enum   stmt {
                    110:        STMT_DELETE = 0, /* delete manpage */
                    111:        STMT_INSERT_DOC, /* insert manpage */
                    112:        STMT_INSERT_KEY, /* insert parsed key */
                    113:        STMT__MAX
1.1       kristaps  114: };
                    115:
1.50      kristaps  116: typedef        int (*mdoc_fp)(struct of *, const struct mdoc_node *);
1.1       kristaps  117:
1.50      kristaps  118: struct mdoc_handler {
                    119:        mdoc_fp          fp; /* optional handler */
                    120:        uint64_t         mask;  /* set unless handler returns 0 */
1.1       kristaps  121: };
                    122:
1.59      schwarze  123: static void     dbclose(int);
                    124: static void     dbindex(struct mchars *, int, const struct of *);
                    125: static int      dbopen(int);
                    126: static void     dbprune(void);
1.50      kristaps  127: static void     fileadd(struct of *);
                    128: static int      filecheck(const char *);
1.59      schwarze  129: static void     filescan(const char *);
1.50      kristaps  130: static void    *hash_alloc(size_t, void *);
                    131: static void     hash_free(void *, size_t, void *);
                    132: static void    *hash_halloc(size_t, void *);
                    133: static void     inoadd(const struct stat *, struct of *);
                    134: static int      inocheck(const struct stat *);
1.59      schwarze  135: static void     ofadd(int, const char *, const char *, const char *,
                    136:                        const char *, const char *, const struct stat *);
1.50      kristaps  137: static void     offree(void);
1.66      schwarze  138: static void     ofmerge(struct mchars *, struct mparse *,
                    139:                        struct ohash_info*);
1.59      schwarze  140: static void     parse_catpage(struct of *);
1.61      schwarze  141: static void     parse_man(struct of *, const struct man_node *);
1.50      kristaps  142: static void     parse_mdoc(struct of *, const struct mdoc_node *);
                    143: static int      parse_mdoc_body(struct of *, const struct mdoc_node *);
                    144: static int      parse_mdoc_head(struct of *, const struct mdoc_node *);
                    145: static int      parse_mdoc_Fd(struct of *, const struct mdoc_node *);
                    146: static int      parse_mdoc_Fn(struct of *, const struct mdoc_node *);
                    147: static int      parse_mdoc_In(struct of *, const struct mdoc_node *);
                    148: static int      parse_mdoc_Nd(struct of *, const struct mdoc_node *);
                    149: static int      parse_mdoc_Nm(struct of *, const struct mdoc_node *);
                    150: static int      parse_mdoc_Sh(struct of *, const struct mdoc_node *);
                    151: static int      parse_mdoc_St(struct of *, const struct mdoc_node *);
                    152: static int      parse_mdoc_Xr(struct of *, const struct mdoc_node *);
1.59      schwarze  153: static int      set_basedir(const char *);
1.50      kristaps  154: static void     putkey(const struct of *,
                    155:                        const char *, uint64_t);
                    156: static void     putkeys(const struct of *,
1.64      schwarze  157:                        const char *, size_t, uint64_t);
1.50      kristaps  158: static void     putmdockey(const struct of *,
                    159:                        const struct mdoc_node *, uint64_t);
1.59      schwarze  160: static void     say(const char *, const char *, ...);
                    161: static int      treescan(void);
1.50      kristaps  162: static size_t   utf8(unsigned int, char [7]);
                    163: static void     utf8key(struct mchars *, struct str *);
                    164:
                    165: static char            *progname;
                    166: static int              use_all; /* use all found files */
                    167: static int              nodb; /* no database changes */
                    168: static int              verb; /* print what we're doing */
                    169: static int              warnings; /* warn about crap */
1.59      schwarze  170: static int              exitcode; /* to be returned by main */
1.50      kristaps  171: static enum op          op; /* operational mode */
1.59      schwarze  172: static char             basedir[PATH_MAX]; /* current base directory */
1.50      kristaps  173: static struct ohash     inos; /* table of inodes/devices */
                    174: static struct ohash     filenames; /* table of filenames */
                    175: static struct ohash     strings; /* table of all strings */
                    176: static struct of       *ofs = NULL; /* vector of files to parse */
                    177: static sqlite3         *db = NULL; /* current database */
                    178: static sqlite3_stmt    *stmts[STMT__MAX]; /* current statements */
1.25      schwarze  179:
                    180: static const struct mdoc_handler mdocs[MDOC_MAX] = {
1.68    ! schwarze  181:        { NULL, 0 },  /* Ap */
        !           182:        { NULL, 0 },  /* Dd */
        !           183:        { NULL, 0 },  /* Dt */
        !           184:        { NULL, 0 },  /* Os */
        !           185:        { parse_mdoc_Sh, TYPE_Sh }, /* Sh */
        !           186:        { parse_mdoc_head, TYPE_Ss }, /* Ss */
        !           187:        { NULL, 0 },  /* Pp */
        !           188:        { NULL, 0 },  /* D1 */
        !           189:        { NULL, 0 },  /* Dl */
        !           190:        { NULL, 0 },  /* Bd */
        !           191:        { NULL, 0 },  /* Ed */
        !           192:        { NULL, 0 },  /* Bl */
        !           193:        { NULL, 0 },  /* El */
        !           194:        { NULL, 0 },  /* It */
        !           195:        { NULL, 0 },  /* Ad */
        !           196:        { NULL, TYPE_An },  /* An */
        !           197:        { NULL, TYPE_Ar },  /* Ar */
        !           198:        { NULL, TYPE_Cd },  /* Cd */
        !           199:        { NULL, TYPE_Cm },  /* Cm */
        !           200:        { NULL, TYPE_Dv },  /* Dv */
        !           201:        { NULL, TYPE_Er },  /* Er */
        !           202:        { NULL, TYPE_Ev },  /* Ev */
        !           203:        { NULL, 0 },  /* Ex */
        !           204:        { NULL, TYPE_Fa },  /* Fa */
        !           205:        { parse_mdoc_Fd, 0 },  /* Fd */
        !           206:        { NULL, TYPE_Fl },  /* Fl */
        !           207:        { parse_mdoc_Fn, 0 },  /* Fn */
        !           208:        { NULL, TYPE_Ft },  /* Ft */
        !           209:        { NULL, TYPE_Ic },  /* Ic */
        !           210:        { parse_mdoc_In, TYPE_In },  /* In */
        !           211:        { NULL, TYPE_Li },  /* Li */
        !           212:        { parse_mdoc_Nd, TYPE_Nd },  /* Nd */
        !           213:        { parse_mdoc_Nm, TYPE_Nm },  /* Nm */
        !           214:        { NULL, 0 },  /* Op */
        !           215:        { NULL, 0 },  /* Ot */
        !           216:        { NULL, TYPE_Pa },  /* Pa */
        !           217:        { NULL, 0 },  /* Rv */
        !           218:        { parse_mdoc_St, 0 },  /* St */
        !           219:        { NULL, TYPE_Va },  /* Va */
        !           220:        { parse_mdoc_body, TYPE_Va },  /* Vt */
        !           221:        { parse_mdoc_Xr, 0 },  /* Xr */
        !           222:        { NULL, 0 },  /* %A */
        !           223:        { NULL, 0 },  /* %B */
        !           224:        { NULL, 0 },  /* %D */
        !           225:        { NULL, 0 },  /* %I */
        !           226:        { NULL, 0 },  /* %J */
        !           227:        { NULL, 0 },  /* %N */
        !           228:        { NULL, 0 },  /* %O */
        !           229:        { NULL, 0 },  /* %P */
        !           230:        { NULL, 0 },  /* %R */
        !           231:        { NULL, 0 },  /* %T */
        !           232:        { NULL, 0 },  /* %V */
        !           233:        { NULL, 0 },  /* Ac */
        !           234:        { NULL, 0 },  /* Ao */
        !           235:        { NULL, 0 },  /* Aq */
        !           236:        { NULL, TYPE_At },  /* At */
        !           237:        { NULL, 0 },  /* Bc */
        !           238:        { NULL, 0 },  /* Bf */
        !           239:        { NULL, 0 },  /* Bo */
        !           240:        { NULL, 0 },  /* Bq */
        !           241:        { NULL, TYPE_Bsx },  /* Bsx */
        !           242:        { NULL, TYPE_Bx },  /* Bx */
        !           243:        { NULL, 0 },  /* Db */
        !           244:        { NULL, 0 },  /* Dc */
        !           245:        { NULL, 0 },  /* Do */
        !           246:        { NULL, 0 },  /* Dq */
        !           247:        { NULL, 0 },  /* Ec */
        !           248:        { NULL, 0 },  /* Ef */
        !           249:        { NULL, TYPE_Em },  /* Em */
        !           250:        { NULL, 0 },  /* Eo */
        !           251:        { NULL, TYPE_Fx },  /* Fx */
        !           252:        { NULL, TYPE_Ms },  /* Ms */
        !           253:        { NULL, 0 },  /* No */
        !           254:        { NULL, 0 },  /* Ns */
        !           255:        { NULL, TYPE_Nx },  /* Nx */
        !           256:        { NULL, TYPE_Ox },  /* Ox */
        !           257:        { NULL, 0 },  /* Pc */
        !           258:        { NULL, 0 },  /* Pf */
        !           259:        { NULL, 0 },  /* Po */
        !           260:        { NULL, 0 },  /* Pq */
        !           261:        { NULL, 0 },  /* Qc */
        !           262:        { NULL, 0 },  /* Ql */
        !           263:        { NULL, 0 },  /* Qo */
        !           264:        { NULL, 0 },  /* Qq */
        !           265:        { NULL, 0 },  /* Re */
        !           266:        { NULL, 0 },  /* Rs */
        !           267:        { NULL, 0 },  /* Sc */
        !           268:        { NULL, 0 },  /* So */
        !           269:        { NULL, 0 },  /* Sq */
        !           270:        { NULL, 0 },  /* Sm */
        !           271:        { NULL, 0 },  /* Sx */
        !           272:        { NULL, TYPE_Sy },  /* Sy */
        !           273:        { NULL, TYPE_Tn },  /* Tn */
        !           274:        { NULL, 0 },  /* Ux */
        !           275:        { NULL, 0 },  /* Xc */
        !           276:        { NULL, 0 },  /* Xo */
        !           277:        { parse_mdoc_head, 0 },  /* Fo */
        !           278:        { NULL, 0 },  /* Fc */
        !           279:        { NULL, 0 },  /* Oo */
        !           280:        { NULL, 0 },  /* Oc */
        !           281:        { NULL, 0 },  /* Bk */
        !           282:        { NULL, 0 },  /* Ek */
        !           283:        { NULL, 0 },  /* Bt */
        !           284:        { NULL, 0 },  /* Hf */
        !           285:        { NULL, 0 },  /* Fr */
        !           286:        { NULL, 0 },  /* Ud */
        !           287:        { NULL, TYPE_Lb },  /* Lb */
        !           288:        { NULL, 0 },  /* Lp */
        !           289:        { NULL, TYPE_Lk },  /* Lk */
        !           290:        { NULL, TYPE_Mt },  /* Mt */
        !           291:        { NULL, 0 },  /* Brq */
        !           292:        { NULL, 0 },  /* Bro */
        !           293:        { NULL, 0 },  /* Brc */
        !           294:        { NULL, 0 },  /* %C */
        !           295:        { NULL, 0 },  /* Es */
        !           296:        { NULL, 0 },  /* En */
        !           297:        { NULL, TYPE_Dx },  /* Dx */
        !           298:        { NULL, 0 },  /* %Q */
        !           299:        { NULL, 0 },  /* br */
        !           300:        { NULL, 0 },  /* sp */
        !           301:        { NULL, 0 },  /* %U */
        !           302:        { NULL, 0 },  /* Ta */
1.1       kristaps  303: };
                    304:
                    305: int
                    306: main(int argc, char *argv[])
                    307: {
1.59      schwarze  308:        int               ch, i;
1.50      kristaps  309:        size_t            j, sz;
1.59      schwarze  310:        const char       *path_arg;
1.50      kristaps  311:        struct mchars    *mc;
                    312:        struct manpaths   dirs;
                    313:        struct mparse    *mp;
                    314:        struct ohash_info ino_info, filename_info, str_info;
                    315:
                    316:        memset(stmts, 0, STMT__MAX * sizeof(sqlite3_stmt *));
                    317:        memset(&dirs, 0, sizeof(struct manpaths));
                    318:
                    319:        ino_info.halloc = filename_info.halloc =
                    320:                str_info.halloc = hash_halloc;
                    321:        ino_info.hfree = filename_info.hfree =
                    322:                str_info.hfree = hash_free;
                    323:        ino_info.alloc = filename_info.alloc =
                    324:                str_info.alloc = hash_alloc;
                    325:
                    326:        ino_info.key_offset = offsetof(struct of, id);
                    327:        filename_info.key_offset = offsetof(struct of, file);
                    328:        str_info.key_offset = offsetof(struct str, key);
1.1       kristaps  329:
                    330:        progname = strrchr(argv[0], '/');
                    331:        if (progname == NULL)
                    332:                progname = argv[0];
                    333:        else
                    334:                ++progname;
                    335:
1.50      kristaps  336:        /*
                    337:         * We accept a few different invocations.
                    338:         * The CHECKOP macro makes sure that invocation styles don't
                    339:         * clobber each other.
                    340:         */
                    341: #define        CHECKOP(_op, _ch) do \
                    342:        if (OP_DEFAULT != (_op)) { \
                    343:                fprintf(stderr, "-%c: Conflicting option\n", (_ch)); \
                    344:                goto usage; \
                    345:        } while (/*CONSTCOND*/0)
1.10      kristaps  346:
1.59      schwarze  347:        path_arg = NULL;
1.38      schwarze  348:        op = OP_DEFAULT;
1.1       kristaps  349:
1.50      kristaps  350:        while (-1 != (ch = getopt(argc, argv, "aC:d:ntu:vW")))
1.1       kristaps  351:                switch (ch) {
1.12      schwarze  352:                case ('a'):
                    353:                        use_all = 1;
                    354:                        break;
1.34      schwarze  355:                case ('C'):
1.50      kristaps  356:                        CHECKOP(op, ch);
1.59      schwarze  357:                        path_arg = optarg;
1.38      schwarze  358:                        op = OP_CONFFILE;
1.34      schwarze  359:                        break;
1.5       kristaps  360:                case ('d'):
1.50      kristaps  361:                        CHECKOP(op, ch);
1.59      schwarze  362:                        path_arg = optarg;
1.5       kristaps  363:                        op = OP_UPDATE;
                    364:                        break;
1.50      kristaps  365:                case ('n'):
                    366:                        nodb = 1;
                    367:                        break;
1.38      schwarze  368:                case ('t'):
1.50      kristaps  369:                        CHECKOP(op, ch);
1.38      schwarze  370:                        dup2(STDOUT_FILENO, STDERR_FILENO);
                    371:                        op = OP_TEST;
1.50      kristaps  372:                        nodb = warnings = 1;
1.38      schwarze  373:                        break;
1.5       kristaps  374:                case ('u'):
1.50      kristaps  375:                        CHECKOP(op, ch);
1.59      schwarze  376:                        path_arg = optarg;
1.5       kristaps  377:                        op = OP_DELETE;
                    378:                        break;
                    379:                case ('v'):
                    380:                        verb++;
                    381:                        break;
1.38      schwarze  382:                case ('W'):
                    383:                        warnings = 1;
                    384:                        break;
1.1       kristaps  385:                default:
1.38      schwarze  386:                        goto usage;
1.1       kristaps  387:                }
                    388:
                    389:        argc -= optind;
                    390:        argv += optind;
                    391:
1.38      schwarze  392:        if (OP_CONFFILE == op && argc > 0) {
1.50      kristaps  393:                fprintf(stderr, "-C: Too many arguments\n");
1.38      schwarze  394:                goto usage;
                    395:        }
                    396:
1.59      schwarze  397:        exitcode = (int)MANDOCLEVEL_OK;
1.50      kristaps  398:        mp = mparse_alloc(MPARSE_AUTO,
                    399:                MANDOCLEVEL_FATAL, NULL, NULL, NULL);
                    400:        mc = mchars_alloc();
                    401:
                    402:        ohash_init(&inos, 6, &ino_info);
                    403:        ohash_init(&filenames, 6, &filename_info);
                    404:
                    405:        if (OP_UPDATE == op || OP_DELETE == op || OP_TEST == op) {
                    406:                /*
                    407:                 * Force processing all files.
                    408:                 */
                    409:                use_all = 1;
1.59      schwarze  410:
1.50      kristaps  411:                /*
                    412:                 * All of these deal with a specific directory.
                    413:                 * Jump into that directory then collect files specified
                    414:                 * on the command-line.
                    415:                 */
1.59      schwarze  416:                if (0 == set_basedir(path_arg))
1.50      kristaps  417:                        goto out;
                    418:                for (i = 0; i < argc; i++)
1.59      schwarze  419:                        filescan(argv[i]);
                    420:                if (0 == dbopen(1))
1.50      kristaps  421:                        goto out;
                    422:                if (OP_TEST != op)
1.59      schwarze  423:                        dbprune();
1.50      kristaps  424:                if (OP_DELETE != op)
1.66      schwarze  425:                        ofmerge(mc, mp, &str_info);
1.59      schwarze  426:                dbclose(1);
1.50      kristaps  427:        } else {
                    428:                /*
                    429:                 * If we have arguments, use them as our manpaths.
                    430:                 * If we don't, grok from manpath(1) or however else
                    431:                 * manpath_parse() wants to do it.
                    432:                 */
                    433:                if (argc > 0) {
                    434:                        dirs.paths = mandoc_calloc
                    435:                                (argc, sizeof(char *));
                    436:                        dirs.sz = (size_t)argc;
                    437:                        for (i = 0; i < argc; i++)
                    438:                                dirs.paths[i] = mandoc_strdup(argv[i]);
                    439:                } else
1.59      schwarze  440:                        manpath_parse(&dirs, path_arg, NULL, NULL);
1.50      kristaps  441:
                    442:                /*
                    443:                 * First scan the tree rooted at a base directory.
                    444:                 * Then whak its database (if one exists), parse, and
                    445:                 * build up the database.
                    446:                 * Ignore zero-length directories and strip trailing
                    447:                 * slashes.
                    448:                 */
                    449:                for (j = 0; j < dirs.sz; j++) {
                    450:                        sz = strlen(dirs.paths[j]);
                    451:                        if (sz && '/' == dirs.paths[j][sz - 1])
                    452:                                dirs.paths[j][--sz] = '\0';
                    453:                        if (0 == sz)
                    454:                                continue;
1.66      schwarze  455:
                    456:                        if (j) {
                    457:                                ohash_init(&inos, 6, &ino_info);
                    458:                                ohash_init(&filenames, 6, &filename_info);
                    459:                        }
                    460:
1.59      schwarze  461:                        if (0 == set_basedir(dirs.paths[j]))
1.50      kristaps  462:                                goto out;
1.59      schwarze  463:                        if (0 == treescan())
1.50      kristaps  464:                                goto out;
1.59      schwarze  465:                        if (0 == set_basedir(dirs.paths[j]))
1.50      kristaps  466:                                goto out;
1.59      schwarze  467:                        if (0 == dbopen(0))
1.50      kristaps  468:                                goto out;
1.52      kristaps  469:
                    470:                        /*
                    471:                         * Since we're opening up a new database, we can
                    472:                         * turn off synchronous mode for much better
                    473:                         * performance.
                    474:                         */
1.54      kristaps  475: #ifndef __APPLE__
1.52      kristaps  476:                        SQL_EXEC("PRAGMA synchronous = OFF");
1.54      kristaps  477: #endif
1.52      kristaps  478:
1.66      schwarze  479:                        ofmerge(mc, mp, &str_info);
1.59      schwarze  480:                        dbclose(0);
1.66      schwarze  481:
                    482:                        if (j + 1 < dirs.sz) {
                    483:                                ohash_delete(&inos);
                    484:                                ohash_delete(&filenames);
                    485:                                offree();
                    486:                        }
1.50      kristaps  487:                }
                    488:        }
                    489: out:
1.59      schwarze  490:        set_basedir(NULL);
1.50      kristaps  491:        manpath_free(&dirs);
                    492:        mchars_free(mc);
                    493:        mparse_free(mp);
                    494:        ohash_delete(&inos);
                    495:        ohash_delete(&filenames);
                    496:        offree();
1.59      schwarze  497:        return(exitcode);
1.50      kristaps  498: usage:
                    499:        fprintf(stderr, "usage: %s [-anvW] [-C file]\n"
                    500:                        "       %s [-anvW] dir ...\n"
                    501:                        "       %s [-nvW] -d dir [file ...]\n"
                    502:                        "       %s [-nvW] -u dir [file ...]\n"
                    503:                        "       %s -t file ...\n",
                    504:                       progname, progname, progname,
                    505:                       progname, progname);
                    506:
1.59      schwarze  507:        return((int)MANDOCLEVEL_BADARG);
1.50      kristaps  508: }
                    509:
                    510: /*
1.59      schwarze  511:  * Scan a directory tree rooted at "basedir" for manpages.
1.50      kristaps  512:  * We use fts(), scanning directory parts along the way for clues to our
                    513:  * section and architecture.
                    514:  *
                    515:  * If use_all has been specified, grok all files.
                    516:  * If not, sanitise paths to the following:
                    517:  *
                    518:  *   [./]man*[/<arch>]/<name>.<section>
                    519:  *   or
                    520:  *   [./]cat<section>[/<arch>]/<name>.0
                    521:  *
                    522:  * TODO: accomodate for multi-language directories.
                    523:  */
                    524: static int
1.59      schwarze  525: treescan(void)
1.50      kristaps  526: {
                    527:        FTS             *f;
                    528:        FTSENT          *ff;
                    529:        int              dform;
                    530:        char            *sec;
1.66      schwarze  531:        const char      *dsec, *arch, *cp, *path;
1.50      kristaps  532:        const char      *argv[2];
                    533:
                    534:        argv[0] = ".";
                    535:        argv[1] = (char *)NULL;
                    536:
                    537:        /*
                    538:         * Walk through all components under the directory, using the
                    539:         * logical descent of files.
                    540:         */
                    541:        f = fts_open((char * const *)argv, FTS_LOGICAL, NULL);
                    542:        if (NULL == f) {
1.59      schwarze  543:                exitcode = (int)MANDOCLEVEL_SYSERR;
                    544:                say("", NULL);
1.50      kristaps  545:                return(0);
                    546:        }
                    547:
                    548:        dsec = arch = NULL;
                    549:        dform = FORM_NONE;
                    550:
                    551:        while (NULL != (ff = fts_read(f))) {
                    552:                path = ff->fts_path + 2;
                    553:                /*
                    554:                 * If we're a regular file, add an "of" by using the
                    555:                 * stored directory data and handling the filename.
                    556:                 * Disallow duplicate (hard-linked) files.
                    557:                 */
                    558:                if (FTS_F == ff->fts_info) {
1.60      schwarze  559:                        if (0 == strcmp(path, MANDOC_DB))
                    560:                                continue;
1.50      kristaps  561:                        if ( ! use_all && ff->fts_level < 2) {
1.56      schwarze  562:                                if (warnings)
1.59      schwarze  563:                                        say(path, "Extraneous file");
1.50      kristaps  564:                                continue;
                    565:                        } else if (inocheck(ff->fts_statp)) {
1.56      schwarze  566:                                if (warnings)
1.59      schwarze  567:                                        say(path, "Duplicate file");
1.50      kristaps  568:                                continue;
1.60      schwarze  569:                        } else if (NULL == (sec =
                    570:                                        strrchr(ff->fts_name, '.'))) {
                    571:                                if ( ! use_all) {
1.56      schwarze  572:                                        if (warnings)
1.60      schwarze  573:                                                say(path,
                    574:                                                    "No filename suffix");
1.50      kristaps  575:                                        continue;
                    576:                                }
1.60      schwarze  577:                        } else if (0 == strcmp(++sec, "html")) {
                    578:                                if (warnings)
                    579:                                        say(path, "Skip html");
                    580:                                continue;
                    581:                        } else if (0 == strcmp(sec, "gz")) {
                    582:                                if (warnings)
                    583:                                        say(path, "Skip gz");
                    584:                                continue;
                    585:                        } else if (0 == strcmp(sec, "ps")) {
                    586:                                if (warnings)
                    587:                                        say(path, "Skip ps");
                    588:                                continue;
                    589:                        } else if (0 == strcmp(sec, "pdf")) {
                    590:                                if (warnings)
                    591:                                        say(path, "Skip pdf");
                    592:                                continue;
                    593:                        } else if ( ! use_all &&
                    594:                            ((FORM_SRC == dform && strcmp(sec, dsec)) ||
                    595:                             (FORM_CAT == dform && strcmp(sec, "0")))) {
                    596:                                if (warnings)
                    597:                                        say(path, "Wrong filename suffix");
                    598:                                continue;
1.66      schwarze  599:                        } else
1.60      schwarze  600:                                sec[-1] = '\0';
1.66      schwarze  601:                        ofadd(dform, path, ff->fts_name, dsec, sec,
                    602:                                        arch, ff->fts_statp);
1.50      kristaps  603:                        continue;
                    604:                } else if (FTS_D != ff->fts_info &&
1.60      schwarze  605:                                FTS_DP != ff->fts_info) {
                    606:                        if (warnings)
                    607:                                say(path, "Not a regular file");
1.50      kristaps  608:                        continue;
1.60      schwarze  609:                }
1.1       kristaps  610:
1.50      kristaps  611:                switch (ff->fts_level) {
                    612:                case (0):
                    613:                        /* Ignore the root directory. */
                    614:                        break;
                    615:                case (1):
                    616:                        /*
                    617:                         * This might contain manX/ or catX/.
                    618:                         * Try to infer this from the name.
                    619:                         * If we're not in use_all, enforce it.
                    620:                         */
                    621:                        dsec = NULL;
                    622:                        dform = FORM_NONE;
                    623:                        cp = ff->fts_name;
                    624:                        if (FTS_DP == ff->fts_info)
                    625:                                break;
1.1       kristaps  626:
1.50      kristaps  627:                        if (0 == strncmp(cp, "man", 3)) {
                    628:                                dform = FORM_SRC;
1.66      schwarze  629:                                dsec = cp + 3;
1.50      kristaps  630:                        } else if (0 == strncmp(cp, "cat", 3)) {
                    631:                                dform = FORM_CAT;
1.66      schwarze  632:                                dsec = cp + 3;
1.50      kristaps  633:                        }
1.1       kristaps  634:
1.50      kristaps  635:                        if (NULL != dsec || use_all)
                    636:                                break;
1.1       kristaps  637:
1.56      schwarze  638:                        if (warnings)
1.59      schwarze  639:                                say(path, "Unknown directory part");
1.50      kristaps  640:                        fts_set(f, ff, FTS_SKIP);
                    641:                        break;
                    642:                case (2):
                    643:                        /*
                    644:                         * Possibly our architecture.
                    645:                         * If we're descending, keep tabs on it.
                    646:                         */
                    647:                        arch = NULL;
                    648:                        if (FTS_DP != ff->fts_info && NULL != dsec)
1.66      schwarze  649:                                arch = ff->fts_name;
1.50      kristaps  650:                        break;
                    651:                default:
                    652:                        if (FTS_DP == ff->fts_info || use_all)
                    653:                                break;
1.56      schwarze  654:                        if (warnings)
1.59      schwarze  655:                                say(path, "Extraneous directory part");
1.50      kristaps  656:                        fts_set(f, ff, FTS_SKIP);
                    657:                        break;
1.5       kristaps  658:                }
1.50      kristaps  659:        }
                    660:
                    661:        fts_close(f);
                    662:        return(1);
                    663: }
1.5       kristaps  664:
1.50      kristaps  665: /*
                    666:  * Add a file to the file vector.
                    667:  * Do not verify that it's a "valid" looking manpage (we'll do that
                    668:  * later).
                    669:  *
                    670:  * Try to infer the manual section, architecture, and page name from the
                    671:  * path, assuming it looks like
                    672:  *
                    673:  *   [./]man*[/<arch>]/<name>.<section>
                    674:  *   or
                    675:  *   [./]cat<section>[/<arch>]/<name>.0
                    676:  *
                    677:  * Stuff this information directly into the "of" vector.
                    678:  * See treescan() for the fts(3) version of this.
                    679:  */
                    680: static void
1.59      schwarze  681: filescan(const char *file)
1.50      kristaps  682: {
1.59      schwarze  683:        char             buf[PATH_MAX];
1.50      kristaps  684:        const char      *sec, *arch, *name, *dsec;
1.59      schwarze  685:        char            *p, *start;
1.50      kristaps  686:        int              dform;
                    687:        struct stat      st;
1.5       kristaps  688:
1.50      kristaps  689:        assert(use_all);
1.5       kristaps  690:
1.50      kristaps  691:        if (0 == strncmp(file, "./", 2))
                    692:                file += 2;
1.5       kristaps  693:
1.59      schwarze  694:        if (NULL == realpath(file, buf)) {
                    695:                exitcode = (int)MANDOCLEVEL_BADARG;
                    696:                say(file, NULL);
                    697:                return;
                    698:        } else if (strstr(buf, basedir) != buf) {
                    699:                exitcode = (int)MANDOCLEVEL_BADARG;
                    700:                say("", "%s: outside base directory", buf);
                    701:                return;
                    702:        } else if (-1 == stat(buf, &st)) {
                    703:                exitcode = (int)MANDOCLEVEL_BADARG;
                    704:                say(file, NULL);
1.50      kristaps  705:                return;
                    706:        } else if ( ! (S_IFREG & st.st_mode)) {
1.59      schwarze  707:                exitcode = (int)MANDOCLEVEL_BADARG;
                    708:                say(file, "Not a regular file");
1.50      kristaps  709:                return;
                    710:        } else if (inocheck(&st)) {
1.56      schwarze  711:                if (warnings)
1.59      schwarze  712:                        say(file, "Duplicate file");
1.50      kristaps  713:                return;
                    714:        }
1.59      schwarze  715:        start = buf + strlen(basedir);
1.50      kristaps  716:        sec = arch = name = dsec = NULL;
                    717:        dform = FORM_NONE;
1.17      schwarze  718:
1.50      kristaps  719:        /*
                    720:         * First try to guess our directory structure.
                    721:         * If we find a separator, try to look for man* or cat*.
                    722:         * If we find one of these and what's underneath is a directory,
                    723:         * assume it's an architecture.
                    724:         */
                    725:        if (NULL != (p = strchr(start, '/'))) {
                    726:                *p++ = '\0';
                    727:                if (0 == strncmp(start, "man", 3)) {
                    728:                        dform = FORM_SRC;
                    729:                        dsec = start + 3;
                    730:                } else if (0 == strncmp(start, "cat", 3)) {
                    731:                        dform = FORM_CAT;
                    732:                        dsec = start + 3;
1.17      schwarze  733:                }
1.5       kristaps  734:
1.50      kristaps  735:                start = p;
                    736:                if (NULL != dsec && NULL != (p = strchr(start, '/'))) {
                    737:                        *p++ = '\0';
                    738:                        arch = start;
                    739:                        start = p;
                    740:                }
                    741:        }
                    742:
                    743:        /*
                    744:         * Now check the file suffix.
                    745:         * Suffix of `.0' indicates a catpage, `.1-9' is a manpage.
                    746:         */
                    747:        p = strrchr(start, '\0');
                    748:        while (p-- > start && '/' != *p && '.' != *p)
                    749:                /* Loop. */ ;
                    750:
                    751:        if ('.' == *p) {
                    752:                *p++ = '\0';
                    753:                sec = p;
1.5       kristaps  754:        }
                    755:
1.10      kristaps  756:        /*
1.50      kristaps  757:         * Now try to parse the name.
                    758:         * Use the filename portion of the path.
1.10      kristaps  759:         */
1.50      kristaps  760:        name = start;
                    761:        if (NULL != (p = strrchr(start, '/'))) {
                    762:                name = p + 1;
                    763:                *p = '\0';
                    764:        }
                    765:
1.59      schwarze  766:        ofadd(dform, file, name, dsec, sec, arch, &st);
1.50      kristaps  767: }
                    768:
                    769: /*
                    770:  * See fileadd().
                    771:  */
                    772: static int
                    773: filecheck(const char *name)
                    774: {
1.10      kristaps  775:
1.65      schwarze  776:        return(NULL != ohash_find(&filenames,
                    777:                        ohash_qlookup(&filenames, name)));
1.50      kristaps  778: }
1.10      kristaps  779:
1.50      kristaps  780: /*
                    781:  * Use the standard hashing mechanism (K&R) to see if the given filename
                    782:  * already exists.
                    783:  */
                    784: static void
                    785: fileadd(struct of *of)
                    786: {
1.65      schwarze  787:        unsigned int     slot;
1.1       kristaps  788:
1.65      schwarze  789:        slot = ohash_qlookup(&filenames, of->file);
                    790:        assert(NULL == ohash_find(&filenames, slot));
                    791:        ohash_insert(&filenames, slot, of);
1.50      kristaps  792: }
1.3       kristaps  793:
1.50      kristaps  794: /*
                    795:  * See inoadd().
                    796:  */
                    797: static int
                    798: inocheck(const struct stat *st)
                    799: {
                    800:        struct id        id;
                    801:        uint32_t         hash;
                    802:
                    803:        memset(&id, 0, sizeof(id));
                    804:        id.ino = hash = st->st_ino;
                    805:        id.dev = st->st_dev;
1.13      schwarze  806:
1.65      schwarze  807:        return(NULL != ohash_find(&inos, ohash_lookup_memory(
                    808:                        &inos, (char *)&id, sizeof(id), hash)));
1.50      kristaps  809: }
1.5       kristaps  810:
1.50      kristaps  811: /*
                    812:  * The hashing function used here is quite simple: simply take the inode
                    813:  * and use uint32_t of its bits.
                    814:  * Then when we do the lookup, use both the inode and device identifier.
                    815:  */
                    816: static void
                    817: inoadd(const struct stat *st, struct of *of)
                    818: {
                    819:        uint32_t         hash;
1.65      schwarze  820:        unsigned int     slot;
1.1       kristaps  821:
1.50      kristaps  822:        of->id.ino = hash = st->st_ino;
                    823:        of->id.dev = st->st_dev;
1.65      schwarze  824:        slot = ohash_lookup_memory
1.50      kristaps  825:                (&inos, (char *)&of->id, sizeof(of->id), hash);
1.1       kristaps  826:
1.65      schwarze  827:        assert(NULL == ohash_find(&inos, slot));
                    828:        ohash_insert(&inos, slot, of);
1.50      kristaps  829: }
1.35      kristaps  830:
1.50      kristaps  831: static void
1.59      schwarze  832: ofadd(int dform, const char *file, const char *name, const char *dsec,
                    833:        const char *sec, const char *arch, const struct stat *st)
1.50      kristaps  834: {
                    835:        struct of       *of;
                    836:        int              sform;
                    837:
                    838:        assert(NULL != file);
                    839:
                    840:        if (NULL == name)
                    841:                name = "";
                    842:        if (NULL == sec)
                    843:                sec = "";
                    844:        if (NULL == dsec)
                    845:                dsec = "";
                    846:        if (NULL == arch)
                    847:                arch = "";
                    848:
                    849:        sform = FORM_NONE;
                    850:        if (NULL != sec && *sec <= '9' && *sec >= '1')
                    851:                sform = FORM_SRC;
                    852:        else if (NULL != sec && *sec == '0') {
                    853:                sec = dsec;
                    854:                sform = FORM_CAT;
                    855:        }
                    856:
                    857:        of = mandoc_calloc(1, sizeof(struct of));
1.58      schwarze  858:        strlcpy(of->file, file, PATH_MAX);
1.66      schwarze  859:        of->name = mandoc_strdup(name);
                    860:        of->sec = mandoc_strdup(sec);
                    861:        of->dsec = mandoc_strdup(dsec);
                    862:        of->arch = mandoc_strdup(arch);
1.50      kristaps  863:        of->sform = sform;
                    864:        of->dform = dform;
                    865:        of->next = ofs;
                    866:        ofs = of;
1.3       kristaps  867:
1.50      kristaps  868:        /*
                    869:         * Add to unique identifier hash.
                    870:         * Then if it's a source manual and we're going to use source in
                    871:         * favour of catpages, add it to that hash.
                    872:         */
                    873:        inoadd(st, of);
                    874:        fileadd(of);
                    875: }
1.3       kristaps  876:
1.50      kristaps  877: static void
                    878: offree(void)
                    879: {
                    880:        struct of       *of;
1.3       kristaps  881:
1.50      kristaps  882:        while (NULL != (of = ofs)) {
                    883:                ofs = of->next;
1.66      schwarze  884:                free(of->name);
                    885:                free(of->sec);
                    886:                free(of->dsec);
                    887:                free(of->arch);
1.50      kristaps  888:                free(of);
                    889:        }
                    890: }
1.38      schwarze  891:
1.50      kristaps  892: /*
                    893:  * Run through the files in the global vector "ofs" and add them to the
1.59      schwarze  894:  * database specified in "basedir".
1.50      kristaps  895:  *
                    896:  * This handles the parsing scheme itself, using the cues of directory
                    897:  * and filename to determine whether the file is parsable or not.
                    898:  */
1.59      schwarze  899: static void
1.66      schwarze  900: ofmerge(struct mchars *mc, struct mparse *mp,
                    901:                struct ohash_info *infop)
1.50      kristaps  902: {
                    903:        int              form;
                    904:        size_t           sz;
1.3       kristaps  905:        struct mdoc     *mdoc;
                    906:        struct man      *man;
1.58      schwarze  907:        char             buf[PATH_MAX];
1.50      kristaps  908:        char            *bufp;
                    909:        const char      *msec, *march, *mtitle, *cp;
                    910:        struct of       *of;
                    911:        enum mandoclevel lvl;
                    912:
                    913:        for (of = ofs; NULL != of; of = of->next) {
                    914:                /*
                    915:                 * If we're a catpage (as defined by our path), then see
                    916:                 * if a manpage exists by the same name (ignoring the
                    917:                 * suffix).
                    918:                 * If it does, then we want to use it instead of our
                    919:                 * own.
                    920:                 */
                    921:                if ( ! use_all && FORM_CAT == of->dform) {
1.58      schwarze  922:                        sz = strlcpy(buf, of->file, PATH_MAX);
                    923:                        if (sz >= PATH_MAX) {
1.56      schwarze  924:                                if (warnings)
1.59      schwarze  925:                                        say(of->file, "Filename too long");
1.50      kristaps  926:                                continue;
                    927:                        }
                    928:                        bufp = strstr(buf, "cat");
                    929:                        assert(NULL != bufp);
                    930:                        memcpy(bufp, "man", 3);
                    931:                        if (NULL != (bufp = strrchr(buf, '.')))
                    932:                                *++bufp = '\0';
1.58      schwarze  933:                        strlcat(buf, of->dsec, PATH_MAX);
1.50      kristaps  934:                        if (filecheck(buf)) {
1.56      schwarze  935:                                if (warnings)
1.59      schwarze  936:                                        say(of->file, "Man "
1.56      schwarze  937:                                            "source exists: %s", buf);
1.50      kristaps  938:                                continue;
                    939:                        }
                    940:                }
                    941:
1.66      schwarze  942:                ohash_init(&strings, 6, infop);
1.50      kristaps  943:                mparse_reset(mp);
                    944:                mdoc = NULL;
                    945:                man = NULL;
                    946:                form = 0;
                    947:                msec = of->dsec;
                    948:                march = of->arch;
                    949:                mtitle = of->name;
1.14      schwarze  950:
                    951:                /*
1.33      schwarze  952:                 * Try interpreting the file as mdoc(7) or man(7)
                    953:                 * source code, unless it is already known to be
                    954:                 * formatted.  Fall back to formatted mode.
1.14      schwarze  955:                 */
1.50      kristaps  956:                if (FORM_SRC == of->dform || FORM_SRC == of->sform) {
                    957:                        lvl = mparse_readfd(mp, -1, of->file);
                    958:                        if (lvl < MANDOCLEVEL_FATAL)
                    959:                                mparse_result(mp, &mdoc, &man);
                    960:                }
1.14      schwarze  961:
                    962:                if (NULL != mdoc) {
1.50      kristaps  963:                        form = 1;
1.14      schwarze  964:                        msec = mdoc_meta(mdoc)->msec;
1.38      schwarze  965:                        march = mdoc_meta(mdoc)->arch;
1.14      schwarze  966:                        mtitle = mdoc_meta(mdoc)->title;
                    967:                } else if (NULL != man) {
1.50      kristaps  968:                        form = 1;
1.14      schwarze  969:                        msec = man_meta(man)->msec;
1.38      schwarze  970:                        march = "";
1.14      schwarze  971:                        mtitle = man_meta(man)->title;
1.50      kristaps  972:                }
                    973:
                    974:                if (NULL == msec)
                    975:                        msec = "";
                    976:                if (NULL == march)
                    977:                        march = "";
                    978:                if (NULL == mtitle)
                    979:                        mtitle = "";
1.1       kristaps  980:
1.12      schwarze  981:                /*
1.44      kristaps  982:                 * Check whether the manual section given in a file
                    983:                 * agrees with the directory where the file is located.
                    984:                 * Some manuals have suffixes like (3p) on their
                    985:                 * section number either inside the file or in the
                    986:                 * directory name, some are linked into more than one
                    987:                 * section, like encrypt(1) = makekey(8).  Do not skip
                    988:                 * manuals for such reasons.
1.12      schwarze  989:                 */
1.56      schwarze  990:                if (warnings && !use_all && form &&
                    991:                                strcasecmp(msec, of->dsec))
1.59      schwarze  992:                        say(of->file, "Section \"%s\" "
1.50      kristaps  993:                                "manual in %s directory",
                    994:                                msec, of->dsec);
1.12      schwarze  995:
1.42      schwarze  996:                /*
                    997:                 * Manual page directories exist for each kernel
                    998:                 * architecture as returned by machine(1).
                    999:                 * However, many manuals only depend on the
                   1000:                 * application architecture as returned by arch(1).
                   1001:                 * For example, some (2/ARM) manuals are shared
                   1002:                 * across the "armish" and "zaurus" kernel
                   1003:                 * architectures.
                   1004:                 * A few manuals are even shared across completely
                   1005:                 * different architectures, for example fdformat(1)
                   1006:                 * on amd64, i386, sparc, and sparc64.
                   1007:                 * Thus, warn about architecture mismatches,
                   1008:                 * but don't skip manuals for this reason.
                   1009:                 */
1.56      schwarze 1010:                if (warnings && !use_all && strcasecmp(march, of->arch))
1.59      schwarze 1011:                        say(of->file, "Architecture \"%s\" "
1.47      schwarze 1012:                                "manual in \"%s\" directory",
1.45      kristaps 1013:                                march, of->arch);
1.12      schwarze 1014:
1.50      kristaps 1015:                putkey(of, of->name, TYPE_Nm);
1.12      schwarze 1016:
1.50      kristaps 1017:                if (NULL != mdoc) {
                   1018:                        if (NULL != (cp = mdoc_meta(mdoc)->name))
                   1019:                                putkey(of, cp, TYPE_Nm);
1.66      schwarze 1020:                        assert(NULL == of->desc);
1.50      kristaps 1021:                        parse_mdoc(of, mdoc_node(mdoc));
1.66      schwarze 1022:                        putkey(of, NULL != of->desc ?
                   1023:                                of->desc : of->name, TYPE_Nd);
1.50      kristaps 1024:                } else if (NULL != man)
                   1025:                        parse_man(of, man_node(man));
                   1026:                else
1.59      schwarze 1027:                        parse_catpage(of);
1.44      kristaps 1028:
1.59      schwarze 1029:                dbindex(mc, form, of);
1.66      schwarze 1030:                ohash_delete(&strings);
1.50      kristaps 1031:        }
                   1032: }
1.12      schwarze 1033:
1.50      kristaps 1034: static void
1.59      schwarze 1035: parse_catpage(struct of *of)
1.50      kristaps 1036: {
                   1037:        FILE            *stream;
                   1038:        char            *line, *p, *title;
                   1039:        size_t           len, plen, titlesz;
1.12      schwarze 1040:
1.50      kristaps 1041:        if (NULL == (stream = fopen(of->file, "r"))) {
1.56      schwarze 1042:                if (warnings)
1.59      schwarze 1043:                        say(of->file, NULL);
1.50      kristaps 1044:                return;
                   1045:        }
1.1       kristaps 1046:
1.50      kristaps 1047:        /* Skip to first blank line. */
1.1       kristaps 1048:
1.50      kristaps 1049:        while (NULL != (line = fgetln(stream, &len)))
                   1050:                if ('\n' == *line)
                   1051:                        break;
1.1       kristaps 1052:
1.50      kristaps 1053:        /*
                   1054:         * Assume the first line that is not indented
                   1055:         * is the first section header.  Skip to it.
                   1056:         */
1.1       kristaps 1057:
1.50      kristaps 1058:        while (NULL != (line = fgetln(stream, &len)))
                   1059:                if ('\n' != *line && ' ' != *line)
                   1060:                        break;
                   1061:
                   1062:        /*
                   1063:         * Read up until the next section into a buffer.
                   1064:         * Strip the leading and trailing newline from each read line,
                   1065:         * appending a trailing space.
                   1066:         * Ignore empty (whitespace-only) lines.
                   1067:         */
1.1       kristaps 1068:
1.50      kristaps 1069:        titlesz = 0;
                   1070:        title = NULL;
1.38      schwarze 1071:
1.50      kristaps 1072:        while (NULL != (line = fgetln(stream, &len))) {
                   1073:                if (' ' != *line || '\n' != line[len - 1])
                   1074:                        break;
                   1075:                while (len > 0 && isspace((unsigned char)*line)) {
                   1076:                        line++;
                   1077:                        len--;
                   1078:                }
                   1079:                if (1 == len)
1.38      schwarze 1080:                        continue;
1.50      kristaps 1081:                title = mandoc_realloc(title, titlesz + len);
                   1082:                memcpy(title + titlesz, line, len);
                   1083:                titlesz += len;
                   1084:                title[titlesz - 1] = ' ';
                   1085:        }
1.38      schwarze 1086:
1.50      kristaps 1087:        /*
                   1088:         * If no page content can be found, or the input line
                   1089:         * is already the next section header, or there is no
                   1090:         * trailing newline, reuse the page title as the page
                   1091:         * description.
                   1092:         */
1.44      kristaps 1093:
1.50      kristaps 1094:        if (NULL == title || '\0' == *title) {
1.56      schwarze 1095:                if (warnings)
1.59      schwarze 1096:                        say(of->file, "Cannot find NAME section");
1.66      schwarze 1097:                assert(NULL == of->desc);
                   1098:                of->desc = mandoc_strdup(of->name);
1.62      schwarze 1099:                putkey(of, of->name, TYPE_Nd);
1.50      kristaps 1100:                fclose(stream);
                   1101:                free(title);
                   1102:                return;
                   1103:        }
1.1       kristaps 1104:
1.50      kristaps 1105:        title = mandoc_realloc(title, titlesz + 1);
                   1106:        title[titlesz] = '\0';
1.33      schwarze 1107:
1.50      kristaps 1108:        /*
                   1109:         * Skip to the first dash.
                   1110:         * Use the remaining line as the description (no more than 70
                   1111:         * bytes).
                   1112:         */
1.33      schwarze 1113:
1.50      kristaps 1114:        if (NULL != (p = strstr(title, "- "))) {
                   1115:                for (p += 2; ' ' == *p || '\b' == *p; p++)
                   1116:                        /* Skip to next word. */ ;
                   1117:        } else {
1.56      schwarze 1118:                if (warnings)
1.59      schwarze 1119:                        say(of->file, "No dash in title line");
1.50      kristaps 1120:                p = title;
                   1121:        }
1.38      schwarze 1122:
1.50      kristaps 1123:        plen = strlen(p);
1.1       kristaps 1124:
1.50      kristaps 1125:        /* Strip backspace-encoding from line. */
1.1       kristaps 1126:
1.50      kristaps 1127:        while (NULL != (line = memchr(p, '\b', plen))) {
                   1128:                len = line - p;
                   1129:                if (0 == len) {
                   1130:                        memmove(line, line + 1, plen--);
                   1131:                        continue;
                   1132:                }
                   1133:                memmove(line - 1, line + 1, plen - len);
                   1134:                plen -= 2;
                   1135:        }
1.1       kristaps 1136:
1.66      schwarze 1137:        assert(NULL == of->desc);
                   1138:        of->desc = mandoc_strdup(p);
                   1139:        putkey(of, of->desc, TYPE_Nd);
1.50      kristaps 1140:        fclose(stream);
                   1141:        free(title);
                   1142: }
1.1       kristaps 1143:
1.50      kristaps 1144: /*
                   1145:  * Put a type/word pair into the word database for this particular file.
                   1146:  */
                   1147: static void
                   1148: putkey(const struct of *of, const char *value, uint64_t type)
                   1149: {
1.18      kristaps 1150:
1.50      kristaps 1151:        assert(NULL != value);
1.64      schwarze 1152:        putkeys(of, value, strlen(value), type);
1.3       kristaps 1153: }
                   1154:
                   1155: /*
1.50      kristaps 1156:  * Grok all nodes at or below a certain mdoc node into putkey().
1.3       kristaps 1157:  */
                   1158: static void
1.50      kristaps 1159: putmdockey(const struct of *of, const struct mdoc_node *n, uint64_t m)
1.3       kristaps 1160: {
1.18      kristaps 1161:
1.50      kristaps 1162:        for ( ; NULL != n; n = n->next) {
                   1163:                if (NULL != n->child)
                   1164:                        putmdockey(of, n->child, m);
                   1165:                if (MDOC_TEXT == n->type)
                   1166:                        putkey(of, n->string, m);
                   1167:        }
                   1168: }
1.18      kristaps 1169:
1.61      schwarze 1170: static void
1.50      kristaps 1171: parse_man(struct of *of, const struct man_node *n)
                   1172: {
                   1173:        const struct man_node *head, *body;
                   1174:        char            *start, *sv, *title;
                   1175:        char             byte;
                   1176:        size_t           sz, titlesz;
1.18      kristaps 1177:
1.50      kristaps 1178:        if (NULL == n)
1.61      schwarze 1179:                return;
1.18      kristaps 1180:
1.50      kristaps 1181:        /*
                   1182:         * We're only searching for one thing: the first text child in
                   1183:         * the BODY of a NAME section.  Since we don't keep track of
                   1184:         * sections in -man, run some hoops to find out whether we're in
                   1185:         * the correct section or not.
                   1186:         */
1.18      kristaps 1187:
1.50      kristaps 1188:        if (MAN_BODY == n->type && MAN_SH == n->tok) {
                   1189:                body = n;
                   1190:                assert(body->parent);
                   1191:                if (NULL != (head = body->parent->head) &&
                   1192:                                1 == head->nchild &&
                   1193:                                NULL != (head = (head->child)) &&
                   1194:                                MAN_TEXT == head->type &&
                   1195:                                0 == strcmp(head->string, "NAME") &&
                   1196:                                NULL != (body = body->child) &&
                   1197:                                MAN_TEXT == body->type) {
1.3       kristaps 1198:
1.50      kristaps 1199:                        title = NULL;
                   1200:                        titlesz = 0;
1.3       kristaps 1201:
1.50      kristaps 1202:                        /*
                   1203:                         * Suck the entire NAME section into memory.
                   1204:                         * Yes, we might run away.
                   1205:                         * But too many manuals have big, spread-out
                   1206:                         * NAME sections over many lines.
                   1207:                         */
1.3       kristaps 1208:
1.50      kristaps 1209:                        for ( ; NULL != body; body = body->next) {
                   1210:                                if (MAN_TEXT != body->type)
                   1211:                                        break;
                   1212:                                if (0 == (sz = strlen(body->string)))
                   1213:                                        continue;
                   1214:                                title = mandoc_realloc
                   1215:                                        (title, titlesz + sz + 1);
                   1216:                                memcpy(title + titlesz, body->string, sz);
                   1217:                                titlesz += sz + 1;
                   1218:                                title[titlesz - 1] = ' ';
                   1219:                        }
                   1220:                        if (NULL == title)
1.61      schwarze 1221:                                return;
1.18      kristaps 1222:
1.50      kristaps 1223:                        title = mandoc_realloc(title, titlesz + 1);
                   1224:                        title[titlesz] = '\0';
1.18      kristaps 1225:
1.50      kristaps 1226:                        /* Skip leading space.  */
1.18      kristaps 1227:
1.50      kristaps 1228:                        sv = title;
                   1229:                        while (isspace((unsigned char)*sv))
                   1230:                                sv++;
1.18      kristaps 1231:
1.50      kristaps 1232:                        if (0 == (sz = strlen(sv))) {
                   1233:                                free(title);
1.61      schwarze 1234:                                return;
1.50      kristaps 1235:                        }
1.1       kristaps 1236:
1.50      kristaps 1237:                        /* Erase trailing space. */
1.1       kristaps 1238:
1.50      kristaps 1239:                        start = &sv[sz - 1];
                   1240:                        while (start > sv && isspace((unsigned char)*start))
                   1241:                                *start-- = '\0';
1.1       kristaps 1242:
1.50      kristaps 1243:                        if (start == sv) {
                   1244:                                free(title);
1.61      schwarze 1245:                                return;
1.50      kristaps 1246:                        }
1.1       kristaps 1247:
1.50      kristaps 1248:                        start = sv;
1.18      kristaps 1249:
1.50      kristaps 1250:                        /*
                   1251:                         * Go through a special heuristic dance here.
                   1252:                         * Conventionally, one or more manual names are
                   1253:                         * comma-specified prior to a whitespace, then a
                   1254:                         * dash, then a description.  Try to puzzle out
                   1255:                         * the name parts here.
                   1256:                         */
1.18      kristaps 1257:
1.50      kristaps 1258:                        for ( ;; ) {
                   1259:                                sz = strcspn(start, " ,");
                   1260:                                if ('\0' == start[sz])
                   1261:                                        break;
1.1       kristaps 1262:
1.50      kristaps 1263:                                byte = start[sz];
                   1264:                                start[sz] = '\0';
1.1       kristaps 1265:
1.50      kristaps 1266:                                putkey(of, start, TYPE_Nm);
1.1       kristaps 1267:
1.50      kristaps 1268:                                if (' ' == byte) {
                   1269:                                        start += sz + 1;
                   1270:                                        break;
                   1271:                                }
1.1       kristaps 1272:
1.50      kristaps 1273:                                assert(',' == byte);
                   1274:                                start += sz + 1;
                   1275:                                while (' ' == *start)
                   1276:                                        start++;
                   1277:                        }
1.1       kristaps 1278:
1.50      kristaps 1279:                        if (sv == start) {
                   1280:                                putkey(of, start, TYPE_Nm);
                   1281:                                free(title);
1.61      schwarze 1282:                                return;
1.50      kristaps 1283:                        }
1.1       kristaps 1284:
1.50      kristaps 1285:                        while (isspace((unsigned char)*start))
                   1286:                                start++;
1.1       kristaps 1287:
1.50      kristaps 1288:                        if (0 == strncmp(start, "-", 1))
                   1289:                                start += 1;
                   1290:                        else if (0 == strncmp(start, "\\-\\-", 4))
                   1291:                                start += 4;
                   1292:                        else if (0 == strncmp(start, "\\-", 2))
                   1293:                                start += 2;
                   1294:                        else if (0 == strncmp(start, "\\(en", 4))
                   1295:                                start += 4;
                   1296:                        else if (0 == strncmp(start, "\\(em", 4))
                   1297:                                start += 4;
1.1       kristaps 1298:
1.50      kristaps 1299:                        while (' ' == *start)
                   1300:                                start++;
1.1       kristaps 1301:
1.50      kristaps 1302:                        assert(NULL == of->desc);
1.66      schwarze 1303:                        of->desc = mandoc_strdup(start);
                   1304:                        putkey(of, of->desc, TYPE_Nd);
1.50      kristaps 1305:                        free(title);
1.61      schwarze 1306:                        return;
1.50      kristaps 1307:                }
                   1308:        }
1.1       kristaps 1309:
1.50      kristaps 1310:        for (n = n->child; n; n = n->next)
1.61      schwarze 1311:                parse_man(of, n);
1.1       kristaps 1312: }
                   1313:
                   1314: static void
1.50      kristaps 1315: parse_mdoc(struct of *of, const struct mdoc_node *n)
1.1       kristaps 1316: {
                   1317:
1.50      kristaps 1318:        assert(NULL != n);
                   1319:        for (n = n->child; NULL != n; n = n->next) {
                   1320:                switch (n->type) {
                   1321:                case (MDOC_ELEM):
                   1322:                        /* FALLTHROUGH */
                   1323:                case (MDOC_BLOCK):
                   1324:                        /* FALLTHROUGH */
                   1325:                case (MDOC_HEAD):
                   1326:                        /* FALLTHROUGH */
                   1327:                case (MDOC_BODY):
                   1328:                        /* FALLTHROUGH */
                   1329:                case (MDOC_TAIL):
                   1330:                        if (NULL != mdocs[n->tok].fp)
                   1331:                               if (0 == (*mdocs[n->tok].fp)(of, n))
                   1332:                                       break;
1.68    ! schwarze 1333:                        if (mdocs[n->tok].mask)
1.50      kristaps 1334:                                putmdockey(of, n->child, mdocs[n->tok].mask);
                   1335:                        break;
                   1336:                default:
                   1337:                        assert(MDOC_ROOT != n->type);
                   1338:                        continue;
                   1339:                }
                   1340:                if (NULL != n->child)
                   1341:                        parse_mdoc(of, n);
1.1       kristaps 1342:        }
                   1343: }
                   1344:
1.25      schwarze 1345: static int
1.50      kristaps 1346: parse_mdoc_Fd(struct of *of, const struct mdoc_node *n)
1.1       kristaps 1347: {
                   1348:        const char      *start, *end;
                   1349:        size_t           sz;
1.25      schwarze 1350:
1.50      kristaps 1351:        if (SEC_SYNOPSIS != n->sec ||
                   1352:                        NULL == (n = n->child) ||
                   1353:                        MDOC_TEXT != n->type)
1.25      schwarze 1354:                return(0);
1.1       kristaps 1355:
                   1356:        /*
                   1357:         * Only consider those `Fd' macro fields that begin with an
                   1358:         * "inclusion" token (versus, e.g., #define).
                   1359:         */
1.50      kristaps 1360:
1.1       kristaps 1361:        if (strcmp("#include", n->string))
1.25      schwarze 1362:                return(0);
1.1       kristaps 1363:
                   1364:        if (NULL == (n = n->next) || MDOC_TEXT != n->type)
1.25      schwarze 1365:                return(0);
1.1       kristaps 1366:
                   1367:        /*
                   1368:         * Strip away the enclosing angle brackets and make sure we're
                   1369:         * not zero-length.
                   1370:         */
                   1371:
                   1372:        start = n->string;
                   1373:        if ('<' == *start || '"' == *start)
                   1374:                start++;
                   1375:
                   1376:        if (0 == (sz = strlen(start)))
1.25      schwarze 1377:                return(0);
1.1       kristaps 1378:
                   1379:        end = &start[(int)sz - 1];
                   1380:        if ('>' == *end || '"' == *end)
                   1381:                end--;
                   1382:
1.50      kristaps 1383:        if (end > start)
                   1384:                putkeys(of, start, end - start + 1, TYPE_In);
1.25      schwarze 1385:        return(1);
1.1       kristaps 1386: }
                   1387:
1.25      schwarze 1388: static int
1.50      kristaps 1389: parse_mdoc_In(struct of *of, const struct mdoc_node *n)
1.1       kristaps 1390: {
                   1391:
1.50      kristaps 1392:        if (NULL != n->child && MDOC_TEXT == n->child->type)
1.25      schwarze 1393:                return(0);
1.1       kristaps 1394:
1.50      kristaps 1395:        putkey(of, n->child->string, TYPE_In);
1.25      schwarze 1396:        return(1);
1.1       kristaps 1397: }
                   1398:
1.25      schwarze 1399: static int
1.50      kristaps 1400: parse_mdoc_Fn(struct of *of, const struct mdoc_node *n)
1.1       kristaps 1401: {
                   1402:        const char      *cp;
                   1403:
1.50      kristaps 1404:        if (NULL == (n = n->child) || MDOC_TEXT != n->type)
1.25      schwarze 1405:                return(0);
                   1406:
1.50      kristaps 1407:        /*
                   1408:         * Parse: .Fn "struct type *name" "char *arg".
                   1409:         * First strip away pointer symbol.
                   1410:         * Then store the function name, then type.
                   1411:         * Finally, store the arguments.
                   1412:         */
1.1       kristaps 1413:
1.50      kristaps 1414:        if (NULL == (cp = strrchr(n->string, ' ')))
                   1415:                cp = n->string;
1.1       kristaps 1416:
                   1417:        while ('*' == *cp)
                   1418:                cp++;
                   1419:
1.50      kristaps 1420:        putkey(of, cp, TYPE_Fn);
1.25      schwarze 1421:
1.50      kristaps 1422:        if (n->string < cp)
                   1423:                putkeys(of, n->string, cp - n->string, TYPE_Ft);
1.25      schwarze 1424:
1.50      kristaps 1425:        for (n = n->next; NULL != n; n = n->next)
                   1426:                if (MDOC_TEXT == n->type)
                   1427:                        putkey(of, n->string, TYPE_Fa);
1.25      schwarze 1428:
                   1429:        return(0);
1.1       kristaps 1430: }
                   1431:
1.25      schwarze 1432: static int
1.50      kristaps 1433: parse_mdoc_St(struct of *of, const struct mdoc_node *n)
1.1       kristaps 1434: {
1.25      schwarze 1435:
1.1       kristaps 1436:        if (NULL == n->child || MDOC_TEXT != n->child->type)
1.25      schwarze 1437:                return(0);
1.1       kristaps 1438:
1.50      kristaps 1439:        putkey(of, n->child->string, TYPE_St);
1.25      schwarze 1440:        return(1);
1.1       kristaps 1441: }
                   1442:
1.25      schwarze 1443: static int
1.50      kristaps 1444: parse_mdoc_Xr(struct of *of, const struct mdoc_node *n)
1.1       kristaps 1445: {
1.67      schwarze 1446:        char    *cp;
1.1       kristaps 1447:
                   1448:        if (NULL == (n = n->child))
1.25      schwarze 1449:                return(0);
1.1       kristaps 1450:
1.67      schwarze 1451:        if (NULL == n->next) {
                   1452:                putkey(of, n->string, TYPE_Xr);
                   1453:                return(0);
                   1454:        }
                   1455:
                   1456:        if (-1 == asprintf(&cp, "%s(%s)", n->string, n->next->string)) {
                   1457:                perror(NULL);
                   1458:                exit((int)MANDOCLEVEL_SYSERR);
                   1459:        }
                   1460:        putkey(of, cp, TYPE_Xr);
                   1461:        free(cp);
                   1462:        return(0);
1.1       kristaps 1463: }
                   1464:
1.25      schwarze 1465: static int
1.50      kristaps 1466: parse_mdoc_Nd(struct of *of, const struct mdoc_node *n)
1.1       kristaps 1467: {
1.50      kristaps 1468:        size_t           sz;
1.1       kristaps 1469:
                   1470:        if (MDOC_BODY != n->type)
1.25      schwarze 1471:                return(0);
1.1       kristaps 1472:
1.50      kristaps 1473:        /*
                   1474:         * Special-case the `Nd' because we need to put the description
                   1475:         * into the document table.
                   1476:         */
                   1477:
                   1478:        for (n = n->child; NULL != n; n = n->next) {
                   1479:                if (MDOC_TEXT == n->type) {
1.66      schwarze 1480:                        if (NULL != of->desc) {
                   1481:                                sz = strlen(of->desc) +
                   1482:                                     strlen(n->string) + 2;
                   1483:                                of->desc = mandoc_realloc(of->desc, sz);
                   1484:                                strlcat(of->desc, " ", sz);
                   1485:                                strlcat(of->desc, n->string, sz);
                   1486:                        } else
                   1487:                                of->desc = mandoc_strdup(n->string);
1.50      kristaps 1488:                }
                   1489:                if (NULL != n->child)
                   1490:                        parse_mdoc_Nd(of, n);
                   1491:        }
1.25      schwarze 1492:        return(1);
1.1       kristaps 1493: }
                   1494:
1.25      schwarze 1495: static int
1.50      kristaps 1496: parse_mdoc_Nm(struct of *of, const struct mdoc_node *n)
1.1       kristaps 1497: {
                   1498:
1.25      schwarze 1499:        if (SEC_NAME == n->sec)
                   1500:                return(1);
                   1501:        else if (SEC_SYNOPSIS != n->sec || MDOC_HEAD != n->type)
                   1502:                return(0);
1.1       kristaps 1503:
1.25      schwarze 1504:        return(1);
1.1       kristaps 1505: }
                   1506:
1.25      schwarze 1507: static int
1.50      kristaps 1508: parse_mdoc_Sh(struct of *of, const struct mdoc_node *n)
1.1       kristaps 1509: {
                   1510:
1.25      schwarze 1511:        return(SEC_CUSTOM == n->sec && MDOC_HEAD == n->type);
1.1       kristaps 1512: }
                   1513:
1.50      kristaps 1514: static int
                   1515: parse_mdoc_head(struct of *of, const struct mdoc_node *n)
1.1       kristaps 1516: {
                   1517:
1.50      kristaps 1518:        return(MDOC_HEAD == n->type);
                   1519: }
1.1       kristaps 1520:
1.50      kristaps 1521: static int
                   1522: parse_mdoc_body(struct of *of, const struct mdoc_node *n)
                   1523: {
1.1       kristaps 1524:
1.50      kristaps 1525:        return(MDOC_BODY == n->type);
1.1       kristaps 1526: }
                   1527:
1.50      kristaps 1528: /*
1.66      schwarze 1529:  * Add a string to the hash table for the current manual.
                   1530:  * Each string has a bitmask telling which macros it belongs to.
                   1531:  * When we finish the manual, we'll dump the table.
1.50      kristaps 1532:  */
                   1533: static void
1.64      schwarze 1534: putkeys(const struct of *of, const char *cp, size_t sz, uint64_t v)
1.50      kristaps 1535: {
                   1536:        struct str      *s;
1.65      schwarze 1537:        unsigned int     slot;
1.50      kristaps 1538:        const char      *end;
1.25      schwarze 1539:
1.50      kristaps 1540:        if (0 == sz)
                   1541:                return;
1.25      schwarze 1542:
1.65      schwarze 1543:        end = cp + sz;
                   1544:        slot = ohash_qlookupi(&strings, cp, &end);
                   1545:        s = ohash_find(&strings, slot);
1.25      schwarze 1546:
1.50      kristaps 1547:        if (NULL != s && of == s->of) {
                   1548:                s->mask |= v;
                   1549:                return;
                   1550:        } else if (NULL == s) {
1.51      kristaps 1551:                s = mandoc_calloc(sizeof(struct str) + sz + 1, 1);
1.50      kristaps 1552:                memcpy(s->key, cp, sz);
1.65      schwarze 1553:                ohash_insert(&strings, slot, s);
1.1       kristaps 1554:        }
1.50      kristaps 1555:        s->of = of;
                   1556:        s->mask = v;
1.1       kristaps 1557: }
                   1558:
1.50      kristaps 1559: /*
                   1560:  * Take a Unicode codepoint and produce its UTF-8 encoding.
                   1561:  * This isn't the best way to do this, but it works.
                   1562:  * The magic numbers are from the UTF-8 packaging.
                   1563:  * They're not as scary as they seem: read the UTF-8 spec for details.
                   1564:  */
                   1565: static size_t
                   1566: utf8(unsigned int cp, char out[7])
1.1       kristaps 1567: {
1.50      kristaps 1568:        size_t           rc;
1.1       kristaps 1569:
1.50      kristaps 1570:        rc = 0;
                   1571:        if (cp <= 0x0000007F) {
                   1572:                rc = 1;
                   1573:                out[0] = (char)cp;
                   1574:        } else if (cp <= 0x000007FF) {
                   1575:                rc = 2;
                   1576:                out[0] = (cp >> 6  & 31) | 192;
                   1577:                out[1] = (cp       & 63) | 128;
                   1578:        } else if (cp <= 0x0000FFFF) {
                   1579:                rc = 3;
                   1580:                out[0] = (cp >> 12 & 15) | 224;
                   1581:                out[1] = (cp >> 6  & 63) | 128;
                   1582:                out[2] = (cp       & 63) | 128;
                   1583:        } else if (cp <= 0x001FFFFF) {
                   1584:                rc = 4;
                   1585:                out[0] = (cp >> 18 &  7) | 240;
                   1586:                out[1] = (cp >> 12 & 63) | 128;
                   1587:                out[2] = (cp >> 6  & 63) | 128;
                   1588:                out[3] = (cp       & 63) | 128;
                   1589:        } else if (cp <= 0x03FFFFFF) {
                   1590:                rc = 5;
                   1591:                out[0] = (cp >> 24 &  3) | 248;
                   1592:                out[1] = (cp >> 18 & 63) | 128;
                   1593:                out[2] = (cp >> 12 & 63) | 128;
                   1594:                out[3] = (cp >> 6  & 63) | 128;
                   1595:                out[4] = (cp       & 63) | 128;
                   1596:        } else if (cp <= 0x7FFFFFFF) {
                   1597:                rc = 6;
                   1598:                out[0] = (cp >> 30 &  1) | 252;
                   1599:                out[1] = (cp >> 24 & 63) | 128;
                   1600:                out[2] = (cp >> 18 & 63) | 128;
                   1601:                out[3] = (cp >> 12 & 63) | 128;
                   1602:                out[4] = (cp >> 6  & 63) | 128;
                   1603:                out[5] = (cp       & 63) | 128;
                   1604:        } else
1.1       kristaps 1605:                return(0);
                   1606:
1.50      kristaps 1607:        out[rc] = '\0';
                   1608:        return(rc);
                   1609: }
1.1       kristaps 1610:
1.50      kristaps 1611: /*
                   1612:  * Store the UTF-8 version of a key, or alias the pointer if the key has
                   1613:  * no UTF-8 transcription marks in it.
                   1614:  */
                   1615: static void
                   1616: utf8key(struct mchars *mc, struct str *key)
                   1617: {
                   1618:        size_t           sz, bsz, pos;
                   1619:        char             utfbuf[7], res[5];
                   1620:        char            *buf;
                   1621:        const char      *seq, *cpp, *val;
                   1622:        int              len, u;
                   1623:        enum mandoc_esc  esc;
                   1624:
                   1625:        assert(NULL == key->utf8);
                   1626:
                   1627:        res[0] = '\\';
                   1628:        res[1] = '\t';
                   1629:        res[2] = ASCII_NBRSP;
                   1630:        res[3] = ASCII_HYPH;
                   1631:        res[4] = '\0';
1.1       kristaps 1632:
1.50      kristaps 1633:        val = key->key;
                   1634:        bsz = strlen(val);
1.46      kristaps 1635:
1.50      kristaps 1636:        /*
                   1637:         * Pre-check: if we have no stop-characters, then set the
                   1638:         * pointer as ourselvse and get out of here.
                   1639:         */
                   1640:        if (strcspn(val, res) == bsz) {
                   1641:                key->utf8 = key->key;
                   1642:                return;
                   1643:        }
1.46      kristaps 1644:
1.50      kristaps 1645:        /* Pre-allocate by the length of the input */
1.46      kristaps 1646:
1.50      kristaps 1647:        buf = mandoc_malloc(++bsz);
                   1648:        pos = 0;
1.46      kristaps 1649:
1.50      kristaps 1650:        while ('\0' != *val) {
                   1651:                /*
                   1652:                 * Halt on the first escape sequence.
                   1653:                 * This also halts on the end of string, in which case
                   1654:                 * we just copy, fallthrough, and exit the loop.
                   1655:                 */
                   1656:                if ((sz = strcspn(val, res)) > 0) {
                   1657:                        memcpy(&buf[pos], val, sz);
                   1658:                        pos += sz;
                   1659:                        val += sz;
                   1660:                }
1.46      kristaps 1661:
1.50      kristaps 1662:                if (ASCII_HYPH == *val) {
                   1663:                        buf[pos++] = '-';
                   1664:                        val++;
                   1665:                        continue;
                   1666:                } else if ('\t' == *val || ASCII_NBRSP == *val) {
                   1667:                        buf[pos++] = ' ';
                   1668:                        val++;
                   1669:                        continue;
                   1670:                } else if ('\\' != *val)
                   1671:                        break;
1.46      kristaps 1672:
1.50      kristaps 1673:                /* Read past the slash. */
1.46      kristaps 1674:
1.50      kristaps 1675:                val++;
                   1676:                u = 0;
1.46      kristaps 1677:
1.50      kristaps 1678:                /*
                   1679:                 * Parse the escape sequence and see if it's a
                   1680:                 * predefined character or special character.
                   1681:                 */
                   1682:                esc = mandoc_escape
                   1683:                        ((const char **)&val, &seq, &len);
                   1684:                if (ESCAPE_ERROR == esc)
                   1685:                        break;
1.1       kristaps 1686:
1.50      kristaps 1687:                if (ESCAPE_SPECIAL != esc)
                   1688:                        continue;
                   1689:                if (0 == (u = mchars_spec2cp(mc, seq, len)))
                   1690:                        continue;
1.1       kristaps 1691:
1.50      kristaps 1692:                /*
                   1693:                 * If we have a Unicode codepoint, try to convert that
                   1694:                 * to a UTF-8 byte string.
                   1695:                 */
                   1696:                cpp = utfbuf;
                   1697:                if (0 == (sz = utf8(u, utfbuf)))
                   1698:                        continue;
1.1       kristaps 1699:
1.50      kristaps 1700:                /* Copy the rendered glyph into the stream. */
1.1       kristaps 1701:
1.50      kristaps 1702:                sz = strlen(cpp);
                   1703:                bsz += sz;
1.1       kristaps 1704:
1.50      kristaps 1705:                buf = mandoc_realloc(buf, bsz);
1.1       kristaps 1706:
1.50      kristaps 1707:                memcpy(&buf[pos], cpp, sz);
                   1708:                pos += sz;
1.1       kristaps 1709:        }
                   1710:
1.50      kristaps 1711:        buf[pos] = '\0';
                   1712:        key->utf8 = buf;
1.1       kristaps 1713: }
                   1714:
1.14      schwarze 1715: /*
1.50      kristaps 1716:  * Flush the current page's terms (and their bits) into the database.
                   1717:  * Wrap the entire set of additions in a transaction to make sqlite be a
                   1718:  * little faster.
                   1719:  * Also, UTF-8-encode the description at the last possible moment.
1.14      schwarze 1720:  */
                   1721: static void
1.59      schwarze 1722: dbindex(struct mchars *mc, int form, const struct of *of)
1.14      schwarze 1723: {
1.50      kristaps 1724:        struct str      *key;
                   1725:        const char      *desc;
                   1726:        int64_t          recno;
1.52      kristaps 1727:        size_t           i;
1.66      schwarze 1728:        unsigned int     slot;
1.14      schwarze 1729:
1.56      schwarze 1730:        if (verb)
1.59      schwarze 1731:                say(of->file, "Adding to index");
1.43      kristaps 1732:
1.50      kristaps 1733:        if (nodb)
1.14      schwarze 1734:                return;
1.28      kristaps 1735:
1.50      kristaps 1736:        desc = "";
                   1737:        if (NULL != of->desc) {
1.65      schwarze 1738:                key = ohash_find(&strings,
                   1739:                        ohash_qlookup(&strings, of->desc));
1.50      kristaps 1740:                assert(NULL != key);
                   1741:                if (NULL == key->utf8)
                   1742:                        utf8key(mc, key);
                   1743:                desc = key->utf8;
                   1744:        }
                   1745:
1.52      kristaps 1746:        SQL_EXEC("BEGIN TRANSACTION");
1.50      kristaps 1747:
1.52      kristaps 1748:        i = 1;
                   1749:        SQL_BIND_TEXT(stmts[STMT_INSERT_DOC], i, of->file);
                   1750:        SQL_BIND_TEXT(stmts[STMT_INSERT_DOC], i, of->sec);
                   1751:        SQL_BIND_TEXT(stmts[STMT_INSERT_DOC], i, of->arch);
                   1752:        SQL_BIND_TEXT(stmts[STMT_INSERT_DOC], i, desc);
                   1753:        SQL_BIND_INT(stmts[STMT_INSERT_DOC], i, form);
                   1754:        SQL_STEP(stmts[STMT_INSERT_DOC]);
1.50      kristaps 1755:        recno = sqlite3_last_insert_rowid(db);
                   1756:        sqlite3_reset(stmts[STMT_INSERT_DOC]);
                   1757:
1.66      schwarze 1758:        for (key = ohash_first(&strings, &slot); NULL != key;
                   1759:             key = ohash_next(&strings, &slot)) {
1.50      kristaps 1760:                assert(key->of == of);
                   1761:                if (NULL == key->utf8)
                   1762:                        utf8key(mc, key);
1.52      kristaps 1763:                i = 1;
                   1764:                SQL_BIND_INT64(stmts[STMT_INSERT_KEY], i, key->mask);
                   1765:                SQL_BIND_TEXT(stmts[STMT_INSERT_KEY], i, key->utf8);
                   1766:                SQL_BIND_INT64(stmts[STMT_INSERT_KEY], i, recno);
                   1767:                SQL_STEP(stmts[STMT_INSERT_KEY]);
1.50      kristaps 1768:                sqlite3_reset(stmts[STMT_INSERT_KEY]);
1.66      schwarze 1769:                if (key->utf8 != key->key)
                   1770:                        free(key->utf8);
                   1771:                free(key);
1.38      schwarze 1772:        }
1.28      kristaps 1773:
1.52      kristaps 1774:        SQL_EXEC("END TRANSACTION");
1.14      schwarze 1775: }
                   1776:
1.5       kristaps 1777: static void
1.59      schwarze 1778: dbprune(void)
1.5       kristaps 1779: {
1.50      kristaps 1780:        struct of       *of;
1.52      kristaps 1781:        size_t           i;
1.5       kristaps 1782:
1.50      kristaps 1783:        if (nodb)
                   1784:                return;
1.12      schwarze 1785:
1.50      kristaps 1786:        for (of = ofs; NULL != of; of = of->next) {
1.52      kristaps 1787:                i = 1;
                   1788:                SQL_BIND_TEXT(stmts[STMT_DELETE], i, of->file);
                   1789:                SQL_STEP(stmts[STMT_DELETE]);
1.50      kristaps 1790:                sqlite3_reset(stmts[STMT_DELETE]);
1.56      schwarze 1791:                if (verb)
1.59      schwarze 1792:                        say(of->file, "Deleted from index");
1.5       kristaps 1793:        }
                   1794: }
                   1795:
1.4       kristaps 1796: /*
1.50      kristaps 1797:  * Close an existing database and its prepared statements.
                   1798:  * If "real" is not set, rename the temporary file into the real one.
1.4       kristaps 1799:  */
1.35      kristaps 1800: static void
1.59      schwarze 1801: dbclose(int real)
1.4       kristaps 1802: {
1.50      kristaps 1803:        size_t           i;
1.4       kristaps 1804:
1.50      kristaps 1805:        if (nodb)
1.38      schwarze 1806:                return;
1.50      kristaps 1807:
                   1808:        for (i = 0; i < STMT__MAX; i++) {
                   1809:                sqlite3_finalize(stmts[i]);
                   1810:                stmts[i] = NULL;
1.4       kristaps 1811:        }
                   1812:
1.50      kristaps 1813:        sqlite3_close(db);
                   1814:        db = NULL;
1.12      schwarze 1815:
1.50      kristaps 1816:        if (real)
                   1817:                return;
1.12      schwarze 1818:
1.63      schwarze 1819:        if (-1 == rename(MANDOC_DB "~", MANDOC_DB)) {
1.59      schwarze 1820:                exitcode = (int)MANDOCLEVEL_SYSERR;
                   1821:                say(MANDOC_DB, NULL);
                   1822:        }
1.50      kristaps 1823: }
1.14      schwarze 1824:
1.50      kristaps 1825: /*
                   1826:  * This is straightforward stuff.
                   1827:  * Open a database connection to a "temporary" database, then open a set
                   1828:  * of prepared statements we'll use over and over again.
                   1829:  * If "real" is set, we use the existing database; if not, we truncate a
                   1830:  * temporary one.
                   1831:  * Must be matched by dbclose().
                   1832:  */
                   1833: static int
1.59      schwarze 1834: dbopen(int real)
1.50      kristaps 1835: {
1.63      schwarze 1836:        const char      *file, *sql;
1.50      kristaps 1837:        int              rc, ofl;
1.12      schwarze 1838:
1.50      kristaps 1839:        if (nodb)
                   1840:                return(1);
1.12      schwarze 1841:
1.63      schwarze 1842:        ofl = SQLITE_OPEN_READWRITE;
                   1843:        if (0 == real) {
                   1844:                file = MANDOC_DB "~";
                   1845:                if (-1 == remove(file) && ENOENT != errno) {
                   1846:                        exitcode = (int)MANDOCLEVEL_SYSERR;
                   1847:                        say(file, NULL);
                   1848:                        return(0);
                   1849:                }
                   1850:                ofl |= SQLITE_OPEN_EXCLUSIVE;
                   1851:        } else
                   1852:                file = MANDOC_DB;
1.45      kristaps 1853:
1.50      kristaps 1854:        rc = sqlite3_open_v2(file, &db, ofl, NULL);
                   1855:        if (SQLITE_OK == rc)
1.57      schwarze 1856:                goto prepare_statements;
1.50      kristaps 1857:        if (SQLITE_CANTOPEN != rc) {
1.59      schwarze 1858:                exitcode = (int)MANDOCLEVEL_SYSERR;
                   1859:                say(file, NULL);
1.50      kristaps 1860:                return(0);
                   1861:        }
1.12      schwarze 1862:
1.50      kristaps 1863:        sqlite3_close(db);
                   1864:        db = NULL;
1.12      schwarze 1865:
1.50      kristaps 1866:        if (SQLITE_OK != (rc = sqlite3_open(file, &db))) {
1.59      schwarze 1867:                exitcode = (int)MANDOCLEVEL_SYSERR;
                   1868:                say(file, NULL);
1.50      kristaps 1869:                return(0);
                   1870:        }
1.12      schwarze 1871:
1.50      kristaps 1872:        sql = "CREATE TABLE \"docs\" (\n"
                   1873:              " \"file\" TEXT NOT NULL,\n"
                   1874:              " \"sec\" TEXT NOT NULL,\n"
                   1875:              " \"arch\" TEXT NOT NULL,\n"
                   1876:              " \"desc\" TEXT NOT NULL,\n"
                   1877:              " \"form\" INTEGER NOT NULL,\n"
                   1878:              " \"id\" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL\n"
                   1879:              ");\n"
                   1880:              "\n"
                   1881:              "CREATE TABLE \"keys\" (\n"
                   1882:              " \"bits\" INTEGER NOT NULL,\n"
                   1883:              " \"key\" TEXT NOT NULL,\n"
                   1884:              " \"docid\" INTEGER NOT NULL REFERENCES docs(id) "
                   1885:                "ON DELETE CASCADE,\n"
                   1886:              " \"id\" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL\n"
                   1887:              ");\n"
                   1888:              "\n"
                   1889:              "CREATE INDEX \"key_index\" ON keys (key);\n";
1.14      schwarze 1890:
1.50      kristaps 1891:        if (SQLITE_OK != sqlite3_exec(db, sql, NULL, NULL, NULL)) {
1.59      schwarze 1892:                exitcode = (int)MANDOCLEVEL_SYSERR;
                   1893:                say(file, "%s", sqlite3_errmsg(db));
1.50      kristaps 1894:                return(0);
                   1895:        }
1.4       kristaps 1896:
1.57      schwarze 1897: prepare_statements:
                   1898:        SQL_EXEC("PRAGMA foreign_keys = ON");
1.50      kristaps 1899:        sql = "DELETE FROM docs where file=?";
                   1900:        sqlite3_prepare_v2(db, sql, -1, &stmts[STMT_DELETE], NULL);
                   1901:        sql = "INSERT INTO docs "
                   1902:                "(file,sec,arch,desc,form) VALUES (?,?,?,?,?)";
                   1903:        sqlite3_prepare_v2(db, sql, -1, &stmts[STMT_INSERT_DOC], NULL);
                   1904:        sql = "INSERT INTO keys "
                   1905:                "(bits,key,docid) VALUES (?,?,?)";
                   1906:        sqlite3_prepare_v2(db, sql, -1, &stmts[STMT_INSERT_KEY], NULL);
                   1907:        return(1);
                   1908: }
1.5       kristaps 1909:
1.50      kristaps 1910: static void *
                   1911: hash_halloc(size_t sz, void *arg)
                   1912: {
1.12      schwarze 1913:
1.50      kristaps 1914:        return(mandoc_calloc(sz, 1));
                   1915: }
1.12      schwarze 1916:
1.50      kristaps 1917: static void *
                   1918: hash_alloc(size_t sz, void *arg)
                   1919: {
1.5       kristaps 1920:
1.50      kristaps 1921:        return(mandoc_malloc(sz));
                   1922: }
1.41      kristaps 1923:
1.50      kristaps 1924: static void
                   1925: hash_free(void *p, size_t sz, void *arg)
                   1926: {
1.4       kristaps 1927:
1.50      kristaps 1928:        free(p);
1.4       kristaps 1929: }
                   1930:
1.50      kristaps 1931: static int
1.59      schwarze 1932: set_basedir(const char *targetdir)
1.4       kristaps 1933: {
1.59      schwarze 1934:        static char      startdir[PATH_MAX];
                   1935:        static int       fd;
1.4       kristaps 1936:
1.59      schwarze 1937:        /*
                   1938:         * Remember where we started by keeping a fd open to the origin
                   1939:         * path component: throughout this utility, we chdir() a lot to
                   1940:         * handle relative paths, and by doing this, we can return to
                   1941:         * the starting point.
                   1942:         */
                   1943:        if ('\0' == *startdir) {
                   1944:                if (NULL == getcwd(startdir, PATH_MAX)) {
                   1945:                        exitcode = (int)MANDOCLEVEL_SYSERR;
                   1946:                        if (NULL != targetdir)
                   1947:                                say(".", NULL);
                   1948:                        return(0);
                   1949:                }
                   1950:                if (-1 == (fd = open(startdir, O_RDONLY, 0))) {
                   1951:                        exitcode = (int)MANDOCLEVEL_SYSERR;
                   1952:                        say(startdir, NULL);
                   1953:                        return(0);
                   1954:                }
                   1955:                if (NULL == targetdir)
                   1956:                        targetdir = startdir;
                   1957:        } else {
                   1958:                if (-1 == fd)
                   1959:                        return(0);
                   1960:                if (-1 == fchdir(fd)) {
                   1961:                        close(fd);
                   1962:                        basedir[0] = '\0';
                   1963:                        exitcode = (int)MANDOCLEVEL_SYSERR;
                   1964:                        say(startdir, NULL);
                   1965:                        return(0);
                   1966:                }
                   1967:                if (NULL == targetdir) {
                   1968:                        close(fd);
                   1969:                        return(1);
                   1970:                }
                   1971:        }
                   1972:        if (NULL == realpath(targetdir, basedir)) {
                   1973:                basedir[0] = '\0';
                   1974:                exitcode = (int)MANDOCLEVEL_BADARG;
                   1975:                say(targetdir, NULL);
1.50      kristaps 1976:                return(0);
1.59      schwarze 1977:        } else if (-1 == chdir(basedir)) {
                   1978:                exitcode = (int)MANDOCLEVEL_BADARG;
                   1979:                say("", NULL);
1.50      kristaps 1980:                return(0);
1.4       kristaps 1981:        }
1.50      kristaps 1982:        return(1);
1.56      schwarze 1983: }
                   1984:
                   1985: static void
1.59      schwarze 1986: say(const char *file, const char *format, ...)
1.56      schwarze 1987: {
                   1988:        va_list          ap;
                   1989:
1.59      schwarze 1990:        if ('\0' != *basedir)
                   1991:                fprintf(stderr, "%s", basedir);
                   1992:        if ('\0' != *basedir && '\0' != *file)
                   1993:                fputs("//", stderr);
1.56      schwarze 1994:        if ('\0' != *file)
1.59      schwarze 1995:                fprintf(stderr, "%s", file);
1.56      schwarze 1996:        fputs(": ", stderr);
1.59      schwarze 1997:
                   1998:        if (NULL == format) {
                   1999:                perror(NULL);
                   2000:                return;
                   2001:        }
1.56      schwarze 2002:
                   2003:        va_start(ap, format);
                   2004:        vfprintf(stderr, format, ap);
                   2005:        va_end(ap);
                   2006:
                   2007:        fputc('\n', stderr);
1.1       kristaps 2008: }

CVSweb