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