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