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