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

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