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

Annotation of mandoc/mandocdb.c, Revision 1.144

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

CVSweb