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

Annotation of mandoc/mandocdb.c, Revision 1.130

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

CVSweb