1 /* $Id: main.c,v 1.283 2017/02/17 14:31:52 schwarze Exp $ */
3 * Copyright (c) 2008-2012 Kristaps Dzonsons <kristaps@bsd.lv>
4 * Copyright (c) 2010-2012, 2014-2017 Ingo Schwarze <schwarze@openbsd.org>
5 * Copyright (c) 2010 Joerg Sonnenberger <joerg@netbsd.org>
7 * Permission to use, copy, modify, and distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
11 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR
14 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
21 #include <sys/types.h>
22 #include <sys/param.h> /* MACHINE */
44 #include "mandoc_aux.h"
52 #include "mansearch.h"
64 OUTT_ASCII = 0, /* -Tascii */
65 OUTT_LOCALE, /* -Tlocale */
66 OUTT_UTF8, /* -Tutf8 */
67 OUTT_TREE, /* -Ttree */
69 OUTT_HTML, /* -Thtml */
70 OUTT_LINT, /* -Tlint */
77 enum mandoclevel wlevel; /* ignore messages below this */
78 int wstop; /* stop after a file with a warning */
79 enum outt outtype; /* which output to use */
80 void *outdata; /* data for output */
81 struct manoutput *outopts; /* output options */
85 int mandocdb(int, char *[]);
87 static int fs_lookup(const struct manpaths *,
88 size_t ipath, const char *,
89 const char *, const char *,
90 struct manpage **, size_t *);
91 static void fs_search(const struct mansearch *,
92 const struct manpaths *, int, char**,
93 struct manpage **, size_t *);
94 static int koptions(int *, char *);
95 static int moptions(int *, char *);
96 static void mmsg(enum mandocerr, enum mandoclevel,
97 const char *, int, int, const char *);
98 static void outdata_alloc(struct curparse *);
99 static void parse(struct curparse *, int, const char *);
100 static void passthrough(const char *, int, int);
101 static pid_t spawn_pager(struct tag_files *);
102 static int toptions(struct curparse *, char *);
103 static void usage(enum argmode) __attribute__((__noreturn__));
104 static int woptions(struct curparse *, char *);
106 static const int sec_prios[] = {1, 4, 5, 8, 6, 3, 7, 2, 9};
107 static char help_arg[] = "help";
108 static char *help_argv[] = {help_arg, NULL};
109 static enum mandoclevel rc;
113 main(int argc, char *argv[])
116 struct mansearch search;
117 struct curparse curp;
118 struct tag_files *tag_files;
119 struct manpage *res, *resp;
120 const char *progname, *sec, *thisarg;
121 char *conf_file, *defpaths, *auxpaths;
126 enum outmode outmode;
133 pid_t pager_pid, tc_pgid, man_pgid, pid;
136 progname = getprogname();
139 progname = mandoc_strdup("mandoc");
140 else if ((progname = strrchr(argv[0], '/')) == NULL)
144 setprogname(progname);
147 if (strncmp(progname, "mandocdb", 8) == 0 ||
148 strcmp(progname, BINM_MAKEWHATIS) == 0)
149 return mandocdb(argc, argv);
152 if (pledge("stdio rpath tmppath tty proc exec flock", NULL) == -1)
153 err((int)MANDOCLEVEL_SYSERR, "pledge");
156 #if HAVE_SANDBOX_INIT
157 if (sandbox_init(kSBXProfileNoInternet, SANDBOX_NAMED, NULL) == -1)
158 errx((int)MANDOCLEVEL_SYSERR, "sandbox_init");
161 /* Search options. */
163 memset(&conf, 0, sizeof(conf));
164 conf_file = defpaths = NULL;
167 memset(&search, 0, sizeof(struct mansearch));
168 search.outkey = "Nd";
171 if (strcmp(progname, BINM_MAN) == 0)
172 search.argmode = ARG_NAME;
173 else if (strcmp(progname, BINM_APROPOS) == 0)
174 search.argmode = ARG_EXPR;
175 else if (strcmp(progname, BINM_WHATIS) == 0)
176 search.argmode = ARG_WORD;
177 else if (strncmp(progname, "help", 4) == 0)
178 search.argmode = ARG_NAME;
180 search.argmode = ARG_FILE;
182 /* Parser and formatter options. */
184 memset(&curp, 0, sizeof(struct curparse));
185 curp.outtype = OUTT_LOCALE;
186 curp.wlevel = MANDOCLEVEL_BADARG;
187 curp.outopts = &conf.output;
188 options = MPARSE_SO | MPARSE_UTF8 | MPARSE_LATIN1;
194 outmode = OUTMODE_DEF;
196 while (-1 != (c = getopt(argc, argv,
197 "aC:cfhI:iK:klM:m:O:S:s:T:VW:w"))) {
200 outmode = OUTMODE_ALL;
209 search.argmode = ARG_WORD;
212 conf.output.synopsisonly = 1;
214 outmode = OUTMODE_ALL;
217 if (strncmp(optarg, "os=", 3)) {
218 warnx("-I %s: Bad argument", optarg);
219 return (int)MANDOCLEVEL_BADARG;
222 warnx("-I %s: Duplicate argument", optarg);
223 return (int)MANDOCLEVEL_BADARG;
225 defos = mandoc_strdup(optarg + 3);
228 outmode = OUTMODE_INT;
231 if ( ! koptions(&options, optarg))
232 return (int)MANDOCLEVEL_BADARG;
235 search.argmode = ARG_EXPR;
238 search.argmode = ARG_FILE;
239 outmode = OUTMODE_ALL;
251 search.arch = optarg;
257 if ( ! toptions(&curp, optarg))
258 return (int)MANDOCLEVEL_BADARG;
261 if ( ! woptions(&curp, optarg))
262 return (int)MANDOCLEVEL_BADARG;
265 outmode = OUTMODE_FLN;
274 usage(search.argmode);
276 /* Postprocess options. */
278 if (outmode == OUTMODE_DEF) {
279 switch (search.argmode) {
281 outmode = OUTMODE_ALL;
285 outmode = OUTMODE_ONE;
288 outmode = OUTMODE_LST;
294 if (outmode == OUTMODE_LST)
295 search.outkey = oarg;
297 while (oarg != NULL) {
299 if (manconf_output(&conf.output,
300 strsep(&oarg, ","), 0) == 0)
302 warnx("-O %s: Bad argument", thisarg);
303 return (int)MANDOCLEVEL_BADARG;
308 if (outmode == OUTMODE_FLN ||
309 outmode == OUTMODE_LST ||
310 !isatty(STDOUT_FILENO))
315 if (pledge("stdio rpath flock", NULL) == -1)
316 err((int)MANDOCLEVEL_SYSERR, "pledge");
319 /* Parse arguments. */
329 * and for a man(1) section argument without -s.
332 if (search.argmode == ARG_NAME) {
333 if (*progname == 'h') {
338 } else if (argc > 1 &&
339 ((uc = (unsigned char *)argv[0]) != NULL) &&
340 ((isdigit(uc[0]) && (uc[1] == '\0' ||
341 (isalpha(uc[1]) && uc[2] == '\0'))) ||
342 (uc[0] == 'n' && uc[1] == '\0'))) {
343 search.sec = (char *)uc;
347 if (search.arch == NULL)
348 search.arch = getenv("MACHINE");
350 if (search.arch == NULL)
351 search.arch = MACHINE;
357 /* man(1), whatis(1), apropos(1) */
359 if (search.argmode != ARG_FILE) {
360 if (search.argmode == ARG_NAME &&
361 outmode == OUTMODE_ONE)
362 search.firstmatch = 1;
364 /* Access the mandoc database. */
366 manconf_parse(&conf, conf_file, defpaths, auxpaths);
367 if ( ! mansearch(&search, &conf.manpath,
368 argc, argv, &res, &sz))
369 usage(search.argmode);
372 if (search.argmode == ARG_NAME)
373 fs_search(&search, &conf.manpath,
374 argc, argv, &res, &sz);
376 warnx("nothing appropriate");
380 rc = MANDOCLEVEL_BADARG;
385 * For standard man(1) and -a output mode,
386 * prepare for copying filename pointers
387 * into the program parameter array.
390 if (outmode == OUTMODE_ONE) {
393 } else if (outmode == OUTMODE_ALL)
396 /* Iterate all matching manuals. */
399 for (i = 0; i < sz; i++) {
400 if (outmode == OUTMODE_FLN)
402 else if (outmode == OUTMODE_LST)
403 printf("%s - %s\n", res[i].names,
404 res[i].output == NULL ? "" :
406 else if (outmode == OUTMODE_ONE) {
407 /* Search for the best section. */
409 sec += strcspn(sec, "123456789");
412 prio = sec_prios[sec[0] - '1'];
415 if (prio >= best_prio)
423 * For man(1), -a and -i output mode, fall through
424 * to the main mandoc(1) code iterating files
425 * and running the parsers on each of them.
428 if (outmode == OUTMODE_FLN || outmode == OUTMODE_LST)
436 if (pledge("stdio rpath tmppath tty proc exec", NULL) == -1)
437 err((int)MANDOCLEVEL_SYSERR, "pledge");
439 if (pledge("stdio rpath", NULL) == -1)
440 err((int)MANDOCLEVEL_SYSERR, "pledge");
444 if (search.argmode == ARG_FILE && ! moptions(&options, auxpaths))
445 return (int)MANDOCLEVEL_BADARG;
448 curp.mp = mparse_alloc(options, curp.wlevel, mmsg, defos);
451 * Conditionally start up the lookaside buffer before parsing.
453 if (OUTT_MAN == curp.outtype)
454 mparse_keep(curp.mp);
458 tag_files = tag_init();
459 parse(&curp, STDIN_FILENO, "<stdin>");
463 fd = mparse_open(curp.mp, resp != NULL ? resp->file : *argv);
466 tag_files = tag_init();
471 parse(&curp, fd, *argv);
472 else if (resp->form == FORM_SRC) {
473 /* For .so only; ignore failure. */
474 chdir(conf.manpath.paths[resp->ipath]);
475 parse(&curp, fd, resp->file);
477 passthrough(resp->file, fd,
478 conf.output.synopsisonly);
480 if (argc > 1 && curp.outtype <= OUTT_UTF8) {
481 if (curp.outdata == NULL)
482 outdata_alloc(&curp);
483 terminal_sepline(curp.outdata);
485 } else if (rc < MANDOCLEVEL_ERROR)
486 rc = MANDOCLEVEL_ERROR;
488 if (MANDOCLEVEL_OK != rc && curp.wstop)
496 mparse_reset(curp.mp);
499 if (curp.outdata != NULL) {
500 switch (curp.outtype) {
502 html_free(curp.outdata);
507 ascii_free(curp.outdata);
511 pspdf_free(curp.outdata);
517 mparse_free(curp.mp);
521 if (search.argmode != ARG_FILE) {
523 mansearch_free(res, sz);
529 * When using a pager, finish writing both temporary files,
530 * fork it, wait for the user to close it, and clean up.
533 if (tag_files != NULL) {
536 man_pgid = getpgid(0);
537 tag_files->tcpgid = man_pgid == getpid() ?
538 getpgid(getppid()) : man_pgid;
543 /* Stop here until moved to the foreground. */
545 tc_pgid = tcgetpgrp(tag_files->ofd);
546 if (tc_pgid != man_pgid) {
547 if (tc_pgid == pager_pid) {
548 (void)tcsetpgrp(tag_files->ofd,
550 if (signum == SIGTTIN)
553 tag_files->tcpgid = tc_pgid;
558 /* Once in the foreground, activate the pager. */
561 (void)tcsetpgrp(tag_files->ofd, pager_pid);
562 kill(pager_pid, SIGCONT);
564 pager_pid = spawn_pager(tag_files);
566 /* Wait for the pager to stop or exit. */
568 while ((pid = waitpid(pager_pid, &status,
569 WUNTRACED)) == -1 && errno == EINTR)
574 rc = MANDOCLEVEL_SYSERR;
577 if (!WIFSTOPPED(status))
580 signum = WSTOPSIG(status);
589 usage(enum argmode argmode)
594 fputs("usage: mandoc [-acfhkl] [-I os=name] "
595 "[-K encoding] [-mformat] [-O option]\n"
596 "\t [-T output] [-W level] [file ...]\n", stderr);
599 fputs("usage: man [-acfhklw] [-C file] [-I os=name] "
600 "[-K encoding] [-M path] [-m path]\n"
601 "\t [-O option=value] [-S subsection] [-s section] "
602 "[-T output] [-W level]\n"
603 "\t [section] name ...\n", stderr);
606 fputs("usage: whatis [-acfhklw] [-C file] "
607 "[-M path] [-m path] [-O outkey] [-S arch]\n"
608 "\t [-s section] name ...\n", stderr);
611 fputs("usage: apropos [-acfhklw] [-C file] "
612 "[-M path] [-m path] [-O outkey] [-S arch]\n"
613 "\t [-s section] expression ...\n", stderr);
616 exit((int)MANDOCLEVEL_BADARG);
620 fs_lookup(const struct manpaths *paths, size_t ipath,
621 const char *sec, const char *arch, const char *name,
622 struct manpage **res, size_t *ressz)
625 struct manpage *page;
631 mandoc_asprintf(&file, "%s/man%s/%s.%s",
632 paths->paths[ipath], sec, name, sec);
633 if (access(file, R_OK) != -1)
637 mandoc_asprintf(&file, "%s/cat%s/%s.0",
638 paths->paths[ipath], sec, name);
639 if (access(file, R_OK) != -1) {
646 mandoc_asprintf(&file, "%s/man%s/%s/%s.%s",
647 paths->paths[ipath], sec, arch, name, sec);
648 if (access(file, R_OK) != -1)
653 mandoc_asprintf(&file, "%s/man%s/%s.[01-9]*",
654 paths->paths[ipath], sec, name);
655 globres = glob(file, 0, NULL, &globinfo);
656 if (globres != 0 && globres != GLOB_NOMATCH)
657 warn("%s: glob", file);
660 file = mandoc_strdup(*globinfo.gl_pathv);
666 warnx("outdated mandoc.db lacks %s(%s) entry, run %s %s",
667 name, sec, BINM_MAKEWHATIS, paths->paths[ipath]);
668 *res = mandoc_reallocarray(*res, ++*ressz, sizeof(struct manpage));
669 page = *res + (*ressz - 1);
674 page->bits = NAME_FILE & NAME_MASK;
675 page->sec = (*sec >= '1' && *sec <= '9') ? *sec - '1' + 1 : 10;
681 fs_search(const struct mansearch *cfg, const struct manpaths *paths,
682 int argc, char **argv, struct manpage **res, size_t *ressz)
684 const char *const sections[] =
685 {"1", "8", "6", "2", "3", "5", "7", "4", "9", "3p"};
686 const size_t nsec = sizeof(sections)/sizeof(sections[0]);
688 size_t ipath, isec, lastsz;
690 assert(cfg->argmode == ARG_NAME);
695 for (ipath = 0; ipath < paths->sz; ipath++) {
696 if (cfg->sec != NULL) {
697 if (fs_lookup(paths, ipath, cfg->sec,
698 cfg->arch, *argv, res, ressz) &&
701 } else for (isec = 0; isec < nsec; isec++)
702 if (fs_lookup(paths, ipath, sections[isec],
703 cfg->arch, *argv, res, ressz) &&
707 if (*ressz == lastsz)
708 warnx("No entry for %s in the manual.", *argv);
716 parse(struct curparse *curp, int fd, const char *file)
718 enum mandoclevel rctmp;
719 struct roff_man *man;
721 /* Begin by parsing the file itself. */
726 rctmp = mparse_readfd(curp->mp, fd, file);
727 if (fd != STDIN_FILENO)
733 * With -Wstop and warnings or errors of at least the requested
734 * level, do not produce output.
737 if (rctmp != MANDOCLEVEL_OK && curp->wstop)
740 if (curp->outdata == NULL)
743 mparse_result(curp->mp, &man, NULL);
745 /* Execute the out device, if it exists. */
749 if (man->macroset == MACROSET_MDOC) {
750 if (curp->outtype != OUTT_TREE || !curp->outopts->noval)
752 switch (curp->outtype) {
754 html_mdoc(curp->outdata, man);
757 tree_mdoc(curp->outdata, man);
760 man_mdoc(curp->outdata, man);
767 terminal_mdoc(curp->outdata, man);
773 if (man->macroset == MACROSET_MAN) {
774 if (curp->outtype != OUTT_TREE || !curp->outopts->noval)
776 switch (curp->outtype) {
778 html_man(curp->outdata, man);
781 tree_man(curp->outdata, man);
784 man_man(curp->outdata, man);
791 terminal_man(curp->outdata, man);
797 mparse_updaterc(curp->mp, &rc);
801 outdata_alloc(struct curparse *curp)
803 switch (curp->outtype) {
805 curp->outdata = html_alloc(curp->outopts);
808 curp->outdata = utf8_alloc(curp->outopts);
811 curp->outdata = locale_alloc(curp->outopts);
814 curp->outdata = ascii_alloc(curp->outopts);
817 curp->outdata = pdf_alloc(curp->outopts);
820 curp->outdata = ps_alloc(curp->outopts);
828 passthrough(const char *file, int fd, int synopsis_only)
830 const char synb[] = "S\bSY\bYN\bNO\bOP\bPS\bSI\bIS\bS";
831 const char synr[] = "SYNOPSIS";
837 ssize_t len, written;
843 if (fflush(stdout) == EOF) {
848 if ((stream = fdopen(fd, "r")) == NULL) {
855 while ((len = getline(&line, &linesz, stream)) != -1) {
859 if ( ! isspace((unsigned char)*cp))
861 while (isspace((unsigned char)*cp)) {
866 if (strcmp(cp, synb) == 0 ||
867 strcmp(cp, synr) == 0)
872 for (; len > 0; len -= written) {
873 if ((written = write(STDOUT_FILENO, cp, len)) != -1)
881 if (ferror(stream)) {
894 warn("%s: SYSERR: %s", file, syscall);
895 if (rc < MANDOCLEVEL_SYSERR)
896 rc = MANDOCLEVEL_SYSERR;
900 koptions(int *options, char *arg)
903 if ( ! strcmp(arg, "utf-8")) {
904 *options |= MPARSE_UTF8;
905 *options &= ~MPARSE_LATIN1;
906 } else if ( ! strcmp(arg, "iso-8859-1")) {
907 *options |= MPARSE_LATIN1;
908 *options &= ~MPARSE_UTF8;
909 } else if ( ! strcmp(arg, "us-ascii")) {
910 *options &= ~(MPARSE_UTF8 | MPARSE_LATIN1);
912 warnx("-K %s: Bad argument", arg);
919 moptions(int *options, char *arg)
924 else if (0 == strcmp(arg, "doc"))
925 *options |= MPARSE_MDOC;
926 else if (0 == strcmp(arg, "andoc"))
928 else if (0 == strcmp(arg, "an"))
929 *options |= MPARSE_MAN;
931 warnx("-m %s: Bad argument", arg);
939 toptions(struct curparse *curp, char *arg)
942 if (0 == strcmp(arg, "ascii"))
943 curp->outtype = OUTT_ASCII;
944 else if (0 == strcmp(arg, "lint")) {
945 curp->outtype = OUTT_LINT;
946 curp->wlevel = MANDOCLEVEL_WARNING;
947 } else if (0 == strcmp(arg, "tree"))
948 curp->outtype = OUTT_TREE;
949 else if (0 == strcmp(arg, "man"))
950 curp->outtype = OUTT_MAN;
951 else if (0 == strcmp(arg, "html"))
952 curp->outtype = OUTT_HTML;
953 else if (0 == strcmp(arg, "utf8"))
954 curp->outtype = OUTT_UTF8;
955 else if (0 == strcmp(arg, "locale"))
956 curp->outtype = OUTT_LOCALE;
957 else if (0 == strcmp(arg, "xhtml"))
958 curp->outtype = OUTT_HTML;
959 else if (0 == strcmp(arg, "ps"))
960 curp->outtype = OUTT_PS;
961 else if (0 == strcmp(arg, "pdf"))
962 curp->outtype = OUTT_PDF;
964 warnx("-T %s: Bad argument", arg);
972 woptions(struct curparse *curp, char *arg)
987 switch (getsubopt(&arg, (char * const *)toks, &v)) {
993 curp->wlevel = MANDOCLEVEL_WARNING;
996 curp->wlevel = MANDOCLEVEL_ERROR;
999 curp->wlevel = MANDOCLEVEL_UNSUPP;
1002 curp->wlevel = MANDOCLEVEL_BADARG;
1005 warnx("-W %s: Bad argument", o);
1014 mmsg(enum mandocerr t, enum mandoclevel lvl,
1015 const char *file, int line, int col, const char *msg)
1017 const char *mparse_msg;
1019 fprintf(stderr, "%s: %s:", getprogname(),
1020 file == NULL ? "<stdin>" : file);
1023 fprintf(stderr, "%d:%d:", line, col + 1);
1025 fprintf(stderr, " %s", mparse_strlevel(lvl));
1027 if (NULL != (mparse_msg = mparse_strerror(t)))
1028 fprintf(stderr, ": %s", mparse_msg);
1031 fprintf(stderr, ": %s", msg);
1033 fputc('\n', stderr);
1037 spawn_pager(struct tag_files *tag_files)
1039 const struct timespec timeout = { 0, 100000000 }; /* 0.1s */
1040 #define MAX_PAGER_ARGS 16
1041 char *argv[MAX_PAGER_ARGS];
1048 pager = getenv("MANPAGER");
1049 if (pager == NULL || *pager == '\0')
1050 pager = getenv("PAGER");
1051 if (pager == NULL || *pager == '\0')
1053 cp = mandoc_strdup(pager);
1056 * Parse the pager command into words.
1057 * Intentionally do not do anything fancy here.
1061 while (argc + 4 < MAX_PAGER_ARGS) {
1063 cp = strchr(cp, ' ');
1073 /* For less(1), use the tag file. */
1075 if ((cmdlen = strlen(argv[0])) >= 4) {
1076 cp = argv[0] + cmdlen - 4;
1077 if (strcmp(cp, "less") == 0) {
1078 argv[argc++] = mandoc_strdup("-T");
1079 argv[argc++] = tag_files->tfn;
1082 argv[argc++] = tag_files->ofn;
1085 switch (pager_pid = fork()) {
1087 err((int)MANDOCLEVEL_SYSERR, "fork");
1091 (void)setpgid(pager_pid, 0);
1092 (void)tcsetpgrp(tag_files->ofd, pager_pid);
1094 if (pledge("stdio rpath tmppath tty proc", NULL) == -1)
1095 err((int)MANDOCLEVEL_SYSERR, "pledge");
1097 tag_files->pager_pid = pager_pid;
1101 /* The child process becomes the pager. */
1103 if (dup2(tag_files->ofd, STDOUT_FILENO) == -1)
1104 err((int)MANDOCLEVEL_SYSERR, "pager stdout");
1105 close(tag_files->ofd);
1106 close(tag_files->tfd);
1108 /* Do not start the pager before controlling the terminal. */
1110 while (tcgetpgrp(STDOUT_FILENO) != getpid())
1111 nanosleep(&timeout, NULL);
1113 execvp(argv[0], argv);
1114 err((int)MANDOCLEVEL_SYSERR, "exec %s", argv[0]);