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