Home | History | Annotate | Line # | Download | only in man
man.c revision 1.59
      1 /*	$NetBSD: man.c,v 1.59 2013/10/06 17:14:49 christos Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1987, 1993, 1994, 1995
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  * 3. Neither the name of the University nor the names of its contributors
     16  *    may be used to endorse or promote products derived from this software
     17  *    without specific prior written permission.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     29  * SUCH DAMAGE.
     30  */
     31 
     32 #include <sys/cdefs.h>
     33 
     34 #ifndef lint
     35 __COPYRIGHT("@(#) Copyright (c) 1987, 1993, 1994, 1995\
     36  The Regents of the University of California.  All rights reserved.");
     37 #endif /* not lint */
     38 
     39 #ifndef lint
     40 #if 0
     41 static char sccsid[] = "@(#)man.c	8.17 (Berkeley) 1/31/95";
     42 #else
     43 __RCSID("$NetBSD: man.c,v 1.59 2013/10/06 17:14:49 christos Exp $");
     44 #endif
     45 #endif /* not lint */
     46 
     47 #include <sys/param.h>
     48 #include <sys/queue.h>
     49 #include <sys/stat.h>
     50 #include <sys/utsname.h>
     51 
     52 #include <ctype.h>
     53 #include <err.h>
     54 #include <errno.h>
     55 #include <fcntl.h>
     56 #include <fnmatch.h>
     57 #include <glob.h>
     58 #include <signal.h>
     59 #include <stdio.h>
     60 #include <stdlib.h>
     61 #include <string.h>
     62 #include <unistd.h>
     63 #include <util.h>
     64 #include <locale.h>
     65 
     66 #include "manconf.h"
     67 #include "pathnames.h"
     68 
     69 #ifndef MAN_DEBUG
     70 #define MAN_DEBUG 0		/* debug path output */
     71 #endif
     72 
     73 /*
     74  * manstate: structure collecting the current global state so we can
     75  * easily identify it and pass it to helper functions in one arg.
     76  */
     77 struct manstate {
     78 	/* command line flags */
     79 	int all;		/* -a: show all matches rather than first */
     80 	int cat;		/* -c: do not use a pager */
     81 	char *conffile;		/* -C: use alternate config file */
     82 	int how;		/* -h: show SYNOPSIS only */
     83 	char *manpath;		/* -M: alternate MANPATH */
     84 	char *addpath;		/* -m: add these dirs to front of manpath */
     85 	char *pathsearch;	/* -S: path of man must contain this string */
     86 	char *sectionname;	/* -s: limit search to a given man section */
     87 	int where;		/* -w: just show paths of all matching files */
     88 	int getpath;	/* -p: print the path of directories containing man pages */
     89 
     90 	/* important tags from the config file */
     91 	TAG *defaultpath;	/* _default: default MANPATH */
     92 	TAG *subdirs;		/* _subdir: default subdir search list */
     93 	TAG *suffixlist;	/* _suffix: for files that can be cat()'d */
     94 	TAG *buildlist;		/* _build: for files that must be built */
     95 
     96 	/* tags for internal use */
     97 	TAG *intmp;		/* _intmp: tmp files we must cleanup */
     98 	TAG *missinglist;	/* _missing: pages we couldn't find */
     99 	TAG *mymanpath;		/* _new_path: final version of MANPATH */
    100 	TAG *section;		/* <sec>: tag for m.sectionname */
    101 
    102 	/* other misc stuff */
    103 	const char *pager;	/* pager to use */
    104 	size_t pagerlen;	/* length of the above */
    105 	const char *machine;	/* machine */
    106 	const char *machclass;	/* machine class */
    107 };
    108 
    109 /*
    110  * prototypes
    111  */
    112 static void	 build_page(const char *, char **, struct manstate *);
    113 static void	 cat(const char *);
    114 static const char	*check_pager(const char *);
    115 static int	 cleanup(void);
    116 static void	 how(const char *);
    117 static void	 jump(char **, const char *, const char *) __dead;
    118 static int	 manual(char *, struct manstate *, glob_t *);
    119 static void	 onsig(int) __dead;
    120 static void	 usage(void) __dead;
    121 static void	 addpath(struct manstate *, const char *, size_t, const char *);
    122 static const char *getclass(const char *);
    123 static void printmanpath(struct manstate *);
    124 
    125 /*
    126  * main function
    127  */
    128 int
    129 main(int argc, char **argv)
    130 {
    131 	static struct manstate m;
    132 	int ch, abs_section, found;
    133 	ENTRY *esubd, *epath;
    134 	char *p, **ap, *cmd;
    135 	size_t len;
    136 	glob_t pg;
    137 
    138 	setprogname(argv[0]);
    139 	setlocale(LC_ALL, "");
    140 	/*
    141 	 * parse command line...
    142 	 */
    143 	while ((ch = getopt(argc, argv, "-aC:cfhkM:m:P:ps:S:w")) != -1)
    144 		switch (ch) {
    145 		case 'a':
    146 			m.all = 1;
    147 			break;
    148 		case 'C':
    149 			m.conffile = optarg;
    150 			break;
    151 		case 'c':
    152 		case '-':	/* XXX: '-' is a deprecated version of '-c' */
    153 			m.cat = 1;
    154 			break;
    155 		case 'h':
    156 			m.how = 1;
    157 			break;
    158 		case 'm':
    159 			m.addpath = optarg;
    160 			break;
    161 		case 'M':
    162 		case 'P':	/* -P for backward compatibility */
    163 			m.manpath = strdup(optarg);
    164 			break;
    165 		case 'p':
    166 			m.getpath = 1;
    167 			break;
    168 		/*
    169 		 * The -f and -k options are backward compatible,
    170 		 * undocumented ways of calling whatis(1) and apropos(1).
    171 		 */
    172 		case 'f':
    173 			jump(argv, "-f", "whatis");
    174 			/* NOTREACHED */
    175 		case 'k':
    176 			jump(argv, "-k", "apropos");
    177 			/* NOTREACHED */
    178 		case 's':
    179 			if (m.sectionname != NULL)
    180 				usage();
    181 			m.sectionname = optarg;
    182 			break;
    183 		case 'S':
    184 			m.pathsearch = optarg;
    185 			break;
    186 		case 'w':
    187 			m.all = m.where = 1;
    188 			break;
    189 		case '?':
    190 		default:
    191 			usage();
    192 		}
    193 	argc -= optind;
    194 	argv += optind;
    195 
    196 	if (!m.getpath && !argc)
    197 		usage();
    198 
    199 	/*
    200 	 * read the configuration file and collect any other information
    201 	 * we will need (machine type, pager, section [if specified
    202 	 * without '-s'], and MANPATH through the environment).
    203 	 */
    204 	config(m.conffile);    /* exits on error ... */
    205 
    206 	if ((m.machine = getenv("MACHINE")) == NULL) {
    207 		struct utsname utsname;
    208 
    209 		if (uname(&utsname) == -1)
    210 			err(EXIT_FAILURE, "uname");
    211 		m.machine = utsname.machine;
    212 	}
    213 
    214 	m.machclass = getclass(m.machine);
    215 
    216 	if (!m.cat && !m.how && !m.where) {  /* if we need a pager ... */
    217 		if (!isatty(STDOUT_FILENO)) {
    218 			m.cat = 1;
    219 		} else {
    220 			if ((m.pager = getenv("PAGER")) != NULL &&
    221 			    m.pager[0] != '\0')
    222 				m.pager = check_pager(m.pager);
    223 			else
    224 				m.pager = _PATH_PAGER;
    225 			m.pagerlen = strlen(m.pager);
    226 		}
    227 	}
    228 
    229 	/* do we need to set m.section to a non-null value? */
    230 	if (m.sectionname) {
    231 
    232 		m.section = gettag(m.sectionname, 0); /* -s must be a section */
    233 		if (m.section == NULL)
    234 			errx(EXIT_FAILURE, "unknown section: %s", m.sectionname);
    235 
    236 	} else if (argc > 1) {
    237 
    238 		m.section = gettag(*argv, 0);  /* might be a section? */
    239 		if (m.section) {
    240 			argv++;
    241 			argc--;
    242 		}
    243 
    244 	}
    245 
    246 	if (m.manpath == NULL)
    247 		m.manpath = getenv("MANPATH"); /* note: -M overrides getenv */
    248 
    249 
    250 	/*
    251 	 * get default values from config file, plus create the tags we
    252 	 * use for keeping internal state.  make sure all our mallocs
    253 	 * go through.
    254 	 */
    255 	/* from cfg file */
    256 	m.defaultpath = gettag("_default", 1);
    257 	m.subdirs = gettag("_subdir", 1);
    258 	m.suffixlist = gettag("_suffix", 1);
    259 	m.buildlist = gettag("_build", 1);
    260 	/* internal use */
    261 	m.mymanpath = gettag("_new_path", 1);
    262 	m.missinglist = gettag("_missing", 1);
    263 	m.intmp = gettag("_intmp", 1);
    264 	if (!m.defaultpath || !m.subdirs || !m.suffixlist || !m.buildlist ||
    265 	    !m.mymanpath || !m.missinglist || !m.intmp)
    266 		errx(EXIT_FAILURE, "malloc failed");
    267 
    268 	/*
    269 	 * are we using a section whose elements are all absolute paths?
    270 	 * (we only need to look at the first entry on the section list,
    271 	 * as config() will ensure that any additional entries will match
    272 	 * the first one.)
    273 	 */
    274 	abs_section = (m.section != NULL &&
    275 		!TAILQ_EMPTY(&m.section->entrylist) &&
    276 	    		*(TAILQ_FIRST(&m.section->entrylist)->s) == '/');
    277 
    278 	/*
    279 	 * now that we have all the data we need, we must determine the
    280 	 * manpath we are going to use to find the requested entries using
    281 	 * the following steps...
    282 	 *
    283 	 * [1] if the user specified a section and that section's elements
    284 	 *     from the config file are all absolute paths, then we override
    285 	 *     defaultpath and -M/MANPATH with the section's absolute paths.
    286 	 */
    287 	if (abs_section) {
    288 		m.manpath = NULL;	   	/* ignore -M/MANPATH */
    289 		m.defaultpath = m.section;	/* overwrite _default path */
    290 		m.section = NULL;		/* promoted to defaultpath */
    291 	}
    292 
    293 	/*
    294 	 * [2] section can now only be non-null if the user asked for
    295 	 *     a section and that section's elements did not have
    296          *     absolute paths.  in this case we use the section's
    297 	 *     elements to override _subdir from the config file.
    298 	 *
    299 	 * after this step, we are done processing "m.section"...
    300 	 */
    301 	if (m.section)
    302 		m.subdirs = m.section;
    303 
    304 	/*
    305 	 * [3] we need to setup the path we want to use (m.mymanpath).
    306 	 *     if the user gave us a path (m.manpath) use it, otherwise
    307 	 *     go with the default.   in either case we need to append
    308 	 *     the subdir and machine spec to each element of the path.
    309 	 *
    310 	 *     for absolute section paths that come from the config file,
    311 	 *     we only append the subdir spec if the path ends in
    312 	 *     a '/' --- elements that do not end in '/' are assumed to
    313 	 *     not have subdirectories.  this is mainly for backward compat,
    314 	 *     but it allows non-subdir configs like:
    315 	 *	sect3       /usr/share/man/{old/,}cat3
    316 	 *	doc         /usr/{pkg,share}/doc/{sendmail/op,sendmail/intro}
    317 	 *
    318 	 *     note that we try and be careful to not put double slashes
    319 	 *     in the path (e.g. we want /usr/share/man/man1, not
    320 	 *     /usr/share/man//man1) because "more" will put the filename
    321 	 *     we generate in its prompt and the double slashes look ugly.
    322 	 */
    323 	if (m.manpath) {
    324 
    325 		/* note: strtok is going to destroy m.manpath */
    326 		for (p = strtok(m.manpath, ":") ; p ; p = strtok(NULL, ":")) {
    327 			len = strlen(p);
    328 			if (len < 1)
    329 				continue;
    330 			TAILQ_FOREACH(esubd, &m.subdirs->entrylist, q)
    331 				addpath(&m, p, len, esubd->s);
    332 		}
    333 
    334 	} else {
    335 
    336 		TAILQ_FOREACH(epath, &m.defaultpath->entrylist, q) {
    337 			/* handle trailing "/" magic here ... */
    338 		  	if (abs_section && epath->s[epath->len - 1] != '/') {
    339 				addpath(&m, "", 1, epath->s);
    340 				continue;
    341 			}
    342 
    343 			TAILQ_FOREACH(esubd, &m.subdirs->entrylist, q)
    344 				addpath(&m, epath->s, epath->len, esubd->s);
    345 		}
    346 
    347 	}
    348 
    349 	/*
    350 	 * [4] finally, prepend the "-m" m.addpath to mymanpath if it
    351 	 *     was specified.   subdirs and machine are always applied to
    352 	 *     m.addpath.
    353 	 */
    354 	if (m.addpath) {
    355 
    356 		/* note: strtok is going to destroy m.addpath */
    357 		for (p = strtok(m.addpath, ":") ; p ; p = strtok(NULL, ":")) {
    358 			len = strlen(p);
    359 			if (len < 1)
    360 				continue;
    361 			TAILQ_FOREACH(esubd, &m.subdirs->entrylist, q)
    362 				addpath(&m, p, len, esubd->s);
    363 		}
    364 
    365 	}
    366 
    367 	if (m.getpath)
    368 		printmanpath(&m);
    369 
    370 	/*
    371 	 * now m.mymanpath is complete!
    372 	 */
    373 #if MAN_DEBUG
    374 	printf("mymanpath:\n");
    375 	TAILQ_FOREACH(epath, &m.mymanpath->entrylist, q) {
    376 		printf("\t%s\n", epath->s);
    377 	}
    378 #endif
    379 
    380 	/*
    381 	 * start searching for matching files and format them if necessary.
    382 	 * setup an interrupt handler so that we can ensure that temporary
    383 	 * files go away.
    384 	 */
    385 	(void)signal(SIGINT, onsig);
    386 	(void)signal(SIGHUP, onsig);
    387 	(void)signal(SIGPIPE, onsig);
    388 
    389 	memset(&pg, 0, sizeof(pg));
    390 	for (found = 0; *argv; ++argv)
    391 		if (manual(*argv, &m, &pg)) {
    392 			found = 1;
    393 		}
    394 
    395 	/* if nothing found, we're done. */
    396 	if (!found) {
    397 		(void)cleanup();
    398 		exit(EXIT_FAILURE);
    399 	}
    400 
    401 	/*
    402 	 * handle the simple display cases first (m.cat, m.how, m.where)
    403 	 */
    404 	if (m.cat) {
    405 		for (ap = pg.gl_pathv; *ap != NULL; ++ap) {
    406 			if (**ap == '\0')
    407 				continue;
    408 			cat(*ap);
    409 		}
    410 		exit(cleanup());
    411 	}
    412 	if (m.how) {
    413 		for (ap = pg.gl_pathv; *ap != NULL; ++ap) {
    414 			if (**ap == '\0')
    415 				continue;
    416 			how(*ap);
    417 		}
    418 		exit(cleanup());
    419 	}
    420 	if (m.where) {
    421 		for (ap = pg.gl_pathv; *ap != NULL; ++ap) {
    422 			if (**ap == '\0')
    423 				continue;
    424 			(void)printf("%s\n", *ap);
    425 		}
    426 		exit(cleanup());
    427 	}
    428 
    429 	/*
    430 	 * normal case - we display things in a single command, so
    431          * build a list of things to display.  first compute total
    432 	 * length of buffer we will need so we can malloc it.
    433 	 */
    434 	for (ap = pg.gl_pathv, len = m.pagerlen + 1; *ap != NULL; ++ap) {
    435 		if (**ap == '\0')
    436 			continue;
    437 		len += strlen(*ap) + 1;
    438 	}
    439 	if ((cmd = malloc(len)) == NULL) {
    440 		warn("malloc");
    441 		(void)cleanup();
    442 		exit(EXIT_FAILURE);
    443 	}
    444 
    445 	/* now build the command string... */
    446 	p = cmd;
    447 	len = m.pagerlen;
    448 	memcpy(p, m.pager, len);
    449 	p += len;
    450 	*p++ = ' ';
    451 	for (ap = pg.gl_pathv; *ap != NULL; ++ap) {
    452 		if (**ap == '\0')
    453 			continue;
    454 		len = strlen(*ap);
    455 		memcpy(p, *ap, len);
    456 		p += len;
    457 		*p++ = ' ';
    458 	}
    459 	*--p = '\0';
    460 
    461 	/* Use system(3) in case someone's pager is "pager arg1 arg2". */
    462 	(void)system(cmd);
    463 
    464 	exit(cleanup());
    465 }
    466 
    467 static int
    468 manual_find_buildkeyword(const char *prefix, const char *escpage,
    469 	struct manstate *mp, glob_t *pg, size_t cnt)
    470 {
    471 	ENTRY *suffix;
    472 	int found;
    473 	char buf[MAXPATHLEN];
    474 	const char *p;
    475 	int suflen;
    476 
    477 	found = 0;
    478 	/* Try the _build keywords next. */
    479 	TAILQ_FOREACH(suffix, &mp->buildlist->entrylist, q) {
    480 		for (p = suffix->s, suflen = 0;
    481 		    *p != '\0' && !isspace((unsigned char)*p);
    482 		    ++p)
    483 			++suflen;
    484 		if (*p == '\0')
    485 			continue;
    486 
    487 		(void)snprintf(buf, sizeof(buf), "%s%s%.*s",
    488 			       prefix, escpage, suflen, suffix->s);
    489 		if (!fnmatch(buf, pg->gl_pathv[cnt], 0)) {
    490 			if (!mp->where)
    491 				build_page(p + 1, &pg->gl_pathv[cnt], mp);
    492 			found = 1;
    493 			break;
    494 		}
    495 	}
    496 
    497 	return found;
    498 }
    499 
    500 /*
    501  * manual --
    502  *	Search the manuals for the pages.
    503  */
    504 static int
    505 manual(char *page, struct manstate *mp, glob_t *pg)
    506 {
    507 	ENTRY *suffix, *mdir;
    508 	int anyfound, error, found;
    509 	size_t cnt;
    510 	char *p, buf[MAXPATHLEN], *escpage, *eptr;
    511 	static const char escglob[] = "\\~?*{}[]";
    512 
    513 	anyfound = 0;
    514 
    515 	/*
    516 	 * Fixup page which may contain glob(3) special characters, e.g.
    517 	 * the famous "No man page for [" FAQ.
    518 	 */
    519 	if ((escpage = malloc((2 * strlen(page)) + 1)) == NULL) {
    520 		warn("malloc");
    521 		(void)cleanup();
    522 		exit(EXIT_FAILURE);
    523 	}
    524 
    525 	p = page;
    526 	eptr = escpage;
    527 
    528 	while (*p) {
    529 		if (strchr(escglob, *p) != NULL) {
    530 			*eptr++ = '\\';
    531 			*eptr++ = *p++;
    532 		} else
    533 			*eptr++ = *p++;
    534 	}
    535 
    536 	*eptr = '\0';
    537 
    538 	/*
    539 	 * If 'page' contains a slash then it's
    540 	 * interpreted as a file specification.
    541 	 */
    542 	if (strchr(page, '/') != NULL) {
    543 		/* check if file actually exists */
    544 		(void)strlcpy(buf, escpage, sizeof(buf));
    545 		error = glob(buf, GLOB_APPEND | GLOB_BRACE | GLOB_NOSORT, NULL, pg);
    546 		if (error != 0) {
    547 			if (error == GLOB_NOMATCH) {
    548 				goto notfound;
    549 			} else {
    550 				errx(EXIT_FAILURE, "glob failed");
    551 			}
    552 		}
    553 
    554 		if (pg->gl_matchc == 0)
    555 			goto notfound;
    556 
    557 		/* clip suffix for the suffix check below */
    558 		if ((p = strrchr(escpage, '.')) != NULL) {
    559 			/* Should get suffixes from the configuration file */
    560 			if (strcmp(p, ".gz") == 0 || strcmp(p, ".bz2") == 0 ||
    561 			    strcmp(p, ".Z") == 0 || strcmp(p, ".xz") == 0) {
    562 				*p = '\0';
    563 				p = strrchr(escpage, '.');
    564 			}
    565 			if (p && strchr("0123456789ln", p[1]) != NULL)
    566 				*p = '\0';
    567 		}
    568 
    569 		found = 0;
    570 		for (cnt = pg->gl_pathc - pg->gl_matchc;
    571 		    cnt < pg->gl_pathc; ++cnt)
    572 		{
    573 			found = manual_find_buildkeyword("", escpage,
    574 				mp, pg, cnt);
    575 			if (found) {
    576 				anyfound = 1;
    577 				if (!mp->all) {
    578 					/* Delete any other matches. */
    579 					while (++cnt< pg->gl_pathc)
    580 						*pg->gl_pathv[cnt] = '\0';
    581 					break;
    582 				}
    583 				continue;
    584 			}
    585 
    586 			/* It's not a man page, forget about it. */
    587 			*pg->gl_pathv[cnt] = '\0';
    588 		}
    589 
    590   notfound:
    591 		if (!anyfound) {
    592 			if (addentry(mp->missinglist, page, 0) < 0) {
    593 				warn("malloc");
    594 				(void)cleanup();
    595 				exit(EXIT_FAILURE);
    596 			}
    597 		}
    598 		free(escpage);
    599 		return anyfound;
    600 	}
    601 
    602 	/* For each man directory in mymanpath ... */
    603 	TAILQ_FOREACH(mdir, &mp->mymanpath->entrylist, q) {
    604 
    605 		/*
    606 		 * use glob(3) to look in the filesystem for matching files.
    607 		 * match any suffix here, as we will check that later.
    608 		 */
    609 		(void)snprintf(buf, sizeof(buf), "%s/%s.*", mdir->s, escpage);
    610 		if ((error = glob(buf,
    611 		    GLOB_APPEND | GLOB_BRACE | GLOB_NOSORT, NULL, pg)) != 0) {
    612 			if (error == GLOB_NOMATCH)
    613 				continue;
    614 			else {
    615 				warn("globbing");
    616 				(void)cleanup();
    617 				exit(EXIT_FAILURE);
    618 			}
    619 		}
    620 		if (pg->gl_matchc == 0)
    621 			continue;
    622 
    623 		/*
    624 		 * start going through the matches glob(3) just found and
    625 		 * use m.pathsearch (if present) to filter out pages we
    626 		 * don't want.  then verify the suffix is valid, and build
    627 		 * the page if we have a _build suffix.
    628 		 */
    629 		for (cnt = pg->gl_pathc - pg->gl_matchc;
    630 		    cnt < pg->gl_pathc; ++cnt) {
    631 
    632 			/* filter on directory path name */
    633 			if (mp->pathsearch) {
    634 				p = strstr(pg->gl_pathv[cnt], mp->pathsearch);
    635 				if (!p || strchr(p, '/') == NULL) {
    636 					*pg->gl_pathv[cnt] = '\0'; /* zap! */
    637 					continue;
    638 				}
    639 			}
    640 
    641 			/*
    642 			 * Try the _suffix keywords first.
    643 			 *
    644 			 * XXX
    645 			 * Older versions of man.conf didn't have the _suffix
    646 			 * keywords, it was assumed that everything was a .0.
    647 			 * We just test for .0 first, it's fast and probably
    648 			 * going to hit.
    649 			 */
    650 			(void)snprintf(buf, sizeof(buf), "*/%s.0", escpage);
    651 			if (!fnmatch(buf, pg->gl_pathv[cnt], 0))
    652 				goto next;
    653 
    654 			found = 0;
    655 			TAILQ_FOREACH(suffix, &mp->suffixlist->entrylist, q) {
    656 				(void)snprintf(buf,
    657 				     sizeof(buf), "*/%s%s", escpage,
    658 				     suffix->s);
    659 				if (!fnmatch(buf, pg->gl_pathv[cnt], 0)) {
    660 					found = 1;
    661 					break;
    662 				}
    663 			}
    664 			if (found)
    665 				goto next;
    666 
    667 			/* Try the _build keywords next. */
    668 			found = manual_find_buildkeyword("*/", escpage,
    669 				mp, pg, cnt);
    670 			if (found) {
    671 next:				anyfound = 1;
    672 				if (!mp->all) {
    673 					/* Delete any other matches. */
    674 					while (++cnt< pg->gl_pathc)
    675 						*pg->gl_pathv[cnt] = '\0';
    676 					break;
    677 				}
    678 				continue;
    679 			}
    680 
    681 			/* It's not a man page, forget about it. */
    682 			*pg->gl_pathv[cnt] = '\0';
    683 		}
    684 
    685 		if (anyfound && !mp->all)
    686 			break;
    687 	}
    688 
    689 	/* If not found, enter onto the missing list. */
    690 	if (!anyfound) {
    691 		if (addentry(mp->missinglist, page, 0) < 0) {
    692 			warn("malloc");
    693 			(void)cleanup();
    694 			exit(EXIT_FAILURE);
    695 		}
    696 	}
    697 
    698 	free(escpage);
    699 	return anyfound;
    700 }
    701 
    702 /*
    703  * build_page --
    704  *	Build a man page for display.
    705  */
    706 static void
    707 build_page(const char *fmt, char **pathp, struct manstate *mp)
    708 {
    709 	static int warned;
    710 	int olddir, fd, n;
    711 	size_t tmpdirlen;
    712 	char *p, *b;
    713 	char buf[MAXPATHLEN], cmd[MAXPATHLEN], tpath[MAXPATHLEN];
    714 	const char *tmpdir;
    715 
    716 	/* Let the user know this may take awhile. */
    717 	if (!warned) {
    718 		warned = 1;
    719 		warnx("Formatting manual page...");
    720 	}
    721 
    722        /*
    723         * Historically man chdir'd to the root of the man tree.
    724         * This was used in man pages that contained relative ".so"
    725         * directives (including other man pages for command aliases etc.)
    726         * It even went one step farther, by examining the first line
    727         * of the man page and parsing the .so filename so it would
    728         * make hard(?) links to the cat'ted man pages for space savings.
    729         * (We don't do that here, but we could).
    730         */
    731 
    732        /* copy and find the end */
    733        for (b = buf, p = *pathp; (*b++ = *p++) != '\0';)
    734                continue;
    735 
    736 	/*
    737 	 * skip the last two path components, page name and man[n] ...
    738 	 * (e.g. buf will be "/usr/share/man" and p will be "man1/man.1")
    739 	 * we also save a pointer to our current directory so that we
    740 	 * can fchdir() back to it.  this allows relative MANDIR paths
    741 	 * to work with multiple man pages... e.g. consider:
    742 	 *   	cd /usr/share && man -M ./man cat ls
    743 	 * when no "cat1" subdir files are present.
    744 	 */
    745 	olddir = -1;
    746 	for (--b, --p, n = 2; b != buf; b--, p--)
    747 		if (*b == '/')
    748 			if (--n == 0) {
    749 				*b = '\0';
    750 				olddir = open(".", O_RDONLY);
    751 				(void) chdir(buf);
    752 				p++;
    753 				break;
    754 			}
    755 
    756 
    757 	/* advance fmt past the suffix spec to the printf format string */
    758 	for (; *fmt && isspace((unsigned char)*fmt); ++fmt)
    759 		continue;
    760 
    761 	/*
    762 	 * Get a temporary file and build a version of the file
    763 	 * to display.  Replace the old file name with the new one.
    764 	 */
    765 	if ((tmpdir = getenv("TMPDIR")) == NULL)
    766 		tmpdir = _PATH_TMP;
    767 	tmpdirlen = strlen(tmpdir);
    768 	(void)snprintf(tpath, sizeof (tpath), "%s%s%s", tmpdir,
    769 	    (tmpdirlen > 0 && tmpdir[tmpdirlen-1] == '/') ? "" : "/", TMPFILE);
    770 	if ((fd = mkstemp(tpath)) == -1) {
    771 		warn("%s", tpath);
    772 		(void)cleanup();
    773 		exit(EXIT_FAILURE);
    774 	}
    775 	(void)snprintf(buf, sizeof(buf), "%s > %s", fmt, tpath);
    776 	(void)snprintf(cmd, sizeof(cmd), buf, p);
    777 	(void)system(cmd);
    778 	(void)close(fd);
    779 	if ((*pathp = strdup(tpath)) == NULL) {
    780 		warn("malloc");
    781 		(void)cleanup();
    782 		exit(EXIT_FAILURE);
    783 	}
    784 
    785 	/* Link the built file into the remove-when-done list. */
    786 	if (addentry(mp->intmp, *pathp, 0) < 0) {
    787 		warn("malloc");
    788 		(void)cleanup();
    789 		exit(EXIT_FAILURE);
    790 	}
    791 
    792 	/* restore old directory so relative manpaths still work */
    793 	if (olddir != -1) {
    794 		fchdir(olddir);
    795 		close(olddir);
    796 	}
    797 }
    798 
    799 /*
    800  * how --
    801  *	display how information
    802  */
    803 static void
    804 how(const char *fname)
    805 {
    806 	FILE *fp;
    807 
    808 	int lcnt, print;
    809 	char buf[256];
    810 	const char *p;
    811 
    812 	if (!(fp = fopen(fname, "r"))) {
    813 		warn("%s", fname);
    814 		(void)cleanup();
    815 		exit(EXIT_FAILURE);
    816 	}
    817 #define	S1	"SYNOPSIS"
    818 #define	S2	"S\bSY\bYN\bNO\bOP\bPS\bSI\bIS\bS"
    819 #define	D1	"DESCRIPTION"
    820 #define	D2	"D\bDE\bES\bSC\bCR\bRI\bIP\bPT\bTI\bIO\bON\bN"
    821 	for (lcnt = print = 0; fgets(buf, sizeof(buf), fp);) {
    822 		if (!strncmp(buf, S1, sizeof(S1) - 1) ||
    823 		    !strncmp(buf, S2, sizeof(S2) - 1)) {
    824 			print = 1;
    825 			continue;
    826 		} else if (!strncmp(buf, D1, sizeof(D1) - 1) ||
    827 		    !strncmp(buf, D2, sizeof(D2) - 1)) {
    828 			if (fp)
    829 				(void)fclose(fp);
    830 			return;
    831 		}
    832 		if (!print)
    833 			continue;
    834 		if (*buf == '\n')
    835 			++lcnt;
    836 		else {
    837 			for(; lcnt; --lcnt)
    838 				(void)putchar('\n');
    839 			for (p = buf; isspace((unsigned char)*p); ++p)
    840 				continue;
    841 			(void)fputs(p, stdout);
    842 		}
    843 	}
    844 	(void)fclose(fp);
    845 }
    846 
    847 /*
    848  * cat --
    849  *	cat out the file
    850  */
    851 static void
    852 cat(const char *fname)
    853 {
    854 	int fd;
    855 	ssize_t n;
    856 	char buf[2048];
    857 
    858 	if ((fd = open(fname, O_RDONLY, 0)) < 0) {
    859 		warn("%s", fname);
    860 		(void)cleanup();
    861 		exit(EXIT_FAILURE);
    862 	}
    863 	while ((n = read(fd, buf, sizeof(buf))) > 0)
    864 		if (write(STDOUT_FILENO, buf, (size_t)n) != n) {
    865 			warn("write");
    866 			(void)cleanup();
    867 			exit(EXIT_FAILURE);
    868 		}
    869 	if (n == -1) {
    870 		warn("read");
    871 		(void)cleanup();
    872 		exit(EXIT_FAILURE);
    873 	}
    874 	(void)close(fd);
    875 }
    876 
    877 /*
    878  * check_pager --
    879  *	check the user supplied page information
    880  */
    881 static const char *
    882 check_pager(const char *name)
    883 {
    884 	const char *p;
    885 
    886 	/*
    887 	 * if the user uses "more", we make it "more -s"; watch out for
    888 	 * PAGER = "mypager /usr/ucb/more"
    889 	 */
    890 	for (p = name; *p && !isspace((unsigned char)*p); ++p)
    891 		continue;
    892 	for (; p > name && *p != '/'; --p);
    893 	if (p != name)
    894 		++p;
    895 
    896 	/* make sure it's "more", not "morex" */
    897 	if (!strncmp(p, "more", 4) && (!p[4] || isspace((unsigned char)p[4]))){
    898 		char *newname;
    899 		(void)asprintf(&newname, "%s %s", p, "-s");
    900 		name = newname;
    901 	}
    902 
    903 	return name;
    904 }
    905 
    906 /*
    907  * jump --
    908  *	strip out flag argument and jump
    909  */
    910 static void
    911 jump(char **argv, const char *flag, const char *name)
    912 {
    913 	char **arg;
    914 
    915 	argv[0] = __UNCONST(name);
    916 	for (arg = argv + 1; *arg; ++arg)
    917 		if (!strcmp(*arg, flag))
    918 			break;
    919 	for (; *arg; ++arg)
    920 		arg[0] = arg[1];
    921 	execvp(name, argv);
    922 	err(EXIT_FAILURE, "Cannot execute `%s'", name);
    923 }
    924 
    925 /*
    926  * onsig --
    927  *	If signaled, delete the temporary files.
    928  */
    929 static void
    930 onsig(int signo)
    931 {
    932 
    933 	(void)cleanup();
    934 
    935 	(void)raise_default_signal(signo);
    936 
    937 	/* NOTREACHED */
    938 	exit(EXIT_FAILURE);
    939 }
    940 
    941 /*
    942  * cleanup --
    943  *	Clean up temporary files, show any error messages.
    944  */
    945 static int
    946 cleanup(void)
    947 {
    948 	TAG *intmpp, *missp;
    949 	ENTRY *ep;
    950 	int rval;
    951 
    952 	rval = EXIT_SUCCESS;
    953 	/*
    954 	 * note that _missing and _intmp were created by main(), so
    955 	 * gettag() cannot return NULL here.
    956 	 */
    957 	missp = gettag("_missing", 0);	/* missing man pages */
    958 	intmpp = gettag("_intmp", 0);	/* tmp files we need to unlink */
    959 
    960 	TAILQ_FOREACH(ep, &missp->entrylist, q) {
    961 		warnx("no entry for %s in the manual.", ep->s);
    962 		rval = EXIT_FAILURE;
    963 	}
    964 
    965 	TAILQ_FOREACH(ep, &intmpp->entrylist, q)
    966 		(void)unlink(ep->s);
    967 
    968 	return rval;
    969 }
    970 
    971 static const char *
    972 getclass(const char *machine)
    973 {
    974 	char buf[BUFSIZ];
    975 	TAG *t;
    976 	snprintf(buf, sizeof(buf), "_%s", machine);
    977 	t = gettag(buf, 0);
    978 	return t != NULL && !TAILQ_EMPTY(&t->entrylist) ?
    979 	    TAILQ_FIRST(&t->entrylist)->s : NULL;
    980 }
    981 
    982 static void
    983 addpath(struct manstate *m, const char *dir, size_t len, const char *sub)
    984 {
    985 	char buf[2 * MAXPATHLEN + 1];
    986 	(void)snprintf(buf, sizeof(buf), "%s%s%s{/%s,%s%s%s}",
    987 	     dir, (dir[len - 1] == '/') ? "" : "/", sub, m->machine,
    988 	     m->machclass ? "/" : "", m->machclass ? m->machclass : "",
    989 	     m->machclass ? "," : "");
    990 	if (addentry(m->mymanpath, buf, 0) < 0)
    991 		errx(EXIT_FAILURE, "malloc failed");
    992 }
    993 
    994 /*
    995  * usage --
    996  *	print usage message and die
    997  */
    998 static void
    999 usage(void)
   1000 {
   1001 	(void)fprintf(stderr, "Usage: %s [-acw|-h] [-C cfg] [-M path] "
   1002 	    "[-m path] [-S srch] [[-s] sect] name ...\n", getprogname());
   1003 	(void)fprintf(stderr,
   1004 	    "Usage: %s -k [-C cfg] [-M path] [-m path] keyword ...\n",
   1005 	    getprogname());
   1006 	(void)fprintf(stderr, "Usage: %s -p\n", getprogname());
   1007 	exit(EXIT_FAILURE);
   1008 }
   1009 
   1010 /*
   1011  * printmanpath --
   1012  *	Prints a list of directories containing man pages.
   1013  */
   1014 static void
   1015 printmanpath(struct manstate *m)
   1016 {
   1017 	ENTRY *esubd;
   1018 	char *defaultpath = NULL; /* _default tag value from man.conf. */
   1019 	char *buf; /* for storing temporary values */
   1020 	char **ap;
   1021 	glob_t pg;
   1022 	struct stat sb;
   1023 	TAG *path = m->defaultpath;
   1024 	TAG *subdirs = m->subdirs;
   1025 
   1026 	/* the tail queue is empty if no _default tag is defined in * man.conf */
   1027 	if (TAILQ_EMPTY(&path->entrylist))
   1028 		errx(EXIT_FAILURE, "Empty manpath");
   1029 
   1030 	defaultpath = TAILQ_LAST(&path->entrylist, tqh)->s;
   1031 
   1032 	if (glob(defaultpath, GLOB_BRACE | GLOB_NOSORT, NULL, &pg) != 0)
   1033 		err(EXIT_FAILURE, "glob failed");
   1034 
   1035 	if (pg.gl_matchc == 0) {
   1036 		warnx("Default path in %s doesn't exist", _PATH_MANCONF);
   1037 		globfree(&pg);
   1038 		return;
   1039 	}
   1040 
   1041 	TAILQ_FOREACH(esubd, &subdirs->entrylist, q) {
   1042 		/* Drop cat page directory, only sources are relevant. */
   1043 		if (strncmp(esubd->s, "man", 3))
   1044 			continue;
   1045 
   1046 		for (ap = pg.gl_pathv; *ap != NULL; ++ap) {
   1047 			if (asprintf(&buf, "%s%s", *ap, esubd->s) == -1)
   1048 				err(EXIT_FAILURE, "memory allocation error");
   1049 			/* Skip non-directories. */
   1050 			if (stat(buf, &sb) == 0 && S_ISDIR(sb.st_mode))
   1051 				printf("%s\n", buf);
   1052 
   1053 			free(buf);
   1054 		}
   1055 	}
   1056 	globfree(&pg);
   1057 }
   1058