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