1 /* $Id: main.c,v 1.262 2016/01/08 02:53:13 schwarze Exp $ */
3 * Copyright (c) 2008-2012 Kristaps Dzonsons <kristaps@bsd.lv>
4 * Copyright (c) 2010-2012, 2014-2016 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 */
40 #include "mandoc_aux.h"
48 #include "mansearch.h"
50 #if !defined(__GNUC__) || (__GNUC__ < 2)
52 # define __attribute__(x)
54 #endif /* !defined(__GNUC__) || (__GNUC__ < 2) */
66 OUTT_ASCII = 0, /* -Tascii */
67 OUTT_LOCALE, /* -Tlocale */
68 OUTT_UTF8, /* -Tutf8 */
69 OUTT_TREE, /* -Ttree */
71 OUTT_HTML, /* -Thtml */
72 OUTT_LINT, /* -Tlint */
79 enum mandoclevel wlevel; /* ignore messages below this */
80 int wstop; /* stop after a file with a warning */
81 enum outt outtype; /* which output to use */
82 void *outdata; /* data for output */
83 struct manoutput *outopts; /* output options */
86 static int fs_lookup(const struct manpaths *,
87 size_t ipath, const char *,
88 const char *, const char *,
89 struct manpage **, size_t *);
90 static void fs_search(const struct mansearch *,
91 const struct manpaths *, int, char**,
92 struct manpage **, size_t *);
93 static int koptions(int *, char *);
95 int mandocdb(int, char**);
97 static int moptions(int *, char *);
98 static void mmsg(enum mandocerr, enum mandoclevel,
99 const char *, int, int, const char *);
100 static void parse(struct curparse *, int, const char *);
101 static void passthrough(const char *, int, int);
102 static pid_t spawn_pager(struct tag_files *);
103 static int toptions(struct curparse *, char *);
104 static void usage(enum argmode) __attribute__((noreturn));
105 static int woptions(struct curparse *, char *);
107 static const int sec_prios[] = {1, 4, 5, 8, 6, 3, 7, 2, 9};
108 static char help_arg[] = "help";
109 static char *help_argv[] = {help_arg, NULL};
110 static enum mandoclevel rc;
114 main(int argc, char *argv[])
117 struct curparse curp;
118 struct mansearch search;
119 struct tag_files *tag_files;
120 const char *progname;
124 struct manpage *res, *resp;
125 char *conf_file, *defpaths;
129 enum outmode outmode;
136 pid_t pager_pid, tc_pgid, man_pgid, pid;
139 progname = getprogname();
142 progname = mandoc_strdup("mandoc");
143 else if ((progname = strrchr(argv[0], '/')) == NULL)
147 setprogname(progname);
151 if (strncmp(progname, "mandocdb", 8) == 0 ||
152 strcmp(progname, BINM_MAKEWHATIS) == 0)
153 return mandocdb(argc, argv);
157 if (pledge("stdio rpath tmppath tty proc exec flock", NULL) == -1)
158 err((int)MANDOCLEVEL_SYSERR, "pledge");
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";
170 if (strcmp(progname, BINM_MAN) == 0)
171 search.argmode = ARG_NAME;
172 else if (strcmp(progname, BINM_APROPOS) == 0)
173 search.argmode = ARG_EXPR;
174 else if (strcmp(progname, BINM_WHATIS) == 0)
175 search.argmode = ARG_WORD;
176 else if (strncmp(progname, "help", 4) == 0)
177 search.argmode = ARG_NAME;
179 search.argmode = ARG_FILE;
181 /* Parser and formatter options. */
183 memset(&curp, 0, sizeof(struct curparse));
184 curp.outtype = OUTT_LOCALE;
185 curp.wlevel = MANDOCLEVEL_BADARG;
186 curp.outopts = &conf.output;
187 options = MPARSE_SO | MPARSE_UTF8 | MPARSE_LATIN1;
193 outmode = OUTMODE_DEF;
195 while (-1 != (c = getopt(argc, argv,
196 "aC:cfhI:iK:klM:m:O:S:s:T:VW:w"))) {
199 outmode = OUTMODE_ALL;
208 search.argmode = ARG_WORD;
211 conf.output.synopsisonly = 1;
213 outmode = OUTMODE_ALL;
216 if (strncmp(optarg, "os=", 3)) {
217 warnx("-I %s: Bad argument", optarg);
218 return (int)MANDOCLEVEL_BADARG;
221 warnx("-I %s: Duplicate argument", optarg);
222 return (int)MANDOCLEVEL_BADARG;
224 defos = mandoc_strdup(optarg + 3);
227 outmode = OUTMODE_INT;
230 if ( ! koptions(&options, optarg))
231 return (int)MANDOCLEVEL_BADARG;
234 search.argmode = ARG_EXPR;
237 search.argmode = ARG_FILE;
238 outmode = OUTMODE_ALL;
247 search.outkey = optarg;
248 while (optarg != NULL)
249 manconf_output(&conf.output,
250 strsep(&optarg, ","));
253 search.arch = optarg;
259 if ( ! toptions(&curp, optarg))
260 return (int)MANDOCLEVEL_BADARG;
263 if ( ! woptions(&curp, optarg))
264 return (int)MANDOCLEVEL_BADARG;
267 outmode = OUTMODE_FLN;
276 usage(search.argmode);
278 /* Postprocess options. */
280 if (outmode == OUTMODE_DEF) {
281 switch (search.argmode) {
283 outmode = OUTMODE_ALL;
287 outmode = OUTMODE_ONE;
290 outmode = OUTMODE_LST;
295 if (outmode == OUTMODE_FLN ||
296 outmode == OUTMODE_LST ||
297 !isatty(STDOUT_FILENO))
302 if (pledge("stdio rpath flock", NULL) == -1)
303 err((int)MANDOCLEVEL_SYSERR, "pledge");
306 /* Parse arguments. */
316 * and for a man(1) section argument without -s.
319 if (search.argmode == ARG_NAME) {
320 if (*progname == 'h') {
325 } else if (argc > 1 &&
326 ((uc = (unsigned char *)argv[0]) != NULL) &&
327 ((isdigit(uc[0]) && (uc[1] == '\0' ||
328 (isalpha(uc[1]) && uc[2] == '\0'))) ||
329 (uc[0] == 'n' && uc[1] == '\0'))) {
330 search.sec = (char *)uc;
334 if (search.arch == NULL)
335 search.arch = getenv("MACHINE");
337 if (search.arch == NULL)
338 search.arch = MACHINE;
344 /* man(1), whatis(1), apropos(1) */
346 if (search.argmode != ARG_FILE) {
348 usage(search.argmode);
350 if (search.argmode == ARG_NAME &&
351 outmode == OUTMODE_ONE)
352 search.firstmatch = 1;
354 /* Access the mandoc database. */
356 manconf_parse(&conf, conf_file, defpaths, auxpaths);
359 if ( ! mansearch(&search, &conf.manpath,
360 argc, argv, &res, &sz))
361 usage(search.argmode);
363 if (search.argmode != ARG_NAME) {
364 fputs("mandoc: database support not compiled in\n",
366 return (int)MANDOCLEVEL_BADARG;
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. */
408 isec = strcspn(res[i].file, "123456789");
409 sec = res[i].file[isec];
412 prio = sec_prios[sec - '1'];
413 if (prio >= best_prio)
421 * For man(1), -a and -i output mode, fall through
422 * to the main mandoc(1) code iterating files
423 * and running the parsers on each of them.
426 if (outmode == OUTMODE_FLN || outmode == OUTMODE_LST)
434 if (pledge("stdio rpath tmppath tty proc exec", NULL) == -1)
435 err((int)MANDOCLEVEL_SYSERR, "pledge");
437 if (pledge("stdio rpath", NULL) == -1)
438 err((int)MANDOCLEVEL_SYSERR, "pledge");
442 if (search.argmode == ARG_FILE && ! moptions(&options, auxpaths))
443 return (int)MANDOCLEVEL_BADARG;
446 curp.mp = mparse_alloc(options, curp.wlevel, mmsg, defos);
449 * Conditionally start up the lookaside buffer before parsing.
451 if (OUTT_MAN == curp.outtype)
452 mparse_keep(curp.mp);
456 tag_files = tag_init();
457 parse(&curp, STDIN_FILENO, "<stdin>");
461 fd = mparse_open(curp.mp, resp != NULL ? resp->file : *argv);
464 tag_files = tag_init();
469 parse(&curp, fd, *argv);
470 else if (resp->form & FORM_SRC) {
471 /* For .so only; ignore failure. */
472 chdir(conf.manpath.paths[resp->ipath]);
473 parse(&curp, fd, resp->file);
475 passthrough(resp->file, fd,
476 conf.output.synopsisonly);
478 if (argc > 1 && curp.outtype <= OUTT_UTF8)
479 ascii_sepline(curp.outdata);
480 } else if (rc < MANDOCLEVEL_ERROR)
481 rc = MANDOCLEVEL_ERROR;
483 if (MANDOCLEVEL_OK != rc && curp.wstop)
491 mparse_reset(curp.mp);
494 if (curp.outdata != NULL) {
495 switch (curp.outtype) {
497 html_free(curp.outdata);
502 ascii_free(curp.outdata);
506 pspdf_free(curp.outdata);
512 mparse_free(curp.mp);
516 if (search.argmode != ARG_FILE) {
519 mansearch_free(res, sz);
527 * When using a pager, finish writing both temporary files,
528 * fork it, wait for the user to close it, and clean up.
531 if (tag_files != NULL) {
534 man_pgid = getpgid(0);
535 tag_files->tcpgid = man_pgid == getpid() ?
536 getpgid(getppid()) : man_pgid;
541 /* Stop here until moved to the foreground. */
543 tc_pgid = tcgetpgrp(STDIN_FILENO);
544 if (tc_pgid != man_pgid) {
545 if (tc_pgid == pager_pid) {
546 (void)tcsetpgrp(STDIN_FILENO,
548 if (signum == SIGTTIN)
551 tag_files->tcpgid = tc_pgid;
556 /* Once in the foreground, activate the pager. */
559 (void)tcsetpgrp(STDIN_FILENO, pager_pid);
560 kill(pager_pid, SIGCONT);
562 pager_pid = spawn_pager(tag_files);
564 /* Wait for the pager to stop or exit. */
566 while ((pid = waitpid(pager_pid, &status,
567 WUNTRACED)) == -1 && errno == EINTR)
572 rc = MANDOCLEVEL_SYSERR;
575 if (!WIFSTOPPED(status))
578 signum = WSTOPSIG(status);
587 usage(enum argmode argmode)
592 fputs("usage: mandoc [-acfhkl] [-I os=name] "
593 "[-K encoding] [-mformat] [-O option]\n"
594 "\t [-T output] [-W level] [file ...]\n", stderr);
597 fputs("usage: man [-acfhklw] [-C file] [-I os=name] "
598 "[-K encoding] [-M path] [-m path]\n"
599 "\t [-O option=value] [-S subsection] [-s section] "
600 "[-T output] [-W level]\n"
601 "\t [section] name ...\n", stderr);
604 fputs("usage: whatis [-acfhklw] [-C file] "
605 "[-M path] [-m path] [-O outkey] [-S arch]\n"
606 "\t [-s section] name ...\n", stderr);
609 fputs("usage: apropos [-acfhklw] [-C file] "
610 "[-M path] [-m path] [-O outkey] [-S arch]\n"
611 "\t [-s section] expression ...\n", stderr);
614 exit((int)MANDOCLEVEL_BADARG);
618 fs_lookup(const struct manpaths *paths, size_t ipath,
619 const char *sec, const char *arch, const char *name,
620 struct manpage **res, size_t *ressz)
623 struct manpage *page;
628 mandoc_asprintf(&file, "%s/man%s/%s.%s",
629 paths->paths[ipath], sec, name, sec);
630 if (access(file, R_OK) != -1)
634 mandoc_asprintf(&file, "%s/cat%s/%s.0",
635 paths->paths[ipath], sec, name);
636 if (access(file, R_OK) != -1) {
643 mandoc_asprintf(&file, "%s/man%s/%s/%s.%s",
644 paths->paths[ipath], sec, arch, name, sec);
645 if (access(file, R_OK) != -1)
650 mandoc_asprintf(&file, "%s/man%s/%s.[01-9]*",
651 paths->paths[ipath], sec, name);
652 globres = glob(file, 0, NULL, &globinfo);
653 if (globres != 0 && globres != GLOB_NOMATCH)
654 warn("%s: glob", file);
657 file = mandoc_strdup(*globinfo.gl_pathv);
664 warnx("outdated mandoc.db lacks %s(%s) entry, run makewhatis %s",
665 name, sec, 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", "3p", "5", "7", "4", "9"};
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 unset, allocate output dev now (if applicable). */
741 if (curp->outdata == NULL) {
742 switch (curp->outtype) {
744 curp->outdata = html_alloc(curp->outopts);
747 curp->outdata = utf8_alloc(curp->outopts);
750 curp->outdata = locale_alloc(curp->outopts);
753 curp->outdata = ascii_alloc(curp->outopts);
756 curp->outdata = pdf_alloc(curp->outopts);
759 curp->outdata = ps_alloc(curp->outopts);
766 mparse_result(curp->mp, &man, NULL);
768 /* Execute the out device, if it exists. */
772 if (man->macroset == MACROSET_MDOC) {
774 switch (curp->outtype) {
776 html_mdoc(curp->outdata, man);
779 tree_mdoc(curp->outdata, man);
782 man_mdoc(curp->outdata, man);
789 terminal_mdoc(curp->outdata, man);
795 if (man->macroset == MACROSET_MAN) {
797 switch (curp->outtype) {
799 html_man(curp->outdata, man);
802 tree_man(curp->outdata, man);
805 man_man(curp->outdata, man);
812 terminal_man(curp->outdata, man);
821 passthrough(const char *file, int fd, int synopsis_only)
823 const char synb[] = "S\bSY\bYN\bNO\bOP\bPS\bSI\bIS\bS";
824 const char synr[] = "SYNOPSIS";
835 if ((stream = fdopen(fd, "r")) == NULL) {
842 while (getline(&line, &linesz, stream) != -1) {
846 if ( ! isspace((unsigned char)*cp))
848 while (isspace((unsigned char)*cp))
851 if (strcmp(cp, synb) == 0 ||
852 strcmp(cp, synr) == 0)
857 if (fputs(cp, stdout)) {
864 if (ferror(stream)) {
877 warn("%s: SYSERR: %s", file, syscall);
878 if (rc < MANDOCLEVEL_SYSERR)
879 rc = MANDOCLEVEL_SYSERR;
883 koptions(int *options, char *arg)
886 if ( ! strcmp(arg, "utf-8")) {
887 *options |= MPARSE_UTF8;
888 *options &= ~MPARSE_LATIN1;
889 } else if ( ! strcmp(arg, "iso-8859-1")) {
890 *options |= MPARSE_LATIN1;
891 *options &= ~MPARSE_UTF8;
892 } else if ( ! strcmp(arg, "us-ascii")) {
893 *options &= ~(MPARSE_UTF8 | MPARSE_LATIN1);
895 warnx("-K %s: Bad argument", arg);
902 moptions(int *options, char *arg)
907 else if (0 == strcmp(arg, "doc"))
908 *options |= MPARSE_MDOC;
909 else if (0 == strcmp(arg, "andoc"))
911 else if (0 == strcmp(arg, "an"))
912 *options |= MPARSE_MAN;
914 warnx("-m %s: Bad argument", arg);
922 toptions(struct curparse *curp, char *arg)
925 if (0 == strcmp(arg, "ascii"))
926 curp->outtype = OUTT_ASCII;
927 else if (0 == strcmp(arg, "lint")) {
928 curp->outtype = OUTT_LINT;
929 curp->wlevel = MANDOCLEVEL_WARNING;
930 } else if (0 == strcmp(arg, "tree"))
931 curp->outtype = OUTT_TREE;
932 else if (0 == strcmp(arg, "man"))
933 curp->outtype = OUTT_MAN;
934 else if (0 == strcmp(arg, "html"))
935 curp->outtype = OUTT_HTML;
936 else if (0 == strcmp(arg, "utf8"))
937 curp->outtype = OUTT_UTF8;
938 else if (0 == strcmp(arg, "locale"))
939 curp->outtype = OUTT_LOCALE;
940 else if (0 == strcmp(arg, "xhtml"))
941 curp->outtype = OUTT_HTML;
942 else if (0 == strcmp(arg, "ps"))
943 curp->outtype = OUTT_PS;
944 else if (0 == strcmp(arg, "pdf"))
945 curp->outtype = OUTT_PDF;
947 warnx("-T %s: Bad argument", arg);
955 woptions(struct curparse *curp, char *arg)
970 switch (getsubopt(&arg, UNCONST(toks), &v)) {
976 curp->wlevel = MANDOCLEVEL_WARNING;
979 curp->wlevel = MANDOCLEVEL_ERROR;
982 curp->wlevel = MANDOCLEVEL_UNSUPP;
985 curp->wlevel = MANDOCLEVEL_BADARG;
988 warnx("-W %s: Bad argument", o);
997 mmsg(enum mandocerr t, enum mandoclevel lvl,
998 const char *file, int line, int col, const char *msg)
1000 const char *mparse_msg;
1002 fprintf(stderr, "%s: %s:", getprogname(), file);
1005 fprintf(stderr, "%d:%d:", line, col + 1);
1007 fprintf(stderr, " %s", mparse_strlevel(lvl));
1009 if (NULL != (mparse_msg = mparse_strerror(t)))
1010 fprintf(stderr, ": %s", mparse_msg);
1013 fprintf(stderr, ": %s", msg);
1015 fputc('\n', stderr);
1019 spawn_pager(struct tag_files *tag_files)
1021 #define MAX_PAGER_ARGS 16
1022 char *argv[MAX_PAGER_ARGS];
1029 pager = getenv("MANPAGER");
1030 if (pager == NULL || *pager == '\0')
1031 pager = getenv("PAGER");
1032 if (pager == NULL || *pager == '\0')
1034 cp = mandoc_strdup(pager);
1037 * Parse the pager command into words.
1038 * Intentionally do not do anything fancy here.
1042 while (argc + 4 < MAX_PAGER_ARGS) {
1044 cp = strchr(cp, ' ');
1054 /* For more(1) and less(1), use the tag file. */
1056 if ((cmdlen = strlen(argv[0])) >= 4) {
1057 cp = argv[0] + cmdlen - 4;
1058 if (strcmp(cp, "less") == 0 || strcmp(cp, "more") == 0) {
1059 argv[argc++] = mandoc_strdup("-T");
1060 argv[argc++] = tag_files->tfn;
1063 argv[argc++] = tag_files->ofn;
1066 switch (pager_pid = fork()) {
1068 err((int)MANDOCLEVEL_SYSERR, "fork");
1070 /* Set pgrp in both parent and child to avoid racing exec. */
1071 (void)setpgid(0, 0);
1074 (void)setpgid(pager_pid, 0);
1075 (void)tcsetpgrp(STDIN_FILENO, pager_pid);
1077 if (pledge("stdio rpath tmppath tty proc", NULL) == -1)
1078 err((int)MANDOCLEVEL_SYSERR, "pledge");
1080 tag_files->pager_pid = pager_pid;
1084 /* The child process becomes the pager. */
1086 if (dup2(tag_files->ofd, STDOUT_FILENO) == -1)
1087 err((int)MANDOCLEVEL_SYSERR, "pager stdout");
1088 close(tag_files->ofd);
1089 close(tag_files->tfd);
1090 execvp(argv[0], argv);
1091 err((int)MANDOCLEVEL_SYSERR, "exec %s", argv[0]);