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