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

Annotation of mandoc/mandocdb.c, Revision 1.173

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

CVSweb