[BACK]Return to mandocdb.c CVS log [TXT][DIR] Up to [local] / src / usr.bin / mandoc

Annotation of src/usr.bin/mandoc/mandocdb.c, Revision 1.69

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