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