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