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