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