]> git.cameronkatri.com Git - mandoc.git/blob - main.c
While we do not recommend the idiom ".Fl Fl long" for long options
[mandoc.git] / main.c
1 /* $Id: main.c,v 1.348 2020/04/02 22:12:55 schwarze Exp $ */
2 /*
3 * Copyright (c) 2010-2012, 2014-2020 Ingo Schwarze <schwarze@openbsd.org>
4 * Copyright (c) 2008-2012 Kristaps Dzonsons <kristaps@bsd.lv>
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 * Main program for mandoc(1), man(1), apropos(1), whatis(1), and help(1).
20 */
21 #include "config.h"
22
23 #include <sys/types.h>
24 #include <sys/ioctl.h>
25 #include <sys/param.h> /* MACHINE */
26 #include <sys/stat.h>
27 #include <sys/wait.h>
28
29 #include <assert.h>
30 #include <ctype.h>
31 #if HAVE_ERR
32 #include <err.h>
33 #endif
34 #include <errno.h>
35 #include <fcntl.h>
36 #include <glob.h>
37 #include <limits.h>
38 #if HAVE_SANDBOX_INIT
39 #include <sandbox.h>
40 #endif
41 #include <signal.h>
42 #include <stdio.h>
43 #include <stdint.h>
44 #include <stdlib.h>
45 #include <string.h>
46 #include <termios.h>
47 #include <time.h>
48 #include <unistd.h>
49
50 #include "mandoc_aux.h"
51 #include "mandoc.h"
52 #include "mandoc_xr.h"
53 #include "roff.h"
54 #include "mdoc.h"
55 #include "man.h"
56 #include "mandoc_parse.h"
57 #include "tag.h"
58 #include "term_tag.h"
59 #include "main.h"
60 #include "manconf.h"
61 #include "mansearch.h"
62
63 enum outmode {
64 OUTMODE_DEF = 0,
65 OUTMODE_FLN,
66 OUTMODE_LST,
67 OUTMODE_ALL,
68 OUTMODE_ONE
69 };
70
71 enum outt {
72 OUTT_ASCII = 0, /* -Tascii */
73 OUTT_LOCALE, /* -Tlocale */
74 OUTT_UTF8, /* -Tutf8 */
75 OUTT_TREE, /* -Ttree */
76 OUTT_MAN, /* -Tman */
77 OUTT_HTML, /* -Thtml */
78 OUTT_MARKDOWN, /* -Tmarkdown */
79 OUTT_LINT, /* -Tlint */
80 OUTT_PS, /* -Tps */
81 OUTT_PDF /* -Tpdf */
82 };
83
84 struct outstate {
85 struct tag_files *tag_files; /* Tagging state variables. */
86 void *outdata; /* data for output */
87 int use_pager;
88 int wstop; /* stop after a file with a warning */
89 int had_output; /* Some output was generated. */
90 enum outt outtype; /* which output to use */
91 };
92
93
94 int mandocdb(int, char *[]);
95
96 static void check_xr(void);
97 static int fs_lookup(const struct manpaths *,
98 size_t ipath, const char *,
99 const char *, const char *,
100 struct manpage **, size_t *);
101 static int fs_search(const struct mansearch *,
102 const struct manpaths *, const char *,
103 struct manpage **, size_t *);
104 static void glob_esc(char **, const char *, const char *);
105 static void outdata_alloc(struct outstate *, struct manoutput *);
106 static void parse(struct mparse *, int, const char *,
107 struct outstate *, struct manoutput *);
108 static void passthrough(int, int);
109 static void process_onefile(struct mparse *, struct manpage *,
110 int, struct outstate *, struct manconf *);
111 static void run_pager(struct tag_files *, char *);
112 static pid_t spawn_pager(struct tag_files *, char *);
113 static void usage(enum argmode) __attribute__((__noreturn__));
114 static int woptions(char *, enum mandoc_os *, int *);
115
116 static const int sec_prios[] = {1, 4, 5, 8, 6, 3, 7, 2, 9};
117 static char help_arg[] = "help";
118 static char *help_argv[] = {help_arg, NULL};
119
120
121 int
122 main(int argc, char *argv[])
123 {
124 struct manconf conf; /* Manpaths and output options. */
125 struct outstate outst; /* Output state. */
126 struct winsize ws; /* Result of ioctl(TIOCGWINSZ). */
127 struct mansearch search; /* Search options. */
128 struct manpage *res; /* Complete list of search results. */
129 struct manpage *resn; /* Search results for one name. */
130 struct mparse *mp; /* Opaque parser object. */
131 const char *conf_file; /* -C: alternate config file. */
132 const char *os_s; /* -I: Operating system for display. */
133 const char *progname, *sec;
134 char *defpaths; /* -M: override manpaths. */
135 char *auxpaths; /* -m: additional manpaths. */
136 char *oarg; /* -O: output option string. */
137 char *tagarg; /* -O tag: default value. */
138 unsigned char *uc;
139 size_t ressz; /* Number of elements in res[]. */
140 size_t resnsz; /* Number of elements in resn[]. */
141 size_t i, ib, ssz;
142 int options; /* Parser options. */
143 int show_usage; /* Invalid argument: give up. */
144 int prio, best_prio;
145 int startdir;
146 int c;
147 enum mandoc_os os_e; /* Check base system conventions. */
148 enum outmode outmode; /* According to command line. */
149
150 #if HAVE_PROGNAME
151 progname = getprogname();
152 #else
153 if (argc < 1)
154 progname = mandoc_strdup("mandoc");
155 else if ((progname = strrchr(argv[0], '/')) == NULL)
156 progname = argv[0];
157 else
158 ++progname;
159 setprogname(progname);
160 #endif
161
162 mandoc_msg_setoutfile(stderr);
163 if (strncmp(progname, "mandocdb", 8) == 0 ||
164 strcmp(progname, BINM_MAKEWHATIS) == 0)
165 return mandocdb(argc, argv);
166
167 #if HAVE_PLEDGE
168 if (pledge("stdio rpath tmppath tty proc exec", NULL) == -1) {
169 mandoc_msg(MANDOCERR_PLEDGE, 0, 0, "%s", strerror(errno));
170 return mandoc_msg_getrc();
171 }
172 #endif
173 #if HAVE_SANDBOX_INIT
174 if (sandbox_init(kSBXProfileNoInternet, SANDBOX_NAMED, NULL) == -1)
175 errx((int)MANDOCLEVEL_SYSERR, "sandbox_init");
176 #endif
177
178 /* Search options. */
179
180 memset(&conf, 0, sizeof(conf));
181 conf_file = NULL;
182 defpaths = auxpaths = NULL;
183
184 memset(&search, 0, sizeof(struct mansearch));
185 search.outkey = "Nd";
186 oarg = NULL;
187
188 if (strcmp(progname, BINM_MAN) == 0)
189 search.argmode = ARG_NAME;
190 else if (strcmp(progname, BINM_APROPOS) == 0)
191 search.argmode = ARG_EXPR;
192 else if (strcmp(progname, BINM_WHATIS) == 0)
193 search.argmode = ARG_WORD;
194 else if (strncmp(progname, "help", 4) == 0)
195 search.argmode = ARG_NAME;
196 else
197 search.argmode = ARG_FILE;
198
199 /* Parser options. */
200
201 options = MPARSE_SO | MPARSE_UTF8 | MPARSE_LATIN1;
202 os_e = MANDOC_OS_OTHER;
203 os_s = NULL;
204
205 /* Formatter options. */
206
207 memset(&outst, 0, sizeof(outst));
208 outst.tag_files = NULL;
209 outst.outtype = OUTT_LOCALE;
210 outst.use_pager = 1;
211
212 show_usage = 0;
213 outmode = OUTMODE_DEF;
214
215 while ((c = getopt(argc, argv,
216 "aC:cfhI:iK:klM:m:O:S:s:T:VW:w")) != -1) {
217 if (c == 'i' && search.argmode == ARG_EXPR) {
218 optind--;
219 break;
220 }
221 switch (c) {
222 case 'a':
223 outmode = OUTMODE_ALL;
224 break;
225 case 'C':
226 conf_file = optarg;
227 break;
228 case 'c':
229 outst.use_pager = 0;
230 break;
231 case 'f':
232 search.argmode = ARG_WORD;
233 break;
234 case 'h':
235 conf.output.synopsisonly = 1;
236 outst.use_pager = 0;
237 outmode = OUTMODE_ALL;
238 break;
239 case 'I':
240 if (strncmp(optarg, "os=", 3) != 0) {
241 mandoc_msg(MANDOCERR_BADARG_BAD, 0, 0,
242 "-I %s", optarg);
243 return mandoc_msg_getrc();
244 }
245 if (os_s != NULL) {
246 mandoc_msg(MANDOCERR_BADARG_DUPE, 0, 0,
247 "-I %s", optarg);
248 return mandoc_msg_getrc();
249 }
250 os_s = optarg + 3;
251 break;
252 case 'K':
253 options &= ~(MPARSE_UTF8 | MPARSE_LATIN1);
254 if (strcmp(optarg, "utf-8") == 0)
255 options |= MPARSE_UTF8;
256 else if (strcmp(optarg, "iso-8859-1") == 0)
257 options |= MPARSE_LATIN1;
258 else if (strcmp(optarg, "us-ascii") != 0) {
259 mandoc_msg(MANDOCERR_BADARG_BAD, 0, 0,
260 "-K %s", optarg);
261 return mandoc_msg_getrc();
262 }
263 break;
264 case 'k':
265 search.argmode = ARG_EXPR;
266 break;
267 case 'l':
268 search.argmode = ARG_FILE;
269 outmode = OUTMODE_ALL;
270 break;
271 case 'M':
272 defpaths = optarg;
273 break;
274 case 'm':
275 auxpaths = optarg;
276 break;
277 case 'O':
278 oarg = optarg;
279 break;
280 case 'S':
281 search.arch = optarg;
282 break;
283 case 's':
284 search.sec = optarg;
285 break;
286 case 'T':
287 if (strcmp(optarg, "ascii") == 0)
288 outst.outtype = OUTT_ASCII;
289 else if (strcmp(optarg, "lint") == 0) {
290 outst.outtype = OUTT_LINT;
291 mandoc_msg_setoutfile(stdout);
292 mandoc_msg_setmin(MANDOCERR_BASE);
293 } else if (strcmp(optarg, "tree") == 0)
294 outst.outtype = OUTT_TREE;
295 else if (strcmp(optarg, "man") == 0)
296 outst.outtype = OUTT_MAN;
297 else if (strcmp(optarg, "html") == 0)
298 outst.outtype = OUTT_HTML;
299 else if (strcmp(optarg, "markdown") == 0)
300 outst.outtype = OUTT_MARKDOWN;
301 else if (strcmp(optarg, "utf8") == 0)
302 outst.outtype = OUTT_UTF8;
303 else if (strcmp(optarg, "locale") == 0)
304 outst.outtype = OUTT_LOCALE;
305 else if (strcmp(optarg, "ps") == 0)
306 outst.outtype = OUTT_PS;
307 else if (strcmp(optarg, "pdf") == 0)
308 outst.outtype = OUTT_PDF;
309 else {
310 mandoc_msg(MANDOCERR_BADARG_BAD, 0, 0,
311 "-T %s", optarg);
312 return mandoc_msg_getrc();
313 }
314 break;
315 case 'W':
316 if (woptions(optarg, &os_e, &outst.wstop) == -1)
317 return mandoc_msg_getrc();
318 break;
319 case 'w':
320 outmode = OUTMODE_FLN;
321 break;
322 default:
323 show_usage = 1;
324 break;
325 }
326 }
327
328 if (show_usage)
329 usage(search.argmode);
330
331 /* Postprocess options. */
332
333 switch (outmode) {
334 case OUTMODE_DEF:
335 switch (search.argmode) {
336 case ARG_FILE:
337 outmode = OUTMODE_ALL;
338 outst.use_pager = 0;
339 break;
340 case ARG_NAME:
341 outmode = OUTMODE_ONE;
342 break;
343 default:
344 outmode = OUTMODE_LST;
345 break;
346 }
347 break;
348 case OUTMODE_FLN:
349 if (search.argmode == ARG_FILE)
350 outmode = OUTMODE_ALL;
351 break;
352 case OUTMODE_ALL:
353 break;
354 case OUTMODE_LST:
355 case OUTMODE_ONE:
356 abort();
357 }
358
359 if (oarg != NULL) {
360 if (outmode == OUTMODE_LST)
361 search.outkey = oarg;
362 else {
363 while (oarg != NULL) {
364 if (manconf_output(&conf.output,
365 strsep(&oarg, ","), 0) == -1)
366 return mandoc_msg_getrc();
367 }
368 }
369 }
370
371 if (outst.outtype != OUTT_TREE || conf.output.noval == 0)
372 options |= MPARSE_VALIDATE;
373
374 if (outmode == OUTMODE_FLN ||
375 outmode == OUTMODE_LST ||
376 !isatty(STDOUT_FILENO))
377 outst.use_pager = 0;
378
379 if (outst.use_pager &&
380 (conf.output.width == 0 || conf.output.indent == 0) &&
381 ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) != -1 &&
382 ws.ws_col > 1) {
383 if (conf.output.width == 0 && ws.ws_col < 79)
384 conf.output.width = ws.ws_col - 1;
385 if (conf.output.indent == 0 && ws.ws_col < 66)
386 conf.output.indent = 3;
387 }
388
389 #if HAVE_PLEDGE
390 if (outst.use_pager == 0) {
391 if (pledge("stdio rpath", NULL) == -1) {
392 mandoc_msg(MANDOCERR_PLEDGE, 0, 0,
393 "%s", strerror(errno));
394 return mandoc_msg_getrc();
395 }
396 }
397 #endif
398
399 /* Parse arguments. */
400
401 if (argc > 0) {
402 argc -= optind;
403 argv += optind;
404 }
405
406 /*
407 * Quirks for help(1) and man(1),
408 * in particular for a section argument without -s.
409 */
410
411 if (search.argmode == ARG_NAME) {
412 if (*progname == 'h') {
413 if (argc == 0) {
414 argv = help_argv;
415 argc = 1;
416 }
417 } else if (argc > 1 &&
418 ((uc = (unsigned char *)argv[0]) != NULL) &&
419 ((isdigit(uc[0]) && (uc[1] == '\0' ||
420 isalpha(uc[1]))) ||
421 (uc[0] == 'n' && uc[1] == '\0'))) {
422 search.sec = (char *)uc;
423 argv++;
424 argc--;
425 }
426 if (search.arch == NULL)
427 search.arch = getenv("MACHINE");
428 #ifdef MACHINE
429 if (search.arch == NULL)
430 search.arch = MACHINE;
431 #endif
432 if (outmode == OUTMODE_ONE)
433 search.firstmatch = 1;
434 }
435
436 /*
437 * Use the first argument for -O tag in addition to
438 * using it as a search term for man(1) or apropos(1).
439 */
440
441 if (conf.output.tag != NULL && *conf.output.tag == '\0') {
442 tagarg = argc > 0 && search.argmode == ARG_EXPR ?
443 strchr(*argv, '=') : NULL;
444 conf.output.tag = tagarg == NULL ? *argv : tagarg + 1;
445 }
446
447 /* Read the configuration file. */
448
449 if (search.argmode != ARG_FILE)
450 manconf_parse(&conf, conf_file, defpaths, auxpaths);
451
452 /* man(1): Resolve each name individually. */
453
454 if (search.argmode == ARG_NAME) {
455 if (argc < 1) {
456 if (outmode != OUTMODE_FLN)
457 usage(ARG_NAME);
458 if (conf.manpath.sz == 0) {
459 warnx("The manpath is empty.");
460 mandoc_msg_setrc(MANDOCLEVEL_BADARG);
461 } else {
462 for (i = 0; i + 1 < conf.manpath.sz; i++)
463 printf("%s:", conf.manpath.paths[i]);
464 printf("%s\n", conf.manpath.paths[i]);
465 }
466 manconf_free(&conf);
467 return (int)mandoc_msg_getrc();
468 }
469 for (res = NULL, ressz = 0; argc > 0; argc--, argv++) {
470 (void)mansearch(&search, &conf.manpath,
471 1, argv, &resn, &resnsz);
472 if (resnsz == 0)
473 (void)fs_search(&search, &conf.manpath,
474 *argv, &resn, &resnsz);
475 if (resnsz == 0 && strchr(*argv, '/') == NULL) {
476 if (search.arch != NULL &&
477 arch_valid(search.arch, OSENUM) == 0)
478 warnx("Unknown architecture \"%s\".",
479 search.arch);
480 else if (search.sec != NULL)
481 warnx("No entry for %s in "
482 "section %s of the manual.",
483 *argv, search.sec);
484 else
485 warnx("No entry for %s in "
486 "the manual.", *argv);
487 mandoc_msg_setrc(MANDOCLEVEL_BADARG);
488 continue;
489 }
490 if (resnsz == 0) {
491 if (access(*argv, R_OK) == -1) {
492 mandoc_msg_setinfilename(*argv);
493 mandoc_msg(MANDOCERR_BADARG_BAD,
494 0, 0, "%s", strerror(errno));
495 mandoc_msg_setinfilename(NULL);
496 continue;
497 }
498 resnsz = 1;
499 resn = mandoc_calloc(resnsz, sizeof(*res));
500 resn->file = mandoc_strdup(*argv);
501 resn->ipath = SIZE_MAX;
502 resn->form = FORM_SRC;
503 }
504 if (outmode != OUTMODE_ONE || resnsz == 1) {
505 res = mandoc_reallocarray(res,
506 ressz + resnsz, sizeof(*res));
507 memcpy(res + ressz, resn,
508 sizeof(*resn) * resnsz);
509 ressz += resnsz;
510 continue;
511 }
512
513 /* Search for the best section. */
514
515 best_prio = 40;
516 for (ib = i = 0; i < resnsz; i++) {
517 sec = resn[i].file;
518 sec += strcspn(sec, "123456789");
519 if (sec[0] == '\0')
520 continue; /* No section at all. */
521 prio = sec_prios[sec[0] - '1'];
522 if (search.sec != NULL) {
523 ssz = strlen(search.sec);
524 if (strncmp(sec, search.sec, ssz) == 0)
525 sec += ssz;
526 } else
527 sec++; /* Prefer without suffix. */
528 if (*sec != '/')
529 prio += 10; /* Wrong dir name. */
530 if (search.sec != NULL &&
531 (strlen(sec) <= ssz + 3 ||
532 strcmp(sec + strlen(sec) - ssz,
533 search.sec) != 0))
534 prio += 20; /* Wrong file ext. */
535 if (prio >= best_prio)
536 continue;
537 best_prio = prio;
538 ib = i;
539 }
540 res = mandoc_reallocarray(res, ressz + 1,
541 sizeof(*res));
542 memcpy(res + ressz++, resn + ib, sizeof(*resn));
543 }
544
545 /* apropos(1), whatis(1): Process the full search expression. */
546
547 } else if (search.argmode != ARG_FILE) {
548 if (mansearch(&search, &conf.manpath,
549 argc, argv, &res, &ressz) == 0)
550 usage(search.argmode);
551
552 if (ressz == 0) {
553 warnx("nothing appropriate");
554 mandoc_msg_setrc(MANDOCLEVEL_BADARG);
555 goto out;
556 }
557
558 /* mandoc(1): Take command line arguments as file names. */
559
560 } else {
561 ressz = argc > 0 ? argc : 1;
562 res = mandoc_calloc(ressz, sizeof(*res));
563 for (i = 0; i < ressz; i++) {
564 if (argc > 0)
565 res[i].file = mandoc_strdup(argv[i]);
566 res[i].ipath = SIZE_MAX;
567 res[i].form = FORM_SRC;
568 }
569 }
570
571 switch (outmode) {
572 case OUTMODE_FLN:
573 for (i = 0; i < ressz; i++)
574 puts(res[i].file);
575 goto out;
576 case OUTMODE_LST:
577 for (i = 0; i < ressz; i++)
578 printf("%s - %s\n", res[i].names,
579 res[i].output == NULL ? "" :
580 res[i].output);
581 goto out;
582 default:
583 break;
584 }
585
586 if (search.argmode == ARG_FILE && auxpaths != NULL) {
587 if (strcmp(auxpaths, "doc") == 0)
588 options |= MPARSE_MDOC;
589 else if (strcmp(auxpaths, "an") == 0)
590 options |= MPARSE_MAN;
591 }
592
593 mchars_alloc();
594 mp = mparse_alloc(options, os_e, os_s);
595
596 /*
597 * Remember the original working directory, if possible.
598 * This will be needed if some names on the command line
599 * are page names and some are relative file names.
600 * Do not error out if the current directory is not
601 * readable: Maybe it won't be needed after all.
602 */
603 startdir = open(".", O_RDONLY | O_DIRECTORY);
604 for (i = 0; i < ressz; i++) {
605 process_onefile(mp, res + i, startdir, &outst, &conf);
606 if (outst.wstop && mandoc_msg_getrc() != MANDOCLEVEL_OK)
607 break;
608 }
609 if (startdir != -1) {
610 (void)fchdir(startdir);
611 close(startdir);
612 }
613 if (conf.output.tag != NULL && conf.output.tag_found == 0) {
614 mandoc_msg(MANDOCERR_TAG, 0, 0, "%s", conf.output.tag);
615 conf.output.tag = NULL;
616 }
617 if (outst.outdata != NULL) {
618 switch (outst.outtype) {
619 case OUTT_HTML:
620 html_free(outst.outdata);
621 break;
622 case OUTT_UTF8:
623 case OUTT_LOCALE:
624 case OUTT_ASCII:
625 ascii_free(outst.outdata);
626 break;
627 case OUTT_PDF:
628 case OUTT_PS:
629 pspdf_free(outst.outdata);
630 break;
631 default:
632 break;
633 }
634 }
635 mandoc_xr_free();
636 mparse_free(mp);
637 mchars_free();
638
639 out:
640 mansearch_free(res, ressz);
641 if (search.argmode != ARG_FILE)
642 manconf_free(&conf);
643
644 if (outst.tag_files != NULL) {
645 if (term_tag_close() != -1)
646 run_pager(outst.tag_files, conf.output.tag);
647 term_tag_unlink();
648 } else if (outst.had_output && outst.outtype != OUTT_LINT)
649 mandoc_msg_summary();
650
651 return (int)mandoc_msg_getrc();
652 }
653
654 static void
655 usage(enum argmode argmode)
656 {
657 switch (argmode) {
658 case ARG_FILE:
659 fputs("usage: mandoc [-ac] [-I os=name] "
660 "[-K encoding] [-mdoc | -man] [-O options]\n"
661 "\t [-T output] [-W level] [file ...]\n", stderr);
662 break;
663 case ARG_NAME:
664 fputs("usage: man [-acfhklw] [-C file] [-M path] "
665 "[-m path] [-S subsection]\n"
666 "\t [[-s] section] name ...\n", stderr);
667 break;
668 case ARG_WORD:
669 fputs("usage: whatis [-afk] [-C file] "
670 "[-M path] [-m path] [-O outkey] [-S arch]\n"
671 "\t [-s section] name ...\n", stderr);
672 break;
673 case ARG_EXPR:
674 fputs("usage: apropos [-afk] [-C file] "
675 "[-M path] [-m path] [-O outkey] [-S arch]\n"
676 "\t [-s section] expression ...\n", stderr);
677 break;
678 }
679 exit((int)MANDOCLEVEL_BADARG);
680 }
681
682 static void
683 glob_esc(char **dst, const char *src, const char *suffix)
684 {
685 while (*src != '\0') {
686 if (strchr("*?[", *src) != NULL)
687 *(*dst)++ = '\\';
688 *(*dst)++ = *src++;
689 }
690 while (*suffix != '\0')
691 *(*dst)++ = *suffix++;
692 }
693
694 static int
695 fs_lookup(const struct manpaths *paths, size_t ipath,
696 const char *sec, const char *arch, const char *name,
697 struct manpage **res, size_t *ressz)
698 {
699 struct stat sb;
700 glob_t globinfo;
701 struct manpage *page;
702 char *file, *cp;
703 int globres;
704 enum form form;
705
706 const char *const slman = "/man";
707 const char *const slash = "/";
708 const char *const sglob = ".[01-9]*";
709
710 form = FORM_SRC;
711 mandoc_asprintf(&file, "%s/man%s/%s.%s",
712 paths->paths[ipath], sec, name, sec);
713 if (stat(file, &sb) != -1)
714 goto found;
715 free(file);
716
717 mandoc_asprintf(&file, "%s/cat%s/%s.0",
718 paths->paths[ipath], sec, name);
719 if (stat(file, &sb) != -1) {
720 form = FORM_CAT;
721 goto found;
722 }
723 free(file);
724
725 if (arch != NULL) {
726 mandoc_asprintf(&file, "%s/man%s/%s/%s.%s",
727 paths->paths[ipath], sec, arch, name, sec);
728 if (stat(file, &sb) != -1)
729 goto found;
730 free(file);
731 }
732
733 cp = file = mandoc_malloc(strlen(paths->paths[ipath]) * 2 +
734 strlen(slman) + strlen(sec) * 2 + strlen(slash) +
735 strlen(name) * 2 + strlen(sglob) + 1);
736 glob_esc(&cp, paths->paths[ipath], slman);
737 glob_esc(&cp, sec, slash);
738 glob_esc(&cp, name, sglob);
739 *cp = '\0';
740 globres = glob(file, 0, NULL, &globinfo);
741 if (globres != 0 && globres != GLOB_NOMATCH)
742 mandoc_msg(MANDOCERR_GLOB, 0, 0,
743 "%s: %s", file, strerror(errno));
744 free(file);
745 if (globres == 0)
746 file = mandoc_strdup(*globinfo.gl_pathv);
747 globfree(&globinfo);
748 if (globres == 0) {
749 if (stat(file, &sb) != -1)
750 goto found;
751 free(file);
752 }
753 if (res != NULL || ipath + 1 != paths->sz)
754 return -1;
755
756 mandoc_asprintf(&file, "%s.%s", name, sec);
757 globres = stat(file, &sb);
758 free(file);
759 return globres;
760
761 found:
762 warnx("outdated mandoc.db lacks %s(%s) entry, run %s %s",
763 name, sec, BINM_MAKEWHATIS, paths->paths[ipath]);
764 if (res == NULL) {
765 free(file);
766 return 0;
767 }
768 *res = mandoc_reallocarray(*res, ++*ressz, sizeof(**res));
769 page = *res + (*ressz - 1);
770 page->file = file;
771 page->names = NULL;
772 page->output = NULL;
773 page->bits = NAME_FILE & NAME_MASK;
774 page->ipath = ipath;
775 page->sec = (*sec >= '1' && *sec <= '9') ? *sec - '1' + 1 : 10;
776 page->form = form;
777 return 0;
778 }
779
780 static int
781 fs_search(const struct mansearch *cfg, const struct manpaths *paths,
782 const char *name, struct manpage **res, size_t *ressz)
783 {
784 const char *const sections[] =
785 {"1", "8", "6", "2", "3", "5", "7", "4", "9", "3p"};
786 const size_t nsec = sizeof(sections)/sizeof(sections[0]);
787
788 size_t ipath, isec;
789
790 assert(cfg->argmode == ARG_NAME);
791 if (res != NULL)
792 *res = NULL;
793 *ressz = 0;
794 for (ipath = 0; ipath < paths->sz; ipath++) {
795 if (cfg->sec != NULL) {
796 if (fs_lookup(paths, ipath, cfg->sec, cfg->arch,
797 name, res, ressz) != -1 && cfg->firstmatch)
798 return 0;
799 } else {
800 for (isec = 0; isec < nsec; isec++)
801 if (fs_lookup(paths, ipath, sections[isec],
802 cfg->arch, name, res, ressz) != -1 &&
803 cfg->firstmatch)
804 return 0;
805 }
806 }
807 return -1;
808 }
809
810 static void
811 process_onefile(struct mparse *mp, struct manpage *resp, int startdir,
812 struct outstate *outst, struct manconf *conf)
813 {
814 int fd;
815
816 /*
817 * Changing directories is not needed in ARG_FILE mode.
818 * Do it on a best-effort basis. Even in case of
819 * failure, some functionality may still work.
820 */
821 if (resp->ipath != SIZE_MAX)
822 (void)chdir(conf->manpath.paths[resp->ipath]);
823 else if (startdir != -1)
824 (void)fchdir(startdir);
825
826 mandoc_msg_setinfilename(resp->file);
827 if (resp->file != NULL) {
828 if ((fd = mparse_open(mp, resp->file)) == -1) {
829 mandoc_msg(resp->ipath == SIZE_MAX ?
830 MANDOCERR_BADARG_BAD : MANDOCERR_OPEN,
831 0, 0, "%s", strerror(errno));
832 mandoc_msg_setinfilename(NULL);
833 return;
834 }
835 } else
836 fd = STDIN_FILENO;
837
838 if (outst->use_pager) {
839 outst->use_pager = 0;
840 outst->tag_files = term_tag_init();
841 }
842 if (outst->had_output && outst->outtype <= OUTT_UTF8) {
843 if (outst->outdata == NULL)
844 outdata_alloc(outst, &conf->output);
845 terminal_sepline(outst->outdata);
846 }
847
848 if (resp->form == FORM_SRC)
849 parse(mp, fd, resp->file, outst, &conf->output);
850 else {
851 passthrough(fd, conf->output.synopsisonly);
852 outst->had_output = 1;
853 }
854
855 if (ferror(stdout)) {
856 if (outst->tag_files != NULL) {
857 mandoc_msg(MANDOCERR_WRITE, 0, 0, "%s: %s",
858 outst->tag_files->ofn, strerror(errno));
859 term_tag_unlink();
860 outst->tag_files = NULL;
861 } else
862 mandoc_msg(MANDOCERR_WRITE, 0, 0, "%s",
863 strerror(errno));
864 }
865 mandoc_msg_setinfilename(NULL);
866 }
867
868 static void
869 parse(struct mparse *mp, int fd, const char *file,
870 struct outstate *outst, struct manoutput *outconf)
871 {
872 static int previous;
873 struct roff_meta *meta;
874
875 assert(fd >= 0);
876 if (file == NULL)
877 file = "<stdin>";
878
879 if (previous)
880 mparse_reset(mp);
881 else
882 previous = 1;
883
884 mparse_readfd(mp, fd, file);
885 if (fd != STDIN_FILENO)
886 close(fd);
887
888 /*
889 * With -Wstop and warnings or errors of at least the requested
890 * level, do not produce output.
891 */
892
893 if (outst->wstop && mandoc_msg_getrc() != MANDOCLEVEL_OK)
894 return;
895
896 if (outst->outdata == NULL)
897 outdata_alloc(outst, outconf);
898 else if (outst->outtype == OUTT_HTML)
899 html_reset(outst);
900
901 mandoc_xr_reset();
902 meta = mparse_result(mp);
903
904 /* Execute the out device, if it exists. */
905
906 outst->had_output = 1;
907 if (meta->macroset == MACROSET_MDOC) {
908 switch (outst->outtype) {
909 case OUTT_HTML:
910 html_mdoc(outst->outdata, meta);
911 break;
912 case OUTT_TREE:
913 tree_mdoc(outst->outdata, meta);
914 break;
915 case OUTT_MAN:
916 man_mdoc(outst->outdata, meta);
917 break;
918 case OUTT_PDF:
919 case OUTT_ASCII:
920 case OUTT_UTF8:
921 case OUTT_LOCALE:
922 case OUTT_PS:
923 terminal_mdoc(outst->outdata, meta);
924 break;
925 case OUTT_MARKDOWN:
926 markdown_mdoc(outst->outdata, meta);
927 break;
928 default:
929 break;
930 }
931 }
932 if (meta->macroset == MACROSET_MAN) {
933 switch (outst->outtype) {
934 case OUTT_HTML:
935 html_man(outst->outdata, meta);
936 break;
937 case OUTT_TREE:
938 tree_man(outst->outdata, meta);
939 break;
940 case OUTT_MAN:
941 mparse_copy(mp);
942 break;
943 case OUTT_PDF:
944 case OUTT_ASCII:
945 case OUTT_UTF8:
946 case OUTT_LOCALE:
947 case OUTT_PS:
948 terminal_man(outst->outdata, meta);
949 break;
950 default:
951 break;
952 }
953 }
954 if (outconf->tag != NULL && outconf->tag_found == 0 &&
955 tag_exists(outconf->tag))
956 outconf->tag_found = 1;
957 if (mandoc_msg_getmin() < MANDOCERR_STYLE)
958 check_xr();
959 }
960
961 static void
962 check_xr(void)
963 {
964 static struct manpaths paths;
965 struct mansearch search;
966 struct mandoc_xr *xr;
967 size_t sz;
968
969 if (paths.sz == 0)
970 manpath_base(&paths);
971
972 for (xr = mandoc_xr_get(); xr != NULL; xr = xr->next) {
973 if (xr->line == -1)
974 continue;
975 search.arch = NULL;
976 search.sec = xr->sec;
977 search.outkey = NULL;
978 search.argmode = ARG_NAME;
979 search.firstmatch = 1;
980 if (mansearch(&search, &paths, 1, &xr->name, NULL, &sz))
981 continue;
982 if (fs_search(&search, &paths, xr->name, NULL, &sz) != -1)
983 continue;
984 if (xr->count == 1)
985 mandoc_msg(MANDOCERR_XR_BAD, xr->line,
986 xr->pos + 1, "Xr %s %s", xr->name, xr->sec);
987 else
988 mandoc_msg(MANDOCERR_XR_BAD, xr->line,
989 xr->pos + 1, "Xr %s %s (%d times)",
990 xr->name, xr->sec, xr->count);
991 }
992 }
993
994 static void
995 outdata_alloc(struct outstate *outst, struct manoutput *outconf)
996 {
997 switch (outst->outtype) {
998 case OUTT_HTML:
999 outst->outdata = html_alloc(outconf);
1000 break;
1001 case OUTT_UTF8:
1002 outst->outdata = utf8_alloc(outconf);
1003 break;
1004 case OUTT_LOCALE:
1005 outst->outdata = locale_alloc(outconf);
1006 break;
1007 case OUTT_ASCII:
1008 outst->outdata = ascii_alloc(outconf);
1009 break;
1010 case OUTT_PDF:
1011 outst->outdata = pdf_alloc(outconf);
1012 break;
1013 case OUTT_PS:
1014 outst->outdata = ps_alloc(outconf);
1015 break;
1016 default:
1017 break;
1018 }
1019 }
1020
1021 static void
1022 passthrough(int fd, int synopsis_only)
1023 {
1024 const char synb[] = "S\bSY\bYN\bNO\bOP\bPS\bSI\bIS\bS";
1025 const char synr[] = "SYNOPSIS";
1026
1027 FILE *stream;
1028 char *line, *cp;
1029 size_t linesz;
1030 ssize_t len, written;
1031 int lno, print;
1032
1033 stream = NULL;
1034 line = NULL;
1035 linesz = 0;
1036
1037 if (fflush(stdout) == EOF) {
1038 mandoc_msg(MANDOCERR_FFLUSH, 0, 0, "%s", strerror(errno));
1039 goto done;
1040 }
1041 if ((stream = fdopen(fd, "r")) == NULL) {
1042 close(fd);
1043 mandoc_msg(MANDOCERR_FDOPEN, 0, 0, "%s", strerror(errno));
1044 goto done;
1045 }
1046
1047 lno = print = 0;
1048 while ((len = getline(&line, &linesz, stream)) != -1) {
1049 lno++;
1050 cp = line;
1051 if (synopsis_only) {
1052 if (print) {
1053 if ( ! isspace((unsigned char)*cp))
1054 goto done;
1055 while (isspace((unsigned char)*cp)) {
1056 cp++;
1057 len--;
1058 }
1059 } else {
1060 if (strcmp(cp, synb) == 0 ||
1061 strcmp(cp, synr) == 0)
1062 print = 1;
1063 continue;
1064 }
1065 }
1066 for (; len > 0; len -= written) {
1067 if ((written = write(STDOUT_FILENO, cp, len)) == -1) {
1068 mandoc_msg(MANDOCERR_WRITE, 0, 0,
1069 "%s", strerror(errno));
1070 goto done;
1071 }
1072 }
1073 }
1074 if (ferror(stream))
1075 mandoc_msg(MANDOCERR_GETLINE, lno, 0, "%s", strerror(errno));
1076
1077 done:
1078 free(line);
1079 if (stream != NULL)
1080 fclose(stream);
1081 }
1082
1083 static int
1084 woptions(char *arg, enum mandoc_os *os_e, int *wstop)
1085 {
1086 char *v, *o;
1087 const char *toks[11];
1088
1089 toks[0] = "stop";
1090 toks[1] = "all";
1091 toks[2] = "base";
1092 toks[3] = "style";
1093 toks[4] = "warning";
1094 toks[5] = "error";
1095 toks[6] = "unsupp";
1096 toks[7] = "fatal";
1097 toks[8] = "openbsd";
1098 toks[9] = "netbsd";
1099 toks[10] = NULL;
1100
1101 while (*arg) {
1102 o = arg;
1103 switch (getsubopt(&arg, (char * const *)toks, &v)) {
1104 case 0:
1105 *wstop = 1;
1106 break;
1107 case 1:
1108 case 2:
1109 mandoc_msg_setmin(MANDOCERR_BASE);
1110 break;
1111 case 3:
1112 mandoc_msg_setmin(MANDOCERR_STYLE);
1113 break;
1114 case 4:
1115 mandoc_msg_setmin(MANDOCERR_WARNING);
1116 break;
1117 case 5:
1118 mandoc_msg_setmin(MANDOCERR_ERROR);
1119 break;
1120 case 6:
1121 mandoc_msg_setmin(MANDOCERR_UNSUPP);
1122 break;
1123 case 7:
1124 mandoc_msg_setmin(MANDOCERR_BADARG);
1125 break;
1126 case 8:
1127 mandoc_msg_setmin(MANDOCERR_BASE);
1128 *os_e = MANDOC_OS_OPENBSD;
1129 break;
1130 case 9:
1131 mandoc_msg_setmin(MANDOCERR_BASE);
1132 *os_e = MANDOC_OS_NETBSD;
1133 break;
1134 default:
1135 mandoc_msg(MANDOCERR_BADARG_BAD, 0, 0, "-W %s", o);
1136 return -1;
1137 }
1138 }
1139 return 0;
1140 }
1141
1142 /*
1143 * Wait until moved to the foreground,
1144 * then fork the pager and wait for the user to close it.
1145 */
1146 static void
1147 run_pager(struct tag_files *tag_files, char *tag_target)
1148 {
1149 int signum, status;
1150 pid_t man_pgid, tc_pgid;
1151 pid_t pager_pid, wait_pid;
1152
1153 man_pgid = getpgid(0);
1154 tag_files->tcpgid = man_pgid == getpid() ? getpgid(getppid()) :
1155 man_pgid;
1156 pager_pid = 0;
1157 signum = SIGSTOP;
1158
1159 for (;;) {
1160 /* Stop here until moved to the foreground. */
1161
1162 tc_pgid = tcgetpgrp(STDOUT_FILENO);
1163 if (tc_pgid != man_pgid) {
1164 if (tc_pgid == pager_pid) {
1165 (void)tcsetpgrp(STDOUT_FILENO, man_pgid);
1166 if (signum == SIGTTIN)
1167 continue;
1168 } else
1169 tag_files->tcpgid = tc_pgid;
1170 kill(0, signum);
1171 continue;
1172 }
1173
1174 /* Once in the foreground, activate the pager. */
1175
1176 if (pager_pid) {
1177 (void)tcsetpgrp(STDOUT_FILENO, pager_pid);
1178 kill(pager_pid, SIGCONT);
1179 } else
1180 pager_pid = spawn_pager(tag_files, tag_target);
1181
1182 /* Wait for the pager to stop or exit. */
1183
1184 while ((wait_pid = waitpid(pager_pid, &status,
1185 WUNTRACED)) == -1 && errno == EINTR)
1186 continue;
1187
1188 if (wait_pid == -1) {
1189 mandoc_msg(MANDOCERR_WAIT, 0, 0,
1190 "%s", strerror(errno));
1191 break;
1192 }
1193 if (!WIFSTOPPED(status))
1194 break;
1195
1196 signum = WSTOPSIG(status);
1197 }
1198 }
1199
1200 static pid_t
1201 spawn_pager(struct tag_files *tag_files, char *tag_target)
1202 {
1203 const struct timespec timeout = { 0, 100000000 }; /* 0.1s */
1204 #define MAX_PAGER_ARGS 16
1205 char *argv[MAX_PAGER_ARGS];
1206 const char *pager;
1207 char *cp;
1208 #if HAVE_LESS_T
1209 size_t cmdlen;
1210 #endif
1211 int argc, use_ofn;
1212 pid_t pager_pid;
1213
1214 assert(tag_files->ofd == -1);
1215 assert(tag_files->tfs == NULL);
1216
1217 pager = getenv("MANPAGER");
1218 if (pager == NULL || *pager == '\0')
1219 pager = getenv("PAGER");
1220 if (pager == NULL || *pager == '\0')
1221 pager = "more -s";
1222 cp = mandoc_strdup(pager);
1223
1224 /*
1225 * Parse the pager command into words.
1226 * Intentionally do not do anything fancy here.
1227 */
1228
1229 argc = 0;
1230 while (argc + 5 < MAX_PAGER_ARGS) {
1231 argv[argc++] = cp;
1232 cp = strchr(cp, ' ');
1233 if (cp == NULL)
1234 break;
1235 *cp++ = '\0';
1236 while (*cp == ' ')
1237 cp++;
1238 if (*cp == '\0')
1239 break;
1240 }
1241
1242 /* For less(1), use the tag file. */
1243
1244 use_ofn = 1;
1245 #if HAVE_LESS_T
1246 if (*tag_files->tfn != '\0' && (cmdlen = strlen(argv[0])) >= 4) {
1247 cp = argv[0] + cmdlen - 4;
1248 if (strcmp(cp, "less") == 0) {
1249 argv[argc++] = mandoc_strdup("-T");
1250 argv[argc++] = tag_files->tfn;
1251 if (tag_target != NULL) {
1252 argv[argc++] = mandoc_strdup("-t");
1253 argv[argc++] = tag_target;
1254 use_ofn = 0;
1255 }
1256 }
1257 }
1258 #endif
1259 if (use_ofn)
1260 argv[argc++] = tag_files->ofn;
1261 argv[argc] = NULL;
1262
1263 switch (pager_pid = fork()) {
1264 case -1:
1265 mandoc_msg(MANDOCERR_FORK, 0, 0, "%s", strerror(errno));
1266 exit(mandoc_msg_getrc());
1267 case 0:
1268 break;
1269 default:
1270 (void)setpgid(pager_pid, 0);
1271 (void)tcsetpgrp(STDOUT_FILENO, pager_pid);
1272 #if HAVE_PLEDGE
1273 if (pledge("stdio rpath tmppath tty proc", NULL) == -1) {
1274 mandoc_msg(MANDOCERR_PLEDGE, 0, 0,
1275 "%s", strerror(errno));
1276 exit(mandoc_msg_getrc());
1277 }
1278 #endif
1279 tag_files->pager_pid = pager_pid;
1280 return pager_pid;
1281 }
1282
1283 /*
1284 * The child process becomes the pager.
1285 * Do not start it before controlling the terminal.
1286 */
1287
1288 while (tcgetpgrp(STDOUT_FILENO) != getpid())
1289 nanosleep(&timeout, NULL);
1290
1291 execvp(argv[0], argv);
1292 mandoc_msg(MANDOCERR_EXEC, 0, 0, "%s: %s", argv[0], strerror(errno));
1293 _exit(mandoc_msg_getrc());
1294 }