#include <sys/cdefs.h>
#ifndef lint
__COPYRIGHT("@(#) Copyright (c) 1987, 1993, 1994, 1995\
The Regents of the University of California. All rights reserved.");
#endif
#ifndef lint
#if 0
static char sccsid[] = "@(#)man.c 8.17 (Berkeley) 1/31/95";
#else
__RCSID("$NetBSD: man.c,v 1.75 2025/09/08 19:44:40 jschauma Exp $");
#endif
#endif
#include <sys/param.h>
#include <sys/queue.h>
#include <sys/stat.h>
#include <sys/utsname.h>
#include <ctype.h>
#include <err.h>
#include <fcntl.h>
#include <fnmatch.h>
#include <glob.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <util.h>
#include <locale.h>
#include "manconf.h"
#include "pathnames.h"
#ifndef MAN_DEBUG
#define MAN_DEBUG 0
#endif
enum inserttype {
INS_TAIL,
INS_HEAD
};
struct manstate {
int all;
int cat;
char *conffile;
int how;
int local;
char *manpath;
char *addpath;
char *pathsearch;
char *sectionname;
int where;
int getpath;
TAG *defaultpath;
TAG *subdirs;
TAG *suffixlist;
TAG *buildlist;
TAG *intmp;
TAG *missinglist;
TAG *mymanpath;
TAG *section;
const char *pager;
size_t pagerlen;
const char *machine;
const char *machclass;
};
static void build_page(const char *, char **, struct manstate *);
static void cat(const char *);
static const char *check_pager(const char *);
static int cleanup(void);
static void how(const char *);
static void jump(char **, const char *, const char *) __dead;
static int manual(char *, struct manstate *, glob_t *);
static void onsig(int) __dead;
static void usage(void) __dead;
static void addpath(struct manstate *, const char *, size_t, const char *,
enum inserttype);
static const char *getclass(const char *);
static void printmanpath(struct manstate *);
int
main(int argc, char **argv)
{
static struct manstate m;
struct utsname utsname;
int ch, abs_section, found;
ENTRY *esubd, *epath;
char *p, **ap, *cmd;
size_t len;
glob_t pg;
setprogname(argv[0]);
setlocale(LC_ALL, "");
while ((ch = getopt(argc, argv, "-aC:cfhklM:m:P:ps:S:w")) != -1)
switch (ch) {
case 'a':
m.all = 1;
break;
case 'C':
m.conffile = optarg;
break;
case 'c':
case '-':
m.cat = 1;
break;
case 'h':
m.how = 1;
break;
case 'l':
m.local = 1;
break;
case 'm':
m.addpath = optarg;
break;
case 'M':
case 'P':
if ((m.manpath = strdup(optarg)) == NULL)
err(EXIT_FAILURE, "malloc failed");
break;
case 'p':
m.getpath = 1;
break;
case 'f':
jump(argv, "-f", "whatis");
case 'k':
jump(argv, "-k", "apropos");
case 's':
if (m.sectionname != NULL)
usage();
m.sectionname = optarg;
break;
case 'S':
m.pathsearch = optarg;
break;
case 'w':
m.all = m.where = 1;
break;
case '?':
default:
usage();
}
argc -= optind;
argv += optind;
if (!m.getpath && !argc)
usage();
config(m.conffile);
if ((m.machine = getenv("MACHINE")) == NULL) {
if (uname(&utsname) == -1)
err(EXIT_FAILURE, "uname");
m.machine = utsname.machine;
}
m.machclass = getclass(m.machine);
if (!m.cat && !m.how && !m.where) {
if (!isatty(STDOUT_FILENO)) {
m.cat = 1;
} else {
if ((m.pager = getenv("PAGER")) != NULL &&
m.pager[0] != '\0')
m.pager = check_pager(m.pager);
else
m.pager = _PATH_PAGER;
m.pagerlen = strlen(m.pager);
}
}
if (m.sectionname) {
m.section = gettag(m.sectionname, 0);
if (m.section == NULL)
errx(EXIT_FAILURE, "unknown section: %s", m.sectionname);
} else if (argc > 1) {
m.section = gettag(*argv, 0);
if (m.section) {
argv++;
argc--;
}
}
if (m.manpath == NULL)
m.manpath = getenv("MANPATH");
m.defaultpath = gettag("_default", 1);
m.subdirs = gettag("_subdir", 1);
m.suffixlist = gettag("_suffix", 1);
m.buildlist = gettag("_build", 1);
m.mymanpath = gettag("_new_path", 1);
m.missinglist = gettag("_missing", 1);
m.intmp = gettag("_intmp", 1);
if (!m.defaultpath || !m.subdirs || !m.suffixlist || !m.buildlist ||
!m.mymanpath || !m.missinglist || !m.intmp)
errx(EXIT_FAILURE, "malloc failed");
abs_section = (m.section != NULL &&
!TAILQ_EMPTY(&m.section->entrylist) &&
*(TAILQ_FIRST(&m.section->entrylist)->s) == '/');
if (abs_section) {
m.manpath = NULL;
m.defaultpath = m.section;
m.section = NULL;
}
if (m.section)
m.subdirs = m.section;
if (m.manpath) {
for (p = strtok(m.manpath, ":") ; p ; p = strtok(NULL, ":")) {
len = strlen(p);
if (len < 1)
continue;
TAILQ_FOREACH(esubd, &m.subdirs->entrylist, q)
addpath(&m, p, len, esubd->s, INS_TAIL);
}
} else {
TAILQ_FOREACH(epath, &m.defaultpath->entrylist, q) {
if (abs_section && epath->s[epath->len - 1] != '/') {
addpath(&m, "", 1, epath->s, INS_TAIL);
continue;
}
TAILQ_FOREACH(esubd, &m.subdirs->entrylist, q)
addpath(&m, epath->s, epath->len, esubd->s, INS_TAIL);
}
}
if (m.addpath) {
for (p = strtok(m.addpath, ":") ; p ; p = strtok(NULL, ":")) {
len = strlen(p);
if (len < 1)
continue;
TAILQ_FOREACH(esubd, &m.subdirs->entrylist, q)
addpath(&m, p, len, esubd->s, INS_HEAD);
}
}
if (m.getpath) {
printmanpath(&m);
exit(cleanup());
}
#if MAN_DEBUG
printf("mymanpath:\n");
TAILQ_FOREACH(epath, &m.mymanpath->entrylist, q) {
printf("\t%s\n", epath->s);
}
#endif
(void)signal(SIGINT, onsig);
(void)signal(SIGHUP, onsig);
(void)signal(SIGPIPE, onsig);
memset(&pg, 0, sizeof(pg));
for (found = 0; *argv; ++argv)
if (manual(*argv, &m, &pg)) {
found = 1;
}
if (!found) {
(void)cleanup();
exit(EXIT_FAILURE);
}
if (m.cat) {
for (ap = pg.gl_pathv; *ap != NULL; ++ap) {
if (**ap == '\0')
continue;
cat(*ap);
}
exit(cleanup());
}
if (m.how) {
for (ap = pg.gl_pathv; *ap != NULL; ++ap) {
if (**ap == '\0')
continue;
how(*ap);
}
exit(cleanup());
}
if (m.where) {
for (ap = pg.gl_pathv; *ap != NULL; ++ap) {
if (**ap == '\0')
continue;
(void)printf("%s\n", *ap);
}
exit(cleanup());
}
for (ap = pg.gl_pathv, len = m.pagerlen + 1; *ap != NULL; ++ap) {
if (**ap == '\0')
continue;
len += strlen(*ap) + 1;
}
if ((cmd = malloc(len)) == NULL) {
warn("malloc");
(void)cleanup();
exit(EXIT_FAILURE);
}
p = cmd;
len = m.pagerlen;
memcpy(p, m.pager, len);
p += len;
*p++ = ' ';
for (ap = pg.gl_pathv; *ap != NULL; ++ap) {
if (**ap == '\0')
continue;
len = strlen(*ap);
memcpy(p, *ap, len);
p += len;
*p++ = ' ';
}
*--p = '\0';
(void)system(cmd);
exit(cleanup());
}
static int
manual_find_literalfile(struct manstate *mp, char **pv)
{
ENTRY *suffix;
int found;
char buf[MAXPATHLEN];
const char *p;
int suflen;
found = 0;
TAILQ_FOREACH(suffix, &mp->buildlist->entrylist, q) {
for (p = suffix->s, suflen = 0;
*p != '\0' && !isspace((unsigned char)*p);
++p)
++suflen;
if (*p == '\0')
continue;
(void)snprintf(buf, sizeof(buf), "*%.*s", suflen, suffix->s);
if (!fnmatch(buf, *pv, 0)) {
if (!mp->where)
build_page(p + 1, pv, mp);
found = 1;
break;
}
}
return found;
}
static int
manual_find_buildkeyword(const char *prefix, const char *escpage,
struct manstate *mp, char **pv)
{
ENTRY *suffix;
int found;
char buf[MAXPATHLEN];
const char *p;
int suflen;
found = 0;
TAILQ_FOREACH(suffix, &mp->buildlist->entrylist, q) {
for (p = suffix->s, suflen = 0;
*p != '\0' && !isspace((unsigned char)*p);
++p)
++suflen;
if (*p == '\0')
continue;
(void)snprintf(buf, sizeof(buf), "%s%s%.*s",
prefix, escpage, suflen, suffix->s);
if (!fnmatch(buf, *pv, 0)) {
if (!mp->where)
build_page(p + 1, pv, mp);
found = 1;
break;
}
}
return found;
}
static int
manual(char *page, struct manstate *mp, glob_t *pg)
{
ENTRY *suffix, *mdir;
int anyfound, error, found;
size_t cnt;
char *p, buf[MAXPATHLEN], *escpage, *eptr;
static const char escglob[] = "\\~?*{}[]";
anyfound = 0;
if ((escpage = malloc((2 * strlen(page)) + 1)) == NULL) {
warn("malloc");
(void)cleanup();
exit(EXIT_FAILURE);
}
p = page;
eptr = escpage;
while (*p) {
if (strchr(escglob, *p) != NULL) {
*eptr++ = '\\';
*eptr++ = *p++;
} else
*eptr++ = *p++;
}
*eptr = '\0';
if (mp->local
|| (page[0] == '/')
|| (page[0] == '.' && page[1] == '/')
|| (page[0] == '.' && page[1] == '.' && page[2] == '/')
) {
(void)strlcpy(buf, escpage, sizeof(buf));
error = glob(buf, GLOB_APPEND | GLOB_BRACE | GLOB_NOSORT, NULL, pg);
if (error != 0) {
if (error == GLOB_NOMATCH) {
goto notfound;
} else {
errx(EXIT_FAILURE, "glob failed");
}
}
if (pg->gl_matchc == 0)
goto notfound;
cnt = pg->gl_pathc - pg->gl_matchc;
if (manual_find_literalfile(mp, &pg->gl_pathv[cnt])) {
anyfound = 1;
} else {
*pg->gl_pathv[cnt] = '\0';
}
notfound:
if (!anyfound) {
if (addentry(mp->missinglist, page, 0) < 0) {
warn("malloc");
(void)cleanup();
exit(EXIT_FAILURE);
}
}
free(escpage);
return anyfound;
}
TAILQ_FOREACH(mdir, &mp->mymanpath->entrylist, q) {
(void)snprintf(buf, sizeof(buf), "%s/%s.*", mdir->s, escpage);
if ((error = glob(buf,
GLOB_APPEND | GLOB_BRACE | GLOB_NOSORT, NULL, pg)) != 0) {
if (error == GLOB_NOMATCH)
continue;
else {
warn("globbing");
(void)cleanup();
exit(EXIT_FAILURE);
}
}
if (pg->gl_matchc == 0)
continue;
for (cnt = pg->gl_pathc - pg->gl_matchc;
cnt < pg->gl_pathc; ++cnt) {
if (mp->pathsearch) {
p = strstr(pg->gl_pathv[cnt], mp->pathsearch);
if (!p || strchr(p, '/') == NULL) {
*pg->gl_pathv[cnt] = '\0';
continue;
}
}
(void)snprintf(buf, sizeof(buf), "*/%s.0", escpage);
if (!fnmatch(buf, pg->gl_pathv[cnt], 0))
goto next;
found = 0;
TAILQ_FOREACH(suffix, &mp->suffixlist->entrylist, q) {
(void)snprintf(buf,
sizeof(buf), "*/%s%s", escpage,
suffix->s);
if (!fnmatch(buf, pg->gl_pathv[cnt], 0)) {
found = 1;
break;
}
}
if (found)
goto next;
found = manual_find_buildkeyword("*/", escpage,
mp, &pg->gl_pathv[cnt]);
if (found) {
next: anyfound = 1;
if (!mp->all) {
while (++cnt< pg->gl_pathc)
*pg->gl_pathv[cnt] = '\0';
break;
}
continue;
}
*pg->gl_pathv[cnt] = '\0';
}
if (anyfound && !mp->all)
break;
}
if (!anyfound) {
if (addentry(mp->missinglist, page, 0) < 0) {
warn("malloc");
(void)cleanup();
exit(EXIT_FAILURE);
}
}
free(escpage);
return anyfound;
}
__always_inline __format_arg(2)
static inline const char *
fmtcheck_ok(const char *userfmt, const char *template)
{
return userfmt;
}
static void
build_page(const char *fmt, char **pathp, struct manstate *mp)
{
static int warned;
int olddir, fd, n;
size_t tmpdirlen;
char *p, *b;
char buf[MAXPATHLEN], cmd[MAXPATHLEN], tpath[MAXPATHLEN];
const char *tmpdir;
if (!warned) {
warned = 1;
warnx("Formatting manual page...");
}
for (b = buf, p = *pathp; (*b++ = *p++) != '\0';)
continue;
olddir = -1;
for (--b, --p, n = 2; b != buf; b--, p--)
if (*b == '/')
if (--n == 0) {
*b = '\0';
olddir = open(".", O_RDONLY);
(void) chdir(buf);
p++;
break;
}
for (; *fmt && isspace((unsigned char)*fmt); ++fmt)
continue;
if ((tmpdir = getenv("TMPDIR")) == NULL)
tmpdir = _PATH_TMP;
tmpdirlen = strlen(tmpdir);
(void)snprintf(tpath, sizeof (tpath), "%s%s%s", tmpdir,
(tmpdirlen > 0 && tmpdir[tmpdirlen-1] == '/') ? "" : "/", TMPFILE);
if ((fd = mkstemp(tpath)) == -1) {
warn("%s", tpath);
(void)cleanup();
exit(EXIT_FAILURE);
}
(void)snprintf(buf, sizeof(buf), "%s > %s", fmt, tpath);
(void)snprintf(cmd, sizeof(cmd), fmtcheck_ok(buf, "%s"), p);
(void)system(cmd);
(void)close(fd);
if ((*pathp = strdup(tpath)) == NULL) {
warn("malloc");
(void)cleanup();
exit(EXIT_FAILURE);
}
if (addentry(mp->intmp, *pathp, 0) < 0) {
warn("malloc");
(void)cleanup();
exit(EXIT_FAILURE);
}
if (olddir != -1) {
fchdir(olddir);
close(olddir);
}
}
static void
how(const char *fname)
{
FILE *fp;
int lcnt, print;
char buf[256];
const char *p;
if (!(fp = fopen(fname, "r"))) {
warn("%s", fname);
(void)cleanup();
exit(EXIT_FAILURE);
}
#define S1 "SYNOPSIS"
#define S2 "S\bSY\bYN\bNO\bOP\bPS\bSI\bIS\bS"
#define D1 "DESCRIPTION"
#define D2 "D\bDE\bES\bSC\bCR\bRI\bIP\bPT\bTI\bIO\bON\bN"
for (lcnt = print = 0; fgets(buf, sizeof(buf), fp);) {
if (!strncmp(buf, S1, sizeof(S1) - 1) ||
!strncmp(buf, S2, sizeof(S2) - 1)) {
print = 1;
continue;
} else if (!strncmp(buf, D1, sizeof(D1) - 1) ||
!strncmp(buf, D2, sizeof(D2) - 1)) {
if (fp)
(void)fclose(fp);
return;
}
if (!print)
continue;
if (*buf == '\n')
++lcnt;
else {
for(; lcnt; --lcnt)
(void)putchar('\n');
for (p = buf; isspace((unsigned char)*p); ++p)
continue;
(void)fputs(p, stdout);
}
}
(void)fclose(fp);
}
static void
cat(const char *fname)
{
int fd;
ssize_t n;
char buf[2048];
if ((fd = open(fname, O_RDONLY, 0)) < 0) {
warn("%s", fname);
(void)cleanup();
exit(EXIT_FAILURE);
}
while ((n = read(fd, buf, sizeof(buf))) > 0)
if (write(STDOUT_FILENO, buf, (size_t)n) != n) {
warn("write");
(void)cleanup();
exit(EXIT_FAILURE);
}
if (n == -1) {
warn("read");
(void)cleanup();
exit(EXIT_FAILURE);
}
(void)close(fd);
}
static const char *
check_pager(const char *name)
{
const char *p;
for (p = name; *p && !isspace((unsigned char)*p); ++p)
continue;
for (; p > name && *p != '/'; --p);
if (p != name)
++p;
if (!strncmp(p, "more", 4) && (!p[4] || isspace((unsigned char)p[4]))) {
char *newname;
(void)asprintf(&newname, "%s %s", p, "-s");
name = newname;
}
return name;
}
static void
jump(char **argv, const char *flag, const char *name)
{
char **arg;
argv[0] = __UNCONST(name);
for (arg = argv + 1; *arg; ++arg)
if (!strcmp(*arg, flag))
break;
for (; *arg; ++arg)
arg[0] = arg[1];
execvp(name, argv);
err(EXIT_FAILURE, "Cannot execute `%s'", name);
}
static void
onsig(int signo)
{
(void)cleanup();
(void)raise_default_signal(signo);
exit(EXIT_FAILURE);
}
static int
cleanup(void)
{
TAG *intmpp, *missp;
ENTRY *ep;
int rval;
rval = EXIT_SUCCESS;
missp = gettag("_missing", 0);
intmpp = gettag("_intmp", 0);
TAILQ_FOREACH(ep, &missp->entrylist, q) {
warnx("no entry for %s in the manual.", ep->s);
rval = EXIT_FAILURE;
}
TAILQ_FOREACH(ep, &intmpp->entrylist, q)
(void)unlink(ep->s);
return rval;
}
static const char *
getclass(const char *machine)
{
char buf[BUFSIZ];
TAG *t;
snprintf(buf, sizeof(buf), "_%s", machine);
t = gettag(buf, 0);
return t != NULL && !TAILQ_EMPTY(&t->entrylist) ?
TAILQ_FIRST(&t->entrylist)->s : NULL;
}
static void
addpath(struct manstate *m, const char *dir, size_t len, const char *sub,
enum inserttype ishead)
{
char buf[2 * MAXPATHLEN + 1];
(void)snprintf(buf, sizeof(buf), "%s%s%s{/%s,%s%s%s}",
dir, (dir[len - 1] == '/') ? "" : "/", sub, m->machine,
m->machclass ? "/" : "", m->machclass ? m->machclass : "",
m->machclass ? "," : "");
if (addentry(m->mymanpath, buf, (int)ishead) < 0)
errx(EXIT_FAILURE, "malloc failed");
}
static void
usage(void)
{
(void)fprintf(stderr, "Usage: %s [-acw|-h] [-C cfg] [-M path] "
"[-m path] [-S srch] [[-s] sect] name ...\n", getprogname());
(void)fprintf(stderr, "Usage: %s [-C file] -f command ...\n", getprogname());
(void)fprintf(stderr,
"Usage: %s [-C file] -k keyword ...\n",
getprogname());
(void)fprintf(stderr, "Usage: %s -p\n", getprogname());
exit(EXIT_FAILURE);
}
static void
printmanpath(struct manstate *m)
{
ENTRY *epath;
char **ap;
glob_t pg;
struct stat sb;
TAG *path = m->mymanpath;
if (TAILQ_EMPTY(&path->entrylist))
errx(EXIT_FAILURE, "Empty manpath");
TAILQ_FOREACH(epath, &path->entrylist, q) {
if (glob(epath->s, GLOB_BRACE | GLOB_NOSORT, NULL, &pg) != 0)
err(EXIT_FAILURE, "glob failed");
if (pg.gl_matchc == 0) {
globfree(&pg);
continue;
}
for (ap = pg.gl_pathv; *ap != NULL; ++ap) {
if (strstr(*ap, "/cat") != NULL)
continue;
if (stat(*ap, &sb) == 0 && S_ISDIR(sb.st_mode))
printf("%s\n", *ap);
}
globfree(&pg);
}
}