]> git.cameronkatri.com Git - mandoc.git/blob - mandocdb.c
cast off_t and uint64_t for printf(3)
[mandoc.git] / mandocdb.c
1 /* $Id: mandocdb.c,v 1.234 2016/10/22 10:09:27 schwarze Exp $ */
2 /*
3 * Copyright (c) 2011, 2012 Kristaps Dzonsons <kristaps@bsd.lv>
4 * Copyright (c) 2011-2016 Ingo Schwarze <schwarze@openbsd.org>
5 * Copyright (c) 2016 Ed Maste <emaste@freebsd.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/stat.h>
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 #if HAVE_FTS
33 #include <fts.h>
34 #else
35 #include "compat_fts.h"
36 #endif
37 #include <limits.h>
38 #if HAVE_SANDBOX_INIT
39 #include <sandbox.h>
40 #endif
41 #include <stdarg.h>
42 #include <stddef.h>
43 #include <stdio.h>
44 #include <stdint.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <unistd.h>
48
49 #include "mandoc_aux.h"
50 #include "mandoc_ohash.h"
51 #include "mandoc.h"
52 #include "roff.h"
53 #include "mdoc.h"
54 #include "man.h"
55 #include "manconf.h"
56 #include "mansearch.h"
57 #include "dba_array.h"
58 #include "dba.h"
59
60 extern const char *const mansearch_keynames[];
61
62 enum op {
63 OP_DEFAULT = 0, /* new dbs from dir list or default config */
64 OP_CONFFILE, /* new databases from custom config file */
65 OP_UPDATE, /* delete/add entries in existing database */
66 OP_DELETE, /* delete entries from existing database */
67 OP_TEST /* change no databases, report potential problems */
68 };
69
70 struct str {
71 const struct mpage *mpage; /* if set, the owning parse */
72 uint64_t mask; /* bitmask in sequence */
73 char key[]; /* rendered text */
74 };
75
76 struct inodev {
77 ino_t st_ino;
78 dev_t st_dev;
79 };
80
81 struct mpage {
82 struct inodev inodev; /* used for hashing routine */
83 struct dba_array *dba;
84 char *sec; /* section from file content */
85 char *arch; /* architecture from file content */
86 char *title; /* title from file content */
87 char *desc; /* description from file content */
88 struct mpage *next; /* singly linked list */
89 struct mlink *mlinks; /* singly linked list */
90 int name_head_done;
91 enum form form; /* format from file content */
92 };
93
94 struct mlink {
95 char file[PATH_MAX]; /* filename rel. to manpath */
96 char *dsec; /* section from directory */
97 char *arch; /* architecture from directory */
98 char *name; /* name from file name (not empty) */
99 char *fsec; /* section from file name suffix */
100 struct mlink *next; /* singly linked list */
101 struct mpage *mpage; /* parent */
102 int gzip; /* filename has a .gz suffix */
103 enum form dform; /* format from directory */
104 enum form fform; /* format from file name suffix */
105 };
106
107 typedef int (*mdoc_fp)(struct mpage *, const struct roff_meta *,
108 const struct roff_node *);
109
110 struct mdoc_handler {
111 mdoc_fp fp; /* optional handler */
112 uint64_t mask; /* set unless handler returns 0 */
113 };
114
115
116 int mandocdb(int, char *[]);
117
118 static void dbadd(struct dba *, struct mpage *);
119 static void dbadd_mlink(const struct mlink *mlink);
120 static void dbprune(struct dba *);
121 static void dbwrite(struct dba *);
122 static void filescan(const char *);
123 #if HAVE_FTS_COMPARE_CONST
124 static int fts_compare(const FTSENT *const *, const FTSENT *const *);
125 #else
126 static int fts_compare(const FTSENT **, const FTSENT **);
127 #endif
128 static void mlink_add(struct mlink *, const struct stat *);
129 static void mlink_check(struct mpage *, struct mlink *);
130 static void mlink_free(struct mlink *);
131 static void mlinks_undupe(struct mpage *);
132 static void mpages_free(void);
133 static void mpages_merge(struct dba *, struct mparse *);
134 static void parse_cat(struct mpage *, int);
135 static void parse_man(struct mpage *, const struct roff_meta *,
136 const struct roff_node *);
137 static void parse_mdoc(struct mpage *, const struct roff_meta *,
138 const struct roff_node *);
139 static int parse_mdoc_head(struct mpage *, const struct roff_meta *,
140 const struct roff_node *);
141 static int parse_mdoc_Fd(struct mpage *, const struct roff_meta *,
142 const struct roff_node *);
143 static void parse_mdoc_fname(struct mpage *, const struct roff_node *);
144 static int parse_mdoc_Fn(struct mpage *, const struct roff_meta *,
145 const struct roff_node *);
146 static int parse_mdoc_Fo(struct mpage *, const struct roff_meta *,
147 const struct roff_node *);
148 static int parse_mdoc_Nd(struct mpage *, const struct roff_meta *,
149 const struct roff_node *);
150 static int parse_mdoc_Nm(struct mpage *, const struct roff_meta *,
151 const struct roff_node *);
152 static int parse_mdoc_Sh(struct mpage *, const struct roff_meta *,
153 const struct roff_node *);
154 static int parse_mdoc_Va(struct mpage *, const struct roff_meta *,
155 const struct roff_node *);
156 static int parse_mdoc_Xr(struct mpage *, const struct roff_meta *,
157 const struct roff_node *);
158 static void putkey(const struct mpage *, char *, uint64_t);
159 static void putkeys(const struct mpage *, char *, size_t, uint64_t);
160 static void putmdockey(const struct mpage *,
161 const struct roff_node *, uint64_t);
162 static int render_string(char **, size_t *);
163 static void say(const char *, const char *, ...)
164 __attribute__((__format__ (printf, 2, 3)));
165 static int set_basedir(const char *, int);
166 static int treescan(void);
167 static size_t utf8(unsigned int, char [7]);
168
169 static int nodb; /* no database changes */
170 static int mparse_options; /* abort the parse early */
171 static int use_all; /* use all found files */
172 static int debug; /* print what we're doing */
173 static int warnings; /* warn about crap */
174 static int write_utf8; /* write UTF-8 output; else ASCII */
175 static int exitcode; /* to be returned by main */
176 static enum op op; /* operational mode */
177 static char basedir[PATH_MAX]; /* current base directory */
178 static struct mpage *mpage_head; /* list of distinct manual pages */
179 static struct ohash mpages; /* table of distinct manual pages */
180 static struct ohash mlinks; /* table of directory entries */
181 static struct ohash names; /* table of all names */
182 static struct ohash strings; /* table of all strings */
183 static uint64_t name_mask;
184
185 static const struct mdoc_handler mdocs[MDOC_MAX] = {
186 { NULL, 0 }, /* Ap */
187 { NULL, 0 }, /* Dd */
188 { NULL, 0 }, /* Dt */
189 { NULL, 0 }, /* Os */
190 { parse_mdoc_Sh, TYPE_Sh }, /* Sh */
191 { parse_mdoc_head, TYPE_Ss }, /* Ss */
192 { NULL, 0 }, /* Pp */
193 { NULL, 0 }, /* D1 */
194 { NULL, 0 }, /* Dl */
195 { NULL, 0 }, /* Bd */
196 { NULL, 0 }, /* Ed */
197 { NULL, 0 }, /* Bl */
198 { NULL, 0 }, /* El */
199 { NULL, 0 }, /* It */
200 { NULL, 0 }, /* Ad */
201 { NULL, TYPE_An }, /* An */
202 { NULL, TYPE_Ar }, /* Ar */
203 { NULL, TYPE_Cd }, /* Cd */
204 { NULL, TYPE_Cm }, /* Cm */
205 { NULL, TYPE_Dv }, /* Dv */
206 { NULL, TYPE_Er }, /* Er */
207 { NULL, TYPE_Ev }, /* Ev */
208 { NULL, 0 }, /* Ex */
209 { NULL, TYPE_Fa }, /* Fa */
210 { parse_mdoc_Fd, 0 }, /* Fd */
211 { NULL, TYPE_Fl }, /* Fl */
212 { parse_mdoc_Fn, 0 }, /* Fn */
213 { NULL, TYPE_Ft }, /* Ft */
214 { NULL, TYPE_Ic }, /* Ic */
215 { NULL, TYPE_In }, /* In */
216 { NULL, TYPE_Li }, /* Li */
217 { parse_mdoc_Nd, 0 }, /* Nd */
218 { parse_mdoc_Nm, 0 }, /* Nm */
219 { NULL, 0 }, /* Op */
220 { NULL, 0 }, /* Ot */
221 { NULL, TYPE_Pa }, /* Pa */
222 { NULL, 0 }, /* Rv */
223 { NULL, TYPE_St }, /* St */
224 { parse_mdoc_Va, TYPE_Va }, /* Va */
225 { parse_mdoc_Va, TYPE_Vt }, /* Vt */
226 { parse_mdoc_Xr, 0 }, /* Xr */
227 { NULL, 0 }, /* %A */
228 { NULL, 0 }, /* %B */
229 { NULL, 0 }, /* %D */
230 { NULL, 0 }, /* %I */
231 { NULL, 0 }, /* %J */
232 { NULL, 0 }, /* %N */
233 { NULL, 0 }, /* %O */
234 { NULL, 0 }, /* %P */
235 { NULL, 0 }, /* %R */
236 { NULL, 0 }, /* %T */
237 { NULL, 0 }, /* %V */
238 { NULL, 0 }, /* Ac */
239 { NULL, 0 }, /* Ao */
240 { NULL, 0 }, /* Aq */
241 { NULL, TYPE_At }, /* At */
242 { NULL, 0 }, /* Bc */
243 { NULL, 0 }, /* Bf */
244 { NULL, 0 }, /* Bo */
245 { NULL, 0 }, /* Bq */
246 { NULL, TYPE_Bsx }, /* Bsx */
247 { NULL, TYPE_Bx }, /* Bx */
248 { NULL, 0 }, /* Db */
249 { NULL, 0 }, /* Dc */
250 { NULL, 0 }, /* Do */
251 { NULL, 0 }, /* Dq */
252 { NULL, 0 }, /* Ec */
253 { NULL, 0 }, /* Ef */
254 { NULL, TYPE_Em }, /* Em */
255 { NULL, 0 }, /* Eo */
256 { NULL, TYPE_Fx }, /* Fx */
257 { NULL, TYPE_Ms }, /* Ms */
258 { NULL, 0 }, /* No */
259 { NULL, 0 }, /* Ns */
260 { NULL, TYPE_Nx }, /* Nx */
261 { NULL, TYPE_Ox }, /* Ox */
262 { NULL, 0 }, /* Pc */
263 { NULL, 0 }, /* Pf */
264 { NULL, 0 }, /* Po */
265 { NULL, 0 }, /* Pq */
266 { NULL, 0 }, /* Qc */
267 { NULL, 0 }, /* Ql */
268 { NULL, 0 }, /* Qo */
269 { NULL, 0 }, /* Qq */
270 { NULL, 0 }, /* Re */
271 { NULL, 0 }, /* Rs */
272 { NULL, 0 }, /* Sc */
273 { NULL, 0 }, /* So */
274 { NULL, 0 }, /* Sq */
275 { NULL, 0 }, /* Sm */
276 { NULL, 0 }, /* Sx */
277 { NULL, TYPE_Sy }, /* Sy */
278 { NULL, TYPE_Tn }, /* Tn */
279 { NULL, 0 }, /* Ux */
280 { NULL, 0 }, /* Xc */
281 { NULL, 0 }, /* Xo */
282 { parse_mdoc_Fo, 0 }, /* Fo */
283 { NULL, 0 }, /* Fc */
284 { NULL, 0 }, /* Oo */
285 { NULL, 0 }, /* Oc */
286 { NULL, 0 }, /* Bk */
287 { NULL, 0 }, /* Ek */
288 { NULL, 0 }, /* Bt */
289 { NULL, 0 }, /* Hf */
290 { NULL, 0 }, /* Fr */
291 { NULL, 0 }, /* Ud */
292 { NULL, TYPE_Lb }, /* Lb */
293 { NULL, 0 }, /* Lp */
294 { NULL, TYPE_Lk }, /* Lk */
295 { NULL, TYPE_Mt }, /* Mt */
296 { NULL, 0 }, /* Brq */
297 { NULL, 0 }, /* Bro */
298 { NULL, 0 }, /* Brc */
299 { NULL, 0 }, /* %C */
300 { NULL, 0 }, /* Es */
301 { NULL, 0 }, /* En */
302 { NULL, TYPE_Dx }, /* Dx */
303 { NULL, 0 }, /* %Q */
304 { NULL, 0 }, /* br */
305 { NULL, 0 }, /* sp */
306 { NULL, 0 }, /* %U */
307 { NULL, 0 }, /* Ta */
308 { NULL, 0 }, /* ll */
309 };
310
311
312 int
313 mandocdb(int argc, char *argv[])
314 {
315 struct manconf conf;
316 struct mparse *mp;
317 struct dba *dba;
318 const char *path_arg, *progname;
319 size_t j, sz;
320 int ch, i;
321
322 #if HAVE_PLEDGE
323 if (pledge("stdio rpath wpath cpath fattr flock proc exec", NULL) == -1) {
324 warn("pledge");
325 return (int)MANDOCLEVEL_SYSERR;
326 }
327 #endif
328
329 #if HAVE_SANDBOX_INIT
330 if (sandbox_init(kSBXProfileNoInternet, SANDBOX_NAMED, NULL) == -1) {
331 warnx("sandbox_init");
332 return (int)MANDOCLEVEL_SYSERR;
333 }
334 #endif
335
336 memset(&conf, 0, sizeof(conf));
337
338 /*
339 * We accept a few different invocations.
340 * The CHECKOP macro makes sure that invocation styles don't
341 * clobber each other.
342 */
343 #define CHECKOP(_op, _ch) do \
344 if (OP_DEFAULT != (_op)) { \
345 warnx("-%c: Conflicting option", (_ch)); \
346 goto usage; \
347 } while (/*CONSTCOND*/0)
348
349 path_arg = NULL;
350 op = OP_DEFAULT;
351
352 while (-1 != (ch = getopt(argc, argv, "aC:Dd:npQT:tu:v")))
353 switch (ch) {
354 case 'a':
355 use_all = 1;
356 break;
357 case 'C':
358 CHECKOP(op, ch);
359 path_arg = optarg;
360 op = OP_CONFFILE;
361 break;
362 case 'D':
363 debug++;
364 break;
365 case 'd':
366 CHECKOP(op, ch);
367 path_arg = optarg;
368 op = OP_UPDATE;
369 break;
370 case 'n':
371 nodb = 1;
372 break;
373 case 'p':
374 warnings = 1;
375 break;
376 case 'Q':
377 mparse_options |= MPARSE_QUICK;
378 break;
379 case 'T':
380 if (strcmp(optarg, "utf8")) {
381 warnx("-T%s: Unsupported output format",
382 optarg);
383 goto usage;
384 }
385 write_utf8 = 1;
386 break;
387 case 't':
388 CHECKOP(op, ch);
389 dup2(STDOUT_FILENO, STDERR_FILENO);
390 op = OP_TEST;
391 nodb = warnings = 1;
392 break;
393 case 'u':
394 CHECKOP(op, ch);
395 path_arg = optarg;
396 op = OP_DELETE;
397 break;
398 case 'v':
399 /* Compatibility with espie@'s makewhatis. */
400 break;
401 default:
402 goto usage;
403 }
404
405 argc -= optind;
406 argv += optind;
407
408 #if HAVE_PLEDGE
409 if (nodb) {
410 if (pledge("stdio rpath", NULL) == -1) {
411 warn("pledge");
412 return (int)MANDOCLEVEL_SYSERR;
413 }
414 }
415 #endif
416
417 if (OP_CONFFILE == op && argc > 0) {
418 warnx("-C: Too many arguments");
419 goto usage;
420 }
421
422 exitcode = (int)MANDOCLEVEL_OK;
423 mchars_alloc();
424 mp = mparse_alloc(mparse_options, MANDOCLEVEL_BADARG, NULL, NULL);
425 mandoc_ohash_init(&mpages, 6, offsetof(struct mpage, inodev));
426 mandoc_ohash_init(&mlinks, 6, offsetof(struct mlink, file));
427
428 if (OP_UPDATE == op || OP_DELETE == op || OP_TEST == op) {
429
430 /*
431 * Most of these deal with a specific directory.
432 * Jump into that directory first.
433 */
434 if (OP_TEST != op && 0 == set_basedir(path_arg, 1))
435 goto out;
436
437 dba = nodb ? dba_new(128) : dba_read(MANDOC_DB);
438 if (dba != NULL) {
439 /*
440 * The existing database is usable. Process
441 * all files specified on the command-line.
442 */
443 #if HAVE_PLEDGE
444 if (!nodb) {
445 if (pledge("stdio rpath wpath cpath fattr flock", NULL) == -1) {
446 warn("pledge");
447 exitcode = (int)MANDOCLEVEL_SYSERR;
448 goto out;
449 }
450 }
451 #endif
452 use_all = 1;
453 for (i = 0; i < argc; i++)
454 filescan(argv[i]);
455 if (nodb == 0)
456 dbprune(dba);
457 } else {
458 /* Database missing or corrupt. */
459 if (op != OP_UPDATE || errno != ENOENT)
460 say(MANDOC_DB, "%s: Automatically recreating"
461 " from scratch", strerror(errno));
462 exitcode = (int)MANDOCLEVEL_OK;
463 op = OP_DEFAULT;
464 if (0 == treescan())
465 goto out;
466 dba = dba_new(128);
467 }
468 if (OP_DELETE != op)
469 mpages_merge(dba, mp);
470 if (nodb == 0)
471 dbwrite(dba);
472 dba_free(dba);
473 } else {
474 /*
475 * If we have arguments, use them as our manpaths.
476 * If we don't, use man.conf(5).
477 */
478 if (argc > 0) {
479 conf.manpath.paths = mandoc_reallocarray(NULL,
480 argc, sizeof(char *));
481 conf.manpath.sz = (size_t)argc;
482 for (i = 0; i < argc; i++)
483 conf.manpath.paths[i] = mandoc_strdup(argv[i]);
484 } else
485 manconf_parse(&conf, path_arg, NULL, NULL);
486
487 if (conf.manpath.sz == 0) {
488 exitcode = (int)MANDOCLEVEL_BADARG;
489 say("", "Empty manpath");
490 }
491
492 /*
493 * First scan the tree rooted at a base directory, then
494 * build a new database and finally move it into place.
495 * Ignore zero-length directories and strip trailing
496 * slashes.
497 */
498 for (j = 0; j < conf.manpath.sz; j++) {
499 sz = strlen(conf.manpath.paths[j]);
500 if (sz && conf.manpath.paths[j][sz - 1] == '/')
501 conf.manpath.paths[j][--sz] = '\0';
502 if (0 == sz)
503 continue;
504
505 if (j) {
506 mandoc_ohash_init(&mpages, 6,
507 offsetof(struct mpage, inodev));
508 mandoc_ohash_init(&mlinks, 6,
509 offsetof(struct mlink, file));
510 }
511
512 if ( ! set_basedir(conf.manpath.paths[j], argc > 0))
513 continue;
514 if (0 == treescan())
515 continue;
516 dba = dba_new(128);
517 mpages_merge(dba, mp);
518 if (nodb == 0)
519 dbwrite(dba);
520 dba_free(dba);
521
522 if (j + 1 < conf.manpath.sz) {
523 mpages_free();
524 ohash_delete(&mpages);
525 ohash_delete(&mlinks);
526 }
527 }
528 }
529 out:
530 manconf_free(&conf);
531 mparse_free(mp);
532 mchars_free();
533 mpages_free();
534 ohash_delete(&mpages);
535 ohash_delete(&mlinks);
536 return exitcode;
537 usage:
538 progname = getprogname();
539 fprintf(stderr, "usage: %s [-aDnpQ] [-C file] [-Tutf8]\n"
540 " %s [-aDnpQ] [-Tutf8] dir ...\n"
541 " %s [-DnpQ] [-Tutf8] -d dir [file ...]\n"
542 " %s [-Dnp] -u dir [file ...]\n"
543 " %s [-Q] -t file ...\n",
544 progname, progname, progname, progname, progname);
545
546 return (int)MANDOCLEVEL_BADARG;
547 }
548
549 /*
550 * To get a singly linked list in alpha order while inserting entries
551 * at the beginning, process directory entries in reverse alpha order.
552 */
553 static int
554 #if HAVE_FTS_COMPARE_CONST
555 fts_compare(const FTSENT *const *a, const FTSENT *const *b)
556 #else
557 fts_compare(const FTSENT **a, const FTSENT **b)
558 #endif
559 {
560 return -strcmp((*a)->fts_name, (*b)->fts_name);
561 }
562
563 /*
564 * Scan a directory tree rooted at "basedir" for manpages.
565 * We use fts(), scanning directory parts along the way for clues to our
566 * section and architecture.
567 *
568 * If use_all has been specified, grok all files.
569 * If not, sanitise paths to the following:
570 *
571 * [./]man*[/<arch>]/<name>.<section>
572 * or
573 * [./]cat<section>[/<arch>]/<name>.0
574 *
575 * TODO: accommodate for multi-language directories.
576 */
577 static int
578 treescan(void)
579 {
580 char buf[PATH_MAX];
581 FTS *f;
582 FTSENT *ff;
583 struct mlink *mlink;
584 int gzip;
585 enum form dform;
586 char *dsec, *arch, *fsec, *cp;
587 const char *path;
588 const char *argv[2];
589
590 argv[0] = ".";
591 argv[1] = (char *)NULL;
592
593 f = fts_open((char * const *)argv, FTS_PHYSICAL | FTS_NOCHDIR,
594 fts_compare);
595 if (f == NULL) {
596 exitcode = (int)MANDOCLEVEL_SYSERR;
597 say("", "&fts_open");
598 return 0;
599 }
600
601 dsec = arch = NULL;
602 dform = FORM_NONE;
603
604 while ((ff = fts_read(f)) != NULL) {
605 path = ff->fts_path + 2;
606 switch (ff->fts_info) {
607
608 /*
609 * Symbolic links require various sanity checks,
610 * then get handled just like regular files.
611 */
612 case FTS_SL:
613 if (realpath(path, buf) == NULL) {
614 if (warnings)
615 say(path, "&realpath");
616 continue;
617 }
618 if (strstr(buf, basedir) != buf
619 #ifdef HOMEBREWDIR
620 && strstr(buf, HOMEBREWDIR) != buf
621 #endif
622 ) {
623 if (warnings) say("",
624 "%s: outside base directory", buf);
625 continue;
626 }
627 /* Use logical inode to avoid mpages dupe. */
628 if (stat(path, ff->fts_statp) == -1) {
629 if (warnings)
630 say(path, "&stat");
631 continue;
632 }
633 /* FALLTHROUGH */
634
635 /*
636 * If we're a regular file, add an mlink by using the
637 * stored directory data and handling the filename.
638 */
639 case FTS_F:
640 if ( ! strcmp(path, MANDOC_DB))
641 continue;
642 if ( ! use_all && ff->fts_level < 2) {
643 if (warnings)
644 say(path, "Extraneous file");
645 continue;
646 }
647 gzip = 0;
648 fsec = NULL;
649 while (fsec == NULL) {
650 fsec = strrchr(ff->fts_name, '.');
651 if (fsec == NULL || strcmp(fsec+1, "gz"))
652 break;
653 gzip = 1;
654 *fsec = '\0';
655 fsec = NULL;
656 }
657 if (fsec == NULL) {
658 if ( ! use_all) {
659 if (warnings)
660 say(path,
661 "No filename suffix");
662 continue;
663 }
664 } else if ( ! strcmp(++fsec, "html")) {
665 if (warnings)
666 say(path, "Skip html");
667 continue;
668 } else if ( ! strcmp(fsec, "ps")) {
669 if (warnings)
670 say(path, "Skip ps");
671 continue;
672 } else if ( ! strcmp(fsec, "pdf")) {
673 if (warnings)
674 say(path, "Skip pdf");
675 continue;
676 } else if ( ! use_all &&
677 ((dform == FORM_SRC &&
678 strncmp(fsec, dsec, strlen(dsec))) ||
679 (dform == FORM_CAT && strcmp(fsec, "0")))) {
680 if (warnings)
681 say(path, "Wrong filename suffix");
682 continue;
683 } else
684 fsec[-1] = '\0';
685
686 mlink = mandoc_calloc(1, sizeof(struct mlink));
687 if (strlcpy(mlink->file, path,
688 sizeof(mlink->file)) >=
689 sizeof(mlink->file)) {
690 say(path, "Filename too long");
691 free(mlink);
692 continue;
693 }
694 mlink->dform = dform;
695 mlink->dsec = dsec;
696 mlink->arch = arch;
697 mlink->name = ff->fts_name;
698 mlink->fsec = fsec;
699 mlink->gzip = gzip;
700 mlink_add(mlink, ff->fts_statp);
701 continue;
702
703 case FTS_D:
704 case FTS_DP:
705 break;
706
707 default:
708 if (warnings)
709 say(path, "Not a regular file");
710 continue;
711 }
712
713 switch (ff->fts_level) {
714 case 0:
715 /* Ignore the root directory. */
716 break;
717 case 1:
718 /*
719 * This might contain manX/ or catX/.
720 * Try to infer this from the name.
721 * If we're not in use_all, enforce it.
722 */
723 cp = ff->fts_name;
724 if (ff->fts_info == FTS_DP) {
725 dform = FORM_NONE;
726 dsec = NULL;
727 break;
728 }
729
730 if ( ! strncmp(cp, "man", 3)) {
731 dform = FORM_SRC;
732 dsec = cp + 3;
733 } else if ( ! strncmp(cp, "cat", 3)) {
734 dform = FORM_CAT;
735 dsec = cp + 3;
736 } else {
737 dform = FORM_NONE;
738 dsec = NULL;
739 }
740
741 if (dsec != NULL || use_all)
742 break;
743
744 if (warnings)
745 say(path, "Unknown directory part");
746 fts_set(f, ff, FTS_SKIP);
747 break;
748 case 2:
749 /*
750 * Possibly our architecture.
751 * If we're descending, keep tabs on it.
752 */
753 if (ff->fts_info != FTS_DP && dsec != NULL)
754 arch = ff->fts_name;
755 else
756 arch = NULL;
757 break;
758 default:
759 if (ff->fts_info == FTS_DP || use_all)
760 break;
761 if (warnings)
762 say(path, "Extraneous directory part");
763 fts_set(f, ff, FTS_SKIP);
764 break;
765 }
766 }
767
768 fts_close(f);
769 return 1;
770 }
771
772 /*
773 * Add a file to the mlinks table.
774 * Do not verify that it's a "valid" looking manpage (we'll do that
775 * later).
776 *
777 * Try to infer the manual section, architecture, and page name from the
778 * path, assuming it looks like
779 *
780 * [./]man*[/<arch>]/<name>.<section>
781 * or
782 * [./]cat<section>[/<arch>]/<name>.0
783 *
784 * See treescan() for the fts(3) version of this.
785 */
786 static void
787 filescan(const char *file)
788 {
789 char buf[PATH_MAX];
790 struct stat st;
791 struct mlink *mlink;
792 char *p, *start;
793
794 assert(use_all);
795
796 if (0 == strncmp(file, "./", 2))
797 file += 2;
798
799 /*
800 * We have to do lstat(2) before realpath(3) loses
801 * the information whether this is a symbolic link.
802 * We need to know that because for symbolic links,
803 * we want to use the orginal file name, while for
804 * regular files, we want to use the real path.
805 */
806 if (-1 == lstat(file, &st)) {
807 exitcode = (int)MANDOCLEVEL_BADARG;
808 say(file, "&lstat");
809 return;
810 } else if (0 == ((S_IFREG | S_IFLNK) & st.st_mode)) {
811 exitcode = (int)MANDOCLEVEL_BADARG;
812 say(file, "Not a regular file");
813 return;
814 }
815
816 /*
817 * We have to resolve the file name to the real path
818 * in any case for the base directory check.
819 */
820 if (NULL == realpath(file, buf)) {
821 exitcode = (int)MANDOCLEVEL_BADARG;
822 say(file, "&realpath");
823 return;
824 }
825
826 if (OP_TEST == op)
827 start = buf;
828 else if (strstr(buf, basedir) == buf)
829 start = buf + strlen(basedir);
830 #ifdef HOMEBREWDIR
831 else if (strstr(buf, HOMEBREWDIR) == buf)
832 start = buf;
833 #endif
834 else {
835 exitcode = (int)MANDOCLEVEL_BADARG;
836 say("", "%s: outside base directory", buf);
837 return;
838 }
839
840 /*
841 * Now we are sure the file is inside our tree.
842 * If it is a symbolic link, ignore the real path
843 * and use the original name.
844 * This implies passing stuff like "cat1/../man1/foo.1"
845 * on the command line won't work. So don't do that.
846 * Note the stat(2) can still fail if the link target
847 * doesn't exist.
848 */
849 if (S_IFLNK & st.st_mode) {
850 if (-1 == stat(buf, &st)) {
851 exitcode = (int)MANDOCLEVEL_BADARG;
852 say(file, "&stat");
853 return;
854 }
855 if (strlcpy(buf, file, sizeof(buf)) >= sizeof(buf)) {
856 say(file, "Filename too long");
857 return;
858 }
859 start = buf;
860 if (OP_TEST != op && strstr(buf, basedir) == buf)
861 start += strlen(basedir);
862 }
863
864 mlink = mandoc_calloc(1, sizeof(struct mlink));
865 mlink->dform = FORM_NONE;
866 if (strlcpy(mlink->file, start, sizeof(mlink->file)) >=
867 sizeof(mlink->file)) {
868 say(start, "Filename too long");
869 free(mlink);
870 return;
871 }
872
873 /*
874 * First try to guess our directory structure.
875 * If we find a separator, try to look for man* or cat*.
876 * If we find one of these and what's underneath is a directory,
877 * assume it's an architecture.
878 */
879 if (NULL != (p = strchr(start, '/'))) {
880 *p++ = '\0';
881 if (0 == strncmp(start, "man", 3)) {
882 mlink->dform = FORM_SRC;
883 mlink->dsec = start + 3;
884 } else if (0 == strncmp(start, "cat", 3)) {
885 mlink->dform = FORM_CAT;
886 mlink->dsec = start + 3;
887 }
888
889 start = p;
890 if (NULL != mlink->dsec && NULL != (p = strchr(start, '/'))) {
891 *p++ = '\0';
892 mlink->arch = start;
893 start = p;
894 }
895 }
896
897 /*
898 * Now check the file suffix.
899 * Suffix of `.0' indicates a catpage, `.1-9' is a manpage.
900 */
901 p = strrchr(start, '\0');
902 while (p-- > start && '/' != *p && '.' != *p)
903 /* Loop. */ ;
904
905 if ('.' == *p) {
906 *p++ = '\0';
907 mlink->fsec = p;
908 }
909
910 /*
911 * Now try to parse the name.
912 * Use the filename portion of the path.
913 */
914 mlink->name = start;
915 if (NULL != (p = strrchr(start, '/'))) {
916 mlink->name = p + 1;
917 *p = '\0';
918 }
919 mlink_add(mlink, &st);
920 }
921
922 static void
923 mlink_add(struct mlink *mlink, const struct stat *st)
924 {
925 struct inodev inodev;
926 struct mpage *mpage;
927 unsigned int slot;
928
929 assert(NULL != mlink->file);
930
931 mlink->dsec = mandoc_strdup(mlink->dsec ? mlink->dsec : "");
932 mlink->arch = mandoc_strdup(mlink->arch ? mlink->arch : "");
933 mlink->name = mandoc_strdup(mlink->name ? mlink->name : "");
934 mlink->fsec = mandoc_strdup(mlink->fsec ? mlink->fsec : "");
935
936 if ('0' == *mlink->fsec) {
937 free(mlink->fsec);
938 mlink->fsec = mandoc_strdup(mlink->dsec);
939 mlink->fform = FORM_CAT;
940 } else if ('1' <= *mlink->fsec && '9' >= *mlink->fsec)
941 mlink->fform = FORM_SRC;
942 else
943 mlink->fform = FORM_NONE;
944
945 slot = ohash_qlookup(&mlinks, mlink->file);
946 assert(NULL == ohash_find(&mlinks, slot));
947 ohash_insert(&mlinks, slot, mlink);
948
949 memset(&inodev, 0, sizeof(inodev)); /* Clear padding. */
950 inodev.st_ino = st->st_ino;
951 inodev.st_dev = st->st_dev;
952 slot = ohash_lookup_memory(&mpages, (char *)&inodev,
953 sizeof(struct inodev), inodev.st_ino);
954 mpage = ohash_find(&mpages, slot);
955 if (NULL == mpage) {
956 mpage = mandoc_calloc(1, sizeof(struct mpage));
957 mpage->inodev.st_ino = inodev.st_ino;
958 mpage->inodev.st_dev = inodev.st_dev;
959 mpage->form = FORM_NONE;
960 mpage->next = mpage_head;
961 mpage_head = mpage;
962 ohash_insert(&mpages, slot, mpage);
963 } else
964 mlink->next = mpage->mlinks;
965 mpage->mlinks = mlink;
966 mlink->mpage = mpage;
967 }
968
969 static void
970 mlink_free(struct mlink *mlink)
971 {
972
973 free(mlink->dsec);
974 free(mlink->arch);
975 free(mlink->name);
976 free(mlink->fsec);
977 free(mlink);
978 }
979
980 static void
981 mpages_free(void)
982 {
983 struct mpage *mpage;
984 struct mlink *mlink;
985
986 while ((mpage = mpage_head) != NULL) {
987 while ((mlink = mpage->mlinks) != NULL) {
988 mpage->mlinks = mlink->next;
989 mlink_free(mlink);
990 }
991 mpage_head = mpage->next;
992 free(mpage->sec);
993 free(mpage->arch);
994 free(mpage->title);
995 free(mpage->desc);
996 free(mpage);
997 }
998 }
999
1000 /*
1001 * For each mlink to the mpage, check whether the path looks like
1002 * it is formatted, and if it does, check whether a source manual
1003 * exists by the same name, ignoring the suffix.
1004 * If both conditions hold, drop the mlink.
1005 */
1006 static void
1007 mlinks_undupe(struct mpage *mpage)
1008 {
1009 char buf[PATH_MAX];
1010 struct mlink **prev;
1011 struct mlink *mlink;
1012 char *bufp;
1013
1014 mpage->form = FORM_CAT;
1015 prev = &mpage->mlinks;
1016 while (NULL != (mlink = *prev)) {
1017 if (FORM_CAT != mlink->dform) {
1018 mpage->form = FORM_NONE;
1019 goto nextlink;
1020 }
1021 (void)strlcpy(buf, mlink->file, sizeof(buf));
1022 bufp = strstr(buf, "cat");
1023 assert(NULL != bufp);
1024 memcpy(bufp, "man", 3);
1025 if (NULL != (bufp = strrchr(buf, '.')))
1026 *++bufp = '\0';
1027 (void)strlcat(buf, mlink->dsec, sizeof(buf));
1028 if (NULL == ohash_find(&mlinks,
1029 ohash_qlookup(&mlinks, buf)))
1030 goto nextlink;
1031 if (warnings)
1032 say(mlink->file, "Man source exists: %s", buf);
1033 if (use_all)
1034 goto nextlink;
1035 *prev = mlink->next;
1036 mlink_free(mlink);
1037 continue;
1038 nextlink:
1039 prev = &(*prev)->next;
1040 }
1041 }
1042
1043 static void
1044 mlink_check(struct mpage *mpage, struct mlink *mlink)
1045 {
1046 struct str *str;
1047 unsigned int slot;
1048
1049 /*
1050 * Check whether the manual section given in a file
1051 * agrees with the directory where the file is located.
1052 * Some manuals have suffixes like (3p) on their
1053 * section number either inside the file or in the
1054 * directory name, some are linked into more than one
1055 * section, like encrypt(1) = makekey(8).
1056 */
1057
1058 if (FORM_SRC == mpage->form &&
1059 strcasecmp(mpage->sec, mlink->dsec))
1060 say(mlink->file, "Section \"%s\" manual in %s directory",
1061 mpage->sec, mlink->dsec);
1062
1063 /*
1064 * Manual page directories exist for each kernel
1065 * architecture as returned by machine(1).
1066 * However, many manuals only depend on the
1067 * application architecture as returned by arch(1).
1068 * For example, some (2/ARM) manuals are shared
1069 * across the "armish" and "zaurus" kernel
1070 * architectures.
1071 * A few manuals are even shared across completely
1072 * different architectures, for example fdformat(1)
1073 * on amd64, i386, and sparc64.
1074 */
1075
1076 if (strcasecmp(mpage->arch, mlink->arch))
1077 say(mlink->file, "Architecture \"%s\" manual in "
1078 "\"%s\" directory", mpage->arch, mlink->arch);
1079
1080 /*
1081 * XXX
1082 * parse_cat() doesn't set NAME_TITLE yet.
1083 */
1084
1085 if (FORM_CAT == mpage->form)
1086 return;
1087
1088 /*
1089 * Check whether this mlink
1090 * appears as a name in the NAME section.
1091 */
1092
1093 slot = ohash_qlookup(&names, mlink->name);
1094 str = ohash_find(&names, slot);
1095 assert(NULL != str);
1096 if ( ! (NAME_TITLE & str->mask))
1097 say(mlink->file, "Name missing in NAME section");
1098 }
1099
1100 /*
1101 * Run through the files in the global vector "mpages"
1102 * and add them to the database specified in "basedir".
1103 *
1104 * This handles the parsing scheme itself, using the cues of directory
1105 * and filename to determine whether the file is parsable or not.
1106 */
1107 static void
1108 mpages_merge(struct dba *dba, struct mparse *mp)
1109 {
1110 struct mpage *mpage, *mpage_dest;
1111 struct mlink *mlink, *mlink_dest;
1112 struct roff_man *man;
1113 char *sodest;
1114 char *cp;
1115 int fd;
1116
1117 for (mpage = mpage_head; mpage != NULL; mpage = mpage->next) {
1118 mlinks_undupe(mpage);
1119 if ((mlink = mpage->mlinks) == NULL)
1120 continue;
1121
1122 name_mask = NAME_MASK;
1123 mandoc_ohash_init(&names, 4, offsetof(struct str, key));
1124 mandoc_ohash_init(&strings, 6, offsetof(struct str, key));
1125 mparse_reset(mp);
1126 man = NULL;
1127 sodest = NULL;
1128
1129 if ((fd = mparse_open(mp, mlink->file)) == -1) {
1130 say(mlink->file, "&open");
1131 goto nextpage;
1132 }
1133
1134 /*
1135 * Interpret the file as mdoc(7) or man(7) source
1136 * code, unless it is known to be formatted.
1137 */
1138 if (mlink->dform != FORM_CAT || mlink->fform != FORM_CAT) {
1139 mparse_readfd(mp, fd, mlink->file);
1140 close(fd);
1141 mparse_result(mp, &man, &sodest);
1142 }
1143
1144 if (sodest != NULL) {
1145 mlink_dest = ohash_find(&mlinks,
1146 ohash_qlookup(&mlinks, sodest));
1147 if (mlink_dest == NULL) {
1148 mandoc_asprintf(&cp, "%s.gz", sodest);
1149 mlink_dest = ohash_find(&mlinks,
1150 ohash_qlookup(&mlinks, cp));
1151 free(cp);
1152 }
1153 if (mlink_dest != NULL) {
1154
1155 /* The .so target exists. */
1156
1157 mpage_dest = mlink_dest->mpage;
1158 while (1) {
1159 mlink->mpage = mpage_dest;
1160
1161 /*
1162 * If the target was already
1163 * processed, add the links
1164 * to the database now.
1165 * Otherwise, this will
1166 * happen when we come
1167 * to the target.
1168 */
1169
1170 if (mpage_dest->dba != NULL)
1171 dbadd_mlink(mlink);
1172
1173 if (mlink->next == NULL)
1174 break;
1175 mlink = mlink->next;
1176 }
1177
1178 /* Move all links to the target. */
1179
1180 mlink->next = mlink_dest->next;
1181 mlink_dest->next = mpage->mlinks;
1182 mpage->mlinks = NULL;
1183 }
1184 goto nextpage;
1185 } else if (man != NULL && man->macroset == MACROSET_MDOC) {
1186 mdoc_validate(man);
1187 mpage->form = FORM_SRC;
1188 mpage->sec = man->meta.msec;
1189 mpage->sec = mandoc_strdup(
1190 mpage->sec == NULL ? "" : mpage->sec);
1191 mpage->arch = man->meta.arch;
1192 mpage->arch = mandoc_strdup(
1193 mpage->arch == NULL ? "" : mpage->arch);
1194 mpage->title = mandoc_strdup(man->meta.title);
1195 } else if (man != NULL && man->macroset == MACROSET_MAN) {
1196 man_validate(man);
1197 mpage->form = FORM_SRC;
1198 mpage->sec = mandoc_strdup(man->meta.msec);
1199 mpage->arch = mandoc_strdup(mlink->arch);
1200 mpage->title = mandoc_strdup(man->meta.title);
1201 } else {
1202 mpage->form = FORM_CAT;
1203 mpage->sec = mandoc_strdup(mlink->dsec);
1204 mpage->arch = mandoc_strdup(mlink->arch);
1205 mpage->title = mandoc_strdup(mlink->name);
1206 }
1207
1208 assert(mpage->desc == NULL);
1209 if (man != NULL && man->macroset == MACROSET_MDOC)
1210 parse_mdoc(mpage, &man->meta, man->first);
1211 else if (man != NULL)
1212 parse_man(mpage, &man->meta, man->first);
1213 else
1214 parse_cat(mpage, fd);
1215 if (mpage->desc == NULL)
1216 mpage->desc = mandoc_strdup(mpage->mlinks->name);
1217
1218 if (warnings && !use_all)
1219 for (mlink = mpage->mlinks; mlink;
1220 mlink = mlink->next)
1221 mlink_check(mpage, mlink);
1222
1223 dbadd(dba, mpage);
1224 mlink = mpage->mlinks;
1225
1226 nextpage:
1227 ohash_delete(&strings);
1228 ohash_delete(&names);
1229 }
1230 }
1231
1232 static void
1233 parse_cat(struct mpage *mpage, int fd)
1234 {
1235 FILE *stream;
1236 char *line, *p, *title;
1237 size_t linesz, plen, titlesz;
1238 ssize_t len;
1239 int offs;
1240
1241 stream = (-1 == fd) ?
1242 fopen(mpage->mlinks->file, "r") :
1243 fdopen(fd, "r");
1244 if (NULL == stream) {
1245 if (-1 != fd)
1246 close(fd);
1247 if (warnings)
1248 say(mpage->mlinks->file, "&fopen");
1249 return;
1250 }
1251
1252 line = NULL;
1253 linesz = 0;
1254
1255 /* Skip to first blank line. */
1256
1257 while (getline(&line, &linesz, stream) != -1)
1258 if (*line == '\n')
1259 break;
1260
1261 /*
1262 * Assume the first line that is not indented
1263 * is the first section header. Skip to it.
1264 */
1265
1266 while (getline(&line, &linesz, stream) != -1)
1267 if (*line != '\n' && *line != ' ')
1268 break;
1269
1270 /*
1271 * Read up until the next section into a buffer.
1272 * Strip the leading and trailing newline from each read line,
1273 * appending a trailing space.
1274 * Ignore empty (whitespace-only) lines.
1275 */
1276
1277 titlesz = 0;
1278 title = NULL;
1279
1280 while ((len = getline(&line, &linesz, stream)) != -1) {
1281 if (*line != ' ')
1282 break;
1283 offs = 0;
1284 while (isspace((unsigned char)line[offs]))
1285 offs++;
1286 if (line[offs] == '\0')
1287 continue;
1288 title = mandoc_realloc(title, titlesz + len - offs);
1289 memcpy(title + titlesz, line + offs, len - offs);
1290 titlesz += len - offs;
1291 title[titlesz - 1] = ' ';
1292 }
1293 free(line);
1294
1295 /*
1296 * If no page content can be found, or the input line
1297 * is already the next section header, or there is no
1298 * trailing newline, reuse the page title as the page
1299 * description.
1300 */
1301
1302 if (NULL == title || '\0' == *title) {
1303 if (warnings)
1304 say(mpage->mlinks->file,
1305 "Cannot find NAME section");
1306 fclose(stream);
1307 free(title);
1308 return;
1309 }
1310
1311 title[titlesz - 1] = '\0';
1312
1313 /*
1314 * Skip to the first dash.
1315 * Use the remaining line as the description (no more than 70
1316 * bytes).
1317 */
1318
1319 if (NULL != (p = strstr(title, "- "))) {
1320 for (p += 2; ' ' == *p || '\b' == *p; p++)
1321 /* Skip to next word. */ ;
1322 } else {
1323 if (warnings)
1324 say(mpage->mlinks->file,
1325 "No dash in title line");
1326 p = title;
1327 }
1328
1329 plen = strlen(p);
1330
1331 /* Strip backspace-encoding from line. */
1332
1333 while (NULL != (line = memchr(p, '\b', plen))) {
1334 len = line - p;
1335 if (0 == len) {
1336 memmove(line, line + 1, plen--);
1337 continue;
1338 }
1339 memmove(line - 1, line + 1, plen - len);
1340 plen -= 2;
1341 }
1342
1343 mpage->desc = mandoc_strdup(p);
1344 fclose(stream);
1345 free(title);
1346 }
1347
1348 /*
1349 * Put a type/word pair into the word database for this particular file.
1350 */
1351 static void
1352 putkey(const struct mpage *mpage, char *value, uint64_t type)
1353 {
1354 putkeys(mpage, value, strlen(value), type);
1355 }
1356
1357 /*
1358 * Grok all nodes at or below a certain mdoc node into putkey().
1359 */
1360 static void
1361 putmdockey(const struct mpage *mpage,
1362 const struct roff_node *n, uint64_t m)
1363 {
1364
1365 for ( ; NULL != n; n = n->next) {
1366 if (NULL != n->child)
1367 putmdockey(mpage, n->child, m);
1368 if (n->type == ROFFT_TEXT)
1369 putkey(mpage, n->string, m);
1370 }
1371 }
1372
1373 static void
1374 parse_man(struct mpage *mpage, const struct roff_meta *meta,
1375 const struct roff_node *n)
1376 {
1377 const struct roff_node *head, *body;
1378 char *start, *title;
1379 char byte;
1380 size_t sz;
1381
1382 if (n == NULL)
1383 return;
1384
1385 /*
1386 * We're only searching for one thing: the first text child in
1387 * the BODY of a NAME section. Since we don't keep track of
1388 * sections in -man, run some hoops to find out whether we're in
1389 * the correct section or not.
1390 */
1391
1392 if (n->type == ROFFT_BODY && n->tok == MAN_SH) {
1393 body = n;
1394 if ((head = body->parent->head) != NULL &&
1395 (head = head->child) != NULL &&
1396 head->next == NULL &&
1397 head->type == ROFFT_TEXT &&
1398 strcmp(head->string, "NAME") == 0 &&
1399 body->child != NULL) {
1400
1401 /*
1402 * Suck the entire NAME section into memory.
1403 * Yes, we might run away.
1404 * But too many manuals have big, spread-out
1405 * NAME sections over many lines.
1406 */
1407
1408 title = NULL;
1409 deroff(&title, body);
1410 if (NULL == title)
1411 return;
1412
1413 /*
1414 * Go through a special heuristic dance here.
1415 * Conventionally, one or more manual names are
1416 * comma-specified prior to a whitespace, then a
1417 * dash, then a description. Try to puzzle out
1418 * the name parts here.
1419 */
1420
1421 start = title;
1422 for ( ;; ) {
1423 sz = strcspn(start, " ,");
1424 if ('\0' == start[sz])
1425 break;
1426
1427 byte = start[sz];
1428 start[sz] = '\0';
1429
1430 /*
1431 * Assume a stray trailing comma in the
1432 * name list if a name begins with a dash.
1433 */
1434
1435 if ('-' == start[0] ||
1436 ('\\' == start[0] && '-' == start[1]))
1437 break;
1438
1439 putkey(mpage, start, NAME_TITLE);
1440 if ( ! (mpage->name_head_done ||
1441 strcasecmp(start, meta->title))) {
1442 putkey(mpage, start, NAME_HEAD);
1443 mpage->name_head_done = 1;
1444 }
1445
1446 if (' ' == byte) {
1447 start += sz + 1;
1448 break;
1449 }
1450
1451 assert(',' == byte);
1452 start += sz + 1;
1453 while (' ' == *start)
1454 start++;
1455 }
1456
1457 if (start == title) {
1458 putkey(mpage, start, NAME_TITLE);
1459 if ( ! (mpage->name_head_done ||
1460 strcasecmp(start, meta->title))) {
1461 putkey(mpage, start, NAME_HEAD);
1462 mpage->name_head_done = 1;
1463 }
1464 free(title);
1465 return;
1466 }
1467
1468 while (isspace((unsigned char)*start))
1469 start++;
1470
1471 if (0 == strncmp(start, "-", 1))
1472 start += 1;
1473 else if (0 == strncmp(start, "\\-\\-", 4))
1474 start += 4;
1475 else if (0 == strncmp(start, "\\-", 2))
1476 start += 2;
1477 else if (0 == strncmp(start, "\\(en", 4))
1478 start += 4;
1479 else if (0 == strncmp(start, "\\(em", 4))
1480 start += 4;
1481
1482 while (' ' == *start)
1483 start++;
1484
1485 mpage->desc = mandoc_strdup(start);
1486 free(title);
1487 return;
1488 }
1489 }
1490
1491 for (n = n->child; n; n = n->next) {
1492 if (NULL != mpage->desc)
1493 break;
1494 parse_man(mpage, meta, n);
1495 }
1496 }
1497
1498 static void
1499 parse_mdoc(struct mpage *mpage, const struct roff_meta *meta,
1500 const struct roff_node *n)
1501 {
1502
1503 assert(NULL != n);
1504 for (n = n->child; NULL != n; n = n->next) {
1505 switch (n->type) {
1506 case ROFFT_ELEM:
1507 case ROFFT_BLOCK:
1508 case ROFFT_HEAD:
1509 case ROFFT_BODY:
1510 case ROFFT_TAIL:
1511 if (NULL != mdocs[n->tok].fp)
1512 if (0 == (*mdocs[n->tok].fp)(mpage, meta, n))
1513 break;
1514 if (mdocs[n->tok].mask)
1515 putmdockey(mpage, n->child,
1516 mdocs[n->tok].mask);
1517 break;
1518 default:
1519 assert(n->type != ROFFT_ROOT);
1520 continue;
1521 }
1522 if (NULL != n->child)
1523 parse_mdoc(mpage, meta, n);
1524 }
1525 }
1526
1527 static int
1528 parse_mdoc_Fd(struct mpage *mpage, const struct roff_meta *meta,
1529 const struct roff_node *n)
1530 {
1531 char *start, *end;
1532 size_t sz;
1533
1534 if (SEC_SYNOPSIS != n->sec ||
1535 NULL == (n = n->child) ||
1536 n->type != ROFFT_TEXT)
1537 return 0;
1538
1539 /*
1540 * Only consider those `Fd' macro fields that begin with an
1541 * "inclusion" token (versus, e.g., #define).
1542 */
1543
1544 if (strcmp("#include", n->string))
1545 return 0;
1546
1547 if ((n = n->next) == NULL || n->type != ROFFT_TEXT)
1548 return 0;
1549
1550 /*
1551 * Strip away the enclosing angle brackets and make sure we're
1552 * not zero-length.
1553 */
1554
1555 start = n->string;
1556 if ('<' == *start || '"' == *start)
1557 start++;
1558
1559 if (0 == (sz = strlen(start)))
1560 return 0;
1561
1562 end = &start[(int)sz - 1];
1563 if ('>' == *end || '"' == *end)
1564 end--;
1565
1566 if (end > start)
1567 putkeys(mpage, start, end - start + 1, TYPE_In);
1568 return 0;
1569 }
1570
1571 static void
1572 parse_mdoc_fname(struct mpage *mpage, const struct roff_node *n)
1573 {
1574 char *cp;
1575 size_t sz;
1576
1577 if (n->type != ROFFT_TEXT)
1578 return;
1579
1580 /* Skip function pointer punctuation. */
1581
1582 cp = n->string;
1583 while (*cp == '(' || *cp == '*')
1584 cp++;
1585 sz = strcspn(cp, "()");
1586
1587 putkeys(mpage, cp, sz, TYPE_Fn);
1588 if (n->sec == SEC_SYNOPSIS)
1589 putkeys(mpage, cp, sz, NAME_SYN);
1590 }
1591
1592 static int
1593 parse_mdoc_Fn(struct mpage *mpage, const struct roff_meta *meta,
1594 const struct roff_node *n)
1595 {
1596
1597 if (n->child == NULL)
1598 return 0;
1599
1600 parse_mdoc_fname(mpage, n->child);
1601
1602 for (n = n->child->next; n != NULL; n = n->next)
1603 if (n->type == ROFFT_TEXT)
1604 putkey(mpage, n->string, TYPE_Fa);
1605
1606 return 0;
1607 }
1608
1609 static int
1610 parse_mdoc_Fo(struct mpage *mpage, const struct roff_meta *meta,
1611 const struct roff_node *n)
1612 {
1613
1614 if (n->type != ROFFT_HEAD)
1615 return 1;
1616
1617 if (n->child != NULL)
1618 parse_mdoc_fname(mpage, n->child);
1619
1620 return 0;
1621 }
1622
1623 static int
1624 parse_mdoc_Va(struct mpage *mpage, const struct roff_meta *meta,
1625 const struct roff_node *n)
1626 {
1627 char *cp;
1628
1629 if (n->type != ROFFT_ELEM && n->type != ROFFT_BODY)
1630 return 0;
1631
1632 if (n->child != NULL &&
1633 n->child->next == NULL &&
1634 n->child->type == ROFFT_TEXT)
1635 return 1;
1636
1637 cp = NULL;
1638 deroff(&cp, n);
1639 if (cp != NULL) {
1640 putkey(mpage, cp, TYPE_Vt | (n->tok == MDOC_Va ||
1641 n->type == ROFFT_BODY ? TYPE_Va : 0));
1642 free(cp);
1643 }
1644
1645 return 0;
1646 }
1647
1648 static int
1649 parse_mdoc_Xr(struct mpage *mpage, const struct roff_meta *meta,
1650 const struct roff_node *n)
1651 {
1652 char *cp;
1653
1654 if (NULL == (n = n->child))
1655 return 0;
1656
1657 if (NULL == n->next) {
1658 putkey(mpage, n->string, TYPE_Xr);
1659 return 0;
1660 }
1661
1662 mandoc_asprintf(&cp, "%s(%s)", n->string, n->next->string);
1663 putkey(mpage, cp, TYPE_Xr);
1664 free(cp);
1665 return 0;
1666 }
1667
1668 static int
1669 parse_mdoc_Nd(struct mpage *mpage, const struct roff_meta *meta,
1670 const struct roff_node *n)
1671 {
1672
1673 if (n->type == ROFFT_BODY)
1674 deroff(&mpage->desc, n);
1675 return 0;
1676 }
1677
1678 static int
1679 parse_mdoc_Nm(struct mpage *mpage, const struct roff_meta *meta,
1680 const struct roff_node *n)
1681 {
1682
1683 if (SEC_NAME == n->sec)
1684 putmdockey(mpage, n->child, NAME_TITLE);
1685 else if (n->sec == SEC_SYNOPSIS && n->type == ROFFT_HEAD) {
1686 if (n->child == NULL)
1687 putkey(mpage, meta->name, NAME_SYN);
1688 else
1689 putmdockey(mpage, n->child, NAME_SYN);
1690 }
1691 if ( ! (mpage->name_head_done ||
1692 n->child == NULL || n->child->string == NULL ||
1693 strcasecmp(n->child->string, meta->title))) {
1694 putkey(mpage, n->child->string, NAME_HEAD);
1695 mpage->name_head_done = 1;
1696 }
1697 return 0;
1698 }
1699
1700 static int
1701 parse_mdoc_Sh(struct mpage *mpage, const struct roff_meta *meta,
1702 const struct roff_node *n)
1703 {
1704
1705 return n->sec == SEC_CUSTOM && n->type == ROFFT_HEAD;
1706 }
1707
1708 static int
1709 parse_mdoc_head(struct mpage *mpage, const struct roff_meta *meta,
1710 const struct roff_node *n)
1711 {
1712
1713 return n->type == ROFFT_HEAD;
1714 }
1715
1716 /*
1717 * Add a string to the hash table for the current manual.
1718 * Each string has a bitmask telling which macros it belongs to.
1719 * When we finish the manual, we'll dump the table.
1720 */
1721 static void
1722 putkeys(const struct mpage *mpage, char *cp, size_t sz, uint64_t v)
1723 {
1724 struct ohash *htab;
1725 struct str *s;
1726 const char *end;
1727 unsigned int slot;
1728 int i, mustfree;
1729
1730 if (0 == sz)
1731 return;
1732
1733 mustfree = render_string(&cp, &sz);
1734
1735 if (TYPE_Nm & v) {
1736 htab = &names;
1737 v &= name_mask;
1738 if (v & NAME_FIRST)
1739 name_mask &= ~NAME_FIRST;
1740 if (debug > 1)
1741 say(mpage->mlinks->file,
1742 "Adding name %*s, bits=0x%llx", (int)sz, cp,
1743 (unsigned long long)v);
1744 } else {
1745 htab = &strings;
1746 if (debug > 1)
1747 for (i = 0; i < KEY_MAX; i++)
1748 if ((uint64_t)1 << i & v)
1749 say(mpage->mlinks->file,
1750 "Adding key %s=%*s",
1751 mansearch_keynames[i], (int)sz, cp);
1752 }
1753
1754 end = cp + sz;
1755 slot = ohash_qlookupi(htab, cp, &end);
1756 s = ohash_find(htab, slot);
1757
1758 if (NULL != s && mpage == s->mpage) {
1759 s->mask |= v;
1760 return;
1761 } else if (NULL == s) {
1762 s = mandoc_calloc(1, sizeof(struct str) + sz + 1);
1763 memcpy(s->key, cp, sz);
1764 ohash_insert(htab, slot, s);
1765 }
1766 s->mpage = mpage;
1767 s->mask = v;
1768
1769 if (mustfree)
1770 free(cp);
1771 }
1772
1773 /*
1774 * Take a Unicode codepoint and produce its UTF-8 encoding.
1775 * This isn't the best way to do this, but it works.
1776 * The magic numbers are from the UTF-8 packaging.
1777 * They're not as scary as they seem: read the UTF-8 spec for details.
1778 */
1779 static size_t
1780 utf8(unsigned int cp, char out[7])
1781 {
1782 size_t rc;
1783
1784 rc = 0;
1785 if (cp <= 0x0000007F) {
1786 rc = 1;
1787 out[0] = (char)cp;
1788 } else if (cp <= 0x000007FF) {
1789 rc = 2;
1790 out[0] = (cp >> 6 & 31) | 192;
1791 out[1] = (cp & 63) | 128;
1792 } else if (cp <= 0x0000FFFF) {
1793 rc = 3;
1794 out[0] = (cp >> 12 & 15) | 224;
1795 out[1] = (cp >> 6 & 63) | 128;
1796 out[2] = (cp & 63) | 128;
1797 } else if (cp <= 0x001FFFFF) {
1798 rc = 4;
1799 out[0] = (cp >> 18 & 7) | 240;
1800 out[1] = (cp >> 12 & 63) | 128;
1801 out[2] = (cp >> 6 & 63) | 128;
1802 out[3] = (cp & 63) | 128;
1803 } else if (cp <= 0x03FFFFFF) {
1804 rc = 5;
1805 out[0] = (cp >> 24 & 3) | 248;
1806 out[1] = (cp >> 18 & 63) | 128;
1807 out[2] = (cp >> 12 & 63) | 128;
1808 out[3] = (cp >> 6 & 63) | 128;
1809 out[4] = (cp & 63) | 128;
1810 } else if (cp <= 0x7FFFFFFF) {
1811 rc = 6;
1812 out[0] = (cp >> 30 & 1) | 252;
1813 out[1] = (cp >> 24 & 63) | 128;
1814 out[2] = (cp >> 18 & 63) | 128;
1815 out[3] = (cp >> 12 & 63) | 128;
1816 out[4] = (cp >> 6 & 63) | 128;
1817 out[5] = (cp & 63) | 128;
1818 } else
1819 return 0;
1820
1821 out[rc] = '\0';
1822 return rc;
1823 }
1824
1825 /*
1826 * If the string contains escape sequences,
1827 * replace it with an allocated rendering and return 1,
1828 * such that the caller can free it after use.
1829 * Otherwise, do nothing and return 0.
1830 */
1831 static int
1832 render_string(char **public, size_t *psz)
1833 {
1834 const char *src, *scp, *addcp, *seq;
1835 char *dst;
1836 size_t ssz, dsz, addsz;
1837 char utfbuf[7], res[6];
1838 int seqlen, unicode;
1839
1840 res[0] = '\\';
1841 res[1] = '\t';
1842 res[2] = ASCII_NBRSP;
1843 res[3] = ASCII_HYPH;
1844 res[4] = ASCII_BREAK;
1845 res[5] = '\0';
1846
1847 src = scp = *public;
1848 ssz = *psz;
1849 dst = NULL;
1850 dsz = 0;
1851
1852 while (scp < src + *psz) {
1853
1854 /* Leave normal characters unchanged. */
1855
1856 if (strchr(res, *scp) == NULL) {
1857 if (dst != NULL)
1858 dst[dsz++] = *scp;
1859 scp++;
1860 continue;
1861 }
1862
1863 /*
1864 * Found something that requires replacing,
1865 * make sure we have a destination buffer.
1866 */
1867
1868 if (dst == NULL) {
1869 dst = mandoc_malloc(ssz + 1);
1870 dsz = scp - src;
1871 memcpy(dst, src, dsz);
1872 }
1873
1874 /* Handle single-char special characters. */
1875
1876 switch (*scp) {
1877 case '\\':
1878 break;
1879 case '\t':
1880 case ASCII_NBRSP:
1881 dst[dsz++] = ' ';
1882 scp++;
1883 continue;
1884 case ASCII_HYPH:
1885 dst[dsz++] = '-';
1886 /* FALLTHROUGH */
1887 case ASCII_BREAK:
1888 scp++;
1889 continue;
1890 default:
1891 abort();
1892 }
1893
1894 /*
1895 * Found an escape sequence.
1896 * Read past the slash, then parse it.
1897 * Ignore everything except characters.
1898 */
1899
1900 scp++;
1901 if (mandoc_escape(&scp, &seq, &seqlen) != ESCAPE_SPECIAL)
1902 continue;
1903
1904 /*
1905 * Render the special character
1906 * as either UTF-8 or ASCII.
1907 */
1908
1909 if (write_utf8) {
1910 unicode = mchars_spec2cp(seq, seqlen);
1911 if (unicode <= 0)
1912 continue;
1913 addsz = utf8(unicode, utfbuf);
1914 if (addsz == 0)
1915 continue;
1916 addcp = utfbuf;
1917 } else {
1918 addcp = mchars_spec2str(seq, seqlen, &addsz);
1919 if (addcp == NULL)
1920 continue;
1921 if (*addcp == ASCII_NBRSP) {
1922 addcp = " ";
1923 addsz = 1;
1924 }
1925 }
1926
1927 /* Copy the rendered glyph into the stream. */
1928
1929 ssz += addsz;
1930 dst = mandoc_realloc(dst, ssz + 1);
1931 memcpy(dst + dsz, addcp, addsz);
1932 dsz += addsz;
1933 }
1934 if (dst != NULL) {
1935 *public = dst;
1936 *psz = dsz;
1937 }
1938
1939 /* Trim trailing whitespace and NUL-terminate. */
1940
1941 while (*psz > 0 && (*public)[*psz - 1] == ' ')
1942 --*psz;
1943 if (dst != NULL) {
1944 (*public)[*psz] = '\0';
1945 return 1;
1946 } else
1947 return 0;
1948 }
1949
1950 static void
1951 dbadd_mlink(const struct mlink *mlink)
1952 {
1953 dba_page_alias(mlink->mpage->dba, mlink->name, NAME_FILE);
1954 dba_page_add(mlink->mpage->dba, DBP_SECT, mlink->dsec);
1955 dba_page_add(mlink->mpage->dba, DBP_SECT, mlink->fsec);
1956 dba_page_add(mlink->mpage->dba, DBP_ARCH, mlink->arch);
1957 dba_page_add(mlink->mpage->dba, DBP_FILE, mlink->file);
1958 }
1959
1960 /*
1961 * Flush the current page's terms (and their bits) into the database.
1962 * Also, handle escape sequences at the last possible moment.
1963 */
1964 static void
1965 dbadd(struct dba *dba, struct mpage *mpage)
1966 {
1967 struct mlink *mlink;
1968 struct str *key;
1969 char *cp;
1970 uint64_t mask;
1971 size_t i;
1972 unsigned int slot;
1973 int mustfree;
1974
1975 mlink = mpage->mlinks;
1976
1977 if (nodb) {
1978 for (key = ohash_first(&names, &slot); NULL != key;
1979 key = ohash_next(&names, &slot))
1980 free(key);
1981 for (key = ohash_first(&strings, &slot); NULL != key;
1982 key = ohash_next(&strings, &slot))
1983 free(key);
1984 if (0 == debug)
1985 return;
1986 while (NULL != mlink) {
1987 fputs(mlink->name, stdout);
1988 if (NULL == mlink->next ||
1989 strcmp(mlink->dsec, mlink->next->dsec) ||
1990 strcmp(mlink->fsec, mlink->next->fsec) ||
1991 strcmp(mlink->arch, mlink->next->arch)) {
1992 putchar('(');
1993 if ('\0' == *mlink->dsec)
1994 fputs(mlink->fsec, stdout);
1995 else
1996 fputs(mlink->dsec, stdout);
1997 if ('\0' != *mlink->arch)
1998 printf("/%s", mlink->arch);
1999 putchar(')');
2000 }
2001 mlink = mlink->next;
2002 if (NULL != mlink)
2003 fputs(", ", stdout);
2004 }
2005 printf(" - %s\n", mpage->desc);
2006 return;
2007 }
2008
2009 if (debug)
2010 say(mlink->file, "Adding to database");
2011
2012 cp = mpage->desc;
2013 i = strlen(cp);
2014 mustfree = render_string(&cp, &i);
2015 mpage->dba = dba_page_new(dba->pages,
2016 *mpage->arch == '\0' ? mlink->arch : mpage->arch,
2017 cp, mlink->file, mpage->form);
2018 if (mustfree)
2019 free(cp);
2020 dba_page_add(mpage->dba, DBP_SECT, mpage->sec);
2021
2022 while (mlink != NULL) {
2023 dbadd_mlink(mlink);
2024 mlink = mlink->next;
2025 }
2026
2027 for (key = ohash_first(&names, &slot); NULL != key;
2028 key = ohash_next(&names, &slot)) {
2029 assert(key->mpage == mpage);
2030 dba_page_alias(mpage->dba, key->key, key->mask);
2031 free(key);
2032 }
2033 for (key = ohash_first(&strings, &slot); NULL != key;
2034 key = ohash_next(&strings, &slot)) {
2035 assert(key->mpage == mpage);
2036 i = 0;
2037 for (mask = TYPE_Xr; mask <= TYPE_Lb; mask *= 2) {
2038 if (key->mask & mask)
2039 dba_macro_add(dba->macros, i,
2040 key->key, mpage->dba);
2041 i++;
2042 }
2043 free(key);
2044 }
2045 }
2046
2047 static void
2048 dbprune(struct dba *dba)
2049 {
2050 struct dba_array *page, *files;
2051 char *file;
2052
2053 dba_array_FOREACH(dba->pages, page) {
2054 files = dba_array_get(page, DBP_FILE);
2055 dba_array_FOREACH(files, file) {
2056 if (*file < ' ')
2057 file++;
2058 if (ohash_find(&mlinks, ohash_qlookup(&mlinks,
2059 file)) != NULL) {
2060 if (debug)
2061 say(file, "Deleting from database");
2062 dba_array_del(dba->pages);
2063 break;
2064 }
2065 }
2066 }
2067 }
2068
2069 /*
2070 * Write the database from memory to disk.
2071 */
2072 static void
2073 dbwrite(struct dba *dba)
2074 {
2075 char tfn[32];
2076 int status;
2077 pid_t child;
2078
2079 if (dba_write(MANDOC_DB "~", dba) != -1) {
2080 if (rename(MANDOC_DB "~", MANDOC_DB) == -1) {
2081 exitcode = (int)MANDOCLEVEL_SYSERR;
2082 say(MANDOC_DB, "&rename");
2083 unlink(MANDOC_DB "~");
2084 }
2085 return;
2086 }
2087
2088 (void)strlcpy(tfn, "/tmp/mandocdb.XXXXXXXX", sizeof(tfn));
2089 if (mkdtemp(tfn) == NULL) {
2090 exitcode = (int)MANDOCLEVEL_SYSERR;
2091 say("", "&%s", tfn);
2092 return;
2093 }
2094
2095 (void)strlcat(tfn, "/" MANDOC_DB, sizeof(tfn));
2096 if (dba_write(tfn, dba) == -1) {
2097 exitcode = (int)MANDOCLEVEL_SYSERR;
2098 say(tfn, "&dba_write");
2099 goto out;
2100 }
2101
2102 switch (child = fork()) {
2103 case -1:
2104 exitcode = (int)MANDOCLEVEL_SYSERR;
2105 say("", "&fork cmp");
2106 return;
2107 case 0:
2108 execlp("cmp", "cmp", "-s", tfn, MANDOC_DB, (char *)NULL);
2109 say("", "&exec cmp");
2110 exit(0);
2111 default:
2112 break;
2113 }
2114 if (waitpid(child, &status, 0) == -1) {
2115 exitcode = (int)MANDOCLEVEL_SYSERR;
2116 say("", "&wait cmp");
2117 } else if (WIFSIGNALED(status)) {
2118 exitcode = (int)MANDOCLEVEL_SYSERR;
2119 say("", "cmp died from signal %d", WTERMSIG(status));
2120 } else if (WEXITSTATUS(status)) {
2121 exitcode = (int)MANDOCLEVEL_SYSERR;
2122 say(MANDOC_DB,
2123 "Data changed, but cannot replace database");
2124 }
2125
2126 out:
2127 *strrchr(tfn, '/') = '\0';
2128 switch (child = fork()) {
2129 case -1:
2130 exitcode = (int)MANDOCLEVEL_SYSERR;
2131 say("", "&fork rm");
2132 return;
2133 case 0:
2134 execlp("rm", "rm", "-rf", tfn, (char *)NULL);
2135 say("", "&exec rm");
2136 exit((int)MANDOCLEVEL_SYSERR);
2137 default:
2138 break;
2139 }
2140 if (waitpid(child, &status, 0) == -1) {
2141 exitcode = (int)MANDOCLEVEL_SYSERR;
2142 say("", "&wait rm");
2143 } else if (WIFSIGNALED(status) || WEXITSTATUS(status)) {
2144 exitcode = (int)MANDOCLEVEL_SYSERR;
2145 say("", "%s: Cannot remove temporary directory", tfn);
2146 }
2147 }
2148
2149 static int
2150 set_basedir(const char *targetdir, int report_baddir)
2151 {
2152 static char startdir[PATH_MAX];
2153 static int getcwd_status; /* 1 = ok, 2 = failure */
2154 static int chdir_status; /* 1 = changed directory */
2155 char *cp;
2156
2157 /*
2158 * Remember the original working directory, if possible.
2159 * This will be needed if the second or a later directory
2160 * on the command line is given as a relative path.
2161 * Do not error out if the current directory is not
2162 * searchable: Maybe it won't be needed after all.
2163 */
2164 if (0 == getcwd_status) {
2165 if (NULL == getcwd(startdir, sizeof(startdir))) {
2166 getcwd_status = 2;
2167 (void)strlcpy(startdir, strerror(errno),
2168 sizeof(startdir));
2169 } else
2170 getcwd_status = 1;
2171 }
2172
2173 /*
2174 * We are leaving the old base directory.
2175 * Do not use it any longer, not even for messages.
2176 */
2177 *basedir = '\0';
2178
2179 /*
2180 * If and only if the directory was changed earlier and
2181 * the next directory to process is given as a relative path,
2182 * first go back, or bail out if that is impossible.
2183 */
2184 if (chdir_status && '/' != *targetdir) {
2185 if (2 == getcwd_status) {
2186 exitcode = (int)MANDOCLEVEL_SYSERR;
2187 say("", "getcwd: %s", startdir);
2188 return 0;
2189 }
2190 if (-1 == chdir(startdir)) {
2191 exitcode = (int)MANDOCLEVEL_SYSERR;
2192 say("", "&chdir %s", startdir);
2193 return 0;
2194 }
2195 }
2196
2197 /*
2198 * Always resolve basedir to the canonicalized absolute
2199 * pathname and append a trailing slash, such that
2200 * we can reliably check whether files are inside.
2201 */
2202 if (NULL == realpath(targetdir, basedir)) {
2203 if (report_baddir || errno != ENOENT) {
2204 exitcode = (int)MANDOCLEVEL_BADARG;
2205 say("", "&%s: realpath", targetdir);
2206 }
2207 return 0;
2208 } else if (-1 == chdir(basedir)) {
2209 if (report_baddir || errno != ENOENT) {
2210 exitcode = (int)MANDOCLEVEL_BADARG;
2211 say("", "&chdir");
2212 }
2213 return 0;
2214 }
2215 chdir_status = 1;
2216 cp = strchr(basedir, '\0');
2217 if ('/' != cp[-1]) {
2218 if (cp - basedir >= PATH_MAX - 1) {
2219 exitcode = (int)MANDOCLEVEL_SYSERR;
2220 say("", "Filename too long");
2221 return 0;
2222 }
2223 *cp++ = '/';
2224 *cp = '\0';
2225 }
2226 return 1;
2227 }
2228
2229 static void
2230 say(const char *file, const char *format, ...)
2231 {
2232 va_list ap;
2233 int use_errno;
2234
2235 if ('\0' != *basedir)
2236 fprintf(stderr, "%s", basedir);
2237 if ('\0' != *basedir && '\0' != *file)
2238 fputc('/', stderr);
2239 if ('\0' != *file)
2240 fprintf(stderr, "%s", file);
2241
2242 use_errno = 1;
2243 if (NULL != format) {
2244 switch (*format) {
2245 case '&':
2246 format++;
2247 break;
2248 case '\0':
2249 format = NULL;
2250 break;
2251 default:
2252 use_errno = 0;
2253 break;
2254 }
2255 }
2256 if (NULL != format) {
2257 if ('\0' != *basedir || '\0' != *file)
2258 fputs(": ", stderr);
2259 va_start(ap, format);
2260 vfprintf(stderr, format, ap);
2261 va_end(ap);
2262 }
2263 if (use_errno) {
2264 if ('\0' != *basedir || '\0' != *file || NULL != format)
2265 fputs(": ", stderr);
2266 perror(NULL);
2267 } else
2268 fputc('\n', stderr);
2269 }