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