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