man.c revision 1.37.10.1 1 /* $NetBSD: man.c,v 1.37.10.1 2010/04/21 05:27:11 matt 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.37.10.1 2010/04/21 05:27:11 matt Exp $");
44 #endif
45 #endif /* not lint */
46
47 #include <sys/param.h>
48 #include <sys/queue.h>
49 #include <sys/utsname.h>
50
51 #include <ctype.h>
52 #include <err.h>
53 #include <errno.h>
54 #include <fcntl.h>
55 #include <fnmatch.h>
56 #include <glob.h>
57 #include <signal.h>
58 #include <stdio.h>
59 #include <stdlib.h>
60 #include <string.h>
61 #include <unistd.h>
62 #include <util.h>
63
64 #include "manconf.h"
65 #include "pathnames.h"
66
67 #ifndef MAN_DEBUG
68 #define MAN_DEBUG 0 /* debug path output */
69 #endif
70
71 /*
72 * manstate: structure collecting the current global state so we can
73 * easily identify it and pass it to helper functions in one arg.
74 */
75 struct manstate {
76 /* command line flags */
77 int all; /* -a: show all matches rather than first */
78 int cat; /* -c: do not use a pager */
79 char *conffile; /* -C: use alternate config file */
80 int how; /* -h: show SYNOPSIS only */
81 char *manpath; /* -M: alternate MANPATH */
82 char *addpath; /* -m: add these dirs to front of manpath */
83 char *pathsearch; /* -S: path of man must contain this string */
84 char *sectionname; /* -s: limit search to a given man section */
85 int where; /* -w: just show paths of all matching files */
86
87 /* important tags from the config file */
88 TAG *defaultpath; /* _default: default MANPATH */
89 TAG *subdirs; /* _subdir: default subdir search list */
90 TAG *suffixlist; /* _suffix: for files that can be cat()'d */
91 TAG *buildlist; /* _build: for files that must be built */
92
93 /* tags for internal use */
94 TAG *intmp; /* _intmp: tmp files we must cleanup */
95 TAG *missinglist; /* _missing: pages we couldn't find */
96 TAG *mymanpath; /* _new_path: final version of MANPATH */
97 TAG *section; /* <sec>: tag for m.sectionname */
98
99 /* other misc stuff */
100 const char *pager; /* pager to use */
101 size_t pagerlen; /* length of the above */
102 };
103
104 /*
105 * prototypes
106 */
107 int main(int, char **);
108 static void build_page(char *, char **, struct manstate *);
109 static void cat(char *);
110 static const char *check_pager(const char *);
111 static int cleanup(void);
112 static void how(char *);
113 static void jump(char **, char *, char *);
114 static int manual(char *, struct manstate *, glob_t *);
115 static void onsig(int);
116 static void usage(void);
117
118 /*
119 * main function
120 */
121 int
122 main(int argc, char **argv)
123 {
124 static struct manstate m = { 0 }; /* init to zero */
125 int ch, abs_section, found;
126 const char *machine;
127 ENTRY *esubd, *epath;
128 char *p, **ap, *cmd, buf[MAXPATHLEN * 2];
129 size_t len;
130 glob_t pg;
131
132 /*
133 * parse command line...
134 */
135 while ((ch = getopt(argc, argv, "-aC:cfhkM:m:P:s:S:w")) != -1)
136 switch (ch) {
137 case 'a':
138 m.all = 1;
139 break;
140 case 'C':
141 m.conffile = optarg;
142 break;
143 case 'c':
144 case '-': /* XXX: '-' is a deprecated version of '-c' */
145 m.cat = 1;
146 break;
147 case 'h':
148 m.how = 1;
149 break;
150 case 'm':
151 m.addpath = optarg;
152 break;
153 case 'M':
154 case 'P': /* -P for backward compatibility */
155 m.manpath = strdup(optarg);
156 break;
157 /*
158 * The -f and -k options are backward compatible,
159 * undocumented ways of calling whatis(1) and apropos(1).
160 */
161 case 'f':
162 jump(argv, "-f", "whatis");
163 /* NOTREACHED */
164 case 'k':
165 jump(argv, "-k", "apropos");
166 /* NOTREACHED */
167 case 's':
168 if (m.sectionname != NULL)
169 usage();
170 m.sectionname = optarg;
171 break;
172 case 'S':
173 m.pathsearch = optarg;
174 break;
175 case 'w':
176 m.all = m.where = 1;
177 break;
178 case '?':
179 default:
180 usage();
181 }
182 argc -= optind;
183 argv += optind;
184
185 if (!argc)
186 usage();
187
188 /*
189 * read the configuration file and collect any other information
190 * we will need (machine type, pager, section [if specified
191 * without '-s'], and MANPATH through the environment).
192 */
193 config(m.conffile); /* exits on error ... */
194
195 if ((machine = getenv("MACHINE")) == NULL) {
196 struct utsname utsname;
197
198 if (uname(&utsname) == -1) {
199 perror("uname");
200 exit(1);
201 }
202 machine = utsname.machine;
203 }
204
205 if (!m.cat && !m.how && !m.where) { /* if we need a pager ... */
206 if (!isatty(STDOUT_FILENO)) {
207 m.cat = 1;
208 } else {
209 if ((m.pager = getenv("PAGER")) != NULL &&
210 m.pager[0] != '\0')
211 m.pager = check_pager(m.pager);
212 else
213 m.pager = _PATH_PAGER;
214 m.pagerlen = strlen(m.pager);
215 }
216 }
217
218 /* do we need to set m.section to a non-null value? */
219 if (m.sectionname) {
220
221 m.section = gettag(m.sectionname, 0); /* -s must be a section */
222 if (m.section == NULL)
223 errx(1, "unknown section: %s", m.sectionname);
224
225 } else if (argc > 1) {
226
227 m.section = gettag(*argv, 0); /* might be a section? */
228 if (m.section) {
229 argv++;
230 argc--;
231 }
232
233 }
234
235 if (m.manpath == NULL)
236 m.manpath = getenv("MANPATH"); /* note: -M overrides getenv */
237
238
239 /*
240 * get default values from config file, plus create the tags we
241 * use for keeping internal state. make sure all our mallocs
242 * go through.
243 */
244 /* from cfg file */
245 m.defaultpath = gettag("_default", 1);
246 m.subdirs = gettag("_subdir", 1);
247 m.suffixlist = gettag("_suffix", 1);
248 m.buildlist = gettag("_build", 1);
249 /* internal use */
250 m.mymanpath = gettag("_new_path", 1);
251 m.missinglist = gettag("_missing", 1);
252 m.intmp = gettag("_intmp", 1);
253 if (!m.defaultpath || !m.subdirs || !m.suffixlist || !m.buildlist ||
254 !m.mymanpath || !m.missinglist || !m.intmp)
255 errx(1, "malloc failed");
256
257 /*
258 * are we using a section whose elements are all absolute paths?
259 * (we only need to look at the first entry on the section list,
260 * as config() will ensure that any additional entries will match
261 * the first one.)
262 */
263 abs_section = (m.section != NULL &&
264 !TAILQ_EMPTY(&m.section->entrylist) &&
265 *(TAILQ_FIRST(&m.section->entrylist)->s) == '/');
266
267 /*
268 * now that we have all the data we need, we must determine the
269 * manpath we are going to use to find the requested entries using
270 * the following steps...
271 *
272 * [1] if the user specified a section and that section's elements
273 * from the config file are all absolute paths, then we override
274 * defaultpath and -M/MANPATH with the section's absolute paths.
275 */
276 if (abs_section) {
277 m.manpath = NULL; /* ignore -M/MANPATH */
278 m.defaultpath = m.section; /* overwrite _default path */
279 m.section = NULL; /* promoted to defaultpath */
280 }
281
282 /*
283 * [2] section can now only be non-null if the user asked for
284 * a section and that section's elements did not have
285 * absolute paths. in this case we use the section's
286 * elements to override _subdir from the config file.
287 *
288 * after this step, we are done processing "m.section"...
289 */
290 if (m.section)
291 m.subdirs = m.section;
292
293 /*
294 * [3] we need to setup the path we want to use (m.mymanpath).
295 * if the user gave us a path (m.manpath) use it, otherwise
296 * go with the default. in either case we need to append
297 * the subdir and machine spec to each element of the path.
298 *
299 * for absolute section paths that come from the config file,
300 * we only append the subdir spec if the path ends in
301 * a '/' --- elements that do not end in '/' are assumed to
302 * not have subdirectories. this is mainly for backward compat,
303 * but it allows non-subdir configs like:
304 * sect3 /usr/share/man/{old/,}cat3
305 * doc /usr/{pkg,share}/doc/{sendmail/op,sendmail/intro}
306 *
307 * note that we try and be careful to not put double slashes
308 * in the path (e.g. we want /usr/share/man/man1, not
309 * /usr/share/man//man1) because "more" will put the filename
310 * we generate in its prompt and the double slashes look ugly.
311 */
312 if (m.manpath) {
313
314 /* note: strtok is going to destroy m.manpath */
315 for (p = strtok(m.manpath, ":") ; p ; p = strtok(NULL, ":")) {
316 len = strlen(p);
317 if (len < 1)
318 continue;
319 TAILQ_FOREACH(esubd, &m.subdirs->entrylist, q) {
320 snprintf(buf, sizeof(buf), "%s%s%s{/%s,}",
321 p, (p[len-1] == '/') ? "" : "/",
322 esubd->s, machine);
323 if (addentry(m.mymanpath, buf, 0) < 0)
324 errx(1, "malloc failed");
325 }
326 }
327
328 } else {
329
330 TAILQ_FOREACH(epath, &m.defaultpath->entrylist, q) {
331 /* handle trailing "/" magic here ... */
332 if (abs_section &&
333 epath->s[epath->len - 1] != '/') {
334
335 (void)snprintf(buf, sizeof(buf),
336 "%s{/%s,}", epath->s, machine);
337 if (addentry(m.mymanpath, buf, 0) < 0)
338 errx(1, "malloc failed");
339 continue;
340 }
341
342 TAILQ_FOREACH(esubd, &m.subdirs->entrylist, q) {
343 snprintf(buf, sizeof(buf), "%s%s%s{/%s,}",
344 epath->s,
345 (epath->s[epath->len-1] == '/') ? ""
346 : "/",
347 esubd->s, machine);
348 if (addentry(m.mymanpath, buf, 0) < 0)
349 errx(1, "malloc failed");
350 }
351 }
352
353 }
354
355 /*
356 * [4] finally, prepend the "-m" m.addpath to mymanpath if it
357 * was specified. subdirs and machine are always applied to
358 * m.addpath.
359 */
360 if (m.addpath) {
361
362 /* note: strtok is going to destroy m.addpath */
363 for (p = strtok(m.addpath, ":") ; p ; p = strtok(NULL, ":")) {
364 len = strlen(p);
365 if (len < 1)
366 continue;
367 TAILQ_FOREACH(esubd, &m.subdirs->entrylist, q) {
368 snprintf(buf, sizeof(buf), "%s%s%s{/%s,}",
369 p, (p[len-1] == '/') ? "" : "/",
370 esubd->s, machine);
371 /* add at front */
372 if (addentry(m.mymanpath, buf, 1) < 0)
373 errx(1, "malloc failed");
374 }
375 }
376
377 }
378
379 /*
380 * now m.mymanpath is complete!
381 */
382 #if MAN_DEBUG
383 printf("mymanpath:\n");
384 TAILQ_FOREACH(epath, &m.mymanpath->entrylist, q) {
385 printf("\t%s\n", epath->s);
386 }
387 #endif
388
389 /*
390 * start searching for matching files and format them if necessary.
391 * setup an interrupt handler so that we can ensure that temporary
392 * files go away.
393 */
394 (void)signal(SIGINT, onsig);
395 (void)signal(SIGHUP, onsig);
396 (void)signal(SIGPIPE, onsig);
397
398 memset(&pg, 0, sizeof(pg));
399 for (found = 0; *argv; ++argv)
400 if (manual(*argv, &m, &pg)) {
401 found = 1;
402 }
403
404 /* if nothing found, we're done. */
405 if (!found) {
406 (void)cleanup();
407 exit (1);
408 }
409
410 /*
411 * handle the simple display cases first (m.cat, m.how, m.where)
412 */
413 if (m.cat) {
414 for (ap = pg.gl_pathv; *ap != NULL; ++ap) {
415 if (**ap == '\0')
416 continue;
417 cat(*ap);
418 }
419 exit (cleanup());
420 }
421 if (m.how) {
422 for (ap = pg.gl_pathv; *ap != NULL; ++ap) {
423 if (**ap == '\0')
424 continue;
425 how(*ap);
426 }
427 exit(cleanup());
428 }
429 if (m.where) {
430 for (ap = pg.gl_pathv; *ap != NULL; ++ap) {
431 if (**ap == '\0')
432 continue;
433 (void)printf("%s\n", *ap);
434 }
435 exit(cleanup());
436 }
437
438 /*
439 * normal case - we display things in a single command, so
440 * build a list of things to display. first compute total
441 * length of buffer we will need so we can malloc it.
442 */
443 for (ap = pg.gl_pathv, len = m.pagerlen + 1; *ap != NULL; ++ap) {
444 if (**ap == '\0')
445 continue;
446 len += strlen(*ap) + 1;
447 }
448 if ((cmd = malloc(len)) == NULL) {
449 warn("malloc");
450 (void)cleanup();
451 exit(1);
452 }
453
454 /* now build the command string... */
455 p = cmd;
456 len = m.pagerlen;
457 memcpy(p, m.pager, len);
458 p += len;
459 *p++ = ' ';
460 for (ap = pg.gl_pathv; *ap != NULL; ++ap) {
461 if (**ap == '\0')
462 continue;
463 len = strlen(*ap);
464 memcpy(p, *ap, len);
465 p += len;
466 *p++ = ' ';
467 }
468 *--p = '\0';
469
470 /* Use system(3) in case someone's pager is "pager arg1 arg2". */
471 (void)system(cmd);
472
473 exit(cleanup());
474 }
475
476 static int
477 manual_find_buildkeyword(char *escpage, const char *fmt,
478 struct manstate *mp, glob_t *pg, size_t cnt)
479 {
480 ENTRY *suffix;
481 int found;
482 char *p, buf[MAXPATHLEN];
483
484 found = 0;
485 /* Try the _build key words next. */
486 TAILQ_FOREACH(suffix, &mp->buildlist->entrylist, q) {
487 for (p = suffix->s;
488 *p != '\0' && !isspace((unsigned char)*p);
489 ++p)
490 continue;
491 if (*p == '\0')
492 continue;
493
494 *p = '\0';
495 (void)snprintf(buf, sizeof(buf), fmt, escpage, suffix->s);
496 if (!fnmatch(buf, pg->gl_pathv[cnt], 0)) {
497 if (!mp->where)
498 build_page(p + 1, &pg->gl_pathv[cnt], mp);
499 *p = ' ';
500 found = 1;
501 break;
502 }
503 *p = ' ';
504 }
505
506 return found;
507 }
508
509 /*
510 * manual --
511 * Search the manuals for the pages.
512 */
513 static int
514 manual(char *page, struct manstate *mp, glob_t *pg)
515 {
516 ENTRY *suffix, *mdir;
517 int anyfound, error, found;
518 size_t cnt;
519 char *p, buf[MAXPATHLEN], *escpage, *eptr;
520 static const char escglob[] = "\\~?*{}[]";
521
522 anyfound = 0;
523
524 /*
525 * Fixup page which may contain glob(3) special characters, e.g.
526 * the famous "No man page for [" FAQ.
527 */
528 if ((escpage = malloc((2 * strlen(page)) + 1)) == NULL) {
529 warn("malloc");
530 (void)cleanup();
531 exit(1);
532 }
533
534 p = page;
535 eptr = escpage;
536
537 while (*p) {
538 if (strchr(escglob, *p) != NULL) {
539 *eptr++ = '\\';
540 *eptr++ = *p++;
541 } else
542 *eptr++ = *p++;
543 }
544
545 *eptr = '\0';
546
547 /*
548 * If 'page' is given with a full or relative path
549 * then interpret it as a file specification.
550 */
551 if ((page[0] == '/') || (page[0] == '.')) {
552 /* check if file actually exists */
553 (void)strlcpy(buf, escpage, sizeof(buf));
554 error = glob(buf, GLOB_APPEND | GLOB_BRACE | GLOB_NOSORT, NULL, pg);
555 if (error != 0) {
556 if (error == GLOB_NOMATCH) {
557 goto notfound;
558 } else {
559 errx(EXIT_FAILURE, "glob failed");
560 }
561 }
562
563 if (pg->gl_matchc == 0)
564 goto notfound;
565
566 /* clip suffix for the suffix check below */
567 p = strrchr(escpage, '.');
568 if (p && p[0] == '.' && isdigit((unsigned char)p[1]))
569 p[0] = '\0';
570
571 found = 0;
572 for (cnt = pg->gl_pathc - pg->gl_matchc;
573 cnt < pg->gl_pathc; ++cnt)
574 {
575 found = manual_find_buildkeyword(escpage, "%s%s",
576 mp, pg, cnt);
577 if (found) {
578 anyfound = 1;
579 if (!mp->all) {
580 /* Delete any other matches. */
581 while (++cnt< pg->gl_pathc)
582 pg->gl_pathv[cnt] = "";
583 break;
584 }
585 continue;
586 }
587
588 /* It's not a man page, forget about it. */
589 pg->gl_pathv[cnt] = "";
590 }
591
592 notfound:
593 if (!anyfound) {
594 if (addentry(mp->missinglist, page, 0) < 0) {
595 warn("malloc");
596 (void)cleanup();
597 exit(EXIT_FAILURE);
598 }
599 }
600 free(escpage);
601 return anyfound;
602 }
603
604 /* For each man directory in mymanpath ... */
605 TAILQ_FOREACH(mdir, &mp->mymanpath->entrylist, q) {
606
607 /*
608 * use glob(3) to look in the filesystem for matching files.
609 * match any suffix here, as we will check that later.
610 */
611 (void)snprintf(buf, sizeof(buf), "%s/%s.*", mdir->s, escpage);
612 if ((error = glob(buf,
613 GLOB_APPEND | GLOB_BRACE | GLOB_NOSORT, NULL, pg)) != 0) {
614 if (error == GLOB_NOMATCH)
615 continue;
616 else {
617 warn("globbing");
618 (void)cleanup();
619 exit(1);
620 }
621 }
622 if (pg->gl_matchc == 0)
623 continue;
624
625 /*
626 * start going through the matches glob(3) just found and
627 * use m.pathsearch (if present) to filter out pages we
628 * don't want. then verify the suffix is valid, and build
629 * the page if we have a _build suffix.
630 */
631 for (cnt = pg->gl_pathc - pg->gl_matchc;
632 cnt < pg->gl_pathc; ++cnt) {
633
634 /* filter on directory path name */
635 if (mp->pathsearch) {
636 p = strstr(pg->gl_pathv[cnt], mp->pathsearch);
637 if (!p || strchr(p, '/') == NULL) {
638 pg->gl_pathv[cnt] = ""; /* zap! */
639 continue;
640 }
641 }
642
643 /*
644 * Try the _suffix key words first.
645 *
646 * XXX
647 * Older versions of man.conf didn't have the suffix
648 * key words, it was assumed that everything was a .0.
649 * We just test for .0 first, it's fast and probably
650 * going to hit.
651 */
652 (void)snprintf(buf, sizeof(buf), "*/%s.0", escpage);
653 if (!fnmatch(buf, pg->gl_pathv[cnt], 0))
654 goto next;
655
656 found = 0;
657 TAILQ_FOREACH(suffix, &mp->suffixlist->entrylist, q) {
658 (void)snprintf(buf,
659 sizeof(buf), "*/%s%s", escpage,
660 suffix->s);
661 if (!fnmatch(buf, pg->gl_pathv[cnt], 0)) {
662 found = 1;
663 break;
664 }
665 }
666 if (found)
667 goto next;
668
669 /* Try the _build key words next. */
670 found = manual_find_buildkeyword(escpage, "*/%s%s",
671 mp, pg, cnt);
672 if (found) {
673 next: anyfound = 1;
674 if (!mp->all) {
675 /* Delete any other matches. */
676 while (++cnt< pg->gl_pathc)
677 pg->gl_pathv[cnt] = "";
678 break;
679 }
680 continue;
681 }
682
683 /* It's not a man page, forget about it. */
684 pg->gl_pathv[cnt] = "";
685 }
686
687 if (anyfound && !mp->all)
688 break;
689 }
690
691 /* If not found, enter onto the missing list. */
692 if (!anyfound) {
693 if (addentry(mp->missinglist, page, 0) < 0) {
694 warn("malloc");
695 (void)cleanup();
696 exit(1);
697 }
698 }
699
700 free(escpage);
701 return (anyfound);
702 }
703
704 /*
705 * build_page --
706 * Build a man page for display.
707 */
708 static void
709 build_page(char *fmt, char **pathp, struct manstate *mp)
710 {
711 static int warned;
712 int olddir, fd, n, tmpdirlen;
713 char *p, *b;
714 char buf[MAXPATHLEN], cmd[MAXPATHLEN], tpath[MAXPATHLEN];
715 const char *tmpdir;
716
717 /* Let the user know this may take awhile. */
718 if (!warned) {
719 warned = 1;
720 warnx("Formatting manual page...");
721 }
722
723 /*
724 * Historically man chdir'd to the root of the man tree.
725 * This was used in man pages that contained relative ".so"
726 * directives (including other man pages for command aliases etc.)
727 * It even went one step farther, by examining the first line
728 * of the man page and parsing the .so filename so it would
729 * make hard(?) links to the cat'ted man pages for space savings.
730 * (We don't do that here, but we could).
731 */
732
733 /* copy and find the end */
734 for (b = buf, p = *pathp; (*b++ = *p++) != '\0';)
735 continue;
736
737 /*
738 * skip the last two path components, page name and man[n] ...
739 * (e.g. buf will be "/usr/share/man" and p will be "man1/man.1")
740 * we also save a pointer to our current directory so that we
741 * can fchdir() back to it. this allows relative MANDIR paths
742 * to work with multiple man pages... e.g. consider:
743 * cd /usr/share && man -M ./man cat ls
744 * when no "cat1" subdir files are present.
745 */
746 olddir = -1;
747 for (--b, --p, n = 2; b != buf; b--, p--)
748 if (*b == '/')
749 if (--n == 0) {
750 *b = '\0';
751 olddir = open(".", O_RDONLY);
752 (void) chdir(buf);
753 p++;
754 break;
755 }
756
757
758 /* advance fmt pass the suffix spec to the printf format string */
759 for (; *fmt && isspace((unsigned char)*fmt); ++fmt)
760 continue;
761
762 /*
763 * Get a temporary file and build a version of the file
764 * to display. Replace the old file name with the new one.
765 */
766 if ((tmpdir = getenv("TMPDIR")) == NULL)
767 tmpdir = _PATH_TMP;
768 tmpdirlen = strlen(tmpdir);
769 (void)snprintf(tpath, sizeof (tpath), "%s%s%s", tmpdir,
770 (tmpdirlen && tmpdir[tmpdirlen-1] == '/') ? "" : "/", TMPFILE);
771 if ((fd = mkstemp(tpath)) == -1) {
772 warn("%s", tpath);
773 (void)cleanup();
774 exit(1);
775 }
776 (void)snprintf(buf, sizeof(buf), "%s > %s", fmt, tpath);
777 (void)snprintf(cmd, sizeof(cmd), buf, p);
778 (void)system(cmd);
779 (void)close(fd);
780 if ((*pathp = strdup(tpath)) == NULL) {
781 warn("malloc");
782 (void)cleanup();
783 exit(1);
784 }
785
786 /* Link the built file into the remove-when-done list. */
787 if (addentry(mp->intmp, *pathp, 0) < 0) {
788 warn("malloc");
789 (void)cleanup();
790 exit(1);
791 }
792
793 /* restore old directory so relative manpaths still work */
794 if (olddir != -1) {
795 fchdir(olddir);
796 close(olddir);
797 }
798 }
799
800 /*
801 * how --
802 * display how information
803 */
804 static void
805 how(char *fname)
806 {
807 FILE *fp;
808
809 int lcnt, print;
810 char *p, buf[256];
811
812 if (!(fp = fopen(fname, "r"))) {
813 warn("%s", fname);
814 (void)cleanup();
815 exit (1);
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(char *fname)
853 {
854 int fd, n;
855 char buf[2048];
856
857 if ((fd = open(fname, O_RDONLY, 0)) < 0) {
858 warn("%s", fname);
859 (void)cleanup();
860 exit(1);
861 }
862 while ((n = read(fd, buf, sizeof(buf))) > 0)
863 if (write(STDOUT_FILENO, buf, n) != n) {
864 warn("write");
865 (void)cleanup();
866 exit (1);
867 }
868 if (n == -1) {
869 warn("read");
870 (void)cleanup();
871 exit(1);
872 }
873 (void)close(fd);
874 }
875
876 /*
877 * check_pager --
878 * check the user supplied page information
879 */
880 static const char *
881 check_pager(const char *name)
882 {
883 const char *p;
884
885 /*
886 * if the user uses "more", we make it "more -s"; watch out for
887 * PAGER = "mypager /usr/ucb/more"
888 */
889 for (p = name; *p && !isspace((unsigned char)*p); ++p)
890 continue;
891 for (; p > name && *p != '/'; --p);
892 if (p != name)
893 ++p;
894
895 /* make sure it's "more", not "morex" */
896 if (!strncmp(p, "more", 4) && (!p[4] || isspace((unsigned char)p[4]))){
897 char *newname;
898 (void)asprintf(&newname, "%s %s", p, "-s");
899 name = newname;
900 }
901
902 return (name);
903 }
904
905 /*
906 * jump --
907 * strip out flag argument and jump
908 */
909 static void
910 jump(char **argv, char *flag, char *name)
911 {
912 char **arg;
913
914 argv[0] = name;
915 for (arg = argv + 1; *arg; ++arg)
916 if (!strcmp(*arg, flag))
917 break;
918 for (; *arg; ++arg)
919 arg[0] = arg[1];
920 execvp(name, argv);
921 (void)fprintf(stderr, "%s: Command not found.\n", name);
922 exit(1);
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 (1);
939 }
940
941 /*
942 * cleanup --
943 * Clean up temporary files, show any error messages.
944 */
945 static int
946 cleanup()
947 {
948 TAG *intmpp, *missp;
949 ENTRY *ep;
950 int rval;
951
952 rval = 0;
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 = 1;
963 }
964
965 TAILQ_FOREACH(ep, &intmpp->entrylist, q)
966 (void)unlink(ep->s);
967
968 return (rval);
969 }
970
971 /*
972 * usage --
973 * print usage message and die
974 */
975 static void
976 usage()
977 {
978 (void)fprintf(stderr, "usage: %s [-acw|-h] [-C cfg] [-M path] "
979 "[-m path] [-S srch] [[-s] sect] name ...\n", getprogname());
980 (void)fprintf(stderr,
981 "usage: %s -k [-C cfg] [-M path] [-m path] keyword ...\n",
982 getprogname());
983 exit(1);
984 }
985