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