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

Annotation of mandoc/mandocdb.c, Revision 1.202

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

CVSweb