[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.50

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