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

Annotation of mandoc/mandocdb.c, Revision 1.124

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

CVSweb