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