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