1 /* $Id: main.c,v 1.292 2017/06/03 12:17:25 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"
63 OUTT_ASCII = 0, /* -Tascii */
64 OUTT_LOCALE, /* -Tlocale */
65 OUTT_UTF8, /* -Tutf8 */
66 OUTT_TREE, /* -Ttree */
68 OUTT_HTML, /* -Thtml */
69 OUTT_MARKDOWN, /* -Tmarkdown */
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 void 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", 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 ((c = getopt(argc, argv,
197 "aC:cfhI:iK:klM:m:O:S:s:T:VW:w")) != -1) {
198 if (c == 'i' && search.argmode == ARG_EXPR) {
204 outmode = OUTMODE_ALL;
213 search.argmode = ARG_WORD;
216 conf.output.synopsisonly = 1;
218 outmode = OUTMODE_ALL;
221 if (strncmp(optarg, "os=", 3)) {
222 warnx("-I %s: Bad argument", optarg);
223 return (int)MANDOCLEVEL_BADARG;
226 warnx("-I %s: Duplicate argument", optarg);
227 return (int)MANDOCLEVEL_BADARG;
229 defos = mandoc_strdup(optarg + 3);
232 if ( ! koptions(&options, optarg))
233 return (int)MANDOCLEVEL_BADARG;
236 search.argmode = ARG_EXPR;
239 search.argmode = ARG_FILE;
240 outmode = OUTMODE_ALL;
252 search.arch = optarg;
258 if ( ! toptions(&curp, optarg))
259 return (int)MANDOCLEVEL_BADARG;
262 if ( ! woptions(&curp, optarg))
263 return (int)MANDOCLEVEL_BADARG;
266 outmode = OUTMODE_FLN;
275 usage(search.argmode);
277 /* Postprocess options. */
279 if (outmode == OUTMODE_DEF) {
280 switch (search.argmode) {
282 outmode = OUTMODE_ALL;
286 outmode = OUTMODE_ONE;
289 outmode = OUTMODE_LST;
295 if (outmode == OUTMODE_LST)
296 search.outkey = oarg;
298 while (oarg != NULL) {
300 if (manconf_output(&conf.output,
301 strsep(&oarg, ","), 0) == 0)
303 warnx("-O %s: Bad argument", thisarg);
304 return (int)MANDOCLEVEL_BADARG;
309 if (outmode == OUTMODE_FLN ||
310 outmode == OUTMODE_LST ||
311 !isatty(STDOUT_FILENO))
316 if (pledge("stdio rpath", NULL) == -1)
317 err((int)MANDOCLEVEL_SYSERR, "pledge");
320 /* Parse arguments. */
330 * and for a man(1) section argument without -s.
333 if (search.argmode == ARG_NAME) {
334 if (*progname == 'h') {
339 } else if (argc > 1 &&
340 ((uc = (unsigned char *)argv[0]) != NULL) &&
341 ((isdigit(uc[0]) && (uc[1] == '\0' ||
342 (isalpha(uc[1]) && uc[2] == '\0'))) ||
343 (uc[0] == 'n' && uc[1] == '\0'))) {
344 search.sec = (char *)uc;
348 if (search.arch == NULL)
349 search.arch = getenv("MACHINE");
351 if (search.arch == NULL)
352 search.arch = MACHINE;
358 /* man(1), whatis(1), apropos(1) */
360 if (search.argmode != ARG_FILE) {
361 if (search.argmode == ARG_NAME &&
362 outmode == OUTMODE_ONE)
363 search.firstmatch = 1;
365 /* Access the mandoc database. */
367 manconf_parse(&conf, conf_file, defpaths, auxpaths);
368 if ( ! mansearch(&search, &conf.manpath,
369 argc, argv, &res, &sz))
370 usage(search.argmode);
373 if (search.argmode == ARG_NAME)
374 fs_search(&search, &conf.manpath,
375 argc, argv, &res, &sz);
377 warnx("nothing appropriate");
381 rc = MANDOCLEVEL_BADARG;
386 * For standard man(1) and -a output mode,
387 * prepare for copying filename pointers
388 * into the program parameter array.
391 if (outmode == OUTMODE_ONE) {
394 } else if (outmode == OUTMODE_ALL)
397 /* Iterate all matching manuals. */
400 for (i = 0; i < sz; i++) {
401 if (outmode == OUTMODE_FLN)
403 else if (outmode == OUTMODE_LST)
404 printf("%s - %s\n", res[i].names,
405 res[i].output == NULL ? "" :
407 else if (outmode == OUTMODE_ONE) {
408 /* Search for the best section. */
410 sec += strcspn(sec, "123456789");
413 prio = sec_prios[sec[0] - '1'];
416 if (prio >= best_prio)
424 * For man(1), -a and -i output mode, fall through
425 * to the main mandoc(1) code iterating files
426 * and running the parsers on each of them.
429 if (outmode == OUTMODE_FLN || outmode == OUTMODE_LST)
437 if (pledge("stdio rpath tmppath tty proc exec", NULL) == -1)
438 err((int)MANDOCLEVEL_SYSERR, "pledge");
440 if (pledge("stdio rpath", NULL) == -1)
441 err((int)MANDOCLEVEL_SYSERR, "pledge");
445 if (search.argmode == ARG_FILE)
446 moptions(&options, auxpaths);
449 curp.mp = mparse_alloc(options, curp.wlevel, mmsg, defos);
452 * Conditionally start up the lookaside buffer before parsing.
454 if (OUTT_MAN == curp.outtype)
455 mparse_keep(curp.mp);
459 tag_files = tag_init();
460 parse(&curp, STDIN_FILENO, "<stdin>");
464 fd = mparse_open(curp.mp, resp != NULL ? resp->file : *argv);
467 tag_files = tag_init();
472 parse(&curp, fd, *argv);
473 else if (resp->form == FORM_SRC) {
474 /* For .so only; ignore failure. */
475 chdir(conf.manpath.paths[resp->ipath]);
476 parse(&curp, fd, resp->file);
478 passthrough(resp->file, fd,
479 conf.output.synopsisonly);
481 if (argc > 1 && curp.outtype <= OUTT_UTF8) {
482 if (curp.outdata == NULL)
483 outdata_alloc(&curp);
484 terminal_sepline(curp.outdata);
486 } else if (rc < MANDOCLEVEL_ERROR)
487 rc = MANDOCLEVEL_ERROR;
489 if (MANDOCLEVEL_OK != rc && curp.wstop)
497 mparse_reset(curp.mp);
500 if (curp.outdata != NULL) {
501 switch (curp.outtype) {
503 html_free(curp.outdata);
508 ascii_free(curp.outdata);
512 pspdf_free(curp.outdata);
518 mparse_free(curp.mp);
522 if (search.argmode != ARG_FILE) {
524 mansearch_free(res, sz);
530 * When using a pager, finish writing both temporary files,
531 * fork it, wait for the user to close it, and clean up.
534 if (tag_files != NULL) {
537 man_pgid = getpgid(0);
538 tag_files->tcpgid = man_pgid == getpid() ?
539 getpgid(getppid()) : man_pgid;
544 /* Stop here until moved to the foreground. */
546 tc_pgid = tcgetpgrp(tag_files->ofd);
547 if (tc_pgid != man_pgid) {
548 if (tc_pgid == pager_pid) {
549 (void)tcsetpgrp(tag_files->ofd,
551 if (signum == SIGTTIN)
554 tag_files->tcpgid = tc_pgid;
559 /* Once in the foreground, activate the pager. */
562 (void)tcsetpgrp(tag_files->ofd, pager_pid);
563 kill(pager_pid, SIGCONT);
565 pager_pid = spawn_pager(tag_files);
567 /* Wait for the pager to stop or exit. */
569 while ((pid = waitpid(pager_pid, &status,
570 WUNTRACED)) == -1 && errno == EINTR)
575 rc = MANDOCLEVEL_SYSERR;
578 if (!WIFSTOPPED(status))
581 signum = WSTOPSIG(status);
590 usage(enum argmode argmode)
595 fputs("usage: mandoc [-ac] [-I os=name] "
596 "[-K encoding] [-mdoc | -man] [-O options]\n"
597 "\t [-T output] [-W level] [file ...]\n", stderr);
600 fputs("usage: man [-acfhklw] [-C file] [-M path] "
601 "[-m path] [-S subsection]\n"
602 "\t [[-s] section] name ...\n", stderr);
605 fputs("usage: whatis [-afk] [-C file] "
606 "[-M path] [-m path] [-O outkey] [-S arch]\n"
607 "\t [-s section] name ...\n", stderr);
610 fputs("usage: apropos [-afk] [-C file] "
611 "[-M path] [-m path] [-O outkey] [-S arch]\n"
612 "\t [-s section] expression ...\n", stderr);
615 exit((int)MANDOCLEVEL_BADARG);
619 fs_lookup(const struct manpaths *paths, size_t ipath,
620 const char *sec, const char *arch, const char *name,
621 struct manpage **res, size_t *ressz)
624 struct manpage *page;
630 mandoc_asprintf(&file, "%s/man%s/%s.%s",
631 paths->paths[ipath], sec, name, sec);
632 if (access(file, R_OK) != -1)
636 mandoc_asprintf(&file, "%s/cat%s/%s.0",
637 paths->paths[ipath], sec, name);
638 if (access(file, R_OK) != -1) {
645 mandoc_asprintf(&file, "%s/man%s/%s/%s.%s",
646 paths->paths[ipath], sec, arch, name, sec);
647 if (access(file, R_OK) != -1)
652 mandoc_asprintf(&file, "%s/man%s/%s.[01-9]*",
653 paths->paths[ipath], sec, name);
654 globres = glob(file, 0, NULL, &globinfo);
655 if (globres != 0 && globres != GLOB_NOMATCH)
656 warn("%s: glob", file);
659 file = mandoc_strdup(*globinfo.gl_pathv);
665 warnx("outdated mandoc.db lacks %s(%s) entry, run %s %s",
666 name, sec, BINM_MAKEWHATIS, paths->paths[ipath]);
667 *res = mandoc_reallocarray(*res, ++*ressz, sizeof(struct manpage));
668 page = *res + (*ressz - 1);
673 page->bits = NAME_FILE & NAME_MASK;
674 page->sec = (*sec >= '1' && *sec <= '9') ? *sec - '1' + 1 : 10;
680 fs_search(const struct mansearch *cfg, const struct manpaths *paths,
681 int argc, char **argv, struct manpage **res, size_t *ressz)
683 const char *const sections[] =
684 {"1", "8", "6", "2", "3", "5", "7", "4", "9", "3p"};
685 const size_t nsec = sizeof(sections)/sizeof(sections[0]);
687 size_t ipath, isec, lastsz;
689 assert(cfg->argmode == ARG_NAME);
694 for (ipath = 0; ipath < paths->sz; ipath++) {
695 if (cfg->sec != NULL) {
696 if (fs_lookup(paths, ipath, cfg->sec,
697 cfg->arch, *argv, res, ressz) &&
700 } else for (isec = 0; isec < nsec; isec++)
701 if (fs_lookup(paths, ipath, sections[isec],
702 cfg->arch, *argv, res, ressz) &&
706 if (*ressz == lastsz)
707 warnx("No entry for %s in the manual.", *argv);
715 parse(struct curparse *curp, int fd, const char *file)
717 enum mandoclevel rctmp;
718 struct roff_man *man;
720 /* Begin by parsing the file itself. */
725 rctmp = mparse_readfd(curp->mp, fd, file);
726 if (fd != STDIN_FILENO)
732 * With -Wstop and warnings or errors of at least the requested
733 * level, do not produce output.
736 if (rctmp != MANDOCLEVEL_OK && curp->wstop)
739 if (curp->outdata == NULL)
742 mparse_result(curp->mp, &man, NULL);
744 /* Execute the out device, if it exists. */
748 if (man->macroset == MACROSET_MDOC) {
749 if (curp->outtype != OUTT_TREE || !curp->outopts->noval)
751 switch (curp->outtype) {
753 html_mdoc(curp->outdata, man);
756 tree_mdoc(curp->outdata, man);
759 man_mdoc(curp->outdata, man);
766 terminal_mdoc(curp->outdata, man);
769 markdown_mdoc(curp->outdata, man);
775 if (man->macroset == MACROSET_MAN) {
776 if (curp->outtype != OUTT_TREE || !curp->outopts->noval)
778 switch (curp->outtype) {
780 html_man(curp->outdata, man);
783 tree_man(curp->outdata, man);
786 man_man(curp->outdata, man);
793 terminal_man(curp->outdata, man);
799 mparse_updaterc(curp->mp, &rc);
803 outdata_alloc(struct curparse *curp)
805 switch (curp->outtype) {
807 curp->outdata = html_alloc(curp->outopts);
810 curp->outdata = utf8_alloc(curp->outopts);
813 curp->outdata = locale_alloc(curp->outopts);
816 curp->outdata = ascii_alloc(curp->outopts);
819 curp->outdata = pdf_alloc(curp->outopts);
822 curp->outdata = ps_alloc(curp->outopts);
830 passthrough(const char *file, int fd, int synopsis_only)
832 const char synb[] = "S\bSY\bYN\bNO\bOP\bPS\bSI\bIS\bS";
833 const char synr[] = "SYNOPSIS";
839 ssize_t len, written;
845 if (fflush(stdout) == EOF) {
850 if ((stream = fdopen(fd, "r")) == NULL) {
857 while ((len = getline(&line, &linesz, stream)) != -1) {
861 if ( ! isspace((unsigned char)*cp))
863 while (isspace((unsigned char)*cp)) {
868 if (strcmp(cp, synb) == 0 ||
869 strcmp(cp, synr) == 0)
874 for (; len > 0; len -= written) {
875 if ((written = write(STDOUT_FILENO, cp, len)) != -1)
883 if (ferror(stream)) {
896 warn("%s: SYSERR: %s", file, syscall);
897 if (rc < MANDOCLEVEL_SYSERR)
898 rc = MANDOCLEVEL_SYSERR;
902 koptions(int *options, char *arg)
905 if ( ! strcmp(arg, "utf-8")) {
906 *options |= MPARSE_UTF8;
907 *options &= ~MPARSE_LATIN1;
908 } else if ( ! strcmp(arg, "iso-8859-1")) {
909 *options |= MPARSE_LATIN1;
910 *options &= ~MPARSE_UTF8;
911 } else if ( ! strcmp(arg, "us-ascii")) {
912 *options &= ~(MPARSE_UTF8 | MPARSE_LATIN1);
914 warnx("-K %s: Bad argument", arg);
921 moptions(int *options, char *arg)
926 if (strcmp(arg, "doc") == 0)
927 *options |= MPARSE_MDOC;
928 else if (strcmp(arg, "an") == 0)
929 *options |= MPARSE_MAN;
933 toptions(struct curparse *curp, char *arg)
936 if (0 == strcmp(arg, "ascii"))
937 curp->outtype = OUTT_ASCII;
938 else if (0 == strcmp(arg, "lint")) {
939 curp->outtype = OUTT_LINT;
940 curp->wlevel = MANDOCLEVEL_STYLE;
941 } else if (0 == strcmp(arg, "tree"))
942 curp->outtype = OUTT_TREE;
943 else if (0 == strcmp(arg, "man"))
944 curp->outtype = OUTT_MAN;
945 else if (0 == strcmp(arg, "html"))
946 curp->outtype = OUTT_HTML;
947 else if (0 == strcmp(arg, "markdown"))
948 curp->outtype = OUTT_MARKDOWN;
949 else if (0 == strcmp(arg, "utf8"))
950 curp->outtype = OUTT_UTF8;
951 else if (0 == strcmp(arg, "locale"))
952 curp->outtype = OUTT_LOCALE;
953 else if (0 == strcmp(arg, "ps"))
954 curp->outtype = OUTT_PS;
955 else if (0 == strcmp(arg, "pdf"))
956 curp->outtype = OUTT_PDF;
958 warnx("-T %s: Bad argument", arg);
966 woptions(struct curparse *curp, char *arg)
982 switch (getsubopt(&arg, (char * const *)toks, &v)) {
988 curp->wlevel = MANDOCLEVEL_STYLE;
991 curp->wlevel = MANDOCLEVEL_WARNING;
994 curp->wlevel = MANDOCLEVEL_ERROR;
997 curp->wlevel = MANDOCLEVEL_UNSUPP;
1000 curp->wlevel = MANDOCLEVEL_BADARG;
1003 warnx("-W %s: Bad argument", o);
1011 mmsg(enum mandocerr t, enum mandoclevel lvl,
1012 const char *file, int line, int col, const char *msg)
1014 const char *mparse_msg;
1016 fprintf(stderr, "%s: %s:", getprogname(),
1017 file == NULL ? "<stdin>" : file);
1020 fprintf(stderr, "%d:%d:", line, col + 1);
1022 fprintf(stderr, " %s", mparse_strlevel(lvl));
1024 if (NULL != (mparse_msg = mparse_strerror(t)))
1025 fprintf(stderr, ": %s", mparse_msg);
1028 fprintf(stderr, ": %s", msg);
1030 fputc('\n', stderr);
1034 spawn_pager(struct tag_files *tag_files)
1036 const struct timespec timeout = { 0, 100000000 }; /* 0.1s */
1037 #define MAX_PAGER_ARGS 16
1038 char *argv[MAX_PAGER_ARGS];
1045 pager = getenv("MANPAGER");
1046 if (pager == NULL || *pager == '\0')
1047 pager = getenv("PAGER");
1048 if (pager == NULL || *pager == '\0')
1050 cp = mandoc_strdup(pager);
1053 * Parse the pager command into words.
1054 * Intentionally do not do anything fancy here.
1058 while (argc + 4 < MAX_PAGER_ARGS) {
1060 cp = strchr(cp, ' ');
1070 /* For less(1), use the tag file. */
1072 if ((cmdlen = strlen(argv[0])) >= 4) {
1073 cp = argv[0] + cmdlen - 4;
1074 if (strcmp(cp, "less") == 0) {
1075 argv[argc++] = mandoc_strdup("-T");
1076 argv[argc++] = tag_files->tfn;
1079 argv[argc++] = tag_files->ofn;
1082 switch (pager_pid = fork()) {
1084 err((int)MANDOCLEVEL_SYSERR, "fork");
1088 (void)setpgid(pager_pid, 0);
1089 (void)tcsetpgrp(tag_files->ofd, pager_pid);
1091 if (pledge("stdio rpath tmppath tty proc", NULL) == -1)
1092 err((int)MANDOCLEVEL_SYSERR, "pledge");
1094 tag_files->pager_pid = pager_pid;
1098 /* The child process becomes the pager. */
1100 if (dup2(tag_files->ofd, STDOUT_FILENO) == -1)
1101 err((int)MANDOCLEVEL_SYSERR, "pager stdout");
1102 close(tag_files->ofd);
1103 close(tag_files->tfd);
1105 /* Do not start the pager before controlling the terminal. */
1107 while (tcgetpgrp(STDOUT_FILENO) != getpid())
1108 nanosleep(&timeout, NULL);
1110 execvp(argv[0], argv);
1111 err((int)MANDOCLEVEL_SYSERR, "exec %s", argv[0]);