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