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

Annotation of mandoc/mandocdb.c, Revision 1.156

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

CVSweb