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