]> git.cameronkatri.com Git - mandoc.git/blob - mandocdb.c
Put mansearch.{h,c}, manpage.c, and compat_ohash.{h,c}
[mandoc.git] / mandocdb.c
1 /* $Id: mandocdb.c,v 1.96 2014/01/02 22:44:10 schwarze Exp $ */
2 /*
3 * Copyright (c) 2011, 2012 Kristaps Dzonsons <kristaps@bsd.lv>
4 * Copyright (c) 2011, 2012, 2013, 2014 Ingo Schwarze <schwarze@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
18 #ifdef HAVE_CONFIG_H
19 #include "config.h"
20 #endif
21
22 #include <sys/stat.h>
23
24 #include <assert.h>
25 #include <ctype.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <fts.h>
29 #include <getopt.h>
30 #include <limits.h>
31 #include <stddef.h>
32 #include <stdio.h>
33 #include <stdint.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <unistd.h>
37
38 #ifdef HAVE_OHASH
39 #include <ohash.h>
40 #else
41 #include "compat_ohash.h"
42 #endif
43 #include <sqlite3.h>
44
45 #include "mdoc.h"
46 #include "man.h"
47 #include "mandoc.h"
48 #include "manpath.h"
49 #include "mansearch.h"
50
51 #define SQL_EXEC(_v) \
52 if (SQLITE_OK != sqlite3_exec(db, (_v), NULL, NULL, NULL)) \
53 fprintf(stderr, "%s\n", sqlite3_errmsg(db))
54 #define SQL_BIND_TEXT(_s, _i, _v) \
55 if (SQLITE_OK != sqlite3_bind_text \
56 ((_s), (_i)++, (_v), -1, SQLITE_STATIC)) \
57 fprintf(stderr, "%s\n", sqlite3_errmsg(db))
58 #define SQL_BIND_INT(_s, _i, _v) \
59 if (SQLITE_OK != sqlite3_bind_int \
60 ((_s), (_i)++, (_v))) \
61 fprintf(stderr, "%s\n", sqlite3_errmsg(db))
62 #define SQL_BIND_INT64(_s, _i, _v) \
63 if (SQLITE_OK != sqlite3_bind_int64 \
64 ((_s), (_i)++, (_v))) \
65 fprintf(stderr, "%s\n", sqlite3_errmsg(db))
66 #define SQL_STEP(_s) \
67 if (SQLITE_DONE != sqlite3_step((_s))) \
68 fprintf(stderr, "%s\n", sqlite3_errmsg(db))
69
70 enum op {
71 OP_DEFAULT = 0, /* new dbs from dir list or default config */
72 OP_CONFFILE, /* new databases from custom config file */
73 OP_UPDATE, /* delete/add entries in existing database */
74 OP_DELETE, /* delete entries from existing database */
75 OP_TEST /* change no databases, report potential problems */
76 };
77
78 enum form {
79 FORM_NONE, /* format is unknown */
80 FORM_SRC, /* format is -man or -mdoc */
81 FORM_CAT /* format is cat */
82 };
83
84 struct str {
85 char *rendered; /* key in UTF-8 or ASCII form */
86 const struct mpage *mpage; /* if set, the owning parse */
87 uint64_t mask; /* bitmask in sequence */
88 char key[]; /* may contain escape sequences */
89 };
90
91 struct inodev {
92 ino_t st_ino;
93 dev_t st_dev;
94 };
95
96 struct mpage {
97 struct inodev inodev; /* used for hashing routine */
98 enum form form; /* format from file content */
99 char *sec; /* section from file content */
100 char *arch; /* architecture from file content */
101 char *title; /* title from file content */
102 char *desc; /* description from file content */
103 struct mlink *mlinks; /* singly linked list */
104 };
105
106 struct mlink {
107 char file[PATH_MAX]; /* filename rel. to manpath */
108 enum form dform; /* format from directory */
109 enum form fform; /* format from file name suffix */
110 char *dsec; /* section from directory */
111 char *arch; /* architecture from directory */
112 char *name; /* name from file name (not empty) */
113 char *fsec; /* section from file name suffix */
114 struct mlink *next; /* singly linked list */
115 };
116
117 struct title {
118 char *title; /* name(sec/arch) given inside the file */
119 char *file; /* file name in case of mismatch */
120 };
121
122 enum stmt {
123 STMT_DELETE_PAGE = 0, /* delete mpage */
124 STMT_INSERT_PAGE, /* insert mpage */
125 STMT_INSERT_LINK, /* insert mlink */
126 STMT_INSERT_KEY, /* insert parsed key */
127 STMT__MAX
128 };
129
130 typedef int (*mdoc_fp)(struct mpage *, const struct mdoc_node *);
131
132 struct mdoc_handler {
133 mdoc_fp fp; /* optional handler */
134 uint64_t mask; /* set unless handler returns 0 */
135 };
136
137 static void dbclose(int);
138 static void dbindex(const struct mpage *, struct mchars *);
139 static int dbopen(int);
140 static void dbprune(void);
141 static void filescan(const char *);
142 static void *hash_alloc(size_t, void *);
143 static void hash_free(void *, size_t, void *);
144 static void *hash_halloc(size_t, void *);
145 static void mlink_add(struct mlink *, const struct stat *);
146 static int mlink_check(struct mpage *, struct mlink *);
147 static void mlink_free(struct mlink *);
148 static void mlinks_undupe(struct mpage *);
149 static void mpages_free(void);
150 static void mpages_merge(struct mchars *, struct mparse *, int);
151 static void parse_cat(struct mpage *);
152 static void parse_man(struct mpage *, const struct man_node *);
153 static void parse_mdoc(struct mpage *, const struct mdoc_node *);
154 static int parse_mdoc_body(struct mpage *, const struct mdoc_node *);
155 static int parse_mdoc_head(struct mpage *, const struct mdoc_node *);
156 static int parse_mdoc_Fd(struct mpage *, const struct mdoc_node *);
157 static int parse_mdoc_Fn(struct mpage *, const struct mdoc_node *);
158 static int parse_mdoc_Nd(struct mpage *, const struct mdoc_node *);
159 static int parse_mdoc_Nm(struct mpage *, const struct mdoc_node *);
160 static int parse_mdoc_Sh(struct mpage *, const struct mdoc_node *);
161 static int parse_mdoc_Xr(struct mpage *, const struct mdoc_node *);
162 static void putkey(const struct mpage *,
163 const char *, uint64_t);
164 static void putkeys(const struct mpage *,
165 const char *, size_t, uint64_t);
166 static void putmdockey(const struct mpage *,
167 const struct mdoc_node *, uint64_t);
168 static void render_key(struct mchars *, struct str *);
169 static void say(const char *, const char *, ...);
170 static int set_basedir(const char *);
171 static int treescan(void);
172 static size_t utf8(unsigned int, char [7]);
173
174 static char *progname;
175 static int use_all; /* use all found files */
176 static int nodb; /* no database changes */
177 static int verb; /* print what we're doing */
178 static int warnings; /* warn about crap */
179 static int write_utf8; /* write UTF-8 output; else ASCII */
180 static int exitcode; /* to be returned by main */
181 static enum op op; /* operational mode */
182 static char basedir[PATH_MAX]; /* current base directory */
183 static struct ohash mpages; /* table of distinct manual pages */
184 static struct ohash mlinks; /* table of directory entries */
185 static struct ohash strings; /* table of all strings */
186 static sqlite3 *db = NULL; /* current database */
187 static sqlite3_stmt *stmts[STMT__MAX]; /* current statements */
188
189 static const struct mdoc_handler mdocs[MDOC_MAX] = {
190 { NULL, 0 }, /* Ap */
191 { NULL, 0 }, /* Dd */
192 { NULL, 0 }, /* Dt */
193 { NULL, 0 }, /* Os */
194 { parse_mdoc_Sh, TYPE_Sh }, /* Sh */
195 { parse_mdoc_head, TYPE_Ss }, /* Ss */
196 { NULL, 0 }, /* Pp */
197 { NULL, 0 }, /* D1 */
198 { NULL, 0 }, /* Dl */
199 { NULL, 0 }, /* Bd */
200 { NULL, 0 }, /* Ed */
201 { NULL, 0 }, /* Bl */
202 { NULL, 0 }, /* El */
203 { NULL, 0 }, /* It */
204 { NULL, 0 }, /* Ad */
205 { NULL, TYPE_An }, /* An */
206 { NULL, TYPE_Ar }, /* Ar */
207 { NULL, TYPE_Cd }, /* Cd */
208 { NULL, TYPE_Cm }, /* Cm */
209 { NULL, TYPE_Dv }, /* Dv */
210 { NULL, TYPE_Er }, /* Er */
211 { NULL, TYPE_Ev }, /* Ev */
212 { NULL, 0 }, /* Ex */
213 { NULL, TYPE_Fa }, /* Fa */
214 { parse_mdoc_Fd, 0 }, /* Fd */
215 { NULL, TYPE_Fl }, /* Fl */
216 { parse_mdoc_Fn, 0 }, /* Fn */
217 { NULL, TYPE_Ft }, /* Ft */
218 { NULL, TYPE_Ic }, /* Ic */
219 { NULL, TYPE_In }, /* In */
220 { NULL, TYPE_Li }, /* Li */
221 { parse_mdoc_Nd, TYPE_Nd }, /* Nd */
222 { parse_mdoc_Nm, TYPE_Nm }, /* Nm */
223 { NULL, 0 }, /* Op */
224 { NULL, 0 }, /* Ot */
225 { NULL, TYPE_Pa }, /* Pa */
226 { NULL, 0 }, /* Rv */
227 { NULL, TYPE_St }, /* St */
228 { NULL, TYPE_Va }, /* Va */
229 { parse_mdoc_body, TYPE_Va }, /* Vt */
230 { parse_mdoc_Xr, 0 }, /* Xr */
231 { NULL, 0 }, /* %A */
232 { NULL, 0 }, /* %B */
233 { NULL, 0 }, /* %D */
234 { NULL, 0 }, /* %I */
235 { NULL, 0 }, /* %J */
236 { NULL, 0 }, /* %N */
237 { NULL, 0 }, /* %O */
238 { NULL, 0 }, /* %P */
239 { NULL, 0 }, /* %R */
240 { NULL, 0 }, /* %T */
241 { NULL, 0 }, /* %V */
242 { NULL, 0 }, /* Ac */
243 { NULL, 0 }, /* Ao */
244 { NULL, 0 }, /* Aq */
245 { NULL, TYPE_At }, /* At */
246 { NULL, 0 }, /* Bc */
247 { NULL, 0 }, /* Bf */
248 { NULL, 0 }, /* Bo */
249 { NULL, 0 }, /* Bq */
250 { NULL, TYPE_Bsx }, /* Bsx */
251 { NULL, TYPE_Bx }, /* Bx */
252 { NULL, 0 }, /* Db */
253 { NULL, 0 }, /* Dc */
254 { NULL, 0 }, /* Do */
255 { NULL, 0 }, /* Dq */
256 { NULL, 0 }, /* Ec */
257 { NULL, 0 }, /* Ef */
258 { NULL, TYPE_Em }, /* Em */
259 { NULL, 0 }, /* Eo */
260 { NULL, TYPE_Fx }, /* Fx */
261 { NULL, TYPE_Ms }, /* Ms */
262 { NULL, 0 }, /* No */
263 { NULL, 0 }, /* Ns */
264 { NULL, TYPE_Nx }, /* Nx */
265 { NULL, TYPE_Ox }, /* Ox */
266 { NULL, 0 }, /* Pc */
267 { NULL, 0 }, /* Pf */
268 { NULL, 0 }, /* Po */
269 { NULL, 0 }, /* Pq */
270 { NULL, 0 }, /* Qc */
271 { NULL, 0 }, /* Ql */
272 { NULL, 0 }, /* Qo */
273 { NULL, 0 }, /* Qq */
274 { NULL, 0 }, /* Re */
275 { NULL, 0 }, /* Rs */
276 { NULL, 0 }, /* Sc */
277 { NULL, 0 }, /* So */
278 { NULL, 0 }, /* Sq */
279 { NULL, 0 }, /* Sm */
280 { NULL, 0 }, /* Sx */
281 { NULL, TYPE_Sy }, /* Sy */
282 { NULL, TYPE_Tn }, /* Tn */
283 { NULL, 0 }, /* Ux */
284 { NULL, 0 }, /* Xc */
285 { NULL, 0 }, /* Xo */
286 { parse_mdoc_head, 0 }, /* Fo */
287 { NULL, 0 }, /* Fc */
288 { NULL, 0 }, /* Oo */
289 { NULL, 0 }, /* Oc */
290 { NULL, 0 }, /* Bk */
291 { NULL, 0 }, /* Ek */
292 { NULL, 0 }, /* Bt */
293 { NULL, 0 }, /* Hf */
294 { NULL, 0 }, /* Fr */
295 { NULL, 0 }, /* Ud */
296 { NULL, TYPE_Lb }, /* Lb */
297 { NULL, 0 }, /* Lp */
298 { NULL, TYPE_Lk }, /* Lk */
299 { NULL, TYPE_Mt }, /* Mt */
300 { NULL, 0 }, /* Brq */
301 { NULL, 0 }, /* Bro */
302 { NULL, 0 }, /* Brc */
303 { NULL, 0 }, /* %C */
304 { NULL, 0 }, /* Es */
305 { NULL, 0 }, /* En */
306 { NULL, TYPE_Dx }, /* Dx */
307 { NULL, 0 }, /* %Q */
308 { NULL, 0 }, /* br */
309 { NULL, 0 }, /* sp */
310 { NULL, 0 }, /* %U */
311 { NULL, 0 }, /* Ta */
312 };
313
314 int
315 main(int argc, char *argv[])
316 {
317 int ch, i;
318 size_t j, sz;
319 const char *path_arg;
320 struct mchars *mc;
321 struct manpaths dirs;
322 struct mparse *mp;
323 struct ohash_info mpages_info, mlinks_info;
324
325 memset(stmts, 0, STMT__MAX * sizeof(sqlite3_stmt *));
326 memset(&dirs, 0, sizeof(struct manpaths));
327
328 mpages_info.alloc = mlinks_info.alloc = hash_alloc;
329 mpages_info.halloc = mlinks_info.halloc = hash_halloc;
330 mpages_info.hfree = mlinks_info.hfree = hash_free;
331
332 mpages_info.key_offset = offsetof(struct mpage, inodev);
333 mlinks_info.key_offset = offsetof(struct mlink, file);
334
335 progname = strrchr(argv[0], '/');
336 if (progname == NULL)
337 progname = argv[0];
338 else
339 ++progname;
340
341 /*
342 * We accept a few different invocations.
343 * The CHECKOP macro makes sure that invocation styles don't
344 * clobber each other.
345 */
346 #define CHECKOP(_op, _ch) do \
347 if (OP_DEFAULT != (_op)) { \
348 fprintf(stderr, "-%c: Conflicting option\n", (_ch)); \
349 goto usage; \
350 } while (/*CONSTCOND*/0)
351
352 path_arg = NULL;
353 op = OP_DEFAULT;
354
355 while (-1 != (ch = getopt(argc, argv, "aC:d:nT:tu:vW")))
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 CHECKOP(op, ch);
367 path_arg = optarg;
368 op = OP_UPDATE;
369 break;
370 case ('n'):
371 nodb = 1;
372 break;
373 case ('T'):
374 if (strcmp(optarg, "utf8")) {
375 fprintf(stderr, "-T%s: Unsupported "
376 "output format\n", optarg);
377 goto usage;
378 }
379 write_utf8 = 1;
380 break;
381 case ('t'):
382 CHECKOP(op, ch);
383 dup2(STDOUT_FILENO, STDERR_FILENO);
384 op = OP_TEST;
385 nodb = warnings = 1;
386 break;
387 case ('u'):
388 CHECKOP(op, ch);
389 path_arg = optarg;
390 op = OP_DELETE;
391 break;
392 case ('v'):
393 verb++;
394 break;
395 case ('W'):
396 warnings = 1;
397 break;
398 default:
399 goto usage;
400 }
401
402 argc -= optind;
403 argv += optind;
404
405 if (OP_CONFFILE == op && argc > 0) {
406 fprintf(stderr, "-C: Too many arguments\n");
407 goto usage;
408 }
409
410 exitcode = (int)MANDOCLEVEL_OK;
411 mp = mparse_alloc(MPARSE_AUTO,
412 MANDOCLEVEL_FATAL, NULL, NULL, NULL);
413 mc = mchars_alloc();
414
415 ohash_init(&mpages, 6, &mpages_info);
416 ohash_init(&mlinks, 6, &mlinks_info);
417
418 if (OP_UPDATE == op || OP_DELETE == op || OP_TEST == op) {
419 /*
420 * Force processing all files.
421 */
422 use_all = 1;
423
424 /*
425 * All of these deal with a specific directory.
426 * Jump into that directory then collect files specified
427 * on the command-line.
428 */
429 if (0 == set_basedir(path_arg))
430 goto out;
431 for (i = 0; i < argc; i++)
432 filescan(argv[i]);
433 if (0 == dbopen(1))
434 goto out;
435 if (OP_TEST != op)
436 dbprune();
437 if (OP_DELETE != op)
438 mpages_merge(mc, mp, 0);
439 dbclose(1);
440 } else {
441 /*
442 * If we have arguments, use them as our manpaths.
443 * If we don't, grok from manpath(1) or however else
444 * manpath_parse() wants to do it.
445 */
446 if (argc > 0) {
447 dirs.paths = mandoc_calloc
448 (argc, sizeof(char *));
449 dirs.sz = (size_t)argc;
450 for (i = 0; i < argc; i++)
451 dirs.paths[i] = mandoc_strdup(argv[i]);
452 } else
453 manpath_parse(&dirs, path_arg, NULL, NULL);
454
455 /*
456 * First scan the tree rooted at a base directory, then
457 * build a new database and finally move it into place.
458 * Ignore zero-length directories and strip trailing
459 * slashes.
460 */
461 for (j = 0; j < dirs.sz; j++) {
462 sz = strlen(dirs.paths[j]);
463 if (sz && '/' == dirs.paths[j][sz - 1])
464 dirs.paths[j][--sz] = '\0';
465 if (0 == sz)
466 continue;
467
468 if (j) {
469 ohash_init(&mpages, 6, &mpages_info);
470 ohash_init(&mlinks, 6, &mlinks_info);
471 }
472
473 if (0 == set_basedir(dirs.paths[j]))
474 goto out;
475 if (0 == treescan())
476 goto out;
477 if (0 == set_basedir(dirs.paths[j]))
478 goto out;
479 if (0 == dbopen(0))
480 goto out;
481
482 mpages_merge(mc, mp, warnings && !use_all);
483 dbclose(0);
484
485 if (j + 1 < dirs.sz) {
486 mpages_free();
487 ohash_delete(&mpages);
488 ohash_delete(&mlinks);
489 }
490 }
491 }
492 out:
493 set_basedir(NULL);
494 manpath_free(&dirs);
495 mchars_free(mc);
496 mparse_free(mp);
497 mpages_free();
498 ohash_delete(&mpages);
499 ohash_delete(&mlinks);
500 return(exitcode);
501 usage:
502 fprintf(stderr, "usage: %s [-anvW] [-C file] [-Tutf8]\n"
503 " %s [-anvW] [-Tutf8] dir ...\n"
504 " %s [-nvW] [-Tutf8] -d dir [file ...]\n"
505 " %s [-nvW] -u dir [file ...]\n"
506 " %s -t file ...\n",
507 progname, progname, progname,
508 progname, progname);
509
510 return((int)MANDOCLEVEL_BADARG);
511 }
512
513 /*
514 * Scan a directory tree rooted at "basedir" for manpages.
515 * We use fts(), scanning directory parts along the way for clues to our
516 * section and architecture.
517 *
518 * If use_all has been specified, grok all files.
519 * If not, sanitise paths to the following:
520 *
521 * [./]man*[/<arch>]/<name>.<section>
522 * or
523 * [./]cat<section>[/<arch>]/<name>.0
524 *
525 * TODO: accomodate for multi-language directories.
526 */
527 static int
528 treescan(void)
529 {
530 FTS *f;
531 FTSENT *ff;
532 struct mlink *mlink;
533 int dform;
534 char *dsec, *arch, *fsec, *cp;
535 const char *path;
536 const char *argv[2];
537
538 argv[0] = ".";
539 argv[1] = (char *)NULL;
540
541 /*
542 * Walk through all components under the directory, using the
543 * logical descent of files.
544 */
545 f = fts_open((char * const *)argv, FTS_LOGICAL, NULL);
546 if (NULL == f) {
547 exitcode = (int)MANDOCLEVEL_SYSERR;
548 say("", NULL);
549 return(0);
550 }
551
552 dsec = arch = NULL;
553 dform = FORM_NONE;
554
555 while (NULL != (ff = fts_read(f))) {
556 path = ff->fts_path + 2;
557 /*
558 * If we're a regular file, add an mlink by using the
559 * stored directory data and handling the filename.
560 */
561 if (FTS_F == ff->fts_info) {
562 if (0 == strcmp(path, MANDOC_DB))
563 continue;
564 if ( ! use_all && ff->fts_level < 2) {
565 if (warnings)
566 say(path, "Extraneous file");
567 continue;
568 } else if (NULL == (fsec =
569 strrchr(ff->fts_name, '.'))) {
570 if ( ! use_all) {
571 if (warnings)
572 say(path,
573 "No filename suffix");
574 continue;
575 }
576 } else if (0 == strcmp(++fsec, "html")) {
577 if (warnings)
578 say(path, "Skip html");
579 continue;
580 } else if (0 == strcmp(fsec, "gz")) {
581 if (warnings)
582 say(path, "Skip gz");
583 continue;
584 } else if (0 == strcmp(fsec, "ps")) {
585 if (warnings)
586 say(path, "Skip ps");
587 continue;
588 } else if (0 == strcmp(fsec, "pdf")) {
589 if (warnings)
590 say(path, "Skip pdf");
591 continue;
592 } else if ( ! use_all &&
593 ((FORM_SRC == dform && strcmp(fsec, dsec)) ||
594 (FORM_CAT == dform && strcmp(fsec, "0")))) {
595 if (warnings)
596 say(path, "Wrong filename suffix");
597 continue;
598 } else
599 fsec[-1] = '\0';
600
601 mlink = mandoc_calloc(1, sizeof(struct mlink));
602 strlcpy(mlink->file, path, sizeof(mlink->file));
603 mlink->dform = dform;
604 mlink->dsec = dsec;
605 mlink->arch = arch;
606 mlink->name = ff->fts_name;
607 mlink->fsec = fsec;
608 mlink_add(mlink, ff->fts_statp);
609 continue;
610 } else if (FTS_D != ff->fts_info &&
611 FTS_DP != ff->fts_info) {
612 if (warnings)
613 say(path, "Not a regular file");
614 continue;
615 }
616
617 switch (ff->fts_level) {
618 case (0):
619 /* Ignore the root directory. */
620 break;
621 case (1):
622 /*
623 * This might contain manX/ or catX/.
624 * Try to infer this from the name.
625 * If we're not in use_all, enforce it.
626 */
627 cp = ff->fts_name;
628 if (FTS_DP == ff->fts_info)
629 break;
630
631 if (0 == strncmp(cp, "man", 3)) {
632 dform = FORM_SRC;
633 dsec = cp + 3;
634 } else if (0 == strncmp(cp, "cat", 3)) {
635 dform = FORM_CAT;
636 dsec = cp + 3;
637 } else {
638 dform = FORM_NONE;
639 dsec = NULL;
640 }
641
642 if (NULL != dsec || use_all)
643 break;
644
645 if (warnings)
646 say(path, "Unknown directory part");
647 fts_set(f, ff, FTS_SKIP);
648 break;
649 case (2):
650 /*
651 * Possibly our architecture.
652 * If we're descending, keep tabs on it.
653 */
654 if (FTS_DP != ff->fts_info && NULL != dsec)
655 arch = ff->fts_name;
656 else
657 arch = NULL;
658 break;
659 default:
660 if (FTS_DP == ff->fts_info || use_all)
661 break;
662 if (warnings)
663 say(path, "Extraneous directory part");
664 fts_set(f, ff, FTS_SKIP);
665 break;
666 }
667 }
668
669 fts_close(f);
670 return(1);
671 }
672
673 /*
674 * Add a file to the mlinks table.
675 * Do not verify that it's a "valid" looking manpage (we'll do that
676 * later).
677 *
678 * Try to infer the manual section, architecture, and page name from the
679 * path, assuming it looks like
680 *
681 * [./]man*[/<arch>]/<name>.<section>
682 * or
683 * [./]cat<section>[/<arch>]/<name>.0
684 *
685 * See treescan() for the fts(3) version of this.
686 */
687 static void
688 filescan(const char *file)
689 {
690 char buf[PATH_MAX];
691 struct stat st;
692 struct mlink *mlink;
693 char *p, *start;
694
695 assert(use_all);
696
697 if (0 == strncmp(file, "./", 2))
698 file += 2;
699
700 if (NULL == realpath(file, buf)) {
701 exitcode = (int)MANDOCLEVEL_BADARG;
702 say(file, NULL);
703 return;
704 } else if (OP_TEST != op && strstr(buf, basedir) != buf) {
705 exitcode = (int)MANDOCLEVEL_BADARG;
706 say("", "%s: outside base directory", buf);
707 return;
708 } else if (-1 == stat(buf, &st)) {
709 exitcode = (int)MANDOCLEVEL_BADARG;
710 say(file, NULL);
711 return;
712 } else if ( ! (S_IFREG & st.st_mode)) {
713 exitcode = (int)MANDOCLEVEL_BADARG;
714 say(file, "Not a regular file");
715 return;
716 }
717 start = buf + strlen(basedir);
718 mlink = mandoc_calloc(1, sizeof(struct mlink));
719 strlcpy(mlink->file, start, sizeof(mlink->file));
720
721 /*
722 * First try to guess our directory structure.
723 * If we find a separator, try to look for man* or cat*.
724 * If we find one of these and what's underneath is a directory,
725 * assume it's an architecture.
726 */
727 if (NULL != (p = strchr(start, '/'))) {
728 *p++ = '\0';
729 if (0 == strncmp(start, "man", 3)) {
730 mlink->dform = FORM_SRC;
731 mlink->dsec = start + 3;
732 } else if (0 == strncmp(start, "cat", 3)) {
733 mlink->dform = FORM_CAT;
734 mlink->dsec = start + 3;
735 }
736
737 start = p;
738 if (NULL != mlink->dsec && NULL != (p = strchr(start, '/'))) {
739 *p++ = '\0';
740 mlink->arch = start;
741 start = p;
742 }
743 }
744
745 /*
746 * Now check the file suffix.
747 * Suffix of `.0' indicates a catpage, `.1-9' is a manpage.
748 */
749 p = strrchr(start, '\0');
750 while (p-- > start && '/' != *p && '.' != *p)
751 /* Loop. */ ;
752
753 if ('.' == *p) {
754 *p++ = '\0';
755 mlink->fsec = p;
756 }
757
758 /*
759 * Now try to parse the name.
760 * Use the filename portion of the path.
761 */
762 mlink->name = start;
763 if (NULL != (p = strrchr(start, '/'))) {
764 mlink->name = p + 1;
765 *p = '\0';
766 }
767 mlink_add(mlink, &st);
768 }
769
770 static void
771 mlink_add(struct mlink *mlink, const struct stat *st)
772 {
773 struct inodev inodev;
774 struct mpage *mpage;
775 unsigned int slot;
776
777 assert(NULL != mlink->file);
778
779 mlink->dsec = mandoc_strdup(mlink->dsec ? mlink->dsec : "");
780 mlink->arch = mandoc_strdup(mlink->arch ? mlink->arch : "");
781 mlink->name = mandoc_strdup(mlink->name ? mlink->name : "");
782 mlink->fsec = mandoc_strdup(mlink->fsec ? mlink->fsec : "");
783
784 if ('0' == *mlink->fsec) {
785 free(mlink->fsec);
786 mlink->fsec = mandoc_strdup(mlink->dsec);
787 mlink->fform = FORM_CAT;
788 } else if ('1' <= *mlink->fsec && '9' >= *mlink->fsec)
789 mlink->fform = FORM_SRC;
790 else
791 mlink->fform = FORM_NONE;
792
793 slot = ohash_qlookup(&mlinks, mlink->file);
794 assert(NULL == ohash_find(&mlinks, slot));
795 ohash_insert(&mlinks, slot, mlink);
796
797 inodev.st_ino = st->st_ino;
798 inodev.st_dev = st->st_dev;
799 slot = ohash_lookup_memory(&mpages, (char *)&inodev,
800 sizeof(struct inodev), inodev.st_ino);
801 mpage = ohash_find(&mpages, slot);
802 if (NULL == mpage) {
803 mpage = mandoc_calloc(1, sizeof(struct mpage));
804 mpage->inodev.st_ino = inodev.st_ino;
805 mpage->inodev.st_dev = inodev.st_dev;
806 ohash_insert(&mpages, slot, mpage);
807 } else
808 mlink->next = mpage->mlinks;
809 mpage->mlinks = mlink;
810 }
811
812 static void
813 mlink_free(struct mlink *mlink)
814 {
815
816 free(mlink->dsec);
817 free(mlink->arch);
818 free(mlink->name);
819 free(mlink->fsec);
820 free(mlink);
821 }
822
823 static void
824 mpages_free(void)
825 {
826 struct mpage *mpage;
827 struct mlink *mlink;
828 unsigned int slot;
829
830 mpage = ohash_first(&mpages, &slot);
831 while (NULL != mpage) {
832 while (NULL != (mlink = mpage->mlinks)) {
833 mpage->mlinks = mlink->next;
834 mlink_free(mlink);
835 }
836 free(mpage->sec);
837 free(mpage->arch);
838 free(mpage->title);
839 free(mpage->desc);
840 free(mpage);
841 mpage = ohash_next(&mpages, &slot);
842 }
843 }
844
845 /*
846 * For each mlink to the mpage, check whether the path looks like
847 * it is formatted, and if it does, check whether a source manual
848 * exists by the same name, ignoring the suffix.
849 * If both conditions hold, drop the mlink.
850 */
851 static void
852 mlinks_undupe(struct mpage *mpage)
853 {
854 char buf[PATH_MAX];
855 struct mlink **prev;
856 struct mlink *mlink;
857 char *bufp;
858
859 mpage->form = FORM_CAT;
860 prev = &mpage->mlinks;
861 while (NULL != (mlink = *prev)) {
862 if (FORM_CAT != mlink->dform) {
863 mpage->form = FORM_NONE;
864 goto nextlink;
865 }
866 if (strlcpy(buf, mlink->file, PATH_MAX) >= PATH_MAX) {
867 if (warnings)
868 say(mlink->file, "Filename too long");
869 goto nextlink;
870 }
871 bufp = strstr(buf, "cat");
872 assert(NULL != bufp);
873 memcpy(bufp, "man", 3);
874 if (NULL != (bufp = strrchr(buf, '.')))
875 *++bufp = '\0';
876 strlcat(buf, mlink->dsec, PATH_MAX);
877 if (NULL == ohash_find(&mlinks,
878 ohash_qlookup(&mlinks, buf)))
879 goto nextlink;
880 if (warnings)
881 say(mlink->file, "Man source exists: %s", buf);
882 if (use_all)
883 goto nextlink;
884 *prev = mlink->next;
885 mlink_free(mlink);
886 continue;
887 nextlink:
888 prev = &(*prev)->next;
889 }
890 }
891
892 static int
893 mlink_check(struct mpage *mpage, struct mlink *mlink)
894 {
895 int match;
896
897 match = 1;
898
899 /*
900 * Check whether the manual section given in a file
901 * agrees with the directory where the file is located.
902 * Some manuals have suffixes like (3p) on their
903 * section number either inside the file or in the
904 * directory name, some are linked into more than one
905 * section, like encrypt(1) = makekey(8).
906 */
907
908 if (FORM_SRC == mpage->form &&
909 strcasecmp(mpage->sec, mlink->dsec)) {
910 match = 0;
911 say(mlink->file, "Section \"%s\" manual in %s directory",
912 mpage->sec, mlink->dsec);
913 }
914
915 /*
916 * Manual page directories exist for each kernel
917 * architecture as returned by machine(1).
918 * However, many manuals only depend on the
919 * application architecture as returned by arch(1).
920 * For example, some (2/ARM) manuals are shared
921 * across the "armish" and "zaurus" kernel
922 * architectures.
923 * A few manuals are even shared across completely
924 * different architectures, for example fdformat(1)
925 * on amd64, i386, sparc, and sparc64.
926 */
927
928 if (strcasecmp(mpage->arch, mlink->arch)) {
929 match = 0;
930 say(mlink->file, "Architecture \"%s\" manual in "
931 "\"%s\" directory", mpage->arch, mlink->arch);
932 }
933
934 if (strcasecmp(mpage->title, mlink->name))
935 match = 0;
936
937 return(match);
938 }
939
940 /*
941 * Run through the files in the global vector "mpages"
942 * and add them to the database specified in "basedir".
943 *
944 * This handles the parsing scheme itself, using the cues of directory
945 * and filename to determine whether the file is parsable or not.
946 */
947 static void
948 mpages_merge(struct mchars *mc, struct mparse *mp, int check_reachable)
949 {
950 struct ohash title_table;
951 struct ohash_info title_info, str_info;
952 struct mpage *mpage;
953 struct mlink *mlink;
954 struct mdoc *mdoc;
955 struct man *man;
956 struct title *title_entry;
957 char *title_str;
958 const char *cp;
959 int match;
960 unsigned int pslot, tslot;
961 enum mandoclevel lvl;
962
963 str_info.alloc = hash_alloc;
964 str_info.halloc = hash_halloc;
965 str_info.hfree = hash_free;
966 str_info.key_offset = offsetof(struct str, key);
967
968 if (check_reachable) {
969 title_info.alloc = hash_alloc;
970 title_info.halloc = hash_halloc;
971 title_info.hfree = hash_free;
972 title_info.key_offset = offsetof(struct title, title);
973 ohash_init(&title_table, 6, &title_info);
974 }
975
976 mpage = ohash_first(&mpages, &pslot);
977 while (NULL != mpage) {
978 mlinks_undupe(mpage);
979 if (NULL == mpage->mlinks) {
980 mpage = ohash_next(&mpages, &pslot);
981 continue;
982 }
983
984 ohash_init(&strings, 6, &str_info);
985 mparse_reset(mp);
986 mdoc = NULL;
987 man = NULL;
988
989 /*
990 * Try interpreting the file as mdoc(7) or man(7)
991 * source code, unless it is already known to be
992 * formatted. Fall back to formatted mode.
993 */
994 if (FORM_CAT != mpage->mlinks->dform ||
995 FORM_CAT != mpage->mlinks->fform) {
996 lvl = mparse_readfd(mp, -1, mpage->mlinks->file);
997 if (lvl < MANDOCLEVEL_FATAL)
998 mparse_result(mp, &mdoc, &man);
999 }
1000
1001 if (NULL != mdoc) {
1002 mpage->form = FORM_SRC;
1003 mpage->sec =
1004 mandoc_strdup(mdoc_meta(mdoc)->msec);
1005 mpage->arch = mdoc_meta(mdoc)->arch;
1006 mpage->arch = mandoc_strdup(
1007 NULL == mpage->arch ? "" : mpage->arch);
1008 mpage->title =
1009 mandoc_strdup(mdoc_meta(mdoc)->title);
1010 } else if (NULL != man) {
1011 mpage->form = FORM_SRC;
1012 mpage->sec =
1013 mandoc_strdup(man_meta(man)->msec);
1014 mpage->arch =
1015 mandoc_strdup(mpage->mlinks->arch);
1016 mpage->title =
1017 mandoc_strdup(man_meta(man)->title);
1018 } else {
1019 mpage->form = FORM_CAT;
1020 mpage->sec =
1021 mandoc_strdup(mpage->mlinks->dsec);
1022 mpage->arch =
1023 mandoc_strdup(mpage->mlinks->arch);
1024 mpage->title =
1025 mandoc_strdup(mpage->mlinks->name);
1026 }
1027
1028 for (mlink = mpage->mlinks; mlink; mlink = mlink->next)
1029 putkey(mpage, mlink->name, TYPE_Nm);
1030
1031 if (warnings && !use_all) {
1032 match = 0;
1033 for (mlink = mpage->mlinks; mlink;
1034 mlink = mlink->next)
1035 if (mlink_check(mpage, mlink))
1036 match = 1;
1037 } else
1038 match = 1;
1039
1040 if (NULL != mdoc) {
1041 if (NULL != (cp = mdoc_meta(mdoc)->name))
1042 putkey(mpage, cp, TYPE_Nm);
1043 assert(NULL == mpage->desc);
1044 parse_mdoc(mpage, mdoc_node(mdoc));
1045 putkey(mpage, NULL != mpage->desc ?
1046 mpage->desc : mpage->mlinks->name, TYPE_Nd);
1047 } else if (NULL != man)
1048 parse_man(mpage, man_node(man));
1049 else
1050 parse_cat(mpage);
1051
1052 /*
1053 * Build a title string for the file. If it matches
1054 * the location of the file, remember the title as
1055 * found; else, remember it as missing.
1056 */
1057
1058 if (check_reachable) {
1059 if (-1 == asprintf(&title_str, "%s(%s%s%s)",
1060 mpage->title, mpage->sec,
1061 '\0' == *mpage->arch ? "" : "/",
1062 mpage->arch)) {
1063 perror(NULL);
1064 exit((int)MANDOCLEVEL_SYSERR);
1065 }
1066 tslot = ohash_qlookup(&title_table, title_str);
1067 title_entry = ohash_find(&title_table, tslot);
1068 if (NULL == title_entry) {
1069 title_entry = mandoc_malloc(
1070 sizeof(struct title));
1071 title_entry->title = title_str;
1072 title_entry->file = mandoc_strdup(
1073 match ? "" : mpage->mlinks->file);
1074 ohash_insert(&title_table, tslot,
1075 title_entry);
1076 } else {
1077 if (match)
1078 *title_entry->file = '\0';
1079 free(title_str);
1080 }
1081 }
1082
1083 dbindex(mpage, mc);
1084 ohash_delete(&strings);
1085 mpage = ohash_next(&mpages, &pslot);
1086 }
1087
1088 if (check_reachable) {
1089 title_entry = ohash_first(&title_table, &tslot);
1090 while (NULL != title_entry) {
1091 if ('\0' != *title_entry->file)
1092 say(title_entry->file,
1093 "Probably unreachable, title is %s",
1094 title_entry->title);
1095 free(title_entry->title);
1096 free(title_entry->file);
1097 free(title_entry);
1098 title_entry = ohash_next(&title_table, &tslot);
1099 }
1100 ohash_delete(&title_table);
1101 }
1102 }
1103
1104 static void
1105 parse_cat(struct mpage *mpage)
1106 {
1107 FILE *stream;
1108 char *line, *p, *title;
1109 size_t len, plen, titlesz;
1110
1111 if (NULL == (stream = fopen(mpage->mlinks->file, "r"))) {
1112 if (warnings)
1113 say(mpage->mlinks->file, NULL);
1114 return;
1115 }
1116
1117 /* Skip to first blank line. */
1118
1119 while (NULL != (line = fgetln(stream, &len)))
1120 if ('\n' == *line)
1121 break;
1122
1123 /*
1124 * Assume the first line that is not indented
1125 * is the first section header. Skip to it.
1126 */
1127
1128 while (NULL != (line = fgetln(stream, &len)))
1129 if ('\n' != *line && ' ' != *line)
1130 break;
1131
1132 /*
1133 * Read up until the next section into a buffer.
1134 * Strip the leading and trailing newline from each read line,
1135 * appending a trailing space.
1136 * Ignore empty (whitespace-only) lines.
1137 */
1138
1139 titlesz = 0;
1140 title = NULL;
1141
1142 while (NULL != (line = fgetln(stream, &len))) {
1143 if (' ' != *line || '\n' != line[len - 1])
1144 break;
1145 while (len > 0 && isspace((unsigned char)*line)) {
1146 line++;
1147 len--;
1148 }
1149 if (1 == len)
1150 continue;
1151 title = mandoc_realloc(title, titlesz + len);
1152 memcpy(title + titlesz, line, len);
1153 titlesz += len;
1154 title[titlesz - 1] = ' ';
1155 }
1156
1157 /*
1158 * If no page content can be found, or the input line
1159 * is already the next section header, or there is no
1160 * trailing newline, reuse the page title as the page
1161 * description.
1162 */
1163
1164 if (NULL == title || '\0' == *title) {
1165 if (warnings)
1166 say(mpage->mlinks->file,
1167 "Cannot find NAME section");
1168 assert(NULL == mpage->desc);
1169 mpage->desc = mandoc_strdup(mpage->mlinks->name);
1170 putkey(mpage, mpage->mlinks->name, TYPE_Nd);
1171 fclose(stream);
1172 free(title);
1173 return;
1174 }
1175
1176 title = mandoc_realloc(title, titlesz + 1);
1177 title[titlesz] = '\0';
1178
1179 /*
1180 * Skip to the first dash.
1181 * Use the remaining line as the description (no more than 70
1182 * bytes).
1183 */
1184
1185 if (NULL != (p = strstr(title, "- "))) {
1186 for (p += 2; ' ' == *p || '\b' == *p; p++)
1187 /* Skip to next word. */ ;
1188 } else {
1189 if (warnings)
1190 say(mpage->mlinks->file,
1191 "No dash in title line");
1192 p = title;
1193 }
1194
1195 plen = strlen(p);
1196
1197 /* Strip backspace-encoding from line. */
1198
1199 while (NULL != (line = memchr(p, '\b', plen))) {
1200 len = line - p;
1201 if (0 == len) {
1202 memmove(line, line + 1, plen--);
1203 continue;
1204 }
1205 memmove(line - 1, line + 1, plen - len);
1206 plen -= 2;
1207 }
1208
1209 assert(NULL == mpage->desc);
1210 mpage->desc = mandoc_strdup(p);
1211 putkey(mpage, mpage->desc, TYPE_Nd);
1212 fclose(stream);
1213 free(title);
1214 }
1215
1216 /*
1217 * Put a type/word pair into the word database for this particular file.
1218 */
1219 static void
1220 putkey(const struct mpage *mpage, const char *value, uint64_t type)
1221 {
1222
1223 assert(NULL != value);
1224 putkeys(mpage, value, strlen(value), type);
1225 }
1226
1227 /*
1228 * Grok all nodes at or below a certain mdoc node into putkey().
1229 */
1230 static void
1231 putmdockey(const struct mpage *mpage,
1232 const struct mdoc_node *n, uint64_t m)
1233 {
1234
1235 for ( ; NULL != n; n = n->next) {
1236 if (NULL != n->child)
1237 putmdockey(mpage, n->child, m);
1238 if (MDOC_TEXT == n->type)
1239 putkey(mpage, n->string, m);
1240 }
1241 }
1242
1243 static void
1244 parse_man(struct mpage *mpage, const struct man_node *n)
1245 {
1246 const struct man_node *head, *body;
1247 char *start, *sv, *title;
1248 char byte;
1249 size_t sz, titlesz;
1250
1251 if (NULL == n)
1252 return;
1253
1254 /*
1255 * We're only searching for one thing: the first text child in
1256 * the BODY of a NAME section. Since we don't keep track of
1257 * sections in -man, run some hoops to find out whether we're in
1258 * the correct section or not.
1259 */
1260
1261 if (MAN_BODY == n->type && MAN_SH == n->tok) {
1262 body = n;
1263 assert(body->parent);
1264 if (NULL != (head = body->parent->head) &&
1265 1 == head->nchild &&
1266 NULL != (head = (head->child)) &&
1267 MAN_TEXT == head->type &&
1268 0 == strcmp(head->string, "NAME") &&
1269 NULL != (body = body->child) &&
1270 MAN_TEXT == body->type) {
1271
1272 title = NULL;
1273 titlesz = 0;
1274
1275 /*
1276 * Suck the entire NAME section into memory.
1277 * Yes, we might run away.
1278 * But too many manuals have big, spread-out
1279 * NAME sections over many lines.
1280 */
1281
1282 for ( ; NULL != body; body = body->next) {
1283 if (MAN_TEXT != body->type)
1284 break;
1285 if (0 == (sz = strlen(body->string)))
1286 continue;
1287 title = mandoc_realloc
1288 (title, titlesz + sz + 1);
1289 memcpy(title + titlesz, body->string, sz);
1290 titlesz += sz + 1;
1291 title[titlesz - 1] = ' ';
1292 }
1293 if (NULL == title)
1294 return;
1295
1296 title = mandoc_realloc(title, titlesz + 1);
1297 title[titlesz] = '\0';
1298
1299 /* Skip leading space. */
1300
1301 sv = title;
1302 while (isspace((unsigned char)*sv))
1303 sv++;
1304
1305 if (0 == (sz = strlen(sv))) {
1306 free(title);
1307 return;
1308 }
1309
1310 /* Erase trailing space. */
1311
1312 start = &sv[sz - 1];
1313 while (start > sv && isspace((unsigned char)*start))
1314 *start-- = '\0';
1315
1316 if (start == sv) {
1317 free(title);
1318 return;
1319 }
1320
1321 start = sv;
1322
1323 /*
1324 * Go through a special heuristic dance here.
1325 * Conventionally, one or more manual names are
1326 * comma-specified prior to a whitespace, then a
1327 * dash, then a description. Try to puzzle out
1328 * the name parts here.
1329 */
1330
1331 for ( ;; ) {
1332 sz = strcspn(start, " ,");
1333 if ('\0' == start[sz])
1334 break;
1335
1336 byte = start[sz];
1337 start[sz] = '\0';
1338
1339 putkey(mpage, start, TYPE_Nm);
1340
1341 if (' ' == byte) {
1342 start += sz + 1;
1343 break;
1344 }
1345
1346 assert(',' == byte);
1347 start += sz + 1;
1348 while (' ' == *start)
1349 start++;
1350 }
1351
1352 if (sv == start) {
1353 putkey(mpage, start, TYPE_Nm);
1354 free(title);
1355 return;
1356 }
1357
1358 while (isspace((unsigned char)*start))
1359 start++;
1360
1361 if (0 == strncmp(start, "-", 1))
1362 start += 1;
1363 else if (0 == strncmp(start, "\\-\\-", 4))
1364 start += 4;
1365 else if (0 == strncmp(start, "\\-", 2))
1366 start += 2;
1367 else if (0 == strncmp(start, "\\(en", 4))
1368 start += 4;
1369 else if (0 == strncmp(start, "\\(em", 4))
1370 start += 4;
1371
1372 while (' ' == *start)
1373 start++;
1374
1375 assert(NULL == mpage->desc);
1376 mpage->desc = mandoc_strdup(start);
1377 putkey(mpage, mpage->desc, TYPE_Nd);
1378 free(title);
1379 return;
1380 }
1381 }
1382
1383 for (n = n->child; n; n = n->next) {
1384 if (NULL != mpage->desc)
1385 break;
1386 parse_man(mpage, n);
1387 }
1388 }
1389
1390 static void
1391 parse_mdoc(struct mpage *mpage, const struct mdoc_node *n)
1392 {
1393
1394 assert(NULL != n);
1395 for (n = n->child; NULL != n; n = n->next) {
1396 switch (n->type) {
1397 case (MDOC_ELEM):
1398 /* FALLTHROUGH */
1399 case (MDOC_BLOCK):
1400 /* FALLTHROUGH */
1401 case (MDOC_HEAD):
1402 /* FALLTHROUGH */
1403 case (MDOC_BODY):
1404 /* FALLTHROUGH */
1405 case (MDOC_TAIL):
1406 if (NULL != mdocs[n->tok].fp)
1407 if (0 == (*mdocs[n->tok].fp)(mpage, n))
1408 break;
1409 if (mdocs[n->tok].mask)
1410 putmdockey(mpage, n->child,
1411 mdocs[n->tok].mask);
1412 break;
1413 default:
1414 assert(MDOC_ROOT != n->type);
1415 continue;
1416 }
1417 if (NULL != n->child)
1418 parse_mdoc(mpage, n);
1419 }
1420 }
1421
1422 static int
1423 parse_mdoc_Fd(struct mpage *mpage, const struct mdoc_node *n)
1424 {
1425 const char *start, *end;
1426 size_t sz;
1427
1428 if (SEC_SYNOPSIS != n->sec ||
1429 NULL == (n = n->child) ||
1430 MDOC_TEXT != n->type)
1431 return(0);
1432
1433 /*
1434 * Only consider those `Fd' macro fields that begin with an
1435 * "inclusion" token (versus, e.g., #define).
1436 */
1437
1438 if (strcmp("#include", n->string))
1439 return(0);
1440
1441 if (NULL == (n = n->next) || MDOC_TEXT != n->type)
1442 return(0);
1443
1444 /*
1445 * Strip away the enclosing angle brackets and make sure we're
1446 * not zero-length.
1447 */
1448
1449 start = n->string;
1450 if ('<' == *start || '"' == *start)
1451 start++;
1452
1453 if (0 == (sz = strlen(start)))
1454 return(0);
1455
1456 end = &start[(int)sz - 1];
1457 if ('>' == *end || '"' == *end)
1458 end--;
1459
1460 if (end > start)
1461 putkeys(mpage, start, end - start + 1, TYPE_In);
1462 return(0);
1463 }
1464
1465 static int
1466 parse_mdoc_Fn(struct mpage *mpage, const struct mdoc_node *n)
1467 {
1468 const char *cp;
1469
1470 if (NULL == (n = n->child) || MDOC_TEXT != n->type)
1471 return(0);
1472
1473 /*
1474 * Parse: .Fn "struct type *name" "char *arg".
1475 * First strip away pointer symbol.
1476 * Then store the function name, then type.
1477 * Finally, store the arguments.
1478 */
1479
1480 if (NULL == (cp = strrchr(n->string, ' ')))
1481 cp = n->string;
1482
1483 while ('*' == *cp)
1484 cp++;
1485
1486 putkey(mpage, cp, TYPE_Fn);
1487
1488 if (n->string < cp)
1489 putkeys(mpage, n->string, cp - n->string, TYPE_Ft);
1490
1491 for (n = n->next; NULL != n; n = n->next)
1492 if (MDOC_TEXT == n->type)
1493 putkey(mpage, n->string, TYPE_Fa);
1494
1495 return(0);
1496 }
1497
1498 static int
1499 parse_mdoc_Xr(struct mpage *mpage, const struct mdoc_node *n)
1500 {
1501 char *cp;
1502
1503 if (NULL == (n = n->child))
1504 return(0);
1505
1506 if (NULL == n->next) {
1507 putkey(mpage, n->string, TYPE_Xr);
1508 return(0);
1509 }
1510
1511 if (-1 == asprintf(&cp, "%s(%s)", n->string, n->next->string)) {
1512 perror(NULL);
1513 exit((int)MANDOCLEVEL_SYSERR);
1514 }
1515 putkey(mpage, cp, TYPE_Xr);
1516 free(cp);
1517 return(0);
1518 }
1519
1520 static int
1521 parse_mdoc_Nd(struct mpage *mpage, const struct mdoc_node *n)
1522 {
1523 size_t sz;
1524
1525 if (MDOC_BODY != n->type)
1526 return(0);
1527
1528 /*
1529 * Special-case the `Nd' because we need to put the description
1530 * into the document table.
1531 */
1532
1533 for (n = n->child; NULL != n; n = n->next) {
1534 if (MDOC_TEXT == n->type) {
1535 if (NULL != mpage->desc) {
1536 sz = strlen(mpage->desc) +
1537 strlen(n->string) + 2;
1538 mpage->desc = mandoc_realloc(
1539 mpage->desc, sz);
1540 strlcat(mpage->desc, " ", sz);
1541 strlcat(mpage->desc, n->string, sz);
1542 } else
1543 mpage->desc = mandoc_strdup(n->string);
1544 }
1545 if (NULL != n->child)
1546 parse_mdoc_Nd(mpage, n);
1547 }
1548 return(1);
1549 }
1550
1551 static int
1552 parse_mdoc_Nm(struct mpage *mpage, const struct mdoc_node *n)
1553 {
1554
1555 return(SEC_NAME == n->sec ||
1556 (SEC_SYNOPSIS == n->sec && MDOC_HEAD == n->type));
1557 }
1558
1559 static int
1560 parse_mdoc_Sh(struct mpage *mpage, const struct mdoc_node *n)
1561 {
1562
1563 return(SEC_CUSTOM == n->sec && MDOC_HEAD == n->type);
1564 }
1565
1566 static int
1567 parse_mdoc_head(struct mpage *mpage, const struct mdoc_node *n)
1568 {
1569
1570 return(MDOC_HEAD == n->type);
1571 }
1572
1573 static int
1574 parse_mdoc_body(struct mpage *mpage, const struct mdoc_node *n)
1575 {
1576
1577 return(MDOC_BODY == n->type);
1578 }
1579
1580 /*
1581 * Add a string to the hash table for the current manual.
1582 * Each string has a bitmask telling which macros it belongs to.
1583 * When we finish the manual, we'll dump the table.
1584 */
1585 static void
1586 putkeys(const struct mpage *mpage,
1587 const char *cp, size_t sz, uint64_t v)
1588 {
1589 struct str *s;
1590 unsigned int slot;
1591 const char *end;
1592
1593 if (0 == sz)
1594 return;
1595
1596 end = cp + sz;
1597 slot = ohash_qlookupi(&strings, cp, &end);
1598 s = ohash_find(&strings, slot);
1599
1600 if (NULL != s && mpage == s->mpage) {
1601 s->mask |= v;
1602 return;
1603 } else if (NULL == s) {
1604 s = mandoc_calloc(sizeof(struct str) + sz + 1, 1);
1605 memcpy(s->key, cp, sz);
1606 ohash_insert(&strings, slot, s);
1607 }
1608 s->mpage = mpage;
1609 s->mask = v;
1610 }
1611
1612 /*
1613 * Take a Unicode codepoint and produce its UTF-8 encoding.
1614 * This isn't the best way to do this, but it works.
1615 * The magic numbers are from the UTF-8 packaging.
1616 * They're not as scary as they seem: read the UTF-8 spec for details.
1617 */
1618 static size_t
1619 utf8(unsigned int cp, char out[7])
1620 {
1621 size_t rc;
1622
1623 rc = 0;
1624 if (cp <= 0x0000007F) {
1625 rc = 1;
1626 out[0] = (char)cp;
1627 } else if (cp <= 0x000007FF) {
1628 rc = 2;
1629 out[0] = (cp >> 6 & 31) | 192;
1630 out[1] = (cp & 63) | 128;
1631 } else if (cp <= 0x0000FFFF) {
1632 rc = 3;
1633 out[0] = (cp >> 12 & 15) | 224;
1634 out[1] = (cp >> 6 & 63) | 128;
1635 out[2] = (cp & 63) | 128;
1636 } else if (cp <= 0x001FFFFF) {
1637 rc = 4;
1638 out[0] = (cp >> 18 & 7) | 240;
1639 out[1] = (cp >> 12 & 63) | 128;
1640 out[2] = (cp >> 6 & 63) | 128;
1641 out[3] = (cp & 63) | 128;
1642 } else if (cp <= 0x03FFFFFF) {
1643 rc = 5;
1644 out[0] = (cp >> 24 & 3) | 248;
1645 out[1] = (cp >> 18 & 63) | 128;
1646 out[2] = (cp >> 12 & 63) | 128;
1647 out[3] = (cp >> 6 & 63) | 128;
1648 out[4] = (cp & 63) | 128;
1649 } else if (cp <= 0x7FFFFFFF) {
1650 rc = 6;
1651 out[0] = (cp >> 30 & 1) | 252;
1652 out[1] = (cp >> 24 & 63) | 128;
1653 out[2] = (cp >> 18 & 63) | 128;
1654 out[3] = (cp >> 12 & 63) | 128;
1655 out[4] = (cp >> 6 & 63) | 128;
1656 out[5] = (cp & 63) | 128;
1657 } else
1658 return(0);
1659
1660 out[rc] = '\0';
1661 return(rc);
1662 }
1663
1664 /*
1665 * Store the rendered version of a key, or alias the pointer
1666 * if the key contains no escape sequences.
1667 */
1668 static void
1669 render_key(struct mchars *mc, struct str *key)
1670 {
1671 size_t sz, bsz, pos;
1672 char utfbuf[7], res[5];
1673 char *buf;
1674 const char *seq, *cpp, *val;
1675 int len, u;
1676 enum mandoc_esc esc;
1677
1678 assert(NULL == key->rendered);
1679
1680 res[0] = '\\';
1681 res[1] = '\t';
1682 res[2] = ASCII_NBRSP;
1683 res[3] = ASCII_HYPH;
1684 res[4] = '\0';
1685
1686 val = key->key;
1687 bsz = strlen(val);
1688
1689 /*
1690 * Pre-check: if we have no stop-characters, then set the
1691 * pointer as ourselvse and get out of here.
1692 */
1693 if (strcspn(val, res) == bsz) {
1694 key->rendered = key->key;
1695 return;
1696 }
1697
1698 /* Pre-allocate by the length of the input */
1699
1700 buf = mandoc_malloc(++bsz);
1701 pos = 0;
1702
1703 while ('\0' != *val) {
1704 /*
1705 * Halt on the first escape sequence.
1706 * This also halts on the end of string, in which case
1707 * we just copy, fallthrough, and exit the loop.
1708 */
1709 if ((sz = strcspn(val, res)) > 0) {
1710 memcpy(&buf[pos], val, sz);
1711 pos += sz;
1712 val += sz;
1713 }
1714
1715 if (ASCII_HYPH == *val) {
1716 buf[pos++] = '-';
1717 val++;
1718 continue;
1719 } else if ('\t' == *val || ASCII_NBRSP == *val) {
1720 buf[pos++] = ' ';
1721 val++;
1722 continue;
1723 } else if ('\\' != *val)
1724 break;
1725
1726 /* Read past the slash. */
1727
1728 val++;
1729
1730 /*
1731 * Parse the escape sequence and see if it's a
1732 * predefined character or special character.
1733 */
1734
1735 esc = mandoc_escape
1736 ((const char **)&val, &seq, &len);
1737 if (ESCAPE_ERROR == esc)
1738 break;
1739 if (ESCAPE_SPECIAL != esc)
1740 continue;
1741
1742 /*
1743 * Render the special character
1744 * as either UTF-8 or ASCII.
1745 */
1746
1747 if (write_utf8) {
1748 if (0 == (u = mchars_spec2cp(mc, seq, len)))
1749 continue;
1750 cpp = utfbuf;
1751 if (0 == (sz = utf8(u, utfbuf)))
1752 continue;
1753 sz = strlen(cpp);
1754 } else {
1755 cpp = mchars_spec2str(mc, seq, len, &sz);
1756 if (NULL == cpp)
1757 continue;
1758 if (ASCII_NBRSP == *cpp) {
1759 cpp = " ";
1760 sz = 1;
1761 }
1762 }
1763
1764 /* Copy the rendered glyph into the stream. */
1765
1766 bsz += sz;
1767 buf = mandoc_realloc(buf, bsz);
1768 memcpy(&buf[pos], cpp, sz);
1769 pos += sz;
1770 }
1771
1772 buf[pos] = '\0';
1773 key->rendered = buf;
1774 }
1775
1776 /*
1777 * Flush the current page's terms (and their bits) into the database.
1778 * Wrap the entire set of additions in a transaction to make sqlite be a
1779 * little faster.
1780 * Also, handle escape sequences at the last possible moment.
1781 */
1782 static void
1783 dbindex(const struct mpage *mpage, struct mchars *mc)
1784 {
1785 struct mlink *mlink;
1786 struct str *key;
1787 const char *desc;
1788 int64_t recno;
1789 size_t i;
1790 unsigned int slot;
1791
1792 if (verb)
1793 say(mpage->mlinks->file, "Adding to index");
1794
1795 if (nodb)
1796 return;
1797
1798 desc = "";
1799 if (NULL != mpage->desc && '\0' != *mpage->desc) {
1800 key = ohash_find(&strings,
1801 ohash_qlookup(&strings, mpage->desc));
1802 assert(NULL != key);
1803 if (NULL == key->rendered)
1804 render_key(mc, key);
1805 desc = key->rendered;
1806 }
1807
1808 SQL_EXEC("BEGIN TRANSACTION");
1809
1810 i = 1;
1811 /*
1812 * XXX The following three lines are obsolete
1813 * and only kept for backward compatibility
1814 * until apropos(1) and friends have caught up.
1815 */
1816 SQL_BIND_TEXT(stmts[STMT_INSERT_PAGE], i, mpage->mlinks->file);
1817 SQL_BIND_TEXT(stmts[STMT_INSERT_PAGE], i, mpage->mlinks->dsec);
1818 SQL_BIND_TEXT(stmts[STMT_INSERT_PAGE], i, mpage->mlinks->arch);
1819 SQL_BIND_TEXT(stmts[STMT_INSERT_PAGE], i, desc);
1820 SQL_BIND_INT(stmts[STMT_INSERT_PAGE], i, FORM_SRC == mpage->form);
1821 SQL_STEP(stmts[STMT_INSERT_PAGE]);
1822 recno = sqlite3_last_insert_rowid(db);
1823 sqlite3_reset(stmts[STMT_INSERT_PAGE]);
1824
1825 for (mlink = mpage->mlinks; mlink; mlink = mlink->next) {
1826 i = 1;
1827 SQL_BIND_TEXT(stmts[STMT_INSERT_LINK], i, mlink->file);
1828 SQL_BIND_TEXT(stmts[STMT_INSERT_LINK], i, mlink->dsec);
1829 SQL_BIND_TEXT(stmts[STMT_INSERT_LINK], i, mlink->arch);
1830 SQL_BIND_TEXT(stmts[STMT_INSERT_LINK], i, mlink->name);
1831 SQL_BIND_INT64(stmts[STMT_INSERT_LINK], i, recno);
1832 SQL_STEP(stmts[STMT_INSERT_LINK]);
1833 sqlite3_reset(stmts[STMT_INSERT_LINK]);
1834 }
1835
1836 for (key = ohash_first(&strings, &slot); NULL != key;
1837 key = ohash_next(&strings, &slot)) {
1838 assert(key->mpage == mpage);
1839 if (NULL == key->rendered)
1840 render_key(mc, key);
1841 i = 1;
1842 SQL_BIND_INT64(stmts[STMT_INSERT_KEY], i, key->mask);
1843 SQL_BIND_TEXT(stmts[STMT_INSERT_KEY], i, key->rendered);
1844 SQL_BIND_INT64(stmts[STMT_INSERT_KEY], i, recno);
1845 SQL_STEP(stmts[STMT_INSERT_KEY]);
1846 sqlite3_reset(stmts[STMT_INSERT_KEY]);
1847 if (key->rendered != key->key)
1848 free(key->rendered);
1849 free(key);
1850 }
1851
1852 SQL_EXEC("END TRANSACTION");
1853 }
1854
1855 static void
1856 dbprune(void)
1857 {
1858 struct mpage *mpage;
1859 struct mlink *mlink;
1860 size_t i;
1861 unsigned int slot;
1862
1863 if (nodb)
1864 return;
1865
1866 mpage = ohash_first(&mpages, &slot);
1867 while (NULL != mpage) {
1868 mlink = mpage->mlinks;
1869 i = 1;
1870 SQL_BIND_TEXT(stmts[STMT_DELETE_PAGE], i, mlink->file);
1871 SQL_STEP(stmts[STMT_DELETE_PAGE]);
1872 sqlite3_reset(stmts[STMT_DELETE_PAGE]);
1873 if (verb)
1874 say(mlink->file, "Deleted from index");
1875 mpage = ohash_next(&mpages, &slot);
1876 }
1877 }
1878
1879 /*
1880 * Close an existing database and its prepared statements.
1881 * If "real" is not set, rename the temporary file into the real one.
1882 */
1883 static void
1884 dbclose(int real)
1885 {
1886 size_t i;
1887
1888 if (nodb)
1889 return;
1890
1891 for (i = 0; i < STMT__MAX; i++) {
1892 sqlite3_finalize(stmts[i]);
1893 stmts[i] = NULL;
1894 }
1895
1896 sqlite3_close(db);
1897 db = NULL;
1898
1899 if (real)
1900 return;
1901
1902 if (-1 == rename(MANDOC_DB "~", MANDOC_DB)) {
1903 exitcode = (int)MANDOCLEVEL_SYSERR;
1904 say(MANDOC_DB, NULL);
1905 }
1906 }
1907
1908 /*
1909 * This is straightforward stuff.
1910 * Open a database connection to a "temporary" database, then open a set
1911 * of prepared statements we'll use over and over again.
1912 * If "real" is set, we use the existing database; if not, we truncate a
1913 * temporary one.
1914 * Must be matched by dbclose().
1915 */
1916 static int
1917 dbopen(int real)
1918 {
1919 const char *file, *sql;
1920 int rc, ofl;
1921
1922 if (nodb)
1923 return(1);
1924
1925 ofl = SQLITE_OPEN_READWRITE;
1926 if (0 == real) {
1927 file = MANDOC_DB "~";
1928 if (-1 == remove(file) && ENOENT != errno) {
1929 exitcode = (int)MANDOCLEVEL_SYSERR;
1930 say(file, NULL);
1931 return(0);
1932 }
1933 ofl |= SQLITE_OPEN_EXCLUSIVE;
1934 } else
1935 file = MANDOC_DB;
1936
1937 rc = sqlite3_open_v2(file, &db, ofl, NULL);
1938 if (SQLITE_OK == rc)
1939 goto prepare_statements;
1940 if (SQLITE_CANTOPEN != rc) {
1941 exitcode = (int)MANDOCLEVEL_SYSERR;
1942 say(file, NULL);
1943 return(0);
1944 }
1945
1946 sqlite3_close(db);
1947 db = NULL;
1948
1949 if (SQLITE_OK != (rc = sqlite3_open(file, &db))) {
1950 exitcode = (int)MANDOCLEVEL_SYSERR;
1951 say(file, NULL);
1952 return(0);
1953 }
1954
1955 /*
1956 * XXX The first three columns in table mpages are obsolete
1957 * and only kept for backward compatibility
1958 * until apropos(1) and friends have caught up.
1959 */
1960 sql = "CREATE TABLE \"mpages\" (\n"
1961 " \"file\" TEXT NOT NULL,\n"
1962 " \"sec\" TEXT NOT NULL,\n"
1963 " \"arch\" TEXT NOT NULL,\n"
1964 " \"desc\" TEXT NOT NULL,\n"
1965 " \"form\" INTEGER NOT NULL,\n"
1966 " \"id\" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL\n"
1967 ");\n"
1968 "\n"
1969 "CREATE TABLE \"mlinks\" (\n"
1970 " \"file\" TEXT NOT NULL,\n"
1971 " \"sec\" TEXT NOT NULL,\n"
1972 " \"arch\" TEXT NOT NULL,\n"
1973 " \"name\" TEXT NOT NULL,\n"
1974 " \"pageid\" INTEGER NOT NULL REFERENCES mpages(id) "
1975 "ON DELETE CASCADE,\n"
1976 " \"id\" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL\n"
1977 ");\n"
1978 "\n"
1979 "CREATE TABLE \"keys\" (\n"
1980 " \"bits\" INTEGER NOT NULL,\n"
1981 " \"key\" TEXT NOT NULL,\n"
1982 " \"pageid\" INTEGER NOT NULL REFERENCES mpages(id) "
1983 "ON DELETE CASCADE,\n"
1984 " \"id\" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL\n"
1985 ");\n"
1986 "\n"
1987 "CREATE INDEX \"key_index\" ON keys (key);\n";
1988
1989 if (SQLITE_OK != sqlite3_exec(db, sql, NULL, NULL, NULL)) {
1990 exitcode = (int)MANDOCLEVEL_SYSERR;
1991 say(file, "%s", sqlite3_errmsg(db));
1992 return(0);
1993 }
1994
1995 prepare_statements:
1996 SQL_EXEC("PRAGMA foreign_keys = ON");
1997 sql = "DELETE FROM mpages where file=?";
1998 sqlite3_prepare_v2(db, sql, -1, &stmts[STMT_DELETE_PAGE], NULL);
1999 sql = "INSERT INTO mpages "
2000 "(file,sec,arch,desc,form) VALUES (?,?,?,?,?)";
2001 sqlite3_prepare_v2(db, sql, -1, &stmts[STMT_INSERT_PAGE], NULL);
2002 sql = "INSERT INTO mlinks "
2003 "(file,sec,arch,name,pageid) VALUES (?,?,?,?,?)";
2004 sqlite3_prepare_v2(db, sql, -1, &stmts[STMT_INSERT_LINK], NULL);
2005 sql = "INSERT INTO keys "
2006 "(bits,key,pageid) VALUES (?,?,?)";
2007 sqlite3_prepare_v2(db, sql, -1, &stmts[STMT_INSERT_KEY], NULL);
2008
2009 #ifndef __APPLE__
2010 /*
2011 * When opening a new database, we can turn off
2012 * synchronous mode for much better performance.
2013 */
2014
2015 if (real)
2016 SQL_EXEC("PRAGMA synchronous = OFF");
2017 #endif
2018
2019 return(1);
2020 }
2021
2022 static void *
2023 hash_halloc(size_t sz, void *arg)
2024 {
2025
2026 return(mandoc_calloc(sz, 1));
2027 }
2028
2029 static void *
2030 hash_alloc(size_t sz, void *arg)
2031 {
2032
2033 return(mandoc_malloc(sz));
2034 }
2035
2036 static void
2037 hash_free(void *p, size_t sz, void *arg)
2038 {
2039
2040 free(p);
2041 }
2042
2043 static int
2044 set_basedir(const char *targetdir)
2045 {
2046 static char startdir[PATH_MAX];
2047 static int fd;
2048
2049 /*
2050 * Remember where we started by keeping a fd open to the origin
2051 * path component: throughout this utility, we chdir() a lot to
2052 * handle relative paths, and by doing this, we can return to
2053 * the starting point.
2054 */
2055 if ('\0' == *startdir) {
2056 if (NULL == getcwd(startdir, PATH_MAX)) {
2057 exitcode = (int)MANDOCLEVEL_SYSERR;
2058 if (NULL != targetdir)
2059 say(".", NULL);
2060 return(0);
2061 }
2062 if (-1 == (fd = open(startdir, O_RDONLY, 0))) {
2063 exitcode = (int)MANDOCLEVEL_SYSERR;
2064 say(startdir, NULL);
2065 return(0);
2066 }
2067 if (NULL == targetdir)
2068 targetdir = startdir;
2069 } else {
2070 if (-1 == fd)
2071 return(0);
2072 if (-1 == fchdir(fd)) {
2073 close(fd);
2074 basedir[0] = '\0';
2075 exitcode = (int)MANDOCLEVEL_SYSERR;
2076 say(startdir, NULL);
2077 return(0);
2078 }
2079 if (NULL == targetdir) {
2080 close(fd);
2081 return(1);
2082 }
2083 }
2084 if (NULL == realpath(targetdir, basedir)) {
2085 basedir[0] = '\0';
2086 exitcode = (int)MANDOCLEVEL_BADARG;
2087 say(targetdir, NULL);
2088 return(0);
2089 } else if (-1 == chdir(basedir)) {
2090 exitcode = (int)MANDOCLEVEL_BADARG;
2091 say("", NULL);
2092 return(0);
2093 }
2094 return(1);
2095 }
2096
2097 static void
2098 say(const char *file, const char *format, ...)
2099 {
2100 va_list ap;
2101
2102 if ('\0' != *basedir)
2103 fprintf(stderr, "%s", basedir);
2104 if ('\0' != *basedir && '\0' != *file)
2105 fputs("//", stderr);
2106 if ('\0' != *file)
2107 fprintf(stderr, "%s", file);
2108 fputs(": ", stderr);
2109
2110 if (NULL == format) {
2111 perror(NULL);
2112 return;
2113 }
2114
2115 va_start(ap, format);
2116 vfprintf(stderr, format, ap);
2117 va_end(ap);
2118
2119 fputc('\n', stderr);
2120 }