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

Annotation of mandoc/mandocdb.c, Revision 1.106

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

CVSweb