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

Annotation of mandoc/mandocdb.c, Revision 1.116

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

CVSweb