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