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