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

Annotation of mandoc/mandocdb.c, Revision 1.120

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

CVSweb