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

Annotation of mandoc/mandocdb.c, Revision 1.220.2.4

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

CVSweb