]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/mdocml/main.c
MFV r319951: 8311 ZFS_READONLY is a little too strict
[FreeBSD/FreeBSD.git] / contrib / mdocml / main.c
1 /*      $Id: main.c,v 1.292 2017/06/03 12:17:25 schwarze Exp $ */
2 /*
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>
6  *
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.
10  *
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.
18  */
19 #include "config.h"
20
21 #include <sys/types.h>
22 #include <sys/param.h>  /* MACHINE */
23 #include <sys/wait.h>
24
25 #include <assert.h>
26 #include <ctype.h>
27 #if HAVE_ERR
28 #include <err.h>
29 #endif
30 #include <errno.h>
31 #include <fcntl.h>
32 #include <glob.h>
33 #if HAVE_SANDBOX_INIT
34 #include <sandbox.h>
35 #endif
36 #include <signal.h>
37 #include <stdio.h>
38 #include <stdint.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <time.h>
42 #include <unistd.h>
43
44 #include "mandoc_aux.h"
45 #include "mandoc.h"
46 #include "roff.h"
47 #include "mdoc.h"
48 #include "man.h"
49 #include "tag.h"
50 #include "main.h"
51 #include "manconf.h"
52 #include "mansearch.h"
53
54 enum    outmode {
55         OUTMODE_DEF = 0,
56         OUTMODE_FLN,
57         OUTMODE_LST,
58         OUTMODE_ALL,
59         OUTMODE_ONE
60 };
61
62 enum    outt {
63         OUTT_ASCII = 0, /* -Tascii */
64         OUTT_LOCALE,    /* -Tlocale */
65         OUTT_UTF8,      /* -Tutf8 */
66         OUTT_TREE,      /* -Ttree */
67         OUTT_MAN,       /* -Tman */
68         OUTT_HTML,      /* -Thtml */
69         OUTT_MARKDOWN,  /* -Tmarkdown */
70         OUTT_LINT,      /* -Tlint */
71         OUTT_PS,        /* -Tps */
72         OUTT_PDF        /* -Tpdf */
73 };
74
75 struct  curparse {
76         struct mparse    *mp;
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 */
82 };
83
84
85 int                       mandocdb(int, char *[]);
86
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 *);
105
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;
110
111
112 int
113 main(int argc, char *argv[])
114 {
115         struct manconf   conf;
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;
122         char            *defos, *oarg;
123         unsigned char   *uc;
124         size_t           i, sz;
125         int              prio, best_prio;
126         enum outmode     outmode;
127         int              fd;
128         int              show_usage;
129         int              options;
130         int              use_pager;
131         int              status, signum;
132         int              c;
133         pid_t            pager_pid, tc_pgid, man_pgid, pid;
134
135 #if HAVE_PROGNAME
136         progname = getprogname();
137 #else
138         if (argc < 1)
139                 progname = mandoc_strdup("mandoc");
140         else if ((progname = strrchr(argv[0], '/')) == NULL)
141                 progname = argv[0];
142         else
143                 ++progname;
144         setprogname(progname);
145 #endif
146
147         if (strncmp(progname, "mandocdb", 8) == 0 ||
148             strcmp(progname, BINM_MAKEWHATIS) == 0)
149                 return mandocdb(argc, argv);
150
151 #if HAVE_PLEDGE
152         if (pledge("stdio rpath tmppath tty proc exec", NULL) == -1)
153                 err((int)MANDOCLEVEL_SYSERR, "pledge");
154 #endif
155
156 #if HAVE_SANDBOX_INIT
157         if (sandbox_init(kSBXProfileNoInternet, SANDBOX_NAMED, NULL) == -1)
158                 errx((int)MANDOCLEVEL_SYSERR, "sandbox_init");
159 #endif
160
161         /* Search options. */
162
163         memset(&conf, 0, sizeof(conf));
164         conf_file = defpaths = NULL;
165         auxpaths = NULL;
166
167         memset(&search, 0, sizeof(struct mansearch));
168         search.outkey = "Nd";
169         oarg = NULL;
170
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;
179         else
180                 search.argmode = ARG_FILE;
181
182         /* Parser and formatter options. */
183
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;
189         defos = NULL;
190
191         use_pager = 1;
192         tag_files = NULL;
193         show_usage = 0;
194         outmode = OUTMODE_DEF;
195
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) {
199                         optind--;
200                         break;
201                 }
202                 switch (c) {
203                 case 'a':
204                         outmode = OUTMODE_ALL;
205                         break;
206                 case 'C':
207                         conf_file = optarg;
208                         break;
209                 case 'c':
210                         use_pager = 0;
211                         break;
212                 case 'f':
213                         search.argmode = ARG_WORD;
214                         break;
215                 case 'h':
216                         conf.output.synopsisonly = 1;
217                         use_pager = 0;
218                         outmode = OUTMODE_ALL;
219                         break;
220                 case 'I':
221                         if (strncmp(optarg, "os=", 3)) {
222                                 warnx("-I %s: Bad argument", optarg);
223                                 return (int)MANDOCLEVEL_BADARG;
224                         }
225                         if (defos) {
226                                 warnx("-I %s: Duplicate argument", optarg);
227                                 return (int)MANDOCLEVEL_BADARG;
228                         }
229                         defos = mandoc_strdup(optarg + 3);
230                         break;
231                 case 'K':
232                         if ( ! koptions(&options, optarg))
233                                 return (int)MANDOCLEVEL_BADARG;
234                         break;
235                 case 'k':
236                         search.argmode = ARG_EXPR;
237                         break;
238                 case 'l':
239                         search.argmode = ARG_FILE;
240                         outmode = OUTMODE_ALL;
241                         break;
242                 case 'M':
243                         defpaths = optarg;
244                         break;
245                 case 'm':
246                         auxpaths = optarg;
247                         break;
248                 case 'O':
249                         oarg = optarg;
250                         break;
251                 case 'S':
252                         search.arch = optarg;
253                         break;
254                 case 's':
255                         search.sec = optarg;
256                         break;
257                 case 'T':
258                         if ( ! toptions(&curp, optarg))
259                                 return (int)MANDOCLEVEL_BADARG;
260                         break;
261                 case 'W':
262                         if ( ! woptions(&curp, optarg))
263                                 return (int)MANDOCLEVEL_BADARG;
264                         break;
265                 case 'w':
266                         outmode = OUTMODE_FLN;
267                         break;
268                 default:
269                         show_usage = 1;
270                         break;
271                 }
272         }
273
274         if (show_usage)
275                 usage(search.argmode);
276
277         /* Postprocess options. */
278
279         if (outmode == OUTMODE_DEF) {
280                 switch (search.argmode) {
281                 case ARG_FILE:
282                         outmode = OUTMODE_ALL;
283                         use_pager = 0;
284                         break;
285                 case ARG_NAME:
286                         outmode = OUTMODE_ONE;
287                         break;
288                 default:
289                         outmode = OUTMODE_LST;
290                         break;
291                 }
292         }
293
294         if (oarg != NULL) {
295                 if (outmode == OUTMODE_LST)
296                         search.outkey = oarg;
297                 else {
298                         while (oarg != NULL) {
299                                 thisarg = oarg;
300                                 if (manconf_output(&conf.output,
301                                     strsep(&oarg, ","), 0) == 0)
302                                         continue;
303                                 warnx("-O %s: Bad argument", thisarg);
304                                 return (int)MANDOCLEVEL_BADARG;
305                         }
306                 }
307         }
308
309         if (outmode == OUTMODE_FLN ||
310             outmode == OUTMODE_LST ||
311             !isatty(STDOUT_FILENO))
312                 use_pager = 0;
313
314 #if HAVE_PLEDGE
315         if (!use_pager)
316                 if (pledge("stdio rpath", NULL) == -1)
317                         err((int)MANDOCLEVEL_SYSERR, "pledge");
318 #endif
319
320         /* Parse arguments. */
321
322         if (argc > 0) {
323                 argc -= optind;
324                 argv += optind;
325         }
326         resp = NULL;
327
328         /*
329          * Quirks for help(1)
330          * and for a man(1) section argument without -s.
331          */
332
333         if (search.argmode == ARG_NAME) {
334                 if (*progname == 'h') {
335                         if (argc == 0) {
336                                 argv = help_argv;
337                                 argc = 1;
338                         }
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;
345                         argv++;
346                         argc--;
347                 }
348                 if (search.arch == NULL)
349                         search.arch = getenv("MACHINE");
350 #ifdef MACHINE
351                 if (search.arch == NULL)
352                         search.arch = MACHINE;
353 #endif
354         }
355
356         rc = MANDOCLEVEL_OK;
357
358         /* man(1), whatis(1), apropos(1) */
359
360         if (search.argmode != ARG_FILE) {
361                 if (search.argmode == ARG_NAME &&
362                     outmode == OUTMODE_ONE)
363                         search.firstmatch = 1;
364
365                 /* Access the mandoc database. */
366
367                 manconf_parse(&conf, conf_file, defpaths, auxpaths);
368                 if ( ! mansearch(&search, &conf.manpath,
369                     argc, argv, &res, &sz))
370                         usage(search.argmode);
371
372                 if (sz == 0) {
373                         if (search.argmode == ARG_NAME)
374                                 fs_search(&search, &conf.manpath,
375                                     argc, argv, &res, &sz);
376                         else
377                                 warnx("nothing appropriate");
378                 }
379
380                 if (sz == 0) {
381                         rc = MANDOCLEVEL_BADARG;
382                         goto out;
383                 }
384
385                 /*
386                  * For standard man(1) and -a output mode,
387                  * prepare for copying filename pointers
388                  * into the program parameter array.
389                  */
390
391                 if (outmode == OUTMODE_ONE) {
392                         argc = 1;
393                         best_prio = 20;
394                 } else if (outmode == OUTMODE_ALL)
395                         argc = (int)sz;
396
397                 /* Iterate all matching manuals. */
398
399                 resp = res;
400                 for (i = 0; i < sz; i++) {
401                         if (outmode == OUTMODE_FLN)
402                                 puts(res[i].file);
403                         else if (outmode == OUTMODE_LST)
404                                 printf("%s - %s\n", res[i].names,
405                                     res[i].output == NULL ? "" :
406                                     res[i].output);
407                         else if (outmode == OUTMODE_ONE) {
408                                 /* Search for the best section. */
409                                 sec = res[i].file;
410                                 sec += strcspn(sec, "123456789");
411                                 if (sec[0] == '\0')
412                                         continue;
413                                 prio = sec_prios[sec[0] - '1'];
414                                 if (sec[1] != '/')
415                                         prio += 10;
416                                 if (prio >= best_prio)
417                                         continue;
418                                 best_prio = prio;
419                                 resp = res + i;
420                         }
421                 }
422
423                 /*
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.
427                  */
428
429                 if (outmode == OUTMODE_FLN || outmode == OUTMODE_LST)
430                         goto out;
431         }
432
433         /* mandoc(1) */
434
435 #if HAVE_PLEDGE
436         if (use_pager) {
437                 if (pledge("stdio rpath tmppath tty proc exec", NULL) == -1)
438                         err((int)MANDOCLEVEL_SYSERR, "pledge");
439         } else {
440                 if (pledge("stdio rpath", NULL) == -1)
441                         err((int)MANDOCLEVEL_SYSERR, "pledge");
442         }
443 #endif
444
445         if (search.argmode == ARG_FILE)
446                 moptions(&options, auxpaths);
447
448         mchars_alloc();
449         curp.mp = mparse_alloc(options, curp.wlevel, mmsg, defos);
450
451         /*
452          * Conditionally start up the lookaside buffer before parsing.
453          */
454         if (OUTT_MAN == curp.outtype)
455                 mparse_keep(curp.mp);
456
457         if (argc < 1) {
458                 if (use_pager)
459                         tag_files = tag_init();
460                 parse(&curp, STDIN_FILENO, "<stdin>");
461         }
462
463         while (argc > 0) {
464                 fd = mparse_open(curp.mp, resp != NULL ? resp->file : *argv);
465                 if (fd != -1) {
466                         if (use_pager) {
467                                 tag_files = tag_init();
468                                 use_pager = 0;
469                         }
470
471                         if (resp == NULL)
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);
477                         } else
478                                 passthrough(resp->file, fd,
479                                     conf.output.synopsisonly);
480
481                         if (argc > 1 && curp.outtype <= OUTT_UTF8) {
482                                 if (curp.outdata == NULL)
483                                         outdata_alloc(&curp);
484                                 terminal_sepline(curp.outdata);
485                         }
486                 } else if (rc < MANDOCLEVEL_ERROR)
487                         rc = MANDOCLEVEL_ERROR;
488
489                 if (MANDOCLEVEL_OK != rc && curp.wstop)
490                         break;
491
492                 if (resp != NULL)
493                         resp++;
494                 else
495                         argv++;
496                 if (--argc)
497                         mparse_reset(curp.mp);
498         }
499
500         if (curp.outdata != NULL) {
501                 switch (curp.outtype) {
502                 case OUTT_HTML:
503                         html_free(curp.outdata);
504                         break;
505                 case OUTT_UTF8:
506                 case OUTT_LOCALE:
507                 case OUTT_ASCII:
508                         ascii_free(curp.outdata);
509                         break;
510                 case OUTT_PDF:
511                 case OUTT_PS:
512                         pspdf_free(curp.outdata);
513                         break;
514                 default:
515                         break;
516                 }
517         }
518         mparse_free(curp.mp);
519         mchars_free();
520
521 out:
522         if (search.argmode != ARG_FILE) {
523                 manconf_free(&conf);
524                 mansearch_free(res, sz);
525         }
526
527         free(defos);
528
529         /*
530          * When using a pager, finish writing both temporary files,
531          * fork it, wait for the user to close it, and clean up.
532          */
533
534         if (tag_files != NULL) {
535                 fclose(stdout);
536                 tag_write();
537                 man_pgid = getpgid(0);
538                 tag_files->tcpgid = man_pgid == getpid() ?
539                     getpgid(getppid()) : man_pgid;
540                 pager_pid = 0;
541                 signum = SIGSTOP;
542                 for (;;) {
543
544                         /* Stop here until moved to the foreground. */
545
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,
550                                             man_pgid);
551                                         if (signum == SIGTTIN)
552                                                 continue;
553                                 } else
554                                         tag_files->tcpgid = tc_pgid;
555                                 kill(0, signum);
556                                 continue;
557                         }
558
559                         /* Once in the foreground, activate the pager. */
560
561                         if (pager_pid) {
562                                 (void)tcsetpgrp(tag_files->ofd, pager_pid);
563                                 kill(pager_pid, SIGCONT);
564                         } else
565                                 pager_pid = spawn_pager(tag_files);
566
567                         /* Wait for the pager to stop or exit. */
568
569                         while ((pid = waitpid(pager_pid, &status,
570                             WUNTRACED)) == -1 && errno == EINTR)
571                                 continue;
572
573                         if (pid == -1) {
574                                 warn("wait");
575                                 rc = MANDOCLEVEL_SYSERR;
576                                 break;
577                         }
578                         if (!WIFSTOPPED(status))
579                                 break;
580
581                         signum = WSTOPSIG(status);
582                 }
583                 tag_unlink();
584         }
585
586         return (int)rc;
587 }
588
589 static void
590 usage(enum argmode argmode)
591 {
592
593         switch (argmode) {
594         case ARG_FILE:
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);
598                 break;
599         case ARG_NAME:
600                 fputs("usage: man [-acfhklw] [-C file] [-M path] "
601                     "[-m path] [-S subsection]\n"
602                     "\t   [[-s] section] name ...\n", stderr);
603                 break;
604         case ARG_WORD:
605                 fputs("usage: whatis [-afk] [-C file] "
606                     "[-M path] [-m path] [-O outkey] [-S arch]\n"
607                     "\t      [-s section] name ...\n", stderr);
608                 break;
609         case ARG_EXPR:
610                 fputs("usage: apropos [-afk] [-C file] "
611                     "[-M path] [-m path] [-O outkey] [-S arch]\n"
612                     "\t       [-s section] expression ...\n", stderr);
613                 break;
614         }
615         exit((int)MANDOCLEVEL_BADARG);
616 }
617
618 static int
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)
622 {
623         glob_t           globinfo;
624         struct manpage  *page;
625         char            *file;
626         int              globres;
627         enum form        form;
628
629         form = FORM_SRC;
630         mandoc_asprintf(&file, "%s/man%s/%s.%s",
631             paths->paths[ipath], sec, name, sec);
632         if (access(file, R_OK) != -1)
633                 goto found;
634         free(file);
635
636         mandoc_asprintf(&file, "%s/cat%s/%s.0",
637             paths->paths[ipath], sec, name);
638         if (access(file, R_OK) != -1) {
639                 form = FORM_CAT;
640                 goto found;
641         }
642         free(file);
643
644         if (arch != NULL) {
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)
648                         goto found;
649                 free(file);
650         }
651
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);
657         free(file);
658         if (globres == 0)
659                 file = mandoc_strdup(*globinfo.gl_pathv);
660         globfree(&globinfo);
661         if (globres != 0)
662                 return 0;
663
664 found:
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);
669         page->file = file;
670         page->names = NULL;
671         page->output = NULL;
672         page->ipath = ipath;
673         page->bits = NAME_FILE & NAME_MASK;
674         page->sec = (*sec >= '1' && *sec <= '9') ? *sec - '1' + 1 : 10;
675         page->form = form;
676         return 1;
677 }
678
679 static void
680 fs_search(const struct mansearch *cfg, const struct manpaths *paths,
681         int argc, char **argv, struct manpage **res, size_t *ressz)
682 {
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]);
686
687         size_t           ipath, isec, lastsz;
688
689         assert(cfg->argmode == ARG_NAME);
690
691         *res = NULL;
692         *ressz = lastsz = 0;
693         while (argc) {
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) &&
698                                     cfg->firstmatch)
699                                         return;
700                         } else for (isec = 0; isec < nsec; isec++)
701                                 if (fs_lookup(paths, ipath, sections[isec],
702                                     cfg->arch, *argv, res, ressz) &&
703                                     cfg->firstmatch)
704                                         return;
705                 }
706                 if (*ressz == lastsz)
707                         warnx("No entry for %s in the manual.", *argv);
708                 lastsz = *ressz;
709                 argv++;
710                 argc--;
711         }
712 }
713
714 static void
715 parse(struct curparse *curp, int fd, const char *file)
716 {
717         enum mandoclevel  rctmp;
718         struct roff_man  *man;
719
720         /* Begin by parsing the file itself. */
721
722         assert(file);
723         assert(fd >= 0);
724
725         rctmp = mparse_readfd(curp->mp, fd, file);
726         if (fd != STDIN_FILENO)
727                 close(fd);
728         if (rc < rctmp)
729                 rc = rctmp;
730
731         /*
732          * With -Wstop and warnings or errors of at least the requested
733          * level, do not produce output.
734          */
735
736         if (rctmp != MANDOCLEVEL_OK && curp->wstop)
737                 return;
738
739         if (curp->outdata == NULL)
740                 outdata_alloc(curp);
741
742         mparse_result(curp->mp, &man, NULL);
743
744         /* Execute the out device, if it exists. */
745
746         if (man == NULL)
747                 return;
748         if (man->macroset == MACROSET_MDOC) {
749                 if (curp->outtype != OUTT_TREE || !curp->outopts->noval)
750                         mdoc_validate(man);
751                 switch (curp->outtype) {
752                 case OUTT_HTML:
753                         html_mdoc(curp->outdata, man);
754                         break;
755                 case OUTT_TREE:
756                         tree_mdoc(curp->outdata, man);
757                         break;
758                 case OUTT_MAN:
759                         man_mdoc(curp->outdata, man);
760                         break;
761                 case OUTT_PDF:
762                 case OUTT_ASCII:
763                 case OUTT_UTF8:
764                 case OUTT_LOCALE:
765                 case OUTT_PS:
766                         terminal_mdoc(curp->outdata, man);
767                         break;
768                 case OUTT_MARKDOWN:
769                         markdown_mdoc(curp->outdata, man);
770                         break;
771                 default:
772                         break;
773                 }
774         }
775         if (man->macroset == MACROSET_MAN) {
776                 if (curp->outtype != OUTT_TREE || !curp->outopts->noval)
777                         man_validate(man);
778                 switch (curp->outtype) {
779                 case OUTT_HTML:
780                         html_man(curp->outdata, man);
781                         break;
782                 case OUTT_TREE:
783                         tree_man(curp->outdata, man);
784                         break;
785                 case OUTT_MAN:
786                         man_man(curp->outdata, man);
787                         break;
788                 case OUTT_PDF:
789                 case OUTT_ASCII:
790                 case OUTT_UTF8:
791                 case OUTT_LOCALE:
792                 case OUTT_PS:
793                         terminal_man(curp->outdata, man);
794                         break;
795                 default:
796                         break;
797                 }
798         }
799         mparse_updaterc(curp->mp, &rc);
800 }
801
802 static void
803 outdata_alloc(struct curparse *curp)
804 {
805         switch (curp->outtype) {
806         case OUTT_HTML:
807                 curp->outdata = html_alloc(curp->outopts);
808                 break;
809         case OUTT_UTF8:
810                 curp->outdata = utf8_alloc(curp->outopts);
811                 break;
812         case OUTT_LOCALE:
813                 curp->outdata = locale_alloc(curp->outopts);
814                 break;
815         case OUTT_ASCII:
816                 curp->outdata = ascii_alloc(curp->outopts);
817                 break;
818         case OUTT_PDF:
819                 curp->outdata = pdf_alloc(curp->outopts);
820                 break;
821         case OUTT_PS:
822                 curp->outdata = ps_alloc(curp->outopts);
823                 break;
824         default:
825                 break;
826         }
827 }
828
829 static void
830 passthrough(const char *file, int fd, int synopsis_only)
831 {
832         const char       synb[] = "S\bSY\bYN\bNO\bOP\bPS\bSI\bIS\bS";
833         const char       synr[] = "SYNOPSIS";
834
835         FILE            *stream;
836         const char      *syscall;
837         char            *line, *cp;
838         size_t           linesz;
839         ssize_t          len, written;
840         int              print;
841
842         line = NULL;
843         linesz = 0;
844
845         if (fflush(stdout) == EOF) {
846                 syscall = "fflush";
847                 goto fail;
848         }
849
850         if ((stream = fdopen(fd, "r")) == NULL) {
851                 close(fd);
852                 syscall = "fdopen";
853                 goto fail;
854         }
855
856         print = 0;
857         while ((len = getline(&line, &linesz, stream)) != -1) {
858                 cp = line;
859                 if (synopsis_only) {
860                         if (print) {
861                                 if ( ! isspace((unsigned char)*cp))
862                                         goto done;
863                                 while (isspace((unsigned char)*cp)) {
864                                         cp++;
865                                         len--;
866                                 }
867                         } else {
868                                 if (strcmp(cp, synb) == 0 ||
869                                     strcmp(cp, synr) == 0)
870                                         print = 1;
871                                 continue;
872                         }
873                 }
874                 for (; len > 0; len -= written) {
875                         if ((written = write(STDOUT_FILENO, cp, len)) != -1)
876                                 continue;
877                         fclose(stream);
878                         syscall = "write";
879                         goto fail;
880                 }
881         }
882
883         if (ferror(stream)) {
884                 fclose(stream);
885                 syscall = "getline";
886                 goto fail;
887         }
888
889 done:
890         free(line);
891         fclose(stream);
892         return;
893
894 fail:
895         free(line);
896         warn("%s: SYSERR: %s", file, syscall);
897         if (rc < MANDOCLEVEL_SYSERR)
898                 rc = MANDOCLEVEL_SYSERR;
899 }
900
901 static int
902 koptions(int *options, char *arg)
903 {
904
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);
913         } else {
914                 warnx("-K %s: Bad argument", arg);
915                 return 0;
916         }
917         return 1;
918 }
919
920 static void
921 moptions(int *options, char *arg)
922 {
923
924         if (arg == NULL)
925                 return;
926         if (strcmp(arg, "doc") == 0)
927                 *options |= MPARSE_MDOC;
928         else if (strcmp(arg, "an") == 0)
929                 *options |= MPARSE_MAN;
930 }
931
932 static int
933 toptions(struct curparse *curp, char *arg)
934 {
935
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;
957         else {
958                 warnx("-T %s: Bad argument", arg);
959                 return 0;
960         }
961
962         return 1;
963 }
964
965 static int
966 woptions(struct curparse *curp, char *arg)
967 {
968         char            *v, *o;
969         const char      *toks[8];
970
971         toks[0] = "stop";
972         toks[1] = "all";
973         toks[2] = "style";
974         toks[3] = "warning";
975         toks[4] = "error";
976         toks[5] = "unsupp";
977         toks[6] = "fatal";
978         toks[7] = NULL;
979
980         while (*arg) {
981                 o = arg;
982                 switch (getsubopt(&arg, (char * const *)toks, &v)) {
983                 case 0:
984                         curp->wstop = 1;
985                         break;
986                 case 1:
987                 case 2:
988                         curp->wlevel = MANDOCLEVEL_STYLE;
989                         break;
990                 case 3:
991                         curp->wlevel = MANDOCLEVEL_WARNING;
992                         break;
993                 case 4:
994                         curp->wlevel = MANDOCLEVEL_ERROR;
995                         break;
996                 case 5:
997                         curp->wlevel = MANDOCLEVEL_UNSUPP;
998                         break;
999                 case 6:
1000                         curp->wlevel = MANDOCLEVEL_BADARG;
1001                         break;
1002                 default:
1003                         warnx("-W %s: Bad argument", o);
1004                         return 0;
1005                 }
1006         }
1007         return 1;
1008 }
1009
1010 static void
1011 mmsg(enum mandocerr t, enum mandoclevel lvl,
1012                 const char *file, int line, int col, const char *msg)
1013 {
1014         const char      *mparse_msg;
1015
1016         fprintf(stderr, "%s: %s:", getprogname(),
1017             file == NULL ? "<stdin>" : file);
1018
1019         if (line)
1020                 fprintf(stderr, "%d:%d:", line, col + 1);
1021
1022         fprintf(stderr, " %s", mparse_strlevel(lvl));
1023
1024         if (NULL != (mparse_msg = mparse_strerror(t)))
1025                 fprintf(stderr, ": %s", mparse_msg);
1026
1027         if (msg)
1028                 fprintf(stderr, ": %s", msg);
1029
1030         fputc('\n', stderr);
1031 }
1032
1033 static pid_t
1034 spawn_pager(struct tag_files *tag_files)
1035 {
1036         const struct timespec timeout = { 0, 100000000 };  /* 0.1s */
1037 #define MAX_PAGER_ARGS 16
1038         char            *argv[MAX_PAGER_ARGS];
1039         const char      *pager;
1040         char            *cp;
1041         size_t           cmdlen;
1042         int              argc;
1043         pid_t            pager_pid;
1044
1045         pager = getenv("MANPAGER");
1046         if (pager == NULL || *pager == '\0')
1047                 pager = getenv("PAGER");
1048         if (pager == NULL || *pager == '\0')
1049                 pager = "more -s";
1050         cp = mandoc_strdup(pager);
1051
1052         /*
1053          * Parse the pager command into words.
1054          * Intentionally do not do anything fancy here.
1055          */
1056
1057         argc = 0;
1058         while (argc + 4 < MAX_PAGER_ARGS) {
1059                 argv[argc++] = cp;
1060                 cp = strchr(cp, ' ');
1061                 if (cp == NULL)
1062                         break;
1063                 *cp++ = '\0';
1064                 while (*cp == ' ')
1065                         cp++;
1066                 if (*cp == '\0')
1067                         break;
1068         }
1069
1070         /* For less(1), use the tag file. */
1071
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;
1077                 }
1078         }
1079         argv[argc++] = tag_files->ofn;
1080         argv[argc] = NULL;
1081
1082         switch (pager_pid = fork()) {
1083         case -1:
1084                 err((int)MANDOCLEVEL_SYSERR, "fork");
1085         case 0:
1086                 break;
1087         default:
1088                 (void)setpgid(pager_pid, 0);
1089                 (void)tcsetpgrp(tag_files->ofd, pager_pid);
1090 #if HAVE_PLEDGE
1091                 if (pledge("stdio rpath tmppath tty proc", NULL) == -1)
1092                         err((int)MANDOCLEVEL_SYSERR, "pledge");
1093 #endif
1094                 tag_files->pager_pid = pager_pid;
1095                 return pager_pid;
1096         }
1097
1098         /* The child process becomes the pager. */
1099
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);
1104
1105         /* Do not start the pager before controlling the terminal. */
1106
1107         while (tcgetpgrp(STDOUT_FILENO) != getpid())
1108                 nanosleep(&timeout, NULL);
1109
1110         execvp(argv[0], argv);
1111         err((int)MANDOCLEVEL_SYSERR, "exec %s", argv[0]);
1112 }