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