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