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