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