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