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

Annotation of mandoc/mandocdb.c, Revision 1.66

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

CVSweb