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