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