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

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