xref: /openbsd/usr.bin/mandoc/main.c (revision 097a140d)
1 /* $OpenBSD: main.c,v 1.256 2021/02/19 19:49:49 kn Exp $ */
2 /*
3  * Copyright (c) 2010-2012, 2014-2020 Ingo Schwarze <schwarze@openbsd.org>
4  * Copyright (c) 2008-2012 Kristaps Dzonsons <kristaps@bsd.lv>
5  * Copyright (c) 2010 Joerg Sonnenberger <joerg@netbsd.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  * Main program for mandoc(1), man(1), apropos(1), whatis(1), and help(1).
20  */
21 #include <sys/types.h>
22 #include <sys/ioctl.h>
23 #include <sys/param.h>	/* MACHINE */
24 #include <sys/stat.h>
25 #include <sys/wait.h>
26 
27 #include <assert.h>
28 #include <ctype.h>
29 #include <err.h>
30 #include <errno.h>
31 #include <fcntl.h>
32 #include <glob.h>
33 #include <limits.h>
34 #include <signal.h>
35 #include <stdio.h>
36 #include <stdint.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include <termios.h>
40 #include <time.h>
41 #include <unistd.h>
42 
43 #include "mandoc_aux.h"
44 #include "mandoc.h"
45 #include "mandoc_xr.h"
46 #include "roff.h"
47 #include "mdoc.h"
48 #include "man.h"
49 #include "mandoc_parse.h"
50 #include "tag.h"
51 #include "term_tag.h"
52 #include "main.h"
53 #include "manconf.h"
54 #include "mansearch.h"
55 
56 #define BINM_APROPOS	"apropos"
57 #define BINM_MAN	"man"
58 #define BINM_MAKEWHATIS	"makewhatis"
59 #define BINM_WHATIS	"whatis"
60 #define OSENUM		MANDOC_OS_OPENBSD
61 
62 enum	outmode {
63 	OUTMODE_DEF = 0,
64 	OUTMODE_FLN,
65 	OUTMODE_LST,
66 	OUTMODE_ALL,
67 	OUTMODE_ONE
68 };
69 
70 enum	outt {
71 	OUTT_ASCII = 0,	/* -Tascii */
72 	OUTT_LOCALE,	/* -Tlocale */
73 	OUTT_UTF8,	/* -Tutf8 */
74 	OUTT_TREE,	/* -Ttree */
75 	OUTT_MAN,	/* -Tman */
76 	OUTT_HTML,	/* -Thtml */
77 	OUTT_MARKDOWN,	/* -Tmarkdown */
78 	OUTT_LINT,	/* -Tlint */
79 	OUTT_PS,	/* -Tps */
80 	OUTT_PDF	/* -Tpdf */
81 };
82 
83 struct	outstate {
84 	struct tag_files *tag_files;	/* Tagging state variables. */
85 	void		 *outdata;	/* data for output */
86 	int		  use_pager;
87 	int		  wstop;	/* stop after a file with a warning */
88 	int		  had_output;	/* Some output was generated. */
89 	enum outt	  outtype;	/* which output to use */
90 };
91 
92 
93 int			  mandocdb(int, char *[]);
94 
95 static	void		  check_xr(void);
96 static	int		  fs_lookup(const struct manpaths *,
97 				size_t ipath, const char *,
98 				const char *, const char *,
99 				struct manpage **, size_t *);
100 static	int		  fs_search(const struct mansearch *,
101 				const struct manpaths *, const char *,
102 				struct manpage **, size_t *);
103 static	void		  glob_esc(char **, const char *, const char *);
104 static	void		  outdata_alloc(struct outstate *, struct manoutput *);
105 static	void		  parse(struct mparse *, int, const char *,
106 				struct outstate *, struct manoutput *);
107 static	void		  passthrough(int, int);
108 static	void		  process_onefile(struct mparse *, struct manpage *,
109 				int, struct outstate *, struct manconf *);
110 static	void		  run_pager(struct outstate *, char *);
111 static	pid_t		  spawn_pager(struct outstate *, char *);
112 static	void		  usage(enum argmode) __attribute__((__noreturn__));
113 static	int		  woptions(char *, enum mandoc_os *, int *);
114 
115 static	const int sec_prios[] = {1, 4, 5, 8, 6, 3, 7, 2, 9};
116 static	char		  help_arg[] = "help";
117 static	char		 *help_argv[] = {help_arg, NULL};
118 
119 
120 int
121 main(int argc, char *argv[])
122 {
123 	struct manconf	 conf;		/* Manpaths and output options. */
124 	struct outstate	 outst;		/* Output state. */
125 	struct winsize	 ws;		/* Result of ioctl(TIOCGWINSZ). */
126 	struct mansearch search;	/* Search options. */
127 	struct manpage	*res;		/* Complete list of search results. */
128 	struct manpage	*resn;		/* Search results for one name. */
129 	struct mparse	*mp;		/* Opaque parser object. */
130 	const char	*conf_file;	/* -C: alternate config file. */
131 	const char	*os_s;		/* -I: Operating system for display. */
132 	const char	*progname, *sec;
133 	char		*defpaths;	/* -M: override manpaths. */
134 	char		*auxpaths;	/* -m: additional manpaths. */
135 	char		*oarg;		/* -O: output option string. */
136 	char		*tagarg;	/* -O tag: default value. */
137 	unsigned char	*uc;
138 	size_t		 ressz;		/* Number of elements in res[]. */
139 	size_t		 resnsz;	/* Number of elements in resn[]. */
140 	size_t		 i, ib, ssz;
141 	int		 options;	/* Parser options. */
142 	int		 show_usage;	/* Invalid argument: give up. */
143 	int		 prio, best_prio;
144 	int		 startdir;
145 	int		 c;
146 	enum mandoc_os	 os_e;		/* Check base system conventions. */
147 	enum outmode	 outmode;	/* According to command line. */
148 
149 	progname = getprogname();
150 	mandoc_msg_setoutfile(stderr);
151 	if (strncmp(progname, "mandocdb", 8) == 0 ||
152 	    strcmp(progname, BINM_MAKEWHATIS) == 0)
153 		return mandocdb(argc, argv);
154 
155 	if (pledge("stdio rpath wpath cpath tmppath tty proc exec", NULL) == -1) {
156 		mandoc_msg(MANDOCERR_PLEDGE, 0, 0, "%s", strerror(errno));
157 		return mandoc_msg_getrc();
158 	}
159 
160 	/* Search options. */
161 
162 	memset(&conf, 0, sizeof(conf));
163 	conf_file = NULL;
164 	defpaths = auxpaths = NULL;
165 
166 	memset(&search, 0, sizeof(struct mansearch));
167 	search.outkey = "Nd";
168 	oarg = NULL;
169 
170 	if (strcmp(progname, BINM_MAN) == 0)
171 		search.argmode = ARG_NAME;
172 	else if (strcmp(progname, BINM_APROPOS) == 0)
173 		search.argmode = ARG_EXPR;
174 	else if (strcmp(progname, BINM_WHATIS) == 0)
175 		search.argmode = ARG_WORD;
176 	else if (strncmp(progname, "help", 4) == 0)
177 		search.argmode = ARG_NAME;
178 	else
179 		search.argmode = ARG_FILE;
180 
181 	/* Parser options. */
182 
183 	options = MPARSE_SO | MPARSE_UTF8 | MPARSE_LATIN1;
184 	os_e = MANDOC_OS_OTHER;
185 	os_s = NULL;
186 
187 	/* Formatter options. */
188 
189 	memset(&outst, 0, sizeof(outst));
190 	outst.tag_files = NULL;
191 	outst.outtype = OUTT_LOCALE;
192 	outst.use_pager = 1;
193 
194 	show_usage = 0;
195 	outmode = OUTMODE_DEF;
196 
197 	while ((c = getopt(argc, argv,
198 	    "aC:cfhI:iK:klM:m:O:S:s:T:VW:w")) != -1) {
199 		if (c == 'i' && search.argmode == ARG_EXPR) {
200 			optind--;
201 			break;
202 		}
203 		switch (c) {
204 		case 'a':
205 			outmode = OUTMODE_ALL;
206 			break;
207 		case 'C':
208 			conf_file = optarg;
209 			break;
210 		case 'c':
211 			outst.use_pager = 0;
212 			break;
213 		case 'f':
214 			search.argmode = ARG_WORD;
215 			break;
216 		case 'h':
217 			conf.output.synopsisonly = 1;
218 			outst.use_pager = 0;
219 			outmode = OUTMODE_ALL;
220 			break;
221 		case 'I':
222 			if (strncmp(optarg, "os=", 3) != 0) {
223 				mandoc_msg(MANDOCERR_BADARG_BAD, 0, 0,
224 				    "-I %s", optarg);
225 				return mandoc_msg_getrc();
226 			}
227 			if (os_s != NULL) {
228 				mandoc_msg(MANDOCERR_BADARG_DUPE, 0, 0,
229 				    "-I %s", optarg);
230 				return mandoc_msg_getrc();
231 			}
232 			os_s = optarg + 3;
233 			break;
234 		case 'K':
235 			options &= ~(MPARSE_UTF8 | MPARSE_LATIN1);
236 			if (strcmp(optarg, "utf-8") == 0)
237 				options |=  MPARSE_UTF8;
238 			else if (strcmp(optarg, "iso-8859-1") == 0)
239 				options |=  MPARSE_LATIN1;
240 			else if (strcmp(optarg, "us-ascii") != 0) {
241 				mandoc_msg(MANDOCERR_BADARG_BAD, 0, 0,
242 				    "-K %s", optarg);
243 				return mandoc_msg_getrc();
244 			}
245 			break;
246 		case 'k':
247 			search.argmode = ARG_EXPR;
248 			break;
249 		case 'l':
250 			search.argmode = ARG_FILE;
251 			outmode = OUTMODE_ALL;
252 			break;
253 		case 'M':
254 			defpaths = optarg;
255 			break;
256 		case 'm':
257 			auxpaths = optarg;
258 			break;
259 		case 'O':
260 			oarg = optarg;
261 			break;
262 		case 'S':
263 			search.arch = optarg;
264 			break;
265 		case 's':
266 			search.sec = optarg;
267 			break;
268 		case 'T':
269 			if (strcmp(optarg, "ascii") == 0)
270 				outst.outtype = OUTT_ASCII;
271 			else if (strcmp(optarg, "lint") == 0) {
272 				outst.outtype = OUTT_LINT;
273 				mandoc_msg_setoutfile(stdout);
274 				mandoc_msg_setmin(MANDOCERR_BASE);
275 			} else if (strcmp(optarg, "tree") == 0)
276 				outst.outtype = OUTT_TREE;
277 			else if (strcmp(optarg, "man") == 0)
278 				outst.outtype = OUTT_MAN;
279 			else if (strcmp(optarg, "html") == 0)
280 				outst.outtype = OUTT_HTML;
281 			else if (strcmp(optarg, "markdown") == 0)
282 				outst.outtype = OUTT_MARKDOWN;
283 			else if (strcmp(optarg, "utf8") == 0)
284 				outst.outtype = OUTT_UTF8;
285 			else if (strcmp(optarg, "locale") == 0)
286 				outst.outtype = OUTT_LOCALE;
287 			else if (strcmp(optarg, "ps") == 0)
288 				outst.outtype = OUTT_PS;
289 			else if (strcmp(optarg, "pdf") == 0)
290 				outst.outtype = OUTT_PDF;
291 			else {
292 				mandoc_msg(MANDOCERR_BADARG_BAD, 0, 0,
293 				    "-T %s", optarg);
294 				return mandoc_msg_getrc();
295 			}
296 			break;
297 		case 'W':
298 			if (woptions(optarg, &os_e, &outst.wstop) == -1)
299 				return mandoc_msg_getrc();
300 			break;
301 		case 'w':
302 			outmode = OUTMODE_FLN;
303 			break;
304 		default:
305 			show_usage = 1;
306 			break;
307 		}
308 	}
309 
310 	if (show_usage)
311 		usage(search.argmode);
312 
313 	/* Postprocess options. */
314 
315 	switch (outmode) {
316 	case OUTMODE_DEF:
317 		switch (search.argmode) {
318 		case ARG_FILE:
319 			outmode = OUTMODE_ALL;
320 			outst.use_pager = 0;
321 			break;
322 		case ARG_NAME:
323 			outmode = OUTMODE_ONE;
324 			break;
325 		default:
326 			outmode = OUTMODE_LST;
327 			break;
328 		}
329 		break;
330 	case OUTMODE_FLN:
331 		if (search.argmode == ARG_FILE)
332 			outmode = OUTMODE_ALL;
333 		break;
334 	case OUTMODE_ALL:
335 		break;
336 	case OUTMODE_LST:
337 	case OUTMODE_ONE:
338 		abort();
339 	}
340 
341 	if (oarg != NULL) {
342 		if (outmode == OUTMODE_LST)
343 			search.outkey = oarg;
344 		else {
345 			while (oarg != NULL) {
346 				if (manconf_output(&conf.output,
347 				    strsep(&oarg, ","), 0) == -1)
348 					return mandoc_msg_getrc();
349 			}
350 		}
351 	}
352 
353 	if (outst.outtype != OUTT_TREE || conf.output.noval == 0)
354 		options |= MPARSE_VALIDATE;
355 
356 	if (outmode == OUTMODE_FLN ||
357 	    outmode == OUTMODE_LST ||
358 	    (conf.output.outfilename == NULL &&
359 	     conf.output.tagfilename == NULL &&
360 	     isatty(STDOUT_FILENO) == 0))
361 		outst.use_pager = 0;
362 
363 	if (outst.use_pager &&
364 	    (conf.output.width == 0 || conf.output.indent == 0) &&
365 	    ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) != -1 &&
366 	    ws.ws_col > 1) {
367 		if (conf.output.width == 0 && ws.ws_col < 79)
368 			conf.output.width = ws.ws_col - 1;
369 		if (conf.output.indent == 0 && ws.ws_col < 66)
370 			conf.output.indent = 3;
371 	}
372 
373 	if (outst.use_pager == 0)
374 		c = pledge("stdio rpath", NULL);
375 	else if (conf.output.outfilename != NULL ||
376 	    conf.output.tagfilename != NULL)
377 		c = pledge("stdio rpath wpath cpath", NULL);
378 	else
379 		c = pledge("stdio rpath tmppath tty proc exec", NULL);
380 	if (c == -1) {
381 		mandoc_msg(MANDOCERR_PLEDGE, 0, 0, "%s", strerror(errno));
382 		return mandoc_msg_getrc();
383 	}
384 
385 	/* Parse arguments. */
386 
387 	if (argc > 0) {
388 		argc -= optind;
389 		argv += optind;
390 	}
391 
392 	/*
393 	 * Quirks for help(1) and man(1),
394 	 * in particular for a section argument without -s.
395 	 */
396 
397 	if (search.argmode == ARG_NAME) {
398 		if (*progname == 'h') {
399 			if (argc == 0) {
400 				argv = help_argv;
401 				argc = 1;
402 			}
403 		} else if (argc > 1 &&
404 		    ((uc = (unsigned char *)argv[0]) != NULL) &&
405 		    ((isdigit(uc[0]) && (uc[1] == '\0' ||
406 		      isalpha(uc[1]))) ||
407 		     (uc[0] == 'n' && uc[1] == '\0'))) {
408 			search.sec = (char *)uc;
409 			argv++;
410 			argc--;
411 		}
412 		if (search.arch == NULL)
413 			search.arch = getenv("MACHINE");
414 		if (search.arch == NULL)
415 			search.arch = MACHINE;
416 		if (outmode == OUTMODE_ONE)
417 			search.firstmatch = 1;
418 	}
419 
420 	/*
421 	 * Use the first argument for -O tag in addition to
422 	 * using it as a search term for man(1) or apropos(1).
423 	 */
424 
425 	if (conf.output.tag != NULL && *conf.output.tag == '\0') {
426 		tagarg = argc > 0 && search.argmode == ARG_EXPR ?
427 		    strchr(*argv, '=') : NULL;
428 		conf.output.tag = tagarg == NULL ? *argv : tagarg + 1;
429 	}
430 
431 	/* Read the configuration file. */
432 
433 	if (search.argmode != ARG_FILE)
434 		manconf_parse(&conf, conf_file, defpaths, auxpaths);
435 
436 	/* man(1): Resolve each name individually. */
437 
438 	if (search.argmode == ARG_NAME) {
439 		if (argc < 1) {
440 			if (outmode != OUTMODE_FLN)
441 				usage(ARG_NAME);
442 			if (conf.manpath.sz == 0) {
443 				warnx("The manpath is empty.");
444 				mandoc_msg_setrc(MANDOCLEVEL_BADARG);
445 			} else {
446 				for (i = 0; i + 1 < conf.manpath.sz; i++)
447 					printf("%s:", conf.manpath.paths[i]);
448 				printf("%s\n", conf.manpath.paths[i]);
449 			}
450 			manconf_free(&conf);
451 			return (int)mandoc_msg_getrc();
452 		}
453 		for (res = NULL, ressz = 0; argc > 0; argc--, argv++) {
454 			(void)mansearch(&search, &conf.manpath,
455 			    1, argv, &resn, &resnsz);
456 			if (resnsz == 0)
457 				(void)fs_search(&search, &conf.manpath,
458 				    *argv, &resn, &resnsz);
459 			if (resnsz == 0 && strchr(*argv, '/') == NULL) {
460 				if (search.arch != NULL &&
461 				    arch_valid(search.arch, OSENUM) == 0)
462 					warnx("Unknown architecture \"%s\".",
463 					    search.arch);
464 				else if (search.sec != NULL)
465 					warnx("No entry for %s in "
466 					    "section %s of the manual.",
467 					    *argv, search.sec);
468 				else
469 					warnx("No entry for %s in "
470 					    "the manual.", *argv);
471 				mandoc_msg_setrc(MANDOCLEVEL_BADARG);
472 				continue;
473 			}
474 			if (resnsz == 0) {
475 				if (access(*argv, R_OK) == -1) {
476 					mandoc_msg_setinfilename(*argv);
477 					mandoc_msg(MANDOCERR_BADARG_BAD,
478 					    0, 0, "%s", strerror(errno));
479 					mandoc_msg_setinfilename(NULL);
480 					continue;
481 				}
482 				resnsz = 1;
483 				resn = mandoc_calloc(resnsz, sizeof(*res));
484 				resn->file = mandoc_strdup(*argv);
485 				resn->ipath = SIZE_MAX;
486 				resn->form = FORM_SRC;
487 			}
488 			if (outmode != OUTMODE_ONE || resnsz == 1) {
489 				res = mandoc_reallocarray(res,
490 				    ressz + resnsz, sizeof(*res));
491 				memcpy(res + ressz, resn,
492 				    sizeof(*resn) * resnsz);
493 				ressz += resnsz;
494 				continue;
495 			}
496 
497 			/* Search for the best section. */
498 
499 			best_prio = 40;
500 			for (ib = i = 0; i < resnsz; i++) {
501 				sec = resn[i].file;
502 				sec += strcspn(sec, "123456789");
503 				if (sec[0] == '\0')
504 					continue; /* No section at all. */
505 				prio = sec_prios[sec[0] - '1'];
506 				if (search.sec != NULL) {
507 					ssz = strlen(search.sec);
508 					if (strncmp(sec, search.sec, ssz) == 0)
509 						sec += ssz;
510 				} else
511 					sec++; /* Prefer without suffix. */
512 				if (*sec != '/')
513 					prio += 10; /* Wrong dir name. */
514 				if (search.sec != NULL &&
515 				    (strlen(sec) <= ssz  + 3 ||
516 				     strcmp(sec + strlen(sec) - ssz,
517 				      search.sec) != 0))
518 					prio += 20; /* Wrong file ext. */
519 				if (prio >= best_prio)
520 					continue;
521 				best_prio = prio;
522 				ib = i;
523 			}
524 			res = mandoc_reallocarray(res, ressz + 1,
525 			    sizeof(*res));
526 			memcpy(res + ressz++, resn + ib, sizeof(*resn));
527 		}
528 
529 	/* apropos(1), whatis(1): Process the full search expression. */
530 
531 	} else if (search.argmode != ARG_FILE) {
532 		if (mansearch(&search, &conf.manpath,
533 		    argc, argv, &res, &ressz) == 0)
534 			usage(search.argmode);
535 
536 		if (ressz == 0) {
537 			warnx("nothing appropriate");
538 			mandoc_msg_setrc(MANDOCLEVEL_BADARG);
539 			goto out;
540 		}
541 
542 	/* mandoc(1): Take command line arguments as file names. */
543 
544 	} else {
545 		ressz = argc > 0 ? argc : 1;
546 		res = mandoc_calloc(ressz, sizeof(*res));
547 		for (i = 0; i < ressz; i++) {
548 			if (argc > 0)
549 				res[i].file = mandoc_strdup(argv[i]);
550 			res[i].ipath = SIZE_MAX;
551 			res[i].form = FORM_SRC;
552 		}
553 	}
554 
555 	switch (outmode) {
556 	case OUTMODE_FLN:
557 		for (i = 0; i < ressz; i++)
558 			puts(res[i].file);
559 		goto out;
560 	case OUTMODE_LST:
561 		for (i = 0; i < ressz; i++)
562 			printf("%s - %s\n", res[i].names,
563 			    res[i].output == NULL ? "" :
564 			    res[i].output);
565 		goto out;
566 	default:
567 		break;
568 	}
569 
570 	if (search.argmode == ARG_FILE && auxpaths != NULL) {
571 		if (strcmp(auxpaths, "doc") == 0)
572 			options |= MPARSE_MDOC;
573 		else if (strcmp(auxpaths, "an") == 0)
574 			options |= MPARSE_MAN;
575 	}
576 
577 	mchars_alloc();
578 	mp = mparse_alloc(options, os_e, os_s);
579 
580 	/*
581 	 * Remember the original working directory, if possible.
582 	 * This will be needed if some names on the command line
583 	 * are page names and some are relative file names.
584 	 * Do not error out if the current directory is not
585 	 * readable: Maybe it won't be needed after all.
586 	 */
587 	startdir = open(".", O_RDONLY | O_DIRECTORY);
588 	for (i = 0; i < ressz; i++) {
589 		process_onefile(mp, res + i, startdir, &outst, &conf);
590 		if (outst.wstop && mandoc_msg_getrc() != MANDOCLEVEL_OK)
591 			break;
592 	}
593 	if (startdir != -1) {
594 		(void)fchdir(startdir);
595 		close(startdir);
596 	}
597 	if (conf.output.tag != NULL && conf.output.tag_found == 0) {
598 		mandoc_msg(MANDOCERR_TAG, 0, 0, "%s", conf.output.tag);
599 		conf.output.tag = NULL;
600 	}
601 	if (outst.outdata != NULL) {
602 		switch (outst.outtype) {
603 		case OUTT_HTML:
604 			html_free(outst.outdata);
605 			break;
606 		case OUTT_UTF8:
607 		case OUTT_LOCALE:
608 		case OUTT_ASCII:
609 			ascii_free(outst.outdata);
610 			break;
611 		case OUTT_PDF:
612 		case OUTT_PS:
613 			pspdf_free(outst.outdata);
614 			break;
615 		default:
616 			break;
617 		}
618 	}
619 	mandoc_xr_free();
620 	mparse_free(mp);
621 	mchars_free();
622 
623 out:
624 	mansearch_free(res, ressz);
625 	if (search.argmode != ARG_FILE)
626 		manconf_free(&conf);
627 
628 	if (outst.tag_files != NULL) {
629 		if (term_tag_close() != -1 &&
630 		    conf.output.outfilename == NULL &&
631 		    conf.output.tagfilename == NULL)
632 			run_pager(&outst, conf.output.tag);
633 		term_tag_unlink();
634 	} else if (outst.had_output && outst.outtype != OUTT_LINT)
635 		mandoc_msg_summary();
636 
637 	return (int)mandoc_msg_getrc();
638 }
639 
640 static void
641 usage(enum argmode argmode)
642 {
643 	switch (argmode) {
644 	case ARG_FILE:
645 		fputs("usage: mandoc [-ac] [-I os=name] "
646 		    "[-K encoding] [-mdoc | -man] [-O options]\n"
647 		    "\t      [-T output] [-W level] [file ...]\n", stderr);
648 		break;
649 	case ARG_NAME:
650 		fputs("usage: man [-acfhklw] [-C file] [-M path] "
651 		    "[-m path] [-S subsection]\n"
652 		    "\t   [[-s] section] name ...\n", stderr);
653 		break;
654 	case ARG_WORD:
655 		fputs("usage: whatis [-afk] [-C file] "
656 		    "[-M path] [-m path] [-O outkey] [-S arch]\n"
657 		    "\t      [-s section] name ...\n", stderr);
658 		break;
659 	case ARG_EXPR:
660 		fputs("usage: apropos [-afk] [-C file] "
661 		    "[-M path] [-m path] [-O outkey] [-S arch]\n"
662 		    "\t       [-s section] expression ...\n", stderr);
663 		break;
664 	}
665 	exit((int)MANDOCLEVEL_BADARG);
666 }
667 
668 static void
669 glob_esc(char **dst, const char *src, const char *suffix)
670 {
671 	while (*src != '\0') {
672 		if (strchr("*?[", *src) != NULL)
673 			*(*dst)++ = '\\';
674 		*(*dst)++ = *src++;
675 	}
676 	while (*suffix != '\0')
677 		*(*dst)++ = *suffix++;
678 }
679 
680 static int
681 fs_lookup(const struct manpaths *paths, size_t ipath,
682 	const char *sec, const char *arch, const char *name,
683 	struct manpage **res, size_t *ressz)
684 {
685 	struct stat	 sb;
686 	glob_t		 globinfo;
687 	struct manpage	*page;
688 	char		*file, *cp;
689 	int		 globres;
690 	enum form	 form;
691 
692 	const char *const slman = "/man";
693 	const char *const slash = "/";
694 	const char *const sglob = ".[01-9]*";
695 
696 	form = FORM_SRC;
697 	mandoc_asprintf(&file, "%s/man%s/%s.%s",
698 	    paths->paths[ipath], sec, name, sec);
699 	if (stat(file, &sb) != -1)
700 		goto found;
701 	free(file);
702 
703 	mandoc_asprintf(&file, "%s/cat%s/%s.0",
704 	    paths->paths[ipath], sec, name);
705 	if (stat(file, &sb) != -1) {
706 		form = FORM_CAT;
707 		goto found;
708 	}
709 	free(file);
710 
711 	if (arch != NULL) {
712 		mandoc_asprintf(&file, "%s/man%s/%s/%s.%s",
713 		    paths->paths[ipath], sec, arch, name, sec);
714 		if (stat(file, &sb) != -1)
715 			goto found;
716 		free(file);
717 	}
718 
719 	cp = file = mandoc_malloc(strlen(paths->paths[ipath]) * 2 +
720 	    strlen(slman) + strlen(sec) * 2 + strlen(slash) +
721 	    strlen(name) * 2 + strlen(sglob) + 1);
722 	glob_esc(&cp, paths->paths[ipath], slman);
723 	glob_esc(&cp, sec, slash);
724 	glob_esc(&cp, name, sglob);
725 	*cp = '\0';
726 	globres = glob(file, 0, NULL, &globinfo);
727 	if (globres != 0 && globres != GLOB_NOMATCH)
728 		mandoc_msg(MANDOCERR_GLOB, 0, 0,
729 		    "%s: %s", file, strerror(errno));
730 	free(file);
731 	if (globres == 0)
732 		file = mandoc_strdup(*globinfo.gl_pathv);
733 	globfree(&globinfo);
734 	if (globres == 0) {
735 		if (stat(file, &sb) != -1)
736 			goto found;
737 		free(file);
738 	}
739 	if (res != NULL || ipath + 1 != paths->sz)
740 		return -1;
741 
742 	mandoc_asprintf(&file, "%s.%s", name, sec);
743 	globres = stat(file, &sb);
744 	free(file);
745 	return globres;
746 
747 found:
748 	warnx("outdated mandoc.db lacks %s(%s) entry, run %s %s",
749 	    name, sec, BINM_MAKEWHATIS, paths->paths[ipath]);
750 	if (res == NULL) {
751 		free(file);
752 		return 0;
753 	}
754 	*res = mandoc_reallocarray(*res, ++*ressz, sizeof(**res));
755 	page = *res + (*ressz - 1);
756 	page->file = file;
757 	page->names = NULL;
758 	page->output = NULL;
759 	page->bits = NAME_FILE & NAME_MASK;
760 	page->ipath = ipath;
761 	page->sec = (*sec >= '1' && *sec <= '9') ? *sec - '1' + 1 : 10;
762 	page->form = form;
763 	return 0;
764 }
765 
766 static int
767 fs_search(const struct mansearch *cfg, const struct manpaths *paths,
768 	const char *name, struct manpage **res, size_t *ressz)
769 {
770 	const char *const sections[] =
771 	    {"1", "8", "6", "2", "3", "5", "7", "4", "9", "3p"};
772 	const size_t nsec = sizeof(sections)/sizeof(sections[0]);
773 
774 	size_t		 ipath, isec;
775 
776 	assert(cfg->argmode == ARG_NAME);
777 	if (res != NULL)
778 		*res = NULL;
779 	*ressz = 0;
780 	for (ipath = 0; ipath < paths->sz; ipath++) {
781 		if (cfg->sec != NULL) {
782 			if (fs_lookup(paths, ipath, cfg->sec, cfg->arch,
783 			    name, res, ressz) != -1 && cfg->firstmatch)
784 				return 0;
785 		} else {
786 			for (isec = 0; isec < nsec; isec++)
787 				if (fs_lookup(paths, ipath, sections[isec],
788 				    cfg->arch, name, res, ressz) != -1 &&
789 				    cfg->firstmatch)
790 					return 0;
791 		}
792 	}
793 	return -1;
794 }
795 
796 static void
797 process_onefile(struct mparse *mp, struct manpage *resp, int startdir,
798     struct outstate *outst, struct manconf *conf)
799 {
800 	int	 fd;
801 
802 	/*
803 	 * Changing directories is not needed in ARG_FILE mode.
804 	 * Do it on a best-effort basis.  Even in case of
805 	 * failure, some functionality may still work.
806 	 */
807 	if (resp->ipath != SIZE_MAX)
808 		(void)chdir(conf->manpath.paths[resp->ipath]);
809 	else if (startdir != -1)
810 		(void)fchdir(startdir);
811 
812 	mandoc_msg_setinfilename(resp->file);
813 	if (resp->file != NULL) {
814 		if ((fd = mparse_open(mp, resp->file)) == -1) {
815 			mandoc_msg(resp->ipath == SIZE_MAX ?
816 			    MANDOCERR_BADARG_BAD : MANDOCERR_OPEN,
817 			    0, 0, "%s", strerror(errno));
818 			mandoc_msg_setinfilename(NULL);
819 			return;
820 		}
821 	} else
822 		fd = STDIN_FILENO;
823 
824 	if (outst->use_pager) {
825 		outst->use_pager = 0;
826 		outst->tag_files = term_tag_init(conf->output.outfilename,
827 		    outst->outtype == OUTT_HTML ? ".html" : "",
828 		    conf->output.tagfilename);
829 		if ((conf->output.outfilename != NULL ||
830 		     conf->output.tagfilename != NULL) &&
831 		    pledge("stdio rpath cpath", NULL) == -1) {
832 			mandoc_msg(MANDOCERR_PLEDGE, 0, 0,
833 			    "%s", strerror(errno));
834 			exit(mandoc_msg_getrc());
835 		}
836 	}
837 	if (outst->had_output && outst->outtype <= OUTT_UTF8) {
838 		if (outst->outdata == NULL)
839 			outdata_alloc(outst, &conf->output);
840 		terminal_sepline(outst->outdata);
841 	}
842 
843 	if (resp->form == FORM_SRC)
844 		parse(mp, fd, resp->file, outst, &conf->output);
845 	else {
846 		passthrough(fd, conf->output.synopsisonly);
847 		outst->had_output = 1;
848 	}
849 
850 	if (ferror(stdout)) {
851 		if (outst->tag_files != NULL) {
852 			mandoc_msg(MANDOCERR_WRITE, 0, 0, "%s: %s",
853 			    outst->tag_files->ofn, strerror(errno));
854 			term_tag_unlink();
855 			outst->tag_files = NULL;
856 		} else
857 			mandoc_msg(MANDOCERR_WRITE, 0, 0, "%s",
858 			    strerror(errno));
859 	}
860 	mandoc_msg_setinfilename(NULL);
861 }
862 
863 static void
864 parse(struct mparse *mp, int fd, const char *file,
865     struct outstate *outst, struct manoutput *outconf)
866 {
867 	static int		 previous;
868 	struct roff_meta	*meta;
869 
870 	assert(fd >= 0);
871 	if (file == NULL)
872 		file = "<stdin>";
873 
874 	if (previous)
875 		mparse_reset(mp);
876 	else
877 		previous = 1;
878 
879 	mparse_readfd(mp, fd, file);
880 	if (fd != STDIN_FILENO)
881 		close(fd);
882 
883 	/*
884 	 * With -Wstop and warnings or errors of at least the requested
885 	 * level, do not produce output.
886 	 */
887 
888 	if (outst->wstop && mandoc_msg_getrc() != MANDOCLEVEL_OK)
889 		return;
890 
891 	if (outst->outdata == NULL)
892 		outdata_alloc(outst, outconf);
893 	else if (outst->outtype == OUTT_HTML)
894 		html_reset(outst->outdata);
895 
896 	mandoc_xr_reset();
897 	meta = mparse_result(mp);
898 
899 	/* Execute the out device, if it exists. */
900 
901 	outst->had_output = 1;
902 	if (meta->macroset == MACROSET_MDOC) {
903 		switch (outst->outtype) {
904 		case OUTT_HTML:
905 			html_mdoc(outst->outdata, meta);
906 			break;
907 		case OUTT_TREE:
908 			tree_mdoc(outst->outdata, meta);
909 			break;
910 		case OUTT_MAN:
911 			man_mdoc(outst->outdata, meta);
912 			break;
913 		case OUTT_PDF:
914 		case OUTT_ASCII:
915 		case OUTT_UTF8:
916 		case OUTT_LOCALE:
917 		case OUTT_PS:
918 			terminal_mdoc(outst->outdata, meta);
919 			break;
920 		case OUTT_MARKDOWN:
921 			markdown_mdoc(outst->outdata, meta);
922 			break;
923 		default:
924 			break;
925 		}
926 	}
927 	if (meta->macroset == MACROSET_MAN) {
928 		switch (outst->outtype) {
929 		case OUTT_HTML:
930 			html_man(outst->outdata, meta);
931 			break;
932 		case OUTT_TREE:
933 			tree_man(outst->outdata, meta);
934 			break;
935 		case OUTT_MAN:
936 			mparse_copy(mp);
937 			break;
938 		case OUTT_PDF:
939 		case OUTT_ASCII:
940 		case OUTT_UTF8:
941 		case OUTT_LOCALE:
942 		case OUTT_PS:
943 			terminal_man(outst->outdata, meta);
944 			break;
945 		default:
946 			break;
947 		}
948 	}
949 	if (outconf->tag != NULL && outconf->tag_found == 0 &&
950 	    tag_exists(outconf->tag))
951 		outconf->tag_found = 1;
952 	if (mandoc_msg_getmin() < MANDOCERR_STYLE)
953 		check_xr();
954 }
955 
956 static void
957 check_xr(void)
958 {
959 	static struct manpaths	 paths;
960 	struct mansearch	 search;
961 	struct mandoc_xr	*xr;
962 	size_t			 sz;
963 
964 	if (paths.sz == 0)
965 		manpath_base(&paths);
966 
967 	for (xr = mandoc_xr_get(); xr != NULL; xr = xr->next) {
968 		if (xr->line == -1)
969 			continue;
970 		search.arch = NULL;
971 		search.sec = xr->sec;
972 		search.outkey = NULL;
973 		search.argmode = ARG_NAME;
974 		search.firstmatch = 1;
975 		if (mansearch(&search, &paths, 1, &xr->name, NULL, &sz))
976 			continue;
977 		if (fs_search(&search, &paths, xr->name, NULL, &sz) != -1)
978 			continue;
979 		if (xr->count == 1)
980 			mandoc_msg(MANDOCERR_XR_BAD, xr->line,
981 			    xr->pos + 1, "Xr %s %s", xr->name, xr->sec);
982 		else
983 			mandoc_msg(MANDOCERR_XR_BAD, xr->line,
984 			    xr->pos + 1, "Xr %s %s (%d times)",
985 			    xr->name, xr->sec, xr->count);
986 	}
987 }
988 
989 static void
990 outdata_alloc(struct outstate *outst, struct manoutput *outconf)
991 {
992 	switch (outst->outtype) {
993 	case OUTT_HTML:
994 		outst->outdata = html_alloc(outconf);
995 		break;
996 	case OUTT_UTF8:
997 		outst->outdata = utf8_alloc(outconf);
998 		break;
999 	case OUTT_LOCALE:
1000 		outst->outdata = locale_alloc(outconf);
1001 		break;
1002 	case OUTT_ASCII:
1003 		outst->outdata = ascii_alloc(outconf);
1004 		break;
1005 	case OUTT_PDF:
1006 		outst->outdata = pdf_alloc(outconf);
1007 		break;
1008 	case OUTT_PS:
1009 		outst->outdata = ps_alloc(outconf);
1010 		break;
1011 	default:
1012 		break;
1013 	}
1014 }
1015 
1016 static void
1017 passthrough(int fd, int synopsis_only)
1018 {
1019 	const char	 synb[] = "S\bSY\bYN\bNO\bOP\bPS\bSI\bIS\bS";
1020 	const char	 synr[] = "SYNOPSIS";
1021 
1022 	FILE		*stream;
1023 	char		*line, *cp;
1024 	size_t		 linesz;
1025 	ssize_t		 len, written;
1026 	int		 lno, print;
1027 
1028 	stream = NULL;
1029 	line = NULL;
1030 	linesz = 0;
1031 
1032 	if (fflush(stdout) == EOF) {
1033 		mandoc_msg(MANDOCERR_FFLUSH, 0, 0, "%s", strerror(errno));
1034 		goto done;
1035 	}
1036 	if ((stream = fdopen(fd, "r")) == NULL) {
1037 		close(fd);
1038 		mandoc_msg(MANDOCERR_FDOPEN, 0, 0, "%s", strerror(errno));
1039 		goto done;
1040 	}
1041 
1042 	lno = print = 0;
1043 	while ((len = getline(&line, &linesz, stream)) != -1) {
1044 		lno++;
1045 		cp = line;
1046 		if (synopsis_only) {
1047 			if (print) {
1048 				if ( ! isspace((unsigned char)*cp))
1049 					goto done;
1050 				while (isspace((unsigned char)*cp)) {
1051 					cp++;
1052 					len--;
1053 				}
1054 			} else {
1055 				if (strcmp(cp, synb) == 0 ||
1056 				    strcmp(cp, synr) == 0)
1057 					print = 1;
1058 				continue;
1059 			}
1060 		}
1061 		for (; len > 0; len -= written) {
1062 			if ((written = write(STDOUT_FILENO, cp, len)) == -1) {
1063 				mandoc_msg(MANDOCERR_WRITE, 0, 0,
1064 				    "%s", strerror(errno));
1065 				goto done;
1066 			}
1067 		}
1068 	}
1069 	if (ferror(stream))
1070 		mandoc_msg(MANDOCERR_GETLINE, lno, 0, "%s", strerror(errno));
1071 
1072 done:
1073 	free(line);
1074 	if (stream != NULL)
1075 		fclose(stream);
1076 }
1077 
1078 static int
1079 woptions(char *arg, enum mandoc_os *os_e, int *wstop)
1080 {
1081 	char		*v, *o;
1082 	const char	*toks[11];
1083 
1084 	toks[0] = "stop";
1085 	toks[1] = "all";
1086 	toks[2] = "base";
1087 	toks[3] = "style";
1088 	toks[4] = "warning";
1089 	toks[5] = "error";
1090 	toks[6] = "unsupp";
1091 	toks[7] = "fatal";
1092 	toks[8] = "openbsd";
1093 	toks[9] = "netbsd";
1094 	toks[10] = NULL;
1095 
1096 	while (*arg) {
1097 		o = arg;
1098 		switch (getsubopt(&arg, (char * const *)toks, &v)) {
1099 		case 0:
1100 			*wstop = 1;
1101 			break;
1102 		case 1:
1103 		case 2:
1104 			mandoc_msg_setmin(MANDOCERR_BASE);
1105 			break;
1106 		case 3:
1107 			mandoc_msg_setmin(MANDOCERR_STYLE);
1108 			break;
1109 		case 4:
1110 			mandoc_msg_setmin(MANDOCERR_WARNING);
1111 			break;
1112 		case 5:
1113 			mandoc_msg_setmin(MANDOCERR_ERROR);
1114 			break;
1115 		case 6:
1116 			mandoc_msg_setmin(MANDOCERR_UNSUPP);
1117 			break;
1118 		case 7:
1119 			mandoc_msg_setmin(MANDOCERR_BADARG);
1120 			break;
1121 		case 8:
1122 			mandoc_msg_setmin(MANDOCERR_BASE);
1123 			*os_e = MANDOC_OS_OPENBSD;
1124 			break;
1125 		case 9:
1126 			mandoc_msg_setmin(MANDOCERR_BASE);
1127 			*os_e = MANDOC_OS_NETBSD;
1128 			break;
1129 		default:
1130 			mandoc_msg(MANDOCERR_BADARG_BAD, 0, 0, "-W %s", o);
1131 			return -1;
1132 		}
1133 	}
1134 	return 0;
1135 }
1136 
1137 /*
1138  * Wait until moved to the foreground,
1139  * then fork the pager and wait for the user to close it.
1140  */
1141 static void
1142 run_pager(struct outstate *outst, char *tag_target)
1143 {
1144 	int	 signum, status;
1145 	pid_t	 man_pgid, tc_pgid;
1146 	pid_t	 pager_pid, wait_pid;
1147 
1148 	man_pgid = getpgid(0);
1149 	outst->tag_files->tcpgid =
1150 	    man_pgid == getpid() ? getpgid(getppid()) : man_pgid;
1151 	pager_pid = 0;
1152 	signum = SIGSTOP;
1153 
1154 	for (;;) {
1155 		/* Stop here until moved to the foreground. */
1156 
1157 		tc_pgid = tcgetpgrp(STDOUT_FILENO);
1158 		if (tc_pgid != man_pgid) {
1159 			if (tc_pgid == pager_pid) {
1160 				(void)tcsetpgrp(STDOUT_FILENO, man_pgid);
1161 				if (signum == SIGTTIN)
1162 					continue;
1163 			} else
1164 				outst->tag_files->tcpgid = tc_pgid;
1165 			kill(0, signum);
1166 			continue;
1167 		}
1168 
1169 		/* Once in the foreground, activate the pager. */
1170 
1171 		if (pager_pid) {
1172 			(void)tcsetpgrp(STDOUT_FILENO, pager_pid);
1173 			kill(pager_pid, SIGCONT);
1174 		} else
1175 			pager_pid = spawn_pager(outst, tag_target);
1176 
1177 		/* Wait for the pager to stop or exit. */
1178 
1179 		while ((wait_pid = waitpid(pager_pid, &status,
1180 		    WUNTRACED)) == -1 && errno == EINTR)
1181 			continue;
1182 
1183 		if (wait_pid == -1) {
1184 			mandoc_msg(MANDOCERR_WAIT, 0, 0,
1185 			    "%s", strerror(errno));
1186 			break;
1187 		}
1188 		if (!WIFSTOPPED(status))
1189 			break;
1190 
1191 		signum = WSTOPSIG(status);
1192 	}
1193 }
1194 
1195 static pid_t
1196 spawn_pager(struct outstate *outst, char *tag_target)
1197 {
1198 	const struct timespec timeout = { 0, 100000000 };  /* 0.1s */
1199 #define MAX_PAGER_ARGS 16
1200 	char		*argv[MAX_PAGER_ARGS];
1201 	const char	*pager;
1202 	char		*cp;
1203 	size_t		 cmdlen;
1204 	int		 argc, use_ofn;
1205 	pid_t		 pager_pid;
1206 
1207 	assert(outst->tag_files->ofd == -1);
1208 	assert(outst->tag_files->tfs == NULL);
1209 
1210 	pager = getenv("MANPAGER");
1211 	if (pager == NULL || *pager == '\0')
1212 		pager = getenv("PAGER");
1213 	if (pager == NULL || *pager == '\0')
1214 		pager = "less";
1215 	cp = mandoc_strdup(pager);
1216 
1217 	/*
1218 	 * Parse the pager command into words.
1219 	 * Intentionally do not do anything fancy here.
1220 	 */
1221 
1222 	argc = 0;
1223 	while (argc + 5 < MAX_PAGER_ARGS) {
1224 		argv[argc++] = cp;
1225 		cp = strchr(cp, ' ');
1226 		if (cp == NULL)
1227 			break;
1228 		*cp++ = '\0';
1229 		while (*cp == ' ')
1230 			cp++;
1231 		if (*cp == '\0')
1232 			break;
1233 	}
1234 
1235 	/* For more(1) and less(1), use the tag file. */
1236 
1237 	use_ofn = 1;
1238 	if (*outst->tag_files->tfn != '\0' &&
1239 	    (cmdlen = strlen(argv[0])) >= 4) {
1240 		cp = argv[0] + cmdlen - 4;
1241 		if (strcmp(cp, "less") == 0 || strcmp(cp, "more") == 0) {
1242 			argv[argc++] = mandoc_strdup("-T");
1243 			argv[argc++] = outst->tag_files->tfn;
1244 			if (tag_target != NULL) {
1245 				argv[argc++] = mandoc_strdup("-t");
1246 				argv[argc++] = tag_target;
1247 				use_ofn = 0;
1248 			}
1249 		}
1250 	}
1251 	if (use_ofn) {
1252 		if (outst->outtype == OUTT_HTML && tag_target != NULL)
1253 			mandoc_asprintf(&argv[argc], "file://%s#%s",
1254 			    outst->tag_files->ofn, tag_target);
1255 		else
1256 			argv[argc] = outst->tag_files->ofn;
1257 		argc++;
1258 	}
1259 	argv[argc] = NULL;
1260 
1261 	switch (pager_pid = fork()) {
1262 	case -1:
1263 		mandoc_msg(MANDOCERR_FORK, 0, 0, "%s", strerror(errno));
1264 		exit(mandoc_msg_getrc());
1265 	case 0:
1266 		break;
1267 	default:
1268 		(void)setpgid(pager_pid, 0);
1269 		(void)tcsetpgrp(STDOUT_FILENO, pager_pid);
1270 		if (pledge("stdio rpath tmppath tty proc", NULL) == -1) {
1271 			mandoc_msg(MANDOCERR_PLEDGE, 0, 0,
1272 			    "%s", strerror(errno));
1273 			exit(mandoc_msg_getrc());
1274 		}
1275 		outst->tag_files->pager_pid = pager_pid;
1276 		return pager_pid;
1277 	}
1278 
1279 	/*
1280 	 * The child process becomes the pager.
1281 	 * Do not start it before controlling the terminal.
1282 	 */
1283 
1284 	while (tcgetpgrp(STDOUT_FILENO) != getpid())
1285 		nanosleep(&timeout, NULL);
1286 
1287 	execvp(argv[0], argv);
1288 	mandoc_msg(MANDOCERR_EXEC, 0, 0, "%s: %s", argv[0], strerror(errno));
1289 	_exit(mandoc_msg_getrc());
1290 }
1291