xref: /openbsd-src/usr.bin/mandoc/mandocdb.c (revision 4b70baf6e17fc8b27fc1f7fa7929335753fa94c3)
1 /*	$OpenBSD: mandocdb.c,v 1.212 2019/05/03 18:16:57 schwarze Exp $ */
2 /*
3  * Copyright (c) 2011, 2012 Kristaps Dzonsons <kristaps@bsd.lv>
4  * Copyright (c) 2011-2019 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 "mandoc_parse.h"
45 #include "manconf.h"
46 #include "mansearch.h"
47 #include "dba_array.h"
48 #include "dba.h"
49 
50 extern const char *const mansearch_keynames[];
51 
52 enum	op {
53 	OP_DEFAULT = 0, /* new dbs from dir list or default config */
54 	OP_CONFFILE, /* new databases from custom config file */
55 	OP_UPDATE, /* delete/add entries in existing database */
56 	OP_DELETE, /* delete entries from existing database */
57 	OP_TEST /* change no databases, report potential problems */
58 };
59 
60 struct	str {
61 	const struct mpage *mpage; /* if set, the owning parse */
62 	uint64_t	 mask; /* bitmask in sequence */
63 	char		 key[]; /* rendered text */
64 };
65 
66 struct	inodev {
67 	ino_t		 st_ino;
68 	dev_t		 st_dev;
69 };
70 
71 struct	mpage {
72 	struct inodev	 inodev;  /* used for hashing routine */
73 	struct dba_array *dba;
74 	char		*sec;     /* section from file content */
75 	char		*arch;    /* architecture from file content */
76 	char		*title;   /* title from file content */
77 	char		*desc;    /* description from file content */
78 	struct mpage	*next;    /* singly linked list */
79 	struct mlink	*mlinks;  /* singly linked list */
80 	int		 name_head_done;
81 	enum form	 form;    /* format from file content */
82 };
83 
84 struct	mlink {
85 	char		 file[PATH_MAX]; /* filename rel. to manpath */
86 	char		*dsec;    /* section from directory */
87 	char		*arch;    /* architecture from directory */
88 	char		*name;    /* name from file name (not empty) */
89 	char		*fsec;    /* section from file name suffix */
90 	struct mlink	*next;    /* singly linked list */
91 	struct mpage	*mpage;   /* parent */
92 	int		 gzip;	  /* filename has a .gz suffix */
93 	enum form	 dform;   /* format from directory */
94 	enum form	 fform;   /* format from file name suffix */
95 };
96 
97 typedef	int (*mdoc_fp)(struct mpage *, const struct roff_meta *,
98 			const struct roff_node *);
99 
100 struct	mdoc_handler {
101 	mdoc_fp		 fp; /* optional handler */
102 	uint64_t	 mask;  /* set unless handler returns 0 */
103 	int		 taboo;  /* node flags that must not be set */
104 };
105 
106 
107 int		 mandocdb(int, char *[]);
108 
109 static	void	 dbadd(struct dba *, struct mpage *);
110 static	void	 dbadd_mlink(const struct mlink *mlink);
111 static	void	 dbprune(struct dba *);
112 static	void	 dbwrite(struct dba *);
113 static	void	 filescan(const char *);
114 static	int	 fts_compare(const FTSENT **, const FTSENT **);
115 static	void	 mlink_add(struct mlink *, const struct stat *);
116 static	void	 mlink_check(struct mpage *, struct mlink *);
117 static	void	 mlink_free(struct mlink *);
118 static	void	 mlinks_undupe(struct mpage *);
119 static	void	 mpages_free(void);
120 static	void	 mpages_merge(struct dba *, struct mparse *);
121 static	void	 parse_cat(struct mpage *, int);
122 static	void	 parse_man(struct mpage *, const struct roff_meta *,
123 			const struct roff_node *);
124 static	void	 parse_mdoc(struct mpage *, const struct roff_meta *,
125 			const struct roff_node *);
126 static	int	 parse_mdoc_head(struct mpage *, const struct roff_meta *,
127 			const struct roff_node *);
128 static	int	 parse_mdoc_Fa(struct mpage *, const struct roff_meta *,
129 			const struct roff_node *);
130 static	int	 parse_mdoc_Fd(struct mpage *, const struct roff_meta *,
131 			const struct roff_node *);
132 static	void	 parse_mdoc_fname(struct mpage *, const struct roff_node *);
133 static	int	 parse_mdoc_Fn(struct mpage *, const struct roff_meta *,
134 			const struct roff_node *);
135 static	int	 parse_mdoc_Fo(struct mpage *, const struct roff_meta *,
136 			const struct roff_node *);
137 static	int	 parse_mdoc_Nd(struct mpage *, const struct roff_meta *,
138 			const struct roff_node *);
139 static	int	 parse_mdoc_Nm(struct mpage *, const struct roff_meta *,
140 			const struct roff_node *);
141 static	int	 parse_mdoc_Sh(struct mpage *, const struct roff_meta *,
142 			const struct roff_node *);
143 static	int	 parse_mdoc_Va(struct mpage *, const struct roff_meta *,
144 			const struct roff_node *);
145 static	int	 parse_mdoc_Xr(struct mpage *, const struct roff_meta *,
146 			const struct roff_node *);
147 static	void	 putkey(const struct mpage *, char *, uint64_t);
148 static	void	 putkeys(const struct mpage *, char *, size_t, uint64_t);
149 static	void	 putmdockey(const struct mpage *,
150 			const struct roff_node *, uint64_t, int);
151 static	int	 render_string(char **, size_t *);
152 static	void	 say(const char *, const char *, ...)
153 			__attribute__((__format__ (__printf__, 2, 3)));
154 static	int	 set_basedir(const char *, int);
155 static	int	 treescan(void);
156 static	size_t	 utf8(unsigned int, char [7]);
157 
158 static	int		 nodb; /* no database changes */
159 static	int		 mparse_options; /* abort the parse early */
160 static	int		 use_all; /* use all found files */
161 static	int		 debug; /* print what we're doing */
162 static	int		 warnings; /* warn about crap */
163 static	int		 write_utf8; /* write UTF-8 output; else ASCII */
164 static	int		 exitcode; /* to be returned by main */
165 static	enum op		 op; /* operational mode */
166 static	char		 basedir[PATH_MAX]; /* current base directory */
167 static	struct mpage	*mpage_head; /* list of distinct manual pages */
168 static	struct ohash	 mpages; /* table of distinct manual pages */
169 static	struct ohash	 mlinks; /* table of directory entries */
170 static	struct ohash	 names; /* table of all names */
171 static	struct ohash	 strings; /* table of all strings */
172 static	uint64_t	 name_mask;
173 
174 static	const struct mdoc_handler mdoc_handlers[MDOC_MAX - MDOC_Dd] = {
175 	{ NULL, 0, NODE_NOPRT },  /* Dd */
176 	{ NULL, 0, NODE_NOPRT },  /* Dt */
177 	{ NULL, 0, NODE_NOPRT },  /* Os */
178 	{ parse_mdoc_Sh, TYPE_Sh, 0 }, /* Sh */
179 	{ parse_mdoc_head, TYPE_Ss, 0 }, /* Ss */
180 	{ NULL, 0, 0 },  /* Pp */
181 	{ NULL, 0, 0 },  /* D1 */
182 	{ NULL, 0, 0 },  /* Dl */
183 	{ NULL, 0, 0 },  /* Bd */
184 	{ NULL, 0, 0 },  /* Ed */
185 	{ NULL, 0, 0 },  /* Bl */
186 	{ NULL, 0, 0 },  /* El */
187 	{ NULL, 0, 0 },  /* It */
188 	{ NULL, 0, 0 },  /* Ad */
189 	{ NULL, TYPE_An, 0 },  /* An */
190 	{ NULL, 0, 0 },  /* Ap */
191 	{ NULL, TYPE_Ar, 0 },  /* Ar */
192 	{ NULL, TYPE_Cd, 0 },  /* Cd */
193 	{ NULL, TYPE_Cm, 0 },  /* Cm */
194 	{ NULL, TYPE_Dv, 0 },  /* Dv */
195 	{ NULL, TYPE_Er, 0 },  /* Er */
196 	{ NULL, TYPE_Ev, 0 },  /* Ev */
197 	{ NULL, 0, 0 },  /* Ex */
198 	{ parse_mdoc_Fa, 0, 0 },  /* Fa */
199 	{ parse_mdoc_Fd, 0, 0 },  /* Fd */
200 	{ NULL, TYPE_Fl, 0 },  /* Fl */
201 	{ parse_mdoc_Fn, 0, 0 },  /* Fn */
202 	{ NULL, TYPE_Ft | TYPE_Vt, 0 },  /* Ft */
203 	{ NULL, TYPE_Ic, 0 },  /* Ic */
204 	{ NULL, TYPE_In, 0 },  /* In */
205 	{ NULL, TYPE_Li, 0 },  /* Li */
206 	{ parse_mdoc_Nd, 0, 0 },  /* Nd */
207 	{ parse_mdoc_Nm, 0, 0 },  /* Nm */
208 	{ NULL, 0, 0 },  /* Op */
209 	{ NULL, 0, 0 },  /* Ot */
210 	{ NULL, TYPE_Pa, NODE_NOSRC },  /* Pa */
211 	{ NULL, 0, 0 },  /* Rv */
212 	{ NULL, TYPE_St, 0 },  /* St */
213 	{ parse_mdoc_Va, TYPE_Va, 0 },  /* Va */
214 	{ parse_mdoc_Va, TYPE_Vt, 0 },  /* Vt */
215 	{ parse_mdoc_Xr, 0, 0 },  /* Xr */
216 	{ NULL, 0, 0 },  /* %A */
217 	{ NULL, 0, 0 },  /* %B */
218 	{ NULL, 0, 0 },  /* %D */
219 	{ NULL, 0, 0 },  /* %I */
220 	{ NULL, 0, 0 },  /* %J */
221 	{ NULL, 0, 0 },  /* %N */
222 	{ NULL, 0, 0 },  /* %O */
223 	{ NULL, 0, 0 },  /* %P */
224 	{ NULL, 0, 0 },  /* %R */
225 	{ NULL, 0, 0 },  /* %T */
226 	{ NULL, 0, 0 },  /* %V */
227 	{ NULL, 0, 0 },  /* Ac */
228 	{ NULL, 0, 0 },  /* Ao */
229 	{ NULL, 0, 0 },  /* Aq */
230 	{ NULL, TYPE_At, 0 },  /* At */
231 	{ NULL, 0, 0 },  /* Bc */
232 	{ NULL, 0, 0 },  /* Bf */
233 	{ NULL, 0, 0 },  /* Bo */
234 	{ NULL, 0, 0 },  /* Bq */
235 	{ NULL, TYPE_Bsx, NODE_NOSRC },  /* Bsx */
236 	{ NULL, TYPE_Bx, NODE_NOSRC },  /* Bx */
237 	{ NULL, 0, 0 },  /* Db */
238 	{ NULL, 0, 0 },  /* Dc */
239 	{ NULL, 0, 0 },  /* Do */
240 	{ NULL, 0, 0 },  /* Dq */
241 	{ NULL, 0, 0 },  /* Ec */
242 	{ NULL, 0, 0 },  /* Ef */
243 	{ NULL, TYPE_Em, 0 },  /* Em */
244 	{ NULL, 0, 0 },  /* Eo */
245 	{ NULL, TYPE_Fx, NODE_NOSRC },  /* Fx */
246 	{ NULL, TYPE_Ms, 0 },  /* Ms */
247 	{ NULL, 0, 0 },  /* No */
248 	{ NULL, 0, 0 },  /* Ns */
249 	{ NULL, TYPE_Nx, NODE_NOSRC },  /* Nx */
250 	{ NULL, TYPE_Ox, NODE_NOSRC },  /* Ox */
251 	{ NULL, 0, 0 },  /* Pc */
252 	{ NULL, 0, 0 },  /* Pf */
253 	{ NULL, 0, 0 },  /* Po */
254 	{ NULL, 0, 0 },  /* Pq */
255 	{ NULL, 0, 0 },  /* Qc */
256 	{ NULL, 0, 0 },  /* Ql */
257 	{ NULL, 0, 0 },  /* Qo */
258 	{ NULL, 0, 0 },  /* Qq */
259 	{ NULL, 0, 0 },  /* Re */
260 	{ NULL, 0, 0 },  /* Rs */
261 	{ NULL, 0, 0 },  /* Sc */
262 	{ NULL, 0, 0 },  /* So */
263 	{ NULL, 0, 0 },  /* Sq */
264 	{ NULL, 0, 0 },  /* Sm */
265 	{ NULL, 0, 0 },  /* Sx */
266 	{ NULL, TYPE_Sy, 0 },  /* Sy */
267 	{ NULL, TYPE_Tn, 0 },  /* Tn */
268 	{ NULL, 0, NODE_NOSRC },  /* Ux */
269 	{ NULL, 0, 0 },  /* Xc */
270 	{ NULL, 0, 0 },  /* Xo */
271 	{ parse_mdoc_Fo, 0, 0 },  /* Fo */
272 	{ NULL, 0, 0 },  /* Fc */
273 	{ NULL, 0, 0 },  /* Oo */
274 	{ NULL, 0, 0 },  /* Oc */
275 	{ NULL, 0, 0 },  /* Bk */
276 	{ NULL, 0, 0 },  /* Ek */
277 	{ NULL, 0, 0 },  /* Bt */
278 	{ NULL, 0, 0 },  /* Hf */
279 	{ NULL, 0, 0 },  /* Fr */
280 	{ NULL, 0, 0 },  /* Ud */
281 	{ NULL, TYPE_Lb, NODE_NOSRC },  /* Lb */
282 	{ NULL, 0, 0 },  /* Lp */
283 	{ NULL, TYPE_Lk, 0 },  /* Lk */
284 	{ NULL, TYPE_Mt, NODE_NOSRC },  /* Mt */
285 	{ NULL, 0, 0 },  /* Brq */
286 	{ NULL, 0, 0 },  /* Bro */
287 	{ NULL, 0, 0 },  /* Brc */
288 	{ NULL, 0, 0 },  /* %C */
289 	{ NULL, 0, 0 },  /* Es */
290 	{ NULL, 0, 0 },  /* En */
291 	{ NULL, TYPE_Dx, NODE_NOSRC },  /* Dx */
292 	{ NULL, 0, 0 },  /* %Q */
293 	{ NULL, 0, 0 },  /* %U */
294 	{ NULL, 0, 0 },  /* Ta */
295 };
296 
297 
298 int
299 mandocdb(int argc, char *argv[])
300 {
301 	struct manconf	  conf;
302 	struct mparse	 *mp;
303 	struct dba	 *dba;
304 	const char	 *path_arg, *progname;
305 	size_t		  j, sz;
306 	int		  ch, i;
307 
308 	if (pledge("stdio rpath wpath cpath", 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 	mparse_options = MPARSE_VALIDATE;
327 	path_arg = NULL;
328 	op = OP_DEFAULT;
329 
330 	while (-1 != (ch = getopt(argc, argv, "aC:Dd:npQT:tu:v")))
331 		switch (ch) {
332 		case 'a':
333 			use_all = 1;
334 			break;
335 		case 'C':
336 			CHECKOP(op, ch);
337 			path_arg = optarg;
338 			op = OP_CONFFILE;
339 			break;
340 		case 'D':
341 			debug++;
342 			break;
343 		case 'd':
344 			CHECKOP(op, ch);
345 			path_arg = optarg;
346 			op = OP_UPDATE;
347 			break;
348 		case 'n':
349 			nodb = 1;
350 			break;
351 		case 'p':
352 			warnings = 1;
353 			break;
354 		case 'Q':
355 			mparse_options |= MPARSE_QUICK;
356 			break;
357 		case 'T':
358 			if (strcmp(optarg, "utf8")) {
359 				warnx("-T%s: Unsupported output format",
360 				    optarg);
361 				goto usage;
362 			}
363 			write_utf8 = 1;
364 			break;
365 		case 't':
366 			CHECKOP(op, ch);
367 			dup2(STDOUT_FILENO, STDERR_FILENO);
368 			op = OP_TEST;
369 			nodb = warnings = 1;
370 			break;
371 		case 'u':
372 			CHECKOP(op, ch);
373 			path_arg = optarg;
374 			op = OP_DELETE;
375 			break;
376 		case 'v':
377 			/* Compatibility with espie@'s makewhatis. */
378 			break;
379 		default:
380 			goto usage;
381 		}
382 
383 	argc -= optind;
384 	argv += optind;
385 
386 	if (nodb) {
387 		if (pledge("stdio rpath", NULL) == -1) {
388 			warn("pledge");
389 			return (int)MANDOCLEVEL_SYSERR;
390 		}
391 	}
392 
393 	if (OP_CONFFILE == op && argc > 0) {
394 		warnx("-C: Too many arguments");
395 		goto usage;
396 	}
397 
398 	exitcode = (int)MANDOCLEVEL_OK;
399 	mchars_alloc();
400 	mp = mparse_alloc(mparse_options, 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_meta	*meta;
1082 	char			*cp;
1083 	int			 fd;
1084 
1085 	for (mpage = mpage_head; mpage != NULL; mpage = mpage->next) {
1086 		mlinks_undupe(mpage);
1087 		if ((mlink = mpage->mlinks) == NULL)
1088 			continue;
1089 
1090 		name_mask = NAME_MASK;
1091 		mandoc_ohash_init(&names, 4, offsetof(struct str, key));
1092 		mandoc_ohash_init(&strings, 6, offsetof(struct str, key));
1093 		mparse_reset(mp);
1094 		meta = NULL;
1095 
1096 		if ((fd = mparse_open(mp, mlink->file)) == -1) {
1097 			say(mlink->file, "&open");
1098 			goto nextpage;
1099 		}
1100 
1101 		/*
1102 		 * Interpret the file as mdoc(7) or man(7) source
1103 		 * code, unless it is known to be formatted.
1104 		 */
1105 		if (mlink->dform != FORM_CAT || mlink->fform != FORM_CAT) {
1106 			mparse_readfd(mp, fd, mlink->file);
1107 			close(fd);
1108 			fd = -1;
1109 			meta = mparse_result(mp);
1110 		}
1111 
1112 		if (meta != NULL && meta->sodest != NULL) {
1113 			mlink_dest = ohash_find(&mlinks,
1114 			    ohash_qlookup(&mlinks, meta->sodest));
1115 			if (mlink_dest == NULL) {
1116 				mandoc_asprintf(&cp, "%s.gz", meta->sodest);
1117 				mlink_dest = ohash_find(&mlinks,
1118 				    ohash_qlookup(&mlinks, cp));
1119 				free(cp);
1120 			}
1121 			if (mlink_dest != NULL) {
1122 
1123 				/* The .so target exists. */
1124 
1125 				mpage_dest = mlink_dest->mpage;
1126 				while (1) {
1127 					mlink->mpage = mpage_dest;
1128 
1129 					/*
1130 					 * If the target was already
1131 					 * processed, add the links
1132 					 * to the database now.
1133 					 * Otherwise, this will
1134 					 * happen when we come
1135 					 * to the target.
1136 					 */
1137 
1138 					if (mpage_dest->dba != NULL)
1139 						dbadd_mlink(mlink);
1140 
1141 					if (mlink->next == NULL)
1142 						break;
1143 					mlink = mlink->next;
1144 				}
1145 
1146 				/* Move all links to the target. */
1147 
1148 				mlink->next = mlink_dest->next;
1149 				mlink_dest->next = mpage->mlinks;
1150 				mpage->mlinks = NULL;
1151 				goto nextpage;
1152 			}
1153 			meta->macroset = MACROSET_NONE;
1154 		}
1155 		if (meta != NULL && meta->macroset == MACROSET_MDOC) {
1156 			mpage->form = FORM_SRC;
1157 			mpage->sec = meta->msec;
1158 			mpage->sec = mandoc_strdup(
1159 			    mpage->sec == NULL ? "" : mpage->sec);
1160 			mpage->arch = meta->arch;
1161 			mpage->arch = mandoc_strdup(
1162 			    mpage->arch == NULL ? "" : mpage->arch);
1163 			mpage->title = mandoc_strdup(meta->title);
1164 		} else if (meta != NULL && meta->macroset == MACROSET_MAN) {
1165 			if (*meta->msec != '\0' || *meta->title != '\0') {
1166 				mpage->form = FORM_SRC;
1167 				mpage->sec = mandoc_strdup(meta->msec);
1168 				mpage->arch = mandoc_strdup(mlink->arch);
1169 				mpage->title = mandoc_strdup(meta->title);
1170 			} else
1171 				meta = NULL;
1172 		}
1173 
1174 		assert(mpage->desc == NULL);
1175 		if (meta == NULL || meta->sodest != NULL) {
1176 			mpage->sec = mandoc_strdup(mlink->dsec);
1177 			mpage->arch = mandoc_strdup(mlink->arch);
1178 			mpage->title = mandoc_strdup(mlink->name);
1179 			if (meta == NULL) {
1180 				mpage->form = FORM_CAT;
1181 				parse_cat(mpage, fd);
1182 			} else
1183 				mpage->form = FORM_SRC;
1184 		} else if (meta->macroset == MACROSET_MDOC)
1185 			parse_mdoc(mpage, meta, meta->first);
1186 		else
1187 			parse_man(mpage, meta, meta->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 	const struct mdoc_handler *handler;
1512 
1513 	for (n = n->child; n != NULL; n = n->next) {
1514 		if (n->tok == TOKEN_NONE || n->tok < ROFF_MAX)
1515 			continue;
1516 		assert(n->tok >= MDOC_Dd && n->tok < MDOC_MAX);
1517 		handler = mdoc_handlers + (n->tok - MDOC_Dd);
1518 		if (n->flags & handler->taboo)
1519 			continue;
1520 
1521 		switch (n->type) {
1522 		case ROFFT_ELEM:
1523 		case ROFFT_BLOCK:
1524 		case ROFFT_HEAD:
1525 		case ROFFT_BODY:
1526 		case ROFFT_TAIL:
1527 			if (handler->fp != NULL &&
1528 			    (*handler->fp)(mpage, meta, n) == 0)
1529 				break;
1530 			if (handler->mask)
1531 				putmdockey(mpage, n->child,
1532 				    handler->mask, handler->taboo);
1533 			break;
1534 		default:
1535 			continue;
1536 		}
1537 		if (NULL != n->child)
1538 			parse_mdoc(mpage, meta, n);
1539 	}
1540 }
1541 
1542 static int
1543 parse_mdoc_Fa(struct mpage *mpage, const struct roff_meta *meta,
1544 	const struct roff_node *n)
1545 {
1546 	uint64_t mask;
1547 
1548 	mask = TYPE_Fa;
1549 	if (n->sec == SEC_SYNOPSIS)
1550 		mask |= TYPE_Vt;
1551 
1552 	putmdockey(mpage, n->child, mask, 0);
1553 	return 0;
1554 }
1555 
1556 static int
1557 parse_mdoc_Fd(struct mpage *mpage, const struct roff_meta *meta,
1558 	const struct roff_node *n)
1559 {
1560 	char		*start, *end;
1561 	size_t		 sz;
1562 
1563 	if (SEC_SYNOPSIS != n->sec ||
1564 	    NULL == (n = n->child) ||
1565 	    n->type != ROFFT_TEXT)
1566 		return 0;
1567 
1568 	/*
1569 	 * Only consider those `Fd' macro fields that begin with an
1570 	 * "inclusion" token (versus, e.g., #define).
1571 	 */
1572 
1573 	if (strcmp("#include", n->string))
1574 		return 0;
1575 
1576 	if ((n = n->next) == NULL || n->type != ROFFT_TEXT)
1577 		return 0;
1578 
1579 	/*
1580 	 * Strip away the enclosing angle brackets and make sure we're
1581 	 * not zero-length.
1582 	 */
1583 
1584 	start = n->string;
1585 	if ('<' == *start || '"' == *start)
1586 		start++;
1587 
1588 	if (0 == (sz = strlen(start)))
1589 		return 0;
1590 
1591 	end = &start[(int)sz - 1];
1592 	if ('>' == *end || '"' == *end)
1593 		end--;
1594 
1595 	if (end > start)
1596 		putkeys(mpage, start, end - start + 1, TYPE_In);
1597 	return 0;
1598 }
1599 
1600 static void
1601 parse_mdoc_fname(struct mpage *mpage, const struct roff_node *n)
1602 {
1603 	char	*cp;
1604 	size_t	 sz;
1605 
1606 	if (n->type != ROFFT_TEXT)
1607 		return;
1608 
1609 	/* Skip function pointer punctuation. */
1610 
1611 	cp = n->string;
1612 	while (*cp == '(' || *cp == '*')
1613 		cp++;
1614 	sz = strcspn(cp, "()");
1615 
1616 	putkeys(mpage, cp, sz, TYPE_Fn);
1617 	if (n->sec == SEC_SYNOPSIS)
1618 		putkeys(mpage, cp, sz, NAME_SYN);
1619 }
1620 
1621 static int
1622 parse_mdoc_Fn(struct mpage *mpage, const struct roff_meta *meta,
1623 	const struct roff_node *n)
1624 {
1625 	uint64_t mask;
1626 
1627 	if (n->child == NULL)
1628 		return 0;
1629 
1630 	parse_mdoc_fname(mpage, n->child);
1631 
1632 	n = n->child->next;
1633 	if (n != NULL && n->type == ROFFT_TEXT) {
1634 		mask = TYPE_Fa;
1635 		if (n->sec == SEC_SYNOPSIS)
1636 			mask |= TYPE_Vt;
1637 		putmdockey(mpage, n, mask, 0);
1638 	}
1639 
1640 	return 0;
1641 }
1642 
1643 static int
1644 parse_mdoc_Fo(struct mpage *mpage, const struct roff_meta *meta,
1645 	const struct roff_node *n)
1646 {
1647 
1648 	if (n->type != ROFFT_HEAD)
1649 		return 1;
1650 
1651 	if (n->child != NULL)
1652 		parse_mdoc_fname(mpage, n->child);
1653 
1654 	return 0;
1655 }
1656 
1657 static int
1658 parse_mdoc_Va(struct mpage *mpage, const struct roff_meta *meta,
1659 	const struct roff_node *n)
1660 {
1661 	char *cp;
1662 
1663 	if (n->type != ROFFT_ELEM && n->type != ROFFT_BODY)
1664 		return 0;
1665 
1666 	if (n->child != NULL &&
1667 	    n->child->next == NULL &&
1668 	    n->child->type == ROFFT_TEXT)
1669 		return 1;
1670 
1671 	cp = NULL;
1672 	deroff(&cp, n);
1673 	if (cp != NULL) {
1674 		putkey(mpage, cp, TYPE_Vt | (n->tok == MDOC_Va ||
1675 		    n->type == ROFFT_BODY ? TYPE_Va : 0));
1676 		free(cp);
1677 	}
1678 
1679 	return 0;
1680 }
1681 
1682 static int
1683 parse_mdoc_Xr(struct mpage *mpage, const struct roff_meta *meta,
1684 	const struct roff_node *n)
1685 {
1686 	char	*cp;
1687 
1688 	if (NULL == (n = n->child))
1689 		return 0;
1690 
1691 	if (NULL == n->next) {
1692 		putkey(mpage, n->string, TYPE_Xr);
1693 		return 0;
1694 	}
1695 
1696 	mandoc_asprintf(&cp, "%s(%s)", n->string, n->next->string);
1697 	putkey(mpage, cp, TYPE_Xr);
1698 	free(cp);
1699 	return 0;
1700 }
1701 
1702 static int
1703 parse_mdoc_Nd(struct mpage *mpage, const struct roff_meta *meta,
1704 	const struct roff_node *n)
1705 {
1706 
1707 	if (n->type == ROFFT_BODY)
1708 		deroff(&mpage->desc, n);
1709 	return 0;
1710 }
1711 
1712 static int
1713 parse_mdoc_Nm(struct mpage *mpage, const struct roff_meta *meta,
1714 	const struct roff_node *n)
1715 {
1716 
1717 	if (SEC_NAME == n->sec)
1718 		putmdockey(mpage, n->child, NAME_TITLE, 0);
1719 	else if (n->sec == SEC_SYNOPSIS && n->type == ROFFT_HEAD) {
1720 		if (n->child == NULL)
1721 			putkey(mpage, meta->name, NAME_SYN);
1722 		else
1723 			putmdockey(mpage, n->child, NAME_SYN, 0);
1724 	}
1725 	if ( ! (mpage->name_head_done ||
1726 	    n->child == NULL || n->child->string == NULL ||
1727 	    strcasecmp(n->child->string, meta->title))) {
1728 		putkey(mpage, n->child->string, NAME_HEAD);
1729 		mpage->name_head_done = 1;
1730 	}
1731 	return 0;
1732 }
1733 
1734 static int
1735 parse_mdoc_Sh(struct mpage *mpage, const struct roff_meta *meta,
1736 	const struct roff_node *n)
1737 {
1738 
1739 	return n->sec == SEC_CUSTOM && n->type == ROFFT_HEAD;
1740 }
1741 
1742 static int
1743 parse_mdoc_head(struct mpage *mpage, const struct roff_meta *meta,
1744 	const struct roff_node *n)
1745 {
1746 
1747 	return n->type == ROFFT_HEAD;
1748 }
1749 
1750 /*
1751  * Add a string to the hash table for the current manual.
1752  * Each string has a bitmask telling which macros it belongs to.
1753  * When we finish the manual, we'll dump the table.
1754  */
1755 static void
1756 putkeys(const struct mpage *mpage, char *cp, size_t sz, uint64_t v)
1757 {
1758 	struct ohash	*htab;
1759 	struct str	*s;
1760 	const char	*end;
1761 	unsigned int	 slot;
1762 	int		 i, mustfree;
1763 
1764 	if (0 == sz)
1765 		return;
1766 
1767 	mustfree = render_string(&cp, &sz);
1768 
1769 	if (TYPE_Nm & v) {
1770 		htab = &names;
1771 		v &= name_mask;
1772 		if (v & NAME_FIRST)
1773 			name_mask &= ~NAME_FIRST;
1774 		if (debug > 1)
1775 			say(mpage->mlinks->file,
1776 			    "Adding name %*s, bits=0x%llx", (int)sz, cp,
1777 			    (unsigned long long)v);
1778 	} else {
1779 		htab = &strings;
1780 		if (debug > 1)
1781 		    for (i = 0; i < KEY_MAX; i++)
1782 			if ((uint64_t)1 << i & v)
1783 			    say(mpage->mlinks->file,
1784 				"Adding key %s=%*s",
1785 				mansearch_keynames[i], (int)sz, cp);
1786 	}
1787 
1788 	end = cp + sz;
1789 	slot = ohash_qlookupi(htab, cp, &end);
1790 	s = ohash_find(htab, slot);
1791 
1792 	if (NULL != s && mpage == s->mpage) {
1793 		s->mask |= v;
1794 		return;
1795 	} else if (NULL == s) {
1796 		s = mandoc_calloc(1, sizeof(struct str) + sz + 1);
1797 		memcpy(s->key, cp, sz);
1798 		ohash_insert(htab, slot, s);
1799 	}
1800 	s->mpage = mpage;
1801 	s->mask = v;
1802 
1803 	if (mustfree)
1804 		free(cp);
1805 }
1806 
1807 /*
1808  * Take a Unicode codepoint and produce its UTF-8 encoding.
1809  * This isn't the best way to do this, but it works.
1810  * The magic numbers are from the UTF-8 packaging.
1811  * They're not as scary as they seem: read the UTF-8 spec for details.
1812  */
1813 static size_t
1814 utf8(unsigned int cp, char out[7])
1815 {
1816 	size_t		 rc;
1817 
1818 	rc = 0;
1819 	if (cp <= 0x0000007F) {
1820 		rc = 1;
1821 		out[0] = (char)cp;
1822 	} else if (cp <= 0x000007FF) {
1823 		rc = 2;
1824 		out[0] = (cp >> 6  & 31) | 192;
1825 		out[1] = (cp       & 63) | 128;
1826 	} else if (cp <= 0x0000FFFF) {
1827 		rc = 3;
1828 		out[0] = (cp >> 12 & 15) | 224;
1829 		out[1] = (cp >> 6  & 63) | 128;
1830 		out[2] = (cp       & 63) | 128;
1831 	} else if (cp <= 0x001FFFFF) {
1832 		rc = 4;
1833 		out[0] = (cp >> 18 &  7) | 240;
1834 		out[1] = (cp >> 12 & 63) | 128;
1835 		out[2] = (cp >> 6  & 63) | 128;
1836 		out[3] = (cp       & 63) | 128;
1837 	} else if (cp <= 0x03FFFFFF) {
1838 		rc = 5;
1839 		out[0] = (cp >> 24 &  3) | 248;
1840 		out[1] = (cp >> 18 & 63) | 128;
1841 		out[2] = (cp >> 12 & 63) | 128;
1842 		out[3] = (cp >> 6  & 63) | 128;
1843 		out[4] = (cp       & 63) | 128;
1844 	} else if (cp <= 0x7FFFFFFF) {
1845 		rc = 6;
1846 		out[0] = (cp >> 30 &  1) | 252;
1847 		out[1] = (cp >> 24 & 63) | 128;
1848 		out[2] = (cp >> 18 & 63) | 128;
1849 		out[3] = (cp >> 12 & 63) | 128;
1850 		out[4] = (cp >> 6  & 63) | 128;
1851 		out[5] = (cp       & 63) | 128;
1852 	} else
1853 		return 0;
1854 
1855 	out[rc] = '\0';
1856 	return rc;
1857 }
1858 
1859 /*
1860  * If the string contains escape sequences,
1861  * replace it with an allocated rendering and return 1,
1862  * such that the caller can free it after use.
1863  * Otherwise, do nothing and return 0.
1864  */
1865 static int
1866 render_string(char **public, size_t *psz)
1867 {
1868 	const char	*src, *scp, *addcp, *seq;
1869 	char		*dst;
1870 	size_t		 ssz, dsz, addsz;
1871 	char		 utfbuf[7], res[6];
1872 	int		 seqlen, unicode;
1873 
1874 	res[0] = '\\';
1875 	res[1] = '\t';
1876 	res[2] = ASCII_NBRSP;
1877 	res[3] = ASCII_HYPH;
1878 	res[4] = ASCII_BREAK;
1879 	res[5] = '\0';
1880 
1881 	src = scp = *public;
1882 	ssz = *psz;
1883 	dst = NULL;
1884 	dsz = 0;
1885 
1886 	while (scp < src + *psz) {
1887 
1888 		/* Leave normal characters unchanged. */
1889 
1890 		if (strchr(res, *scp) == NULL) {
1891 			if (dst != NULL)
1892 				dst[dsz++] = *scp;
1893 			scp++;
1894 			continue;
1895 		}
1896 
1897 		/*
1898 		 * Found something that requires replacing,
1899 		 * make sure we have a destination buffer.
1900 		 */
1901 
1902 		if (dst == NULL) {
1903 			dst = mandoc_malloc(ssz + 1);
1904 			dsz = scp - src;
1905 			memcpy(dst, src, dsz);
1906 		}
1907 
1908 		/* Handle single-char special characters. */
1909 
1910 		switch (*scp) {
1911 		case '\\':
1912 			break;
1913 		case '\t':
1914 		case ASCII_NBRSP:
1915 			dst[dsz++] = ' ';
1916 			scp++;
1917 			continue;
1918 		case ASCII_HYPH:
1919 			dst[dsz++] = '-';
1920 			/* FALLTHROUGH */
1921 		case ASCII_BREAK:
1922 			scp++;
1923 			continue;
1924 		default:
1925 			abort();
1926 		}
1927 
1928 		/*
1929 		 * Found an escape sequence.
1930 		 * Read past the slash, then parse it.
1931 		 * Ignore everything except characters.
1932 		 */
1933 
1934 		scp++;
1935 		if (mandoc_escape(&scp, &seq, &seqlen) != ESCAPE_SPECIAL)
1936 			continue;
1937 
1938 		/*
1939 		 * Render the special character
1940 		 * as either UTF-8 or ASCII.
1941 		 */
1942 
1943 		if (write_utf8) {
1944 			unicode = mchars_spec2cp(seq, seqlen);
1945 			if (unicode <= 0)
1946 				continue;
1947 			addsz = utf8(unicode, utfbuf);
1948 			if (addsz == 0)
1949 				continue;
1950 			addcp = utfbuf;
1951 		} else {
1952 			addcp = mchars_spec2str(seq, seqlen, &addsz);
1953 			if (addcp == NULL)
1954 				continue;
1955 			if (*addcp == ASCII_NBRSP) {
1956 				addcp = " ";
1957 				addsz = 1;
1958 			}
1959 		}
1960 
1961 		/* Copy the rendered glyph into the stream. */
1962 
1963 		ssz += addsz;
1964 		dst = mandoc_realloc(dst, ssz + 1);
1965 		memcpy(dst + dsz, addcp, addsz);
1966 		dsz += addsz;
1967 	}
1968 	if (dst != NULL) {
1969 		*public = dst;
1970 		*psz = dsz;
1971 	}
1972 
1973 	/* Trim trailing whitespace and NUL-terminate. */
1974 
1975 	while (*psz > 0 && (*public)[*psz - 1] == ' ')
1976 		--*psz;
1977 	if (dst != NULL) {
1978 		(*public)[*psz] = '\0';
1979 		return 1;
1980 	} else
1981 		return 0;
1982 }
1983 
1984 static void
1985 dbadd_mlink(const struct mlink *mlink)
1986 {
1987 	dba_page_alias(mlink->mpage->dba, mlink->name, NAME_FILE);
1988 	dba_page_add(mlink->mpage->dba, DBP_SECT, mlink->dsec);
1989 	dba_page_add(mlink->mpage->dba, DBP_SECT, mlink->fsec);
1990 	dba_page_add(mlink->mpage->dba, DBP_ARCH, mlink->arch);
1991 	dba_page_add(mlink->mpage->dba, DBP_FILE, mlink->file);
1992 }
1993 
1994 /*
1995  * Flush the current page's terms (and their bits) into the database.
1996  * Also, handle escape sequences at the last possible moment.
1997  */
1998 static void
1999 dbadd(struct dba *dba, struct mpage *mpage)
2000 {
2001 	struct mlink	*mlink;
2002 	struct str	*key;
2003 	char		*cp;
2004 	uint64_t	 mask;
2005 	size_t		 i;
2006 	unsigned int	 slot;
2007 	int		 mustfree;
2008 
2009 	mlink = mpage->mlinks;
2010 
2011 	if (nodb) {
2012 		for (key = ohash_first(&names, &slot); NULL != key;
2013 		     key = ohash_next(&names, &slot))
2014 			free(key);
2015 		for (key = ohash_first(&strings, &slot); NULL != key;
2016 		     key = ohash_next(&strings, &slot))
2017 			free(key);
2018 		if (0 == debug)
2019 			return;
2020 		while (NULL != mlink) {
2021 			fputs(mlink->name, stdout);
2022 			if (NULL == mlink->next ||
2023 			    strcmp(mlink->dsec, mlink->next->dsec) ||
2024 			    strcmp(mlink->fsec, mlink->next->fsec) ||
2025 			    strcmp(mlink->arch, mlink->next->arch)) {
2026 				putchar('(');
2027 				if ('\0' == *mlink->dsec)
2028 					fputs(mlink->fsec, stdout);
2029 				else
2030 					fputs(mlink->dsec, stdout);
2031 				if ('\0' != *mlink->arch)
2032 					printf("/%s", mlink->arch);
2033 				putchar(')');
2034 			}
2035 			mlink = mlink->next;
2036 			if (NULL != mlink)
2037 				fputs(", ", stdout);
2038 		}
2039 		printf(" - %s\n", mpage->desc);
2040 		return;
2041 	}
2042 
2043 	if (debug)
2044 		say(mlink->file, "Adding to database");
2045 
2046 	cp = mpage->desc;
2047 	i = strlen(cp);
2048 	mustfree = render_string(&cp, &i);
2049 	mpage->dba = dba_page_new(dba->pages,
2050 	    *mpage->arch == '\0' ? mlink->arch : mpage->arch,
2051 	    cp, mlink->file, mpage->form);
2052 	if (mustfree)
2053 		free(cp);
2054 	dba_page_add(mpage->dba, DBP_SECT, mpage->sec);
2055 
2056 	while (mlink != NULL) {
2057 		dbadd_mlink(mlink);
2058 		mlink = mlink->next;
2059 	}
2060 
2061 	for (key = ohash_first(&names, &slot); NULL != key;
2062 	     key = ohash_next(&names, &slot)) {
2063 		assert(key->mpage == mpage);
2064 		dba_page_alias(mpage->dba, key->key, key->mask);
2065 		free(key);
2066 	}
2067 	for (key = ohash_first(&strings, &slot); NULL != key;
2068 	     key = ohash_next(&strings, &slot)) {
2069 		assert(key->mpage == mpage);
2070 		i = 0;
2071 		for (mask = TYPE_Xr; mask <= TYPE_Lb; mask *= 2) {
2072 			if (key->mask & mask)
2073 				dba_macro_add(dba->macros, i,
2074 				    key->key, mpage->dba);
2075 			i++;
2076 		}
2077 		free(key);
2078 	}
2079 }
2080 
2081 static void
2082 dbprune(struct dba *dba)
2083 {
2084 	struct dba_array	*page, *files;
2085 	char			*file;
2086 
2087 	dba_array_FOREACH(dba->pages, page) {
2088 		files = dba_array_get(page, DBP_FILE);
2089 		dba_array_FOREACH(files, file) {
2090 			if (*file < ' ')
2091 				file++;
2092 			if (ohash_find(&mlinks, ohash_qlookup(&mlinks,
2093 			    file)) != NULL) {
2094 				if (debug)
2095 					say(file, "Deleting from database");
2096 				dba_array_del(dba->pages);
2097 				break;
2098 			}
2099 		}
2100 	}
2101 }
2102 
2103 /*
2104  * Write the database from memory to disk.
2105  */
2106 static void
2107 dbwrite(struct dba *dba)
2108 {
2109 	struct stat	 sb1, sb2;
2110 	char		 tfn[33], *cp1, *cp2;
2111 	off_t		 i;
2112 	int		 fd1, fd2;
2113 
2114 	/*
2115 	 * Do not write empty databases, and delete existing ones
2116 	 * when makewhatis -u causes them to become empty.
2117 	 */
2118 
2119 	dba_array_start(dba->pages);
2120 	if (dba_array_next(dba->pages) == NULL) {
2121 		if (unlink(MANDOC_DB) == -1 && errno != ENOENT)
2122 			say(MANDOC_DB, "&unlink");
2123 		return;
2124 	}
2125 
2126 	/*
2127 	 * Build the database in a temporary file,
2128 	 * then atomically move it into place.
2129 	 */
2130 
2131 	if (dba_write(MANDOC_DB "~", dba) != -1) {
2132 		if (rename(MANDOC_DB "~", MANDOC_DB) == -1) {
2133 			exitcode = (int)MANDOCLEVEL_SYSERR;
2134 			say(MANDOC_DB, "&rename");
2135 			unlink(MANDOC_DB "~");
2136 		}
2137 		return;
2138 	}
2139 
2140 	/*
2141 	 * We lack write permission and cannot replace the database
2142 	 * file, but let's at least check whether the data changed.
2143 	 */
2144 
2145 	(void)strlcpy(tfn, "/tmp/mandocdb.XXXXXXXX", sizeof(tfn));
2146 	if (mkdtemp(tfn) == NULL) {
2147 		exitcode = (int)MANDOCLEVEL_SYSERR;
2148 		say("", "&%s", tfn);
2149 		return;
2150 	}
2151 	cp1 = cp2 = MAP_FAILED;
2152 	fd1 = fd2 = -1;
2153 	(void)strlcat(tfn, "/" MANDOC_DB, sizeof(tfn));
2154 	if (dba_write(tfn, dba) == -1) {
2155 		say(tfn, "&dba_write");
2156 		goto err;
2157 	}
2158 	if ((fd1 = open(MANDOC_DB, O_RDONLY, 0)) == -1) {
2159 		say(MANDOC_DB, "&open");
2160 		goto err;
2161 	}
2162 	if ((fd2 = open(tfn, O_RDONLY, 0)) == -1) {
2163 		say(tfn, "&open");
2164 		goto err;
2165 	}
2166 	if (fstat(fd1, &sb1) == -1) {
2167 		say(MANDOC_DB, "&fstat");
2168 		goto err;
2169 	}
2170 	if (fstat(fd2, &sb2) == -1) {
2171 		say(tfn, "&fstat");
2172 		goto err;
2173 	}
2174 	if (sb1.st_size != sb2.st_size)
2175 		goto err;
2176 	if ((cp1 = mmap(NULL, sb1.st_size, PROT_READ, MAP_PRIVATE,
2177 	    fd1, 0)) == MAP_FAILED) {
2178 		say(MANDOC_DB, "&mmap");
2179 		goto err;
2180 	}
2181 	if ((cp2 = mmap(NULL, sb2.st_size, PROT_READ, MAP_PRIVATE,
2182 	    fd2, 0)) == MAP_FAILED) {
2183 		say(tfn, "&mmap");
2184 		goto err;
2185 	}
2186 	for (i = 0; i < sb1.st_size; i++)
2187 		if (cp1[i] != cp2[i])
2188 			goto err;
2189 	goto out;
2190 
2191 err:
2192 	exitcode = (int)MANDOCLEVEL_SYSERR;
2193 	say(MANDOC_DB, "Data changed, but cannot replace database");
2194 
2195 out:
2196 	if (cp1 != MAP_FAILED)
2197 		munmap(cp1, sb1.st_size);
2198 	if (cp2 != MAP_FAILED)
2199 		munmap(cp2, sb2.st_size);
2200 	if (fd1 != -1)
2201 		close(fd1);
2202 	if (fd2 != -1)
2203 		close(fd2);
2204 	unlink(tfn);
2205 	*strrchr(tfn, '/') = '\0';
2206 	rmdir(tfn);
2207 }
2208 
2209 static int
2210 set_basedir(const char *targetdir, int report_baddir)
2211 {
2212 	static char	 startdir[PATH_MAX];
2213 	static int	 getcwd_status;  /* 1 = ok, 2 = failure */
2214 	static int	 chdir_status;  /* 1 = changed directory */
2215 	char		*cp;
2216 
2217 	/*
2218 	 * Remember the original working directory, if possible.
2219 	 * This will be needed if the second or a later directory
2220 	 * on the command line is given as a relative path.
2221 	 * Do not error out if the current directory is not
2222 	 * searchable: Maybe it won't be needed after all.
2223 	 */
2224 	if (0 == getcwd_status) {
2225 		if (NULL == getcwd(startdir, sizeof(startdir))) {
2226 			getcwd_status = 2;
2227 			(void)strlcpy(startdir, strerror(errno),
2228 			    sizeof(startdir));
2229 		} else
2230 			getcwd_status = 1;
2231 	}
2232 
2233 	/*
2234 	 * We are leaving the old base directory.
2235 	 * Do not use it any longer, not even for messages.
2236 	 */
2237 	*basedir = '\0';
2238 
2239 	/*
2240 	 * If and only if the directory was changed earlier and
2241 	 * the next directory to process is given as a relative path,
2242 	 * first go back, or bail out if that is impossible.
2243 	 */
2244 	if (chdir_status && '/' != *targetdir) {
2245 		if (2 == getcwd_status) {
2246 			exitcode = (int)MANDOCLEVEL_SYSERR;
2247 			say("", "getcwd: %s", startdir);
2248 			return 0;
2249 		}
2250 		if (-1 == chdir(startdir)) {
2251 			exitcode = (int)MANDOCLEVEL_SYSERR;
2252 			say("", "&chdir %s", startdir);
2253 			return 0;
2254 		}
2255 	}
2256 
2257 	/*
2258 	 * Always resolve basedir to the canonicalized absolute
2259 	 * pathname and append a trailing slash, such that
2260 	 * we can reliably check whether files are inside.
2261 	 */
2262 	if (NULL == realpath(targetdir, basedir)) {
2263 		if (report_baddir || errno != ENOENT) {
2264 			exitcode = (int)MANDOCLEVEL_BADARG;
2265 			say("", "&%s: realpath", targetdir);
2266 		}
2267 		return 0;
2268 	} else if (-1 == chdir(basedir)) {
2269 		if (report_baddir || errno != ENOENT) {
2270 			exitcode = (int)MANDOCLEVEL_BADARG;
2271 			say("", "&chdir");
2272 		}
2273 		return 0;
2274 	}
2275 	chdir_status = 1;
2276 	cp = strchr(basedir, '\0');
2277 	if ('/' != cp[-1]) {
2278 		if (cp - basedir >= PATH_MAX - 1) {
2279 			exitcode = (int)MANDOCLEVEL_SYSERR;
2280 			say("", "Filename too long");
2281 			return 0;
2282 		}
2283 		*cp++ = '/';
2284 		*cp = '\0';
2285 	}
2286 	return 1;
2287 }
2288 
2289 static void
2290 say(const char *file, const char *format, ...)
2291 {
2292 	va_list		 ap;
2293 	int		 use_errno;
2294 
2295 	if ('\0' != *basedir)
2296 		fprintf(stderr, "%s", basedir);
2297 	if ('\0' != *basedir && '\0' != *file)
2298 		fputc('/', stderr);
2299 	if ('\0' != *file)
2300 		fprintf(stderr, "%s", file);
2301 
2302 	use_errno = 1;
2303 	if (NULL != format) {
2304 		switch (*format) {
2305 		case '&':
2306 			format++;
2307 			break;
2308 		case '\0':
2309 			format = NULL;
2310 			break;
2311 		default:
2312 			use_errno = 0;
2313 			break;
2314 		}
2315 	}
2316 	if (NULL != format) {
2317 		if ('\0' != *basedir || '\0' != *file)
2318 			fputs(": ", stderr);
2319 		va_start(ap, format);
2320 		vfprintf(stderr, format, ap);
2321 		va_end(ap);
2322 	}
2323 	if (use_errno) {
2324 		if ('\0' != *basedir || '\0' != *file || NULL != format)
2325 			fputs(": ", stderr);
2326 		perror(NULL);
2327 	} else
2328 		fputc('\n', stderr);
2329 }
2330