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

Annotation of mandoc/mandocdb.c, Revision 1.220.2.6

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

CVSweb