]> git.cameronkatri.com Git - mandoc.git/blob - mandocdb.c
Fatal errors no longer exist.
[mandoc.git] / mandocdb.c
1 /* $Id: mandocdb.c,v 1.183 2015/01/15 04:26:40 schwarze Exp $ */
2 /*
3 * Copyright (c) 2011, 2012 Kristaps Dzonsons <kristaps@bsd.lv>
4 * Copyright (c) 2011-2015 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 #include "config.h"
19
20 #include <sys/types.h>
21 #include <sys/stat.h>
22 #include <sys/wait.h>
23
24 #include <assert.h>
25 #include <ctype.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #if HAVE_FTS
29 #include <fts.h>
30 #else
31 #include "compat_fts.h"
32 #endif
33 #include <getopt.h>
34 #include <limits.h>
35 #include <stddef.h>
36 #include <stdio.h>
37 #include <stdint.h>
38 #include <stdlib.h>
39 #include <string.h>
40 #include <unistd.h>
41
42 #if HAVE_OHASH
43 #include <ohash.h>
44 #else
45 #include "compat_ohash.h"
46 #endif
47 #include <sqlite3.h>
48
49 #include "mdoc.h"
50 #include "man.h"
51 #include "mandoc.h"
52 #include "mandoc_aux.h"
53 #include "manpath.h"
54 #include "mansearch.h"
55
56 extern int mansearch_keymax;
57 extern const char *const mansearch_keynames[];
58
59 #define SQL_EXEC(_v) \
60 if (SQLITE_OK != sqlite3_exec(db, (_v), NULL, NULL, NULL)) \
61 say("", "%s: %s", (_v), sqlite3_errmsg(db))
62 #define SQL_BIND_TEXT(_s, _i, _v) \
63 if (SQLITE_OK != sqlite3_bind_text \
64 ((_s), (_i)++, (_v), -1, SQLITE_STATIC)) \
65 say(mlink->file, "%s", sqlite3_errmsg(db))
66 #define SQL_BIND_INT(_s, _i, _v) \
67 if (SQLITE_OK != sqlite3_bind_int \
68 ((_s), (_i)++, (_v))) \
69 say(mlink->file, "%s", sqlite3_errmsg(db))
70 #define SQL_BIND_INT64(_s, _i, _v) \
71 if (SQLITE_OK != sqlite3_bind_int64 \
72 ((_s), (_i)++, (_v))) \
73 say(mlink->file, "%s", sqlite3_errmsg(db))
74 #define SQL_STEP(_s) \
75 if (SQLITE_DONE != sqlite3_step((_s))) \
76 say(mlink->file, "%s", sqlite3_errmsg(db))
77
78 enum op {
79 OP_DEFAULT = 0, /* new dbs from dir list or default config */
80 OP_CONFFILE, /* new databases from custom config file */
81 OP_UPDATE, /* delete/add entries in existing database */
82 OP_DELETE, /* delete entries from existing database */
83 OP_TEST /* change no databases, report potential problems */
84 };
85
86 struct str {
87 const struct mpage *mpage; /* if set, the owning parse */
88 uint64_t mask; /* bitmask in sequence */
89 char key[]; /* rendered text */
90 };
91
92 struct inodev {
93 ino_t st_ino;
94 dev_t st_dev;
95 };
96
97 struct mpage {
98 struct inodev inodev; /* used for hashing routine */
99 int64_t pageid; /* pageid in mpages SQL table */
100 char *sec; /* section from file content */
101 char *arch; /* architecture from file content */
102 char *title; /* title from file content */
103 char *desc; /* description from file content */
104 struct mlink *mlinks; /* singly linked list */
105 int form; /* format from file content */
106 int name_head_done;
107 };
108
109 struct mlink {
110 char file[PATH_MAX]; /* filename rel. to manpath */
111 char *dsec; /* section from directory */
112 char *arch; /* architecture from directory */
113 char *name; /* name from file name (not empty) */
114 char *fsec; /* section from file name suffix */
115 struct mlink *next; /* singly linked list */
116 struct mpage *mpage; /* parent */
117 int dform; /* format from directory */
118 int fform; /* format from file name suffix */
119 int gzip; /* filename has a .gz suffix */
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_NAME, /* insert name */
127 STMT_SELECT_NAME, /* retrieve existing name flags */
128 STMT_INSERT_KEY, /* insert parsed key */
129 STMT__MAX
130 };
131
132 typedef int (*mdoc_fp)(struct mpage *, const struct mdoc_meta *,
133 const struct mdoc_node *);
134
135 struct mdoc_handler {
136 mdoc_fp fp; /* optional handler */
137 uint64_t mask; /* set unless handler returns 0 */
138 };
139
140 static void dbclose(int);
141 static void dbadd(struct mpage *);
142 static void dbadd_mlink(const struct mlink *mlink);
143 static void dbadd_mlink_name(const struct mlink *mlink);
144 static int dbopen(int);
145 static void dbprune(void);
146 static void filescan(const char *);
147 static void *hash_alloc(size_t, void *);
148 static void hash_free(void *, void *);
149 static void *hash_calloc(size_t, size_t, void *);
150 static void mlink_add(struct mlink *, const struct stat *);
151 static void mlink_check(struct mpage *, struct mlink *);
152 static void mlink_free(struct mlink *);
153 static void mlinks_undupe(struct mpage *);
154 static void mpages_free(void);
155 static void mpages_merge(struct mparse *);
156 static void names_check(void);
157 static void parse_cat(struct mpage *, int);
158 static void parse_man(struct mpage *, const struct man_meta *,
159 const struct man_node *);
160 static void parse_mdoc(struct mpage *, const struct mdoc_meta *,
161 const struct mdoc_node *);
162 static int parse_mdoc_body(struct mpage *, const struct mdoc_meta *,
163 const struct mdoc_node *);
164 static int parse_mdoc_head(struct mpage *, const struct mdoc_meta *,
165 const struct mdoc_node *);
166 static int parse_mdoc_Fd(struct mpage *, const struct mdoc_meta *,
167 const struct mdoc_node *);
168 static void parse_mdoc_fname(struct mpage *, const struct mdoc_node *);
169 static int parse_mdoc_Fn(struct mpage *, const struct mdoc_meta *,
170 const struct mdoc_node *);
171 static int parse_mdoc_Fo(struct mpage *, const struct mdoc_meta *,
172 const struct mdoc_node *);
173 static int parse_mdoc_Nd(struct mpage *, const struct mdoc_meta *,
174 const struct mdoc_node *);
175 static int parse_mdoc_Nm(struct mpage *, const struct mdoc_meta *,
176 const struct mdoc_node *);
177 static int parse_mdoc_Sh(struct mpage *, const struct mdoc_meta *,
178 const struct mdoc_node *);
179 static int parse_mdoc_Xr(struct mpage *, const struct mdoc_meta *,
180 const struct mdoc_node *);
181 static void putkey(const struct mpage *, char *, uint64_t);
182 static void putkeys(const struct mpage *, char *, size_t, uint64_t);
183 static void putmdockey(const struct mpage *,
184 const struct mdoc_node *, uint64_t);
185 static int render_string(char **, size_t *);
186 static void say(const char *, const char *, ...);
187 static int set_basedir(const char *, int);
188 static int treescan(void);
189 static size_t utf8(unsigned int, char [7]);
190
191 static char tempfilename[32];
192 static char *progname;
193 static int nodb; /* no database changes */
194 static int mparse_options; /* abort the parse early */
195 static int use_all; /* use all found files */
196 static int debug; /* print what we're doing */
197 static int warnings; /* warn about crap */
198 static int write_utf8; /* write UTF-8 output; else ASCII */
199 static int exitcode; /* to be returned by main */
200 static enum op op; /* operational mode */
201 static char basedir[PATH_MAX]; /* current base directory */
202 static struct mchars *mchars; /* table of named characters */
203 static struct ohash mpages; /* table of distinct manual pages */
204 static struct ohash mlinks; /* table of directory entries */
205 static struct ohash names; /* table of all names */
206 static struct ohash strings; /* table of all strings */
207 static sqlite3 *db = NULL; /* current database */
208 static sqlite3_stmt *stmts[STMT__MAX]; /* current statements */
209 static uint64_t name_mask;
210
211 static const struct mdoc_handler mdocs[MDOC_MAX] = {
212 { NULL, 0 }, /* Ap */
213 { NULL, 0 }, /* Dd */
214 { NULL, 0 }, /* Dt */
215 { NULL, 0 }, /* Os */
216 { parse_mdoc_Sh, TYPE_Sh }, /* Sh */
217 { parse_mdoc_head, TYPE_Ss }, /* Ss */
218 { NULL, 0 }, /* Pp */
219 { NULL, 0 }, /* D1 */
220 { NULL, 0 }, /* Dl */
221 { NULL, 0 }, /* Bd */
222 { NULL, 0 }, /* Ed */
223 { NULL, 0 }, /* Bl */
224 { NULL, 0 }, /* El */
225 { NULL, 0 }, /* It */
226 { NULL, 0 }, /* Ad */
227 { NULL, TYPE_An }, /* An */
228 { NULL, TYPE_Ar }, /* Ar */
229 { NULL, TYPE_Cd }, /* Cd */
230 { NULL, TYPE_Cm }, /* Cm */
231 { NULL, TYPE_Dv }, /* Dv */
232 { NULL, TYPE_Er }, /* Er */
233 { NULL, TYPE_Ev }, /* Ev */
234 { NULL, 0 }, /* Ex */
235 { NULL, TYPE_Fa }, /* Fa */
236 { parse_mdoc_Fd, 0 }, /* Fd */
237 { NULL, TYPE_Fl }, /* Fl */
238 { parse_mdoc_Fn, 0 }, /* Fn */
239 { NULL, TYPE_Ft }, /* Ft */
240 { NULL, TYPE_Ic }, /* Ic */
241 { NULL, TYPE_In }, /* In */
242 { NULL, TYPE_Li }, /* Li */
243 { parse_mdoc_Nd, 0 }, /* Nd */
244 { parse_mdoc_Nm, 0 }, /* Nm */
245 { NULL, 0 }, /* Op */
246 { NULL, 0 }, /* Ot */
247 { NULL, TYPE_Pa }, /* Pa */
248 { NULL, 0 }, /* Rv */
249 { NULL, TYPE_St }, /* St */
250 { NULL, TYPE_Va }, /* Va */
251 { parse_mdoc_body, TYPE_Va }, /* Vt */
252 { parse_mdoc_Xr, 0 }, /* Xr */
253 { NULL, 0 }, /* %A */
254 { NULL, 0 }, /* %B */
255 { NULL, 0 }, /* %D */
256 { NULL, 0 }, /* %I */
257 { NULL, 0 }, /* %J */
258 { NULL, 0 }, /* %N */
259 { NULL, 0 }, /* %O */
260 { NULL, 0 }, /* %P */
261 { NULL, 0 }, /* %R */
262 { NULL, 0 }, /* %T */
263 { NULL, 0 }, /* %V */
264 { NULL, 0 }, /* Ac */
265 { NULL, 0 }, /* Ao */
266 { NULL, 0 }, /* Aq */
267 { NULL, TYPE_At }, /* At */
268 { NULL, 0 }, /* Bc */
269 { NULL, 0 }, /* Bf */
270 { NULL, 0 }, /* Bo */
271 { NULL, 0 }, /* Bq */
272 { NULL, TYPE_Bsx }, /* Bsx */
273 { NULL, TYPE_Bx }, /* Bx */
274 { NULL, 0 }, /* Db */
275 { NULL, 0 }, /* Dc */
276 { NULL, 0 }, /* Do */
277 { NULL, 0 }, /* Dq */
278 { NULL, 0 }, /* Ec */
279 { NULL, 0 }, /* Ef */
280 { NULL, TYPE_Em }, /* Em */
281 { NULL, 0 }, /* Eo */
282 { NULL, TYPE_Fx }, /* Fx */
283 { NULL, TYPE_Ms }, /* Ms */
284 { NULL, 0 }, /* No */
285 { NULL, 0 }, /* Ns */
286 { NULL, TYPE_Nx }, /* Nx */
287 { NULL, TYPE_Ox }, /* Ox */
288 { NULL, 0 }, /* Pc */
289 { NULL, 0 }, /* Pf */
290 { NULL, 0 }, /* Po */
291 { NULL, 0 }, /* Pq */
292 { NULL, 0 }, /* Qc */
293 { NULL, 0 }, /* Ql */
294 { NULL, 0 }, /* Qo */
295 { NULL, 0 }, /* Qq */
296 { NULL, 0 }, /* Re */
297 { NULL, 0 }, /* Rs */
298 { NULL, 0 }, /* Sc */
299 { NULL, 0 }, /* So */
300 { NULL, 0 }, /* Sq */
301 { NULL, 0 }, /* Sm */
302 { NULL, 0 }, /* Sx */
303 { NULL, TYPE_Sy }, /* Sy */
304 { NULL, TYPE_Tn }, /* Tn */
305 { NULL, 0 }, /* Ux */
306 { NULL, 0 }, /* Xc */
307 { NULL, 0 }, /* Xo */
308 { parse_mdoc_Fo, 0 }, /* Fo */
309 { NULL, 0 }, /* Fc */
310 { NULL, 0 }, /* Oo */
311 { NULL, 0 }, /* Oc */
312 { NULL, 0 }, /* Bk */
313 { NULL, 0 }, /* Ek */
314 { NULL, 0 }, /* Bt */
315 { NULL, 0 }, /* Hf */
316 { NULL, 0 }, /* Fr */
317 { NULL, 0 }, /* Ud */
318 { NULL, TYPE_Lb }, /* Lb */
319 { NULL, 0 }, /* Lp */
320 { NULL, TYPE_Lk }, /* Lk */
321 { NULL, TYPE_Mt }, /* Mt */
322 { NULL, 0 }, /* Brq */
323 { NULL, 0 }, /* Bro */
324 { NULL, 0 }, /* Brc */
325 { NULL, 0 }, /* %C */
326 { NULL, 0 }, /* Es */
327 { NULL, 0 }, /* En */
328 { NULL, TYPE_Dx }, /* Dx */
329 { NULL, 0 }, /* %Q */
330 { NULL, 0 }, /* br */
331 { NULL, 0 }, /* sp */
332 { NULL, 0 }, /* %U */
333 { NULL, 0 }, /* Ta */
334 { NULL, 0 }, /* ll */
335 };
336
337
338 int
339 mandocdb(int argc, char *argv[])
340 {
341 int ch, i;
342 size_t j, sz;
343 const char *path_arg;
344 struct manpaths dirs;
345 struct mparse *mp;
346 struct ohash_info mpages_info, mlinks_info;
347
348 memset(stmts, 0, STMT__MAX * sizeof(sqlite3_stmt *));
349 memset(&dirs, 0, sizeof(struct manpaths));
350
351 mpages_info.alloc = mlinks_info.alloc = hash_alloc;
352 mpages_info.calloc = mlinks_info.calloc = hash_calloc;
353 mpages_info.free = mlinks_info.free = hash_free;
354 mpages_info.data = mlinks_info.data = NULL;
355
356 mpages_info.key_offset = offsetof(struct mpage, inodev);
357 mlinks_info.key_offset = offsetof(struct mlink, file);
358
359 progname = strrchr(argv[0], '/');
360 if (progname == NULL)
361 progname = argv[0];
362 else
363 ++progname;
364
365 /*
366 * We accept a few different invocations.
367 * The CHECKOP macro makes sure that invocation styles don't
368 * clobber each other.
369 */
370 #define CHECKOP(_op, _ch) do \
371 if (OP_DEFAULT != (_op)) { \
372 fprintf(stderr, "%s: -%c: Conflicting option\n", \
373 progname, (_ch)); \
374 goto usage; \
375 } while (/*CONSTCOND*/0)
376
377 path_arg = NULL;
378 op = OP_DEFAULT;
379
380 while (-1 != (ch = getopt(argc, argv, "aC:Dd:npQT:tu:v")))
381 switch (ch) {
382 case 'a':
383 use_all = 1;
384 break;
385 case 'C':
386 CHECKOP(op, ch);
387 path_arg = optarg;
388 op = OP_CONFFILE;
389 break;
390 case 'D':
391 debug++;
392 break;
393 case 'd':
394 CHECKOP(op, ch);
395 path_arg = optarg;
396 op = OP_UPDATE;
397 break;
398 case 'n':
399 nodb = 1;
400 break;
401 case 'p':
402 warnings = 1;
403 break;
404 case 'Q':
405 mparse_options |= MPARSE_QUICK;
406 break;
407 case 'T':
408 if (strcmp(optarg, "utf8")) {
409 fprintf(stderr, "%s: -T%s: "
410 "Unsupported output format\n",
411 progname, optarg);
412 goto usage;
413 }
414 write_utf8 = 1;
415 break;
416 case 't':
417 CHECKOP(op, ch);
418 dup2(STDOUT_FILENO, STDERR_FILENO);
419 op = OP_TEST;
420 nodb = warnings = 1;
421 break;
422 case 'u':
423 CHECKOP(op, ch);
424 path_arg = optarg;
425 op = OP_DELETE;
426 break;
427 case 'v':
428 /* Compatibility with espie@'s makewhatis. */
429 break;
430 default:
431 goto usage;
432 }
433
434 argc -= optind;
435 argv += optind;
436
437 if (OP_CONFFILE == op && argc > 0) {
438 fprintf(stderr, "%s: -C: Too many arguments\n",
439 progname);
440 goto usage;
441 }
442
443 exitcode = (int)MANDOCLEVEL_OK;
444 mchars = mchars_alloc();
445 mp = mparse_alloc(mparse_options, MANDOCLEVEL_BADARG, NULL,
446 mchars, NULL);
447 ohash_init(&mpages, 6, &mpages_info);
448 ohash_init(&mlinks, 6, &mlinks_info);
449
450 if (OP_UPDATE == op || OP_DELETE == op || OP_TEST == op) {
451
452 /*
453 * Most of these deal with a specific directory.
454 * Jump into that directory first.
455 */
456 if (OP_TEST != op && 0 == set_basedir(path_arg, 1))
457 goto out;
458
459 if (dbopen(1)) {
460 /*
461 * The existing database is usable. Process
462 * all files specified on the command-line.
463 */
464 use_all = 1;
465 for (i = 0; i < argc; i++)
466 filescan(argv[i]);
467 if (OP_TEST != op)
468 dbprune();
469 } else {
470 /*
471 * Database missing or corrupt.
472 * Recreate from scratch.
473 */
474 exitcode = (int)MANDOCLEVEL_OK;
475 op = OP_DEFAULT;
476 if (0 == treescan())
477 goto out;
478 if (0 == dbopen(0))
479 goto out;
480 }
481 if (OP_DELETE != op)
482 mpages_merge(mp);
483 dbclose(OP_DEFAULT == op ? 0 : 1);
484 } else {
485 /*
486 * If we have arguments, use them as our manpaths.
487 * If we don't, grok from manpath(1) or however else
488 * manpath_parse() wants to do it.
489 */
490 if (argc > 0) {
491 dirs.paths = mandoc_reallocarray(NULL,
492 argc, sizeof(char *));
493 dirs.sz = (size_t)argc;
494 for (i = 0; i < argc; i++)
495 dirs.paths[i] = mandoc_strdup(argv[i]);
496 } else
497 manpath_parse(&dirs, path_arg, NULL, NULL);
498
499 if (0 == dirs.sz) {
500 exitcode = (int)MANDOCLEVEL_BADARG;
501 say("", "Empty manpath");
502 }
503
504 /*
505 * First scan the tree rooted at a base directory, then
506 * build a new database and finally move it into place.
507 * Ignore zero-length directories and strip trailing
508 * slashes.
509 */
510 for (j = 0; j < dirs.sz; j++) {
511 sz = strlen(dirs.paths[j]);
512 if (sz && '/' == dirs.paths[j][sz - 1])
513 dirs.paths[j][--sz] = '\0';
514 if (0 == sz)
515 continue;
516
517 if (j) {
518 ohash_init(&mpages, 6, &mpages_info);
519 ohash_init(&mlinks, 6, &mlinks_info);
520 }
521
522 if (0 == set_basedir(dirs.paths[j], argc > 0))
523 continue;
524 if (0 == treescan())
525 continue;
526 if (0 == dbopen(0))
527 continue;
528
529 mpages_merge(mp);
530 if (warnings && !nodb &&
531 ! (MPARSE_QUICK & mparse_options))
532 names_check();
533 dbclose(0);
534
535 if (j + 1 < dirs.sz) {
536 mpages_free();
537 ohash_delete(&mpages);
538 ohash_delete(&mlinks);
539 }
540 }
541 }
542 out:
543 manpath_free(&dirs);
544 mparse_free(mp);
545 mchars_free(mchars);
546 mpages_free();
547 ohash_delete(&mpages);
548 ohash_delete(&mlinks);
549 return(exitcode);
550 usage:
551 fprintf(stderr, "usage: %s [-aDnpQ] [-C file] [-Tutf8]\n"
552 " %s [-aDnpQ] [-Tutf8] dir ...\n"
553 " %s [-DnpQ] [-Tutf8] -d dir [file ...]\n"
554 " %s [-Dnp] -u dir [file ...]\n"
555 " %s [-Q] -t file ...\n",
556 progname, progname, progname,
557 progname, progname);
558
559 return((int)MANDOCLEVEL_BADARG);
560 }
561
562 /*
563 * Scan a directory tree rooted at "basedir" for manpages.
564 * We use fts(), scanning directory parts along the way for clues to our
565 * section and architecture.
566 *
567 * If use_all has been specified, grok all files.
568 * If not, sanitise paths to the following:
569 *
570 * [./]man*[/<arch>]/<name>.<section>
571 * or
572 * [./]cat<section>[/<arch>]/<name>.0
573 *
574 * TODO: accomodate for multi-language directories.
575 */
576 static int
577 treescan(void)
578 {
579 char buf[PATH_MAX];
580 FTS *f;
581 FTSENT *ff;
582 struct mlink *mlink;
583 int dform, gzip;
584 char *dsec, *arch, *fsec, *cp;
585 const char *path;
586 const char *argv[2];
587
588 argv[0] = ".";
589 argv[1] = (char *)NULL;
590
591 f = fts_open((char * const *)argv,
592 FTS_PHYSICAL | FTS_NOCHDIR, NULL);
593 if (NULL == f) {
594 exitcode = (int)MANDOCLEVEL_SYSERR;
595 say("", "&fts_open");
596 return(0);
597 }
598
599 dsec = arch = NULL;
600 dform = FORM_NONE;
601
602 while (NULL != (ff = fts_read(f))) {
603 path = ff->fts_path + 2;
604 switch (ff->fts_info) {
605
606 /*
607 * Symbolic links require various sanity checks,
608 * then get handled just like regular files.
609 */
610 case FTS_SL:
611 if (NULL == realpath(path, buf)) {
612 if (warnings)
613 say(path, "&realpath");
614 continue;
615 }
616 if (strstr(buf, basedir) != buf) {
617 if (warnings) say("",
618 "%s: outside base directory", buf);
619 continue;
620 }
621 /* Use logical inode to avoid mpages dupe. */
622 if (-1 == stat(path, ff->fts_statp)) {
623 if (warnings)
624 say(path, "&stat");
625 continue;
626 }
627 /* FALLTHROUGH */
628
629 /*
630 * If we're a regular file, add an mlink by using the
631 * stored directory data and handling the filename.
632 */
633 case FTS_F:
634 if (0 == strcmp(path, MANDOC_DB))
635 continue;
636 if ( ! use_all && ff->fts_level < 2) {
637 if (warnings)
638 say(path, "Extraneous file");
639 continue;
640 }
641 gzip = 0;
642 fsec = NULL;
643 while (NULL == fsec) {
644 fsec = strrchr(ff->fts_name, '.');
645 if (NULL == fsec || strcmp(fsec+1, "gz"))
646 break;
647 gzip = 1;
648 *fsec = '\0';
649 fsec = NULL;
650 }
651 if (NULL == fsec) {
652 if ( ! use_all) {
653 if (warnings)
654 say(path,
655 "No filename suffix");
656 continue;
657 }
658 } else if (0 == strcmp(++fsec, "html")) {
659 if (warnings)
660 say(path, "Skip html");
661 continue;
662 } else if (0 == strcmp(fsec, "ps")) {
663 if (warnings)
664 say(path, "Skip ps");
665 continue;
666 } else if (0 == strcmp(fsec, "pdf")) {
667 if (warnings)
668 say(path, "Skip pdf");
669 continue;
670 } else if ( ! use_all &&
671 ((FORM_SRC == dform && strcmp(fsec, dsec)) ||
672 (FORM_CAT == dform && strcmp(fsec, "0")))) {
673 if (warnings)
674 say(path, "Wrong filename suffix");
675 continue;
676 } else
677 fsec[-1] = '\0';
678
679 mlink = mandoc_calloc(1, sizeof(struct mlink));
680 if (strlcpy(mlink->file, path,
681 sizeof(mlink->file)) >=
682 sizeof(mlink->file)) {
683 say(path, "Filename too long");
684 free(mlink);
685 continue;
686 }
687 mlink->dform = dform;
688 mlink->dsec = dsec;
689 mlink->arch = arch;
690 mlink->name = ff->fts_name;
691 mlink->fsec = fsec;
692 mlink->gzip = gzip;
693 mlink_add(mlink, ff->fts_statp);
694 continue;
695
696 case FTS_D:
697 /* FALLTHROUGH */
698 case FTS_DP:
699 break;
700
701 default:
702 if (warnings)
703 say(path, "Not a regular file");
704 continue;
705 }
706
707 switch (ff->fts_level) {
708 case 0:
709 /* Ignore the root directory. */
710 break;
711 case 1:
712 /*
713 * This might contain manX/ or catX/.
714 * Try to infer this from the name.
715 * If we're not in use_all, enforce it.
716 */
717 cp = ff->fts_name;
718 if (FTS_DP == ff->fts_info)
719 break;
720
721 if (0 == strncmp(cp, "man", 3)) {
722 dform = FORM_SRC;
723 dsec = cp + 3;
724 } else if (0 == strncmp(cp, "cat", 3)) {
725 dform = FORM_CAT;
726 dsec = cp + 3;
727 } else {
728 dform = FORM_NONE;
729 dsec = NULL;
730 }
731
732 if (NULL != dsec || use_all)
733 break;
734
735 if (warnings)
736 say(path, "Unknown directory part");
737 fts_set(f, ff, FTS_SKIP);
738 break;
739 case 2:
740 /*
741 * Possibly our architecture.
742 * If we're descending, keep tabs on it.
743 */
744 if (FTS_DP != ff->fts_info && NULL != dsec)
745 arch = ff->fts_name;
746 else
747 arch = NULL;
748 break;
749 default:
750 if (FTS_DP == ff->fts_info || use_all)
751 break;
752 if (warnings)
753 say(path, "Extraneous directory part");
754 fts_set(f, ff, FTS_SKIP);
755 break;
756 }
757 }
758
759 fts_close(f);
760 return(1);
761 }
762
763 /*
764 * Add a file to the mlinks table.
765 * Do not verify that it's a "valid" looking manpage (we'll do that
766 * later).
767 *
768 * Try to infer the manual section, architecture, and page name from the
769 * path, assuming it looks like
770 *
771 * [./]man*[/<arch>]/<name>.<section>
772 * or
773 * [./]cat<section>[/<arch>]/<name>.0
774 *
775 * See treescan() for the fts(3) version of this.
776 */
777 static void
778 filescan(const char *file)
779 {
780 char buf[PATH_MAX];
781 struct stat st;
782 struct mlink *mlink;
783 char *p, *start;
784
785 assert(use_all);
786
787 if (0 == strncmp(file, "./", 2))
788 file += 2;
789
790 /*
791 * We have to do lstat(2) before realpath(3) loses
792 * the information whether this is a symbolic link.
793 * We need to know that because for symbolic links,
794 * we want to use the orginal file name, while for
795 * regular files, we want to use the real path.
796 */
797 if (-1 == lstat(file, &st)) {
798 exitcode = (int)MANDOCLEVEL_BADARG;
799 say(file, "&lstat");
800 return;
801 } else if (0 == ((S_IFREG | S_IFLNK) & st.st_mode)) {
802 exitcode = (int)MANDOCLEVEL_BADARG;
803 say(file, "Not a regular file");
804 return;
805 }
806
807 /*
808 * We have to resolve the file name to the real path
809 * in any case for the base directory check.
810 */
811 if (NULL == realpath(file, buf)) {
812 exitcode = (int)MANDOCLEVEL_BADARG;
813 say(file, "&realpath");
814 return;
815 }
816
817 if (OP_TEST == op)
818 start = buf;
819 else if (strstr(buf, basedir) == buf)
820 start = buf + strlen(basedir);
821 else {
822 exitcode = (int)MANDOCLEVEL_BADARG;
823 say("", "%s: outside base directory", buf);
824 return;
825 }
826
827 /*
828 * Now we are sure the file is inside our tree.
829 * If it is a symbolic link, ignore the real path
830 * and use the original name.
831 * This implies passing stuff like "cat1/../man1/foo.1"
832 * on the command line won't work. So don't do that.
833 * Note the stat(2) can still fail if the link target
834 * doesn't exist.
835 */
836 if (S_IFLNK & st.st_mode) {
837 if (-1 == stat(buf, &st)) {
838 exitcode = (int)MANDOCLEVEL_BADARG;
839 say(file, "&stat");
840 return;
841 }
842 if (strlcpy(buf, file, sizeof(buf)) >= sizeof(buf)) {
843 say(file, "Filename too long");
844 return;
845 }
846 start = buf;
847 if (OP_TEST != op && strstr(buf, basedir) == buf)
848 start += strlen(basedir);
849 }
850
851 mlink = mandoc_calloc(1, sizeof(struct mlink));
852 mlink->dform = FORM_NONE;
853 if (strlcpy(mlink->file, start, sizeof(mlink->file)) >=
854 sizeof(mlink->file)) {
855 say(start, "Filename too long");
856 free(mlink);
857 return;
858 }
859
860 /*
861 * First try to guess our directory structure.
862 * If we find a separator, try to look for man* or cat*.
863 * If we find one of these and what's underneath is a directory,
864 * assume it's an architecture.
865 */
866 if (NULL != (p = strchr(start, '/'))) {
867 *p++ = '\0';
868 if (0 == strncmp(start, "man", 3)) {
869 mlink->dform = FORM_SRC;
870 mlink->dsec = start + 3;
871 } else if (0 == strncmp(start, "cat", 3)) {
872 mlink->dform = FORM_CAT;
873 mlink->dsec = start + 3;
874 }
875
876 start = p;
877 if (NULL != mlink->dsec && NULL != (p = strchr(start, '/'))) {
878 *p++ = '\0';
879 mlink->arch = start;
880 start = p;
881 }
882 }
883
884 /*
885 * Now check the file suffix.
886 * Suffix of `.0' indicates a catpage, `.1-9' is a manpage.
887 */
888 p = strrchr(start, '\0');
889 while (p-- > start && '/' != *p && '.' != *p)
890 /* Loop. */ ;
891
892 if ('.' == *p) {
893 *p++ = '\0';
894 mlink->fsec = p;
895 }
896
897 /*
898 * Now try to parse the name.
899 * Use the filename portion of the path.
900 */
901 mlink->name = start;
902 if (NULL != (p = strrchr(start, '/'))) {
903 mlink->name = p + 1;
904 *p = '\0';
905 }
906 mlink_add(mlink, &st);
907 }
908
909 static void
910 mlink_add(struct mlink *mlink, const struct stat *st)
911 {
912 struct inodev inodev;
913 struct mpage *mpage;
914 unsigned int slot;
915
916 assert(NULL != mlink->file);
917
918 mlink->dsec = mandoc_strdup(mlink->dsec ? mlink->dsec : "");
919 mlink->arch = mandoc_strdup(mlink->arch ? mlink->arch : "");
920 mlink->name = mandoc_strdup(mlink->name ? mlink->name : "");
921 mlink->fsec = mandoc_strdup(mlink->fsec ? mlink->fsec : "");
922
923 if ('0' == *mlink->fsec) {
924 free(mlink->fsec);
925 mlink->fsec = mandoc_strdup(mlink->dsec);
926 mlink->fform = FORM_CAT;
927 } else if ('1' <= *mlink->fsec && '9' >= *mlink->fsec)
928 mlink->fform = FORM_SRC;
929 else
930 mlink->fform = FORM_NONE;
931
932 slot = ohash_qlookup(&mlinks, mlink->file);
933 assert(NULL == ohash_find(&mlinks, slot));
934 ohash_insert(&mlinks, slot, mlink);
935
936 inodev.st_ino = st->st_ino;
937 inodev.st_dev = st->st_dev;
938 slot = ohash_lookup_memory(&mpages, (char *)&inodev,
939 sizeof(struct inodev), inodev.st_ino);
940 mpage = ohash_find(&mpages, slot);
941 if (NULL == mpage) {
942 mpage = mandoc_calloc(1, sizeof(struct mpage));
943 mpage->inodev.st_ino = inodev.st_ino;
944 mpage->inodev.st_dev = inodev.st_dev;
945 ohash_insert(&mpages, slot, mpage);
946 } else
947 mlink->next = mpage->mlinks;
948 mpage->mlinks = mlink;
949 mlink->mpage = mpage;
950 }
951
952 static void
953 mlink_free(struct mlink *mlink)
954 {
955
956 free(mlink->dsec);
957 free(mlink->arch);
958 free(mlink->name);
959 free(mlink->fsec);
960 free(mlink);
961 }
962
963 static void
964 mpages_free(void)
965 {
966 struct mpage *mpage;
967 struct mlink *mlink;
968 unsigned int slot;
969
970 mpage = ohash_first(&mpages, &slot);
971 while (NULL != mpage) {
972 while (NULL != (mlink = mpage->mlinks)) {
973 mpage->mlinks = mlink->next;
974 mlink_free(mlink);
975 }
976 free(mpage->sec);
977 free(mpage->arch);
978 free(mpage->title);
979 free(mpage->desc);
980 free(mpage);
981 mpage = ohash_next(&mpages, &slot);
982 }
983 }
984
985 /*
986 * For each mlink to the mpage, check whether the path looks like
987 * it is formatted, and if it does, check whether a source manual
988 * exists by the same name, ignoring the suffix.
989 * If both conditions hold, drop the mlink.
990 */
991 static void
992 mlinks_undupe(struct mpage *mpage)
993 {
994 char buf[PATH_MAX];
995 struct mlink **prev;
996 struct mlink *mlink;
997 char *bufp;
998
999 mpage->form = FORM_CAT;
1000 prev = &mpage->mlinks;
1001 while (NULL != (mlink = *prev)) {
1002 if (FORM_CAT != mlink->dform) {
1003 mpage->form = FORM_NONE;
1004 goto nextlink;
1005 }
1006 (void)strlcpy(buf, mlink->file, sizeof(buf));
1007 bufp = strstr(buf, "cat");
1008 assert(NULL != bufp);
1009 memcpy(bufp, "man", 3);
1010 if (NULL != (bufp = strrchr(buf, '.')))
1011 *++bufp = '\0';
1012 (void)strlcat(buf, mlink->dsec, sizeof(buf));
1013 if (NULL == ohash_find(&mlinks,
1014 ohash_qlookup(&mlinks, buf)))
1015 goto nextlink;
1016 if (warnings)
1017 say(mlink->file, "Man source exists: %s", buf);
1018 if (use_all)
1019 goto nextlink;
1020 *prev = mlink->next;
1021 mlink_free(mlink);
1022 continue;
1023 nextlink:
1024 prev = &(*prev)->next;
1025 }
1026 }
1027
1028 static void
1029 mlink_check(struct mpage *mpage, struct mlink *mlink)
1030 {
1031 struct str *str;
1032 unsigned int slot;
1033
1034 /*
1035 * Check whether the manual section given in a file
1036 * agrees with the directory where the file is located.
1037 * Some manuals have suffixes like (3p) on their
1038 * section number either inside the file or in the
1039 * directory name, some are linked into more than one
1040 * section, like encrypt(1) = makekey(8).
1041 */
1042
1043 if (FORM_SRC == mpage->form &&
1044 strcasecmp(mpage->sec, mlink->dsec))
1045 say(mlink->file, "Section \"%s\" manual in %s directory",
1046 mpage->sec, mlink->dsec);
1047
1048 /*
1049 * Manual page directories exist for each kernel
1050 * architecture as returned by machine(1).
1051 * However, many manuals only depend on the
1052 * application architecture as returned by arch(1).
1053 * For example, some (2/ARM) manuals are shared
1054 * across the "armish" and "zaurus" kernel
1055 * architectures.
1056 * A few manuals are even shared across completely
1057 * different architectures, for example fdformat(1)
1058 * on amd64, i386, sparc, and sparc64.
1059 */
1060
1061 if (strcasecmp(mpage->arch, mlink->arch))
1062 say(mlink->file, "Architecture \"%s\" manual in "
1063 "\"%s\" directory", mpage->arch, mlink->arch);
1064
1065 /*
1066 * XXX
1067 * parse_cat() doesn't set NAME_TITLE yet.
1068 */
1069
1070 if (FORM_CAT == mpage->form)
1071 return;
1072
1073 /*
1074 * Check whether this mlink
1075 * appears as a name in the NAME section.
1076 */
1077
1078 slot = ohash_qlookup(&names, mlink->name);
1079 str = ohash_find(&names, slot);
1080 assert(NULL != str);
1081 if ( ! (NAME_TITLE & str->mask))
1082 say(mlink->file, "Name missing in NAME section");
1083 }
1084
1085 /*
1086 * Run through the files in the global vector "mpages"
1087 * and add them to the database specified in "basedir".
1088 *
1089 * This handles the parsing scheme itself, using the cues of directory
1090 * and filename to determine whether the file is parsable or not.
1091 */
1092 static void
1093 mpages_merge(struct mparse *mp)
1094 {
1095 char any[] = "any";
1096 struct ohash_info str_info;
1097 struct mpage *mpage, *mpage_dest;
1098 struct mlink *mlink, *mlink_dest;
1099 struct mdoc *mdoc;
1100 struct man *man;
1101 char *sodest;
1102 char *cp;
1103 int fd;
1104 unsigned int pslot;
1105
1106 str_info.alloc = hash_alloc;
1107 str_info.calloc = hash_calloc;
1108 str_info.free = hash_free;
1109 str_info.data = NULL;
1110 str_info.key_offset = offsetof(struct str, key);
1111
1112 if ( ! nodb)
1113 SQL_EXEC("BEGIN TRANSACTION");
1114
1115 mpage = ohash_first(&mpages, &pslot);
1116 while (mpage != NULL) {
1117 mlinks_undupe(mpage);
1118 if ((mlink = mpage->mlinks) == NULL) {
1119 mpage = ohash_next(&mpages, &pslot);
1120 continue;
1121 }
1122
1123 name_mask = NAME_MASK;
1124 ohash_init(&names, 4, &str_info);
1125 ohash_init(&strings, 6, &str_info);
1126 mparse_reset(mp);
1127 mdoc = NULL;
1128 man = NULL;
1129 sodest = NULL;
1130
1131 mparse_open(mp, &fd, mlink->file);
1132 if (fd == -1) {
1133 say(mlink->file, "&open");
1134 goto nextpage;
1135 }
1136
1137 /*
1138 * Interpret the file as mdoc(7) or man(7) source
1139 * code, unless it is known to be formatted.
1140 */
1141 if (mlink->dform != FORM_CAT || mlink->fform != FORM_CAT) {
1142 mparse_readfd(mp, fd, mlink->file);
1143 mparse_result(mp, &mdoc, &man, &sodest);
1144 }
1145
1146 if (sodest != NULL) {
1147 mlink_dest = ohash_find(&mlinks,
1148 ohash_qlookup(&mlinks, sodest));
1149 if (mlink_dest == NULL) {
1150 mandoc_asprintf(&cp, "%s.gz", sodest);
1151 mlink_dest = ohash_find(&mlinks,
1152 ohash_qlookup(&mlinks, cp));
1153 free(cp);
1154 }
1155 if (mlink_dest != NULL) {
1156
1157 /* The .so target exists. */
1158
1159 mpage_dest = mlink_dest->mpage;
1160 while (1) {
1161 mlink->mpage = mpage_dest;
1162
1163 /*
1164 * If the target was already
1165 * processed, add the links
1166 * to the database now.
1167 * Otherwise, this will
1168 * happen when we come
1169 * to the target.
1170 */
1171
1172 if (mpage_dest->pageid)
1173 dbadd_mlink_name(mlink);
1174
1175 if (mlink->next == NULL)
1176 break;
1177 mlink = mlink->next;
1178 }
1179
1180 /* Move all links to the target. */
1181
1182 mlink->next = mlink_dest->next;
1183 mlink_dest->next = mpage->mlinks;
1184 mpage->mlinks = NULL;
1185 }
1186 goto nextpage;
1187 } else if (mdoc != NULL) {
1188 mpage->form = FORM_SRC;
1189 mpage->sec = mdoc_meta(mdoc)->msec;
1190 mpage->sec = mandoc_strdup(
1191 mpage->sec == NULL ? "" : mpage->sec);
1192 mpage->arch = mdoc_meta(mdoc)->arch;
1193 mpage->arch = mandoc_strdup(
1194 mpage->arch == NULL ? "" : mpage->arch);
1195 mpage->title =
1196 mandoc_strdup(mdoc_meta(mdoc)->title);
1197 } else if (man != NULL) {
1198 mpage->form = FORM_SRC;
1199 mpage->sec = mandoc_strdup(man_meta(man)->msec);
1200 mpage->arch = mandoc_strdup(mlink->arch);
1201 mpage->title = mandoc_strdup(man_meta(man)->title);
1202 } else {
1203 mpage->form = FORM_CAT;
1204 mpage->sec = mandoc_strdup(mlink->dsec);
1205 mpage->arch = mandoc_strdup(mlink->arch);
1206 mpage->title = mandoc_strdup(mlink->name);
1207 }
1208 putkey(mpage, mpage->sec, TYPE_sec);
1209 if (*mpage->arch != '\0')
1210 putkey(mpage, mpage->arch, TYPE_arch);
1211
1212 for ( ; mlink != NULL; mlink = mlink->next) {
1213 if ('\0' != *mlink->dsec)
1214 putkey(mpage, mlink->dsec, TYPE_sec);
1215 if ('\0' != *mlink->fsec)
1216 putkey(mpage, mlink->fsec, TYPE_sec);
1217 putkey(mpage, '\0' == *mlink->arch ?
1218 any : mlink->arch, TYPE_arch);
1219 putkey(mpage, mlink->name, NAME_FILE);
1220 }
1221
1222 assert(mpage->desc == NULL);
1223 if (mdoc != NULL)
1224 parse_mdoc(mpage, mdoc_meta(mdoc), mdoc_node(mdoc));
1225 else if (man != NULL)
1226 parse_man(mpage, man_meta(man), man_node(man));
1227 else
1228 parse_cat(mpage, fd);
1229 if (mpage->desc == NULL)
1230 mpage->desc = mandoc_strdup(mpage->mlinks->name);
1231
1232 if (warnings && !use_all)
1233 for (mlink = mpage->mlinks; mlink;
1234 mlink = mlink->next)
1235 mlink_check(mpage, mlink);
1236
1237 dbadd(mpage);
1238 mlink = mpage->mlinks;
1239
1240 nextpage:
1241 if (mparse_wait(mp) != MANDOCLEVEL_OK) {
1242 exitcode = (int)MANDOCLEVEL_SYSERR;
1243 say(mlink->file, "&wait gunzip");
1244 }
1245 ohash_delete(&strings);
1246 ohash_delete(&names);
1247 mpage = ohash_next(&mpages, &pslot);
1248 }
1249
1250 if (0 == nodb)
1251 SQL_EXEC("END TRANSACTION");
1252 }
1253
1254 static void
1255 names_check(void)
1256 {
1257 sqlite3_stmt *stmt;
1258 const char *name, *sec, *arch, *key;
1259 int irc;
1260
1261 sqlite3_prepare_v2(db,
1262 "SELECT name, sec, arch, key FROM ("
1263 "SELECT name AS key, pageid FROM names "
1264 "WHERE bits & ? AND NOT EXISTS ("
1265 "SELECT pageid FROM mlinks "
1266 "WHERE mlinks.pageid == names.pageid "
1267 "AND mlinks.name == names.name"
1268 ")"
1269 ") JOIN ("
1270 "SELECT sec, arch, name, pageid FROM mlinks "
1271 "GROUP BY pageid"
1272 ") USING (pageid);",
1273 -1, &stmt, NULL);
1274
1275 if (SQLITE_OK != sqlite3_bind_int64(stmt, 1, NAME_TITLE))
1276 say("", "%s", sqlite3_errmsg(db));
1277
1278 while (SQLITE_ROW == (irc = sqlite3_step(stmt))) {
1279 name = (const char *)sqlite3_column_text(stmt, 0);
1280 sec = (const char *)sqlite3_column_text(stmt, 1);
1281 arch = (const char *)sqlite3_column_text(stmt, 2);
1282 key = (const char *)sqlite3_column_text(stmt, 3);
1283 say("", "%s(%s%s%s) lacks mlink \"%s\"", name, sec,
1284 '\0' == *arch ? "" : "/",
1285 '\0' == *arch ? "" : arch, key);
1286 }
1287 sqlite3_finalize(stmt);
1288 }
1289
1290 static void
1291 parse_cat(struct mpage *mpage, int fd)
1292 {
1293 FILE *stream;
1294 char *line, *p, *title;
1295 size_t len, plen, titlesz;
1296
1297 stream = (-1 == fd) ?
1298 fopen(mpage->mlinks->file, "r") :
1299 fdopen(fd, "r");
1300 if (NULL == stream) {
1301 if (-1 != fd)
1302 close(fd);
1303 if (warnings)
1304 say(mpage->mlinks->file, "&fopen");
1305 return;
1306 }
1307
1308 /* Skip to first blank line. */
1309
1310 while (NULL != (line = fgetln(stream, &len)))
1311 if ('\n' == *line)
1312 break;
1313
1314 /*
1315 * Assume the first line that is not indented
1316 * is the first section header. Skip to it.
1317 */
1318
1319 while (NULL != (line = fgetln(stream, &len)))
1320 if ('\n' != *line && ' ' != *line)
1321 break;
1322
1323 /*
1324 * Read up until the next section into a buffer.
1325 * Strip the leading and trailing newline from each read line,
1326 * appending a trailing space.
1327 * Ignore empty (whitespace-only) lines.
1328 */
1329
1330 titlesz = 0;
1331 title = NULL;
1332
1333 while (NULL != (line = fgetln(stream, &len))) {
1334 if (' ' != *line || '\n' != line[len - 1])
1335 break;
1336 while (len > 0 && isspace((unsigned char)*line)) {
1337 line++;
1338 len--;
1339 }
1340 if (1 == len)
1341 continue;
1342 title = mandoc_realloc(title, titlesz + len);
1343 memcpy(title + titlesz, line, len);
1344 titlesz += len;
1345 title[titlesz - 1] = ' ';
1346 }
1347
1348 /*
1349 * If no page content can be found, or the input line
1350 * is already the next section header, or there is no
1351 * trailing newline, reuse the page title as the page
1352 * description.
1353 */
1354
1355 if (NULL == title || '\0' == *title) {
1356 if (warnings)
1357 say(mpage->mlinks->file,
1358 "Cannot find NAME section");
1359 fclose(stream);
1360 free(title);
1361 return;
1362 }
1363
1364 title = mandoc_realloc(title, titlesz + 1);
1365 title[titlesz] = '\0';
1366
1367 /*
1368 * Skip to the first dash.
1369 * Use the remaining line as the description (no more than 70
1370 * bytes).
1371 */
1372
1373 if (NULL != (p = strstr(title, "- "))) {
1374 for (p += 2; ' ' == *p || '\b' == *p; p++)
1375 /* Skip to next word. */ ;
1376 } else {
1377 if (warnings)
1378 say(mpage->mlinks->file,
1379 "No dash in title line");
1380 p = title;
1381 }
1382
1383 plen = strlen(p);
1384
1385 /* Strip backspace-encoding from line. */
1386
1387 while (NULL != (line = memchr(p, '\b', plen))) {
1388 len = line - p;
1389 if (0 == len) {
1390 memmove(line, line + 1, plen--);
1391 continue;
1392 }
1393 memmove(line - 1, line + 1, plen - len);
1394 plen -= 2;
1395 }
1396
1397 mpage->desc = mandoc_strdup(p);
1398 fclose(stream);
1399 free(title);
1400 }
1401
1402 /*
1403 * Put a type/word pair into the word database for this particular file.
1404 */
1405 static void
1406 putkey(const struct mpage *mpage, char *value, uint64_t type)
1407 {
1408 char *cp;
1409
1410 assert(NULL != value);
1411 if (TYPE_arch == type)
1412 for (cp = value; *cp; cp++)
1413 if (isupper((unsigned char)*cp))
1414 *cp = _tolower((unsigned char)*cp);
1415 putkeys(mpage, value, strlen(value), type);
1416 }
1417
1418 /*
1419 * Grok all nodes at or below a certain mdoc node into putkey().
1420 */
1421 static void
1422 putmdockey(const struct mpage *mpage,
1423 const struct mdoc_node *n, uint64_t m)
1424 {
1425
1426 for ( ; NULL != n; n = n->next) {
1427 if (NULL != n->child)
1428 putmdockey(mpage, n->child, m);
1429 if (MDOC_TEXT == n->type)
1430 putkey(mpage, n->string, m);
1431 }
1432 }
1433
1434 static void
1435 parse_man(struct mpage *mpage, const struct man_meta *meta,
1436 const struct man_node *n)
1437 {
1438 const struct man_node *head, *body;
1439 char *start, *title;
1440 char byte;
1441 size_t sz;
1442
1443 if (NULL == n)
1444 return;
1445
1446 /*
1447 * We're only searching for one thing: the first text child in
1448 * the BODY of a NAME section. Since we don't keep track of
1449 * sections in -man, run some hoops to find out whether we're in
1450 * the correct section or not.
1451 */
1452
1453 if (MAN_BODY == n->type && MAN_SH == n->tok) {
1454 body = n;
1455 assert(body->parent);
1456 if (NULL != (head = body->parent->head) &&
1457 1 == head->nchild &&
1458 NULL != (head = (head->child)) &&
1459 MAN_TEXT == head->type &&
1460 0 == strcmp(head->string, "NAME") &&
1461 NULL != body->child) {
1462
1463 /*
1464 * Suck the entire NAME section into memory.
1465 * Yes, we might run away.
1466 * But too many manuals have big, spread-out
1467 * NAME sections over many lines.
1468 */
1469
1470 title = NULL;
1471 man_deroff(&title, body);
1472 if (NULL == title)
1473 return;
1474
1475 /*
1476 * Go through a special heuristic dance here.
1477 * Conventionally, one or more manual names are
1478 * comma-specified prior to a whitespace, then a
1479 * dash, then a description. Try to puzzle out
1480 * the name parts here.
1481 */
1482
1483 start = title;
1484 for ( ;; ) {
1485 sz = strcspn(start, " ,");
1486 if ('\0' == start[sz])
1487 break;
1488
1489 byte = start[sz];
1490 start[sz] = '\0';
1491
1492 /*
1493 * Assume a stray trailing comma in the
1494 * name list if a name begins with a dash.
1495 */
1496
1497 if ('-' == start[0] ||
1498 ('\\' == start[0] && '-' == start[1]))
1499 break;
1500
1501 putkey(mpage, start, NAME_TITLE);
1502 if ( ! (mpage->name_head_done ||
1503 strcasecmp(start, meta->title))) {
1504 putkey(mpage, start, NAME_HEAD);
1505 mpage->name_head_done = 1;
1506 }
1507
1508 if (' ' == byte) {
1509 start += sz + 1;
1510 break;
1511 }
1512
1513 assert(',' == byte);
1514 start += sz + 1;
1515 while (' ' == *start)
1516 start++;
1517 }
1518
1519 if (start == title) {
1520 putkey(mpage, start, NAME_TITLE);
1521 if ( ! (mpage->name_head_done ||
1522 strcasecmp(start, meta->title))) {
1523 putkey(mpage, start, NAME_HEAD);
1524 mpage->name_head_done = 1;
1525 }
1526 free(title);
1527 return;
1528 }
1529
1530 while (isspace((unsigned char)*start))
1531 start++;
1532
1533 if (0 == strncmp(start, "-", 1))
1534 start += 1;
1535 else if (0 == strncmp(start, "\\-\\-", 4))
1536 start += 4;
1537 else if (0 == strncmp(start, "\\-", 2))
1538 start += 2;
1539 else if (0 == strncmp(start, "\\(en", 4))
1540 start += 4;
1541 else if (0 == strncmp(start, "\\(em", 4))
1542 start += 4;
1543
1544 while (' ' == *start)
1545 start++;
1546
1547 mpage->desc = mandoc_strdup(start);
1548 free(title);
1549 return;
1550 }
1551 }
1552
1553 for (n = n->child; n; n = n->next) {
1554 if (NULL != mpage->desc)
1555 break;
1556 parse_man(mpage, meta, n);
1557 }
1558 }
1559
1560 static void
1561 parse_mdoc(struct mpage *mpage, const struct mdoc_meta *meta,
1562 const struct mdoc_node *n)
1563 {
1564
1565 assert(NULL != n);
1566 for (n = n->child; NULL != n; n = n->next) {
1567 switch (n->type) {
1568 case MDOC_ELEM:
1569 /* FALLTHROUGH */
1570 case MDOC_BLOCK:
1571 /* FALLTHROUGH */
1572 case MDOC_HEAD:
1573 /* FALLTHROUGH */
1574 case MDOC_BODY:
1575 /* FALLTHROUGH */
1576 case MDOC_TAIL:
1577 if (NULL != mdocs[n->tok].fp)
1578 if (0 == (*mdocs[n->tok].fp)(mpage, meta, n))
1579 break;
1580 if (mdocs[n->tok].mask)
1581 putmdockey(mpage, n->child,
1582 mdocs[n->tok].mask);
1583 break;
1584 default:
1585 assert(MDOC_ROOT != n->type);
1586 continue;
1587 }
1588 if (NULL != n->child)
1589 parse_mdoc(mpage, meta, n);
1590 }
1591 }
1592
1593 static int
1594 parse_mdoc_Fd(struct mpage *mpage, const struct mdoc_meta *meta,
1595 const struct mdoc_node *n)
1596 {
1597 char *start, *end;
1598 size_t sz;
1599
1600 if (SEC_SYNOPSIS != n->sec ||
1601 NULL == (n = n->child) ||
1602 MDOC_TEXT != n->type)
1603 return(0);
1604
1605 /*
1606 * Only consider those `Fd' macro fields that begin with an
1607 * "inclusion" token (versus, e.g., #define).
1608 */
1609
1610 if (strcmp("#include", n->string))
1611 return(0);
1612
1613 if (NULL == (n = n->next) || MDOC_TEXT != n->type)
1614 return(0);
1615
1616 /*
1617 * Strip away the enclosing angle brackets and make sure we're
1618 * not zero-length.
1619 */
1620
1621 start = n->string;
1622 if ('<' == *start || '"' == *start)
1623 start++;
1624
1625 if (0 == (sz = strlen(start)))
1626 return(0);
1627
1628 end = &start[(int)sz - 1];
1629 if ('>' == *end || '"' == *end)
1630 end--;
1631
1632 if (end > start)
1633 putkeys(mpage, start, end - start + 1, TYPE_In);
1634 return(0);
1635 }
1636
1637 static void
1638 parse_mdoc_fname(struct mpage *mpage, const struct mdoc_node *n)
1639 {
1640 char *cp;
1641 size_t sz;
1642
1643 if (n->type != MDOC_TEXT)
1644 return;
1645
1646 /* Skip function pointer punctuation. */
1647
1648 cp = n->string;
1649 while (*cp == '(' || *cp == '*')
1650 cp++;
1651 sz = strcspn(cp, "()");
1652
1653 putkeys(mpage, cp, sz, TYPE_Fn);
1654 if (n->sec == SEC_SYNOPSIS)
1655 putkeys(mpage, cp, sz, NAME_SYN);
1656 }
1657
1658 static int
1659 parse_mdoc_Fn(struct mpage *mpage, const struct mdoc_meta *meta,
1660 const struct mdoc_node *n)
1661 {
1662
1663 if (n->child == NULL)
1664 return(0);
1665
1666 parse_mdoc_fname(mpage, n->child);
1667
1668 for (n = n->child->next; n != NULL; n = n->next)
1669 if (n->type == MDOC_TEXT)
1670 putkey(mpage, n->string, TYPE_Fa);
1671
1672 return(0);
1673 }
1674
1675 static int
1676 parse_mdoc_Fo(struct mpage *mpage, const struct mdoc_meta *meta,
1677 const struct mdoc_node *n)
1678 {
1679
1680 if (n->type != MDOC_HEAD)
1681 return(1);
1682
1683 if (n->child != NULL)
1684 parse_mdoc_fname(mpage, n->child);
1685
1686 return(0);
1687 }
1688
1689 static int
1690 parse_mdoc_Xr(struct mpage *mpage, const struct mdoc_meta *meta,
1691 const struct mdoc_node *n)
1692 {
1693 char *cp;
1694
1695 if (NULL == (n = n->child))
1696 return(0);
1697
1698 if (NULL == n->next) {
1699 putkey(mpage, n->string, TYPE_Xr);
1700 return(0);
1701 }
1702
1703 mandoc_asprintf(&cp, "%s(%s)", n->string, n->next->string);
1704 putkey(mpage, cp, TYPE_Xr);
1705 free(cp);
1706 return(0);
1707 }
1708
1709 static int
1710 parse_mdoc_Nd(struct mpage *mpage, const struct mdoc_meta *meta,
1711 const struct mdoc_node *n)
1712 {
1713
1714 if (MDOC_BODY == n->type)
1715 mdoc_deroff(&mpage->desc, n);
1716 return(0);
1717 }
1718
1719 static int
1720 parse_mdoc_Nm(struct mpage *mpage, const struct mdoc_meta *meta,
1721 const struct mdoc_node *n)
1722 {
1723
1724 if (SEC_NAME == n->sec)
1725 putmdockey(mpage, n->child, NAME_TITLE);
1726 else if (SEC_SYNOPSIS == n->sec && MDOC_HEAD == n->type) {
1727 if (n->child == NULL)
1728 putkey(mpage, meta->name, NAME_SYN);
1729 else
1730 putmdockey(mpage, n->child, NAME_SYN);
1731 }
1732 if ( ! (mpage->name_head_done ||
1733 n->child == NULL || n->child->string == NULL ||
1734 strcasecmp(n->child->string, meta->title))) {
1735 putkey(mpage, n->child->string, NAME_HEAD);
1736 mpage->name_head_done = 1;
1737 }
1738 return(0);
1739 }
1740
1741 static int
1742 parse_mdoc_Sh(struct mpage *mpage, const struct mdoc_meta *meta,
1743 const struct mdoc_node *n)
1744 {
1745
1746 return(SEC_CUSTOM == n->sec && MDOC_HEAD == n->type);
1747 }
1748
1749 static int
1750 parse_mdoc_head(struct mpage *mpage, const struct mdoc_meta *meta,
1751 const struct mdoc_node *n)
1752 {
1753
1754 return(MDOC_HEAD == n->type);
1755 }
1756
1757 static int
1758 parse_mdoc_body(struct mpage *mpage, const struct mdoc_meta *meta,
1759 const struct mdoc_node *n)
1760 {
1761
1762 return(MDOC_BODY == n->type);
1763 }
1764
1765 /*
1766 * Add a string to the hash table for the current manual.
1767 * Each string has a bitmask telling which macros it belongs to.
1768 * When we finish the manual, we'll dump the table.
1769 */
1770 static void
1771 putkeys(const struct mpage *mpage, char *cp, size_t sz, uint64_t v)
1772 {
1773 struct ohash *htab;
1774 struct str *s;
1775 const char *end;
1776 unsigned int slot;
1777 int i, mustfree;
1778
1779 if (0 == sz)
1780 return;
1781
1782 mustfree = render_string(&cp, &sz);
1783
1784 if (TYPE_Nm & v) {
1785 htab = &names;
1786 v &= name_mask;
1787 if (v & NAME_FIRST)
1788 name_mask &= ~NAME_FIRST;
1789 if (debug > 1)
1790 say(mpage->mlinks->file,
1791 "Adding name %*s, bits=%d", sz, cp, v);
1792 } else {
1793 htab = &strings;
1794 if (debug > 1)
1795 for (i = 0; i < mansearch_keymax; i++)
1796 if ((uint64_t)1 << i & v)
1797 say(mpage->mlinks->file,
1798 "Adding key %s=%*s",
1799 mansearch_keynames[i], sz, cp);
1800 }
1801
1802 end = cp + sz;
1803 slot = ohash_qlookupi(htab, cp, &end);
1804 s = ohash_find(htab, slot);
1805
1806 if (NULL != s && mpage == s->mpage) {
1807 s->mask |= v;
1808 return;
1809 } else if (NULL == s) {
1810 s = mandoc_calloc(1, sizeof(struct str) + sz + 1);
1811 memcpy(s->key, cp, sz);
1812 ohash_insert(htab, slot, s);
1813 }
1814 s->mpage = mpage;
1815 s->mask = v;
1816
1817 if (mustfree)
1818 free(cp);
1819 }
1820
1821 /*
1822 * Take a Unicode codepoint and produce its UTF-8 encoding.
1823 * This isn't the best way to do this, but it works.
1824 * The magic numbers are from the UTF-8 packaging.
1825 * They're not as scary as they seem: read the UTF-8 spec for details.
1826 */
1827 static size_t
1828 utf8(unsigned int cp, char out[7])
1829 {
1830 size_t rc;
1831
1832 rc = 0;
1833 if (cp <= 0x0000007F) {
1834 rc = 1;
1835 out[0] = (char)cp;
1836 } else if (cp <= 0x000007FF) {
1837 rc = 2;
1838 out[0] = (cp >> 6 & 31) | 192;
1839 out[1] = (cp & 63) | 128;
1840 } else if (cp <= 0x0000FFFF) {
1841 rc = 3;
1842 out[0] = (cp >> 12 & 15) | 224;
1843 out[1] = (cp >> 6 & 63) | 128;
1844 out[2] = (cp & 63) | 128;
1845 } else if (cp <= 0x001FFFFF) {
1846 rc = 4;
1847 out[0] = (cp >> 18 & 7) | 240;
1848 out[1] = (cp >> 12 & 63) | 128;
1849 out[2] = (cp >> 6 & 63) | 128;
1850 out[3] = (cp & 63) | 128;
1851 } else if (cp <= 0x03FFFFFF) {
1852 rc = 5;
1853 out[0] = (cp >> 24 & 3) | 248;
1854 out[1] = (cp >> 18 & 63) | 128;
1855 out[2] = (cp >> 12 & 63) | 128;
1856 out[3] = (cp >> 6 & 63) | 128;
1857 out[4] = (cp & 63) | 128;
1858 } else if (cp <= 0x7FFFFFFF) {
1859 rc = 6;
1860 out[0] = (cp >> 30 & 1) | 252;
1861 out[1] = (cp >> 24 & 63) | 128;
1862 out[2] = (cp >> 18 & 63) | 128;
1863 out[3] = (cp >> 12 & 63) | 128;
1864 out[4] = (cp >> 6 & 63) | 128;
1865 out[5] = (cp & 63) | 128;
1866 } else
1867 return(0);
1868
1869 out[rc] = '\0';
1870 return(rc);
1871 }
1872
1873 /*
1874 * If the string contains escape sequences,
1875 * replace it with an allocated rendering and return 1,
1876 * such that the caller can free it after use.
1877 * Otherwise, do nothing and return 0.
1878 */
1879 static int
1880 render_string(char **public, size_t *psz)
1881 {
1882 const char *src, *scp, *addcp, *seq;
1883 char *dst;
1884 size_t ssz, dsz, addsz;
1885 char utfbuf[7], res[6];
1886 int seqlen, unicode;
1887
1888 res[0] = '\\';
1889 res[1] = '\t';
1890 res[2] = ASCII_NBRSP;
1891 res[3] = ASCII_HYPH;
1892 res[4] = ASCII_BREAK;
1893 res[5] = '\0';
1894
1895 src = scp = *public;
1896 ssz = *psz;
1897 dst = NULL;
1898 dsz = 0;
1899
1900 while (scp < src + *psz) {
1901
1902 /* Leave normal characters unchanged. */
1903
1904 if (strchr(res, *scp) == NULL) {
1905 if (dst != NULL)
1906 dst[dsz++] = *scp;
1907 scp++;
1908 continue;
1909 }
1910
1911 /*
1912 * Found something that requires replacing,
1913 * make sure we have a destination buffer.
1914 */
1915
1916 if (dst == NULL) {
1917 dst = mandoc_malloc(ssz + 1);
1918 dsz = scp - src;
1919 memcpy(dst, src, dsz);
1920 }
1921
1922 /* Handle single-char special characters. */
1923
1924 switch (*scp) {
1925 case '\\':
1926 break;
1927 case '\t':
1928 /* FALLTHROUGH */
1929 case ASCII_NBRSP:
1930 dst[dsz++] = ' ';
1931 scp++;
1932 continue;
1933 case ASCII_HYPH:
1934 dst[dsz++] = '-';
1935 /* FALLTHROUGH */
1936 case ASCII_BREAK:
1937 scp++;
1938 continue;
1939 default:
1940 abort();
1941 }
1942
1943 /*
1944 * Found an escape sequence.
1945 * Read past the slash, then parse it.
1946 * Ignore everything except characters.
1947 */
1948
1949 scp++;
1950 if (mandoc_escape(&scp, &seq, &seqlen) != ESCAPE_SPECIAL)
1951 continue;
1952
1953 /*
1954 * Render the special character
1955 * as either UTF-8 or ASCII.
1956 */
1957
1958 if (write_utf8) {
1959 unicode = mchars_spec2cp(mchars, seq, seqlen);
1960 if (unicode <= 0)
1961 continue;
1962 addsz = utf8(unicode, utfbuf);
1963 if (addsz == 0)
1964 continue;
1965 addcp = utfbuf;
1966 } else {
1967 addcp = mchars_spec2str(mchars, seq, seqlen, &addsz);
1968 if (addcp == NULL)
1969 continue;
1970 if (*addcp == ASCII_NBRSP) {
1971 addcp = " ";
1972 addsz = 1;
1973 }
1974 }
1975
1976 /* Copy the rendered glyph into the stream. */
1977
1978 ssz += addsz;
1979 dst = mandoc_realloc(dst, ssz + 1);
1980 memcpy(dst + dsz, addcp, addsz);
1981 dsz += addsz;
1982 }
1983 if (dst != NULL) {
1984 *public = dst;
1985 *psz = dsz;
1986 }
1987
1988 /* Trim trailing whitespace and NUL-terminate. */
1989
1990 while (*psz > 0 && (*public)[*psz - 1] == ' ')
1991 --*psz;
1992 if (dst != NULL) {
1993 (*public)[*psz] = '\0';
1994 return(1);
1995 } else
1996 return(0);
1997 }
1998
1999 static void
2000 dbadd_mlink(const struct mlink *mlink)
2001 {
2002 size_t i;
2003
2004 i = 1;
2005 SQL_BIND_TEXT(stmts[STMT_INSERT_LINK], i, mlink->dsec);
2006 SQL_BIND_TEXT(stmts[STMT_INSERT_LINK], i, mlink->arch);
2007 SQL_BIND_TEXT(stmts[STMT_INSERT_LINK], i, mlink->name);
2008 SQL_BIND_INT64(stmts[STMT_INSERT_LINK], i, mlink->mpage->pageid);
2009 SQL_STEP(stmts[STMT_INSERT_LINK]);
2010 sqlite3_reset(stmts[STMT_INSERT_LINK]);
2011 }
2012
2013 static void
2014 dbadd_mlink_name(const struct mlink *mlink)
2015 {
2016 uint64_t bits;
2017 size_t i;
2018
2019 dbadd_mlink(mlink);
2020
2021 i = 1;
2022 SQL_BIND_INT64(stmts[STMT_SELECT_NAME], i, mlink->mpage->pageid);
2023 bits = NAME_FILE & NAME_MASK;
2024 if (sqlite3_step(stmts[STMT_SELECT_NAME]) == SQLITE_ROW) {
2025 bits |= sqlite3_column_int64(stmts[STMT_SELECT_NAME], 0);
2026 sqlite3_reset(stmts[STMT_SELECT_NAME]);
2027 }
2028
2029 i = 1;
2030 SQL_BIND_INT64(stmts[STMT_INSERT_NAME], i, bits);
2031 SQL_BIND_TEXT(stmts[STMT_INSERT_NAME], i, mlink->name);
2032 SQL_BIND_INT64(stmts[STMT_INSERT_NAME], i, mlink->mpage->pageid);
2033 SQL_STEP(stmts[STMT_INSERT_NAME]);
2034 sqlite3_reset(stmts[STMT_INSERT_NAME]);
2035 }
2036
2037 /*
2038 * Flush the current page's terms (and their bits) into the database.
2039 * Wrap the entire set of additions in a transaction to make sqlite be a
2040 * little faster.
2041 * Also, handle escape sequences at the last possible moment.
2042 */
2043 static void
2044 dbadd(struct mpage *mpage)
2045 {
2046 struct mlink *mlink;
2047 struct str *key;
2048 char *cp;
2049 size_t i;
2050 unsigned int slot;
2051 int mustfree;
2052
2053 mlink = mpage->mlinks;
2054
2055 if (nodb) {
2056 for (key = ohash_first(&names, &slot); NULL != key;
2057 key = ohash_next(&names, &slot))
2058 free(key);
2059 for (key = ohash_first(&strings, &slot); NULL != key;
2060 key = ohash_next(&strings, &slot))
2061 free(key);
2062 if (0 == debug)
2063 return;
2064 while (NULL != mlink) {
2065 fputs(mlink->name, stdout);
2066 if (NULL == mlink->next ||
2067 strcmp(mlink->dsec, mlink->next->dsec) ||
2068 strcmp(mlink->fsec, mlink->next->fsec) ||
2069 strcmp(mlink->arch, mlink->next->arch)) {
2070 putchar('(');
2071 if ('\0' == *mlink->dsec)
2072 fputs(mlink->fsec, stdout);
2073 else
2074 fputs(mlink->dsec, stdout);
2075 if ('\0' != *mlink->arch)
2076 printf("/%s", mlink->arch);
2077 putchar(')');
2078 }
2079 mlink = mlink->next;
2080 if (NULL != mlink)
2081 fputs(", ", stdout);
2082 }
2083 printf(" - %s\n", mpage->desc);
2084 return;
2085 }
2086
2087 if (debug)
2088 say(mlink->file, "Adding to database");
2089
2090 cp = mpage->desc;
2091 i = strlen(cp);
2092 mustfree = render_string(&cp, &i);
2093 i = 1;
2094 SQL_BIND_TEXT(stmts[STMT_INSERT_PAGE], i, cp);
2095 SQL_BIND_INT(stmts[STMT_INSERT_PAGE], i, mpage->form);
2096 SQL_STEP(stmts[STMT_INSERT_PAGE]);
2097 mpage->pageid = sqlite3_last_insert_rowid(db);
2098 sqlite3_reset(stmts[STMT_INSERT_PAGE]);
2099 if (mustfree)
2100 free(cp);
2101
2102 while (NULL != mlink) {
2103 dbadd_mlink(mlink);
2104 mlink = mlink->next;
2105 }
2106 mlink = mpage->mlinks;
2107
2108 for (key = ohash_first(&names, &slot); NULL != key;
2109 key = ohash_next(&names, &slot)) {
2110 assert(key->mpage == mpage);
2111 i = 1;
2112 SQL_BIND_INT64(stmts[STMT_INSERT_NAME], i, key->mask);
2113 SQL_BIND_TEXT(stmts[STMT_INSERT_NAME], i, key->key);
2114 SQL_BIND_INT64(stmts[STMT_INSERT_NAME], i, mpage->pageid);
2115 SQL_STEP(stmts[STMT_INSERT_NAME]);
2116 sqlite3_reset(stmts[STMT_INSERT_NAME]);
2117 free(key);
2118 }
2119 for (key = ohash_first(&strings, &slot); NULL != key;
2120 key = ohash_next(&strings, &slot)) {
2121 assert(key->mpage == mpage);
2122 i = 1;
2123 SQL_BIND_INT64(stmts[STMT_INSERT_KEY], i, key->mask);
2124 SQL_BIND_TEXT(stmts[STMT_INSERT_KEY], i, key->key);
2125 SQL_BIND_INT64(stmts[STMT_INSERT_KEY], i, mpage->pageid);
2126 SQL_STEP(stmts[STMT_INSERT_KEY]);
2127 sqlite3_reset(stmts[STMT_INSERT_KEY]);
2128 free(key);
2129 }
2130 }
2131
2132 static void
2133 dbprune(void)
2134 {
2135 struct mpage *mpage;
2136 struct mlink *mlink;
2137 size_t i;
2138 unsigned int slot;
2139
2140 if (0 == nodb)
2141 SQL_EXEC("BEGIN TRANSACTION");
2142
2143 for (mpage = ohash_first(&mpages, &slot); NULL != mpage;
2144 mpage = ohash_next(&mpages, &slot)) {
2145 mlink = mpage->mlinks;
2146 if (debug)
2147 say(mlink->file, "Deleting from database");
2148 if (nodb)
2149 continue;
2150 for ( ; NULL != mlink; mlink = mlink->next) {
2151 i = 1;
2152 SQL_BIND_TEXT(stmts[STMT_DELETE_PAGE],
2153 i, mlink->dsec);
2154 SQL_BIND_TEXT(stmts[STMT_DELETE_PAGE],
2155 i, mlink->arch);
2156 SQL_BIND_TEXT(stmts[STMT_DELETE_PAGE],
2157 i, mlink->name);
2158 SQL_STEP(stmts[STMT_DELETE_PAGE]);
2159 sqlite3_reset(stmts[STMT_DELETE_PAGE]);
2160 }
2161 }
2162
2163 if (0 == nodb)
2164 SQL_EXEC("END TRANSACTION");
2165 }
2166
2167 /*
2168 * Close an existing database and its prepared statements.
2169 * If "real" is not set, rename the temporary file into the real one.
2170 */
2171 static void
2172 dbclose(int real)
2173 {
2174 size_t i;
2175 int status;
2176 pid_t child;
2177
2178 if (nodb)
2179 return;
2180
2181 for (i = 0; i < STMT__MAX; i++) {
2182 sqlite3_finalize(stmts[i]);
2183 stmts[i] = NULL;
2184 }
2185
2186 sqlite3_close(db);
2187 db = NULL;
2188
2189 if (real)
2190 return;
2191
2192 if ('\0' == *tempfilename) {
2193 if (-1 == rename(MANDOC_DB "~", MANDOC_DB)) {
2194 exitcode = (int)MANDOCLEVEL_SYSERR;
2195 say(MANDOC_DB, "&rename");
2196 }
2197 return;
2198 }
2199
2200 switch (child = fork()) {
2201 case -1:
2202 exitcode = (int)MANDOCLEVEL_SYSERR;
2203 say("", "&fork cmp");
2204 return;
2205 case 0:
2206 execlp("cmp", "cmp", "-s",
2207 tempfilename, MANDOC_DB, NULL);
2208 say("", "&exec cmp");
2209 exit(0);
2210 default:
2211 break;
2212 }
2213 if (-1 == waitpid(child, &status, 0)) {
2214 exitcode = (int)MANDOCLEVEL_SYSERR;
2215 say("", "&wait cmp");
2216 } else if (WIFSIGNALED(status)) {
2217 exitcode = (int)MANDOCLEVEL_SYSERR;
2218 say("", "cmp died from signal %d", WTERMSIG(status));
2219 } else if (WEXITSTATUS(status)) {
2220 exitcode = (int)MANDOCLEVEL_SYSERR;
2221 say(MANDOC_DB,
2222 "Data changed, but cannot replace database");
2223 }
2224
2225 *strrchr(tempfilename, '/') = '\0';
2226 switch (child = fork()) {
2227 case -1:
2228 exitcode = (int)MANDOCLEVEL_SYSERR;
2229 say("", "&fork rm");
2230 return;
2231 case 0:
2232 execlp("rm", "rm", "-rf", tempfilename, NULL);
2233 say("", "&exec rm");
2234 exit((int)MANDOCLEVEL_SYSERR);
2235 default:
2236 break;
2237 }
2238 if (-1 == waitpid(child, &status, 0)) {
2239 exitcode = (int)MANDOCLEVEL_SYSERR;
2240 say("", "&wait rm");
2241 } else if (WIFSIGNALED(status) || WEXITSTATUS(status)) {
2242 exitcode = (int)MANDOCLEVEL_SYSERR;
2243 say("", "%s: Cannot remove temporary directory",
2244 tempfilename);
2245 }
2246 }
2247
2248 /*
2249 * This is straightforward stuff.
2250 * Open a database connection to a "temporary" database, then open a set
2251 * of prepared statements we'll use over and over again.
2252 * If "real" is set, we use the existing database; if not, we truncate a
2253 * temporary one.
2254 * Must be matched by dbclose().
2255 */
2256 static int
2257 dbopen(int real)
2258 {
2259 const char *sql;
2260 int rc, ofl;
2261
2262 if (nodb)
2263 return(1);
2264
2265 *tempfilename = '\0';
2266 ofl = SQLITE_OPEN_READWRITE;
2267
2268 if (real) {
2269 rc = sqlite3_open_v2(MANDOC_DB, &db, ofl, NULL);
2270 if (SQLITE_OK != rc) {
2271 exitcode = (int)MANDOCLEVEL_SYSERR;
2272 if (SQLITE_CANTOPEN != rc)
2273 say(MANDOC_DB, "%s", sqlite3_errstr(rc));
2274 return(0);
2275 }
2276 goto prepare_statements;
2277 }
2278
2279 ofl |= SQLITE_OPEN_CREATE | SQLITE_OPEN_EXCLUSIVE;
2280
2281 remove(MANDOC_DB "~");
2282 rc = sqlite3_open_v2(MANDOC_DB "~", &db, ofl, NULL);
2283 if (SQLITE_OK == rc)
2284 goto create_tables;
2285 if (MPARSE_QUICK & mparse_options) {
2286 exitcode = (int)MANDOCLEVEL_SYSERR;
2287 say(MANDOC_DB "~", "%s", sqlite3_errstr(rc));
2288 return(0);
2289 }
2290
2291 (void)strlcpy(tempfilename, "/tmp/mandocdb.XXXXXX",
2292 sizeof(tempfilename));
2293 if (NULL == mkdtemp(tempfilename)) {
2294 exitcode = (int)MANDOCLEVEL_SYSERR;
2295 say("", "&%s", tempfilename);
2296 return(0);
2297 }
2298 (void)strlcat(tempfilename, "/" MANDOC_DB,
2299 sizeof(tempfilename));
2300 rc = sqlite3_open_v2(tempfilename, &db, ofl, NULL);
2301 if (SQLITE_OK != rc) {
2302 exitcode = (int)MANDOCLEVEL_SYSERR;
2303 say("", "%s: %s", tempfilename, sqlite3_errstr(rc));
2304 return(0);
2305 }
2306
2307 create_tables:
2308 sql = "CREATE TABLE \"mpages\" (\n"
2309 " \"desc\" TEXT NOT NULL,\n"
2310 " \"form\" INTEGER NOT NULL,\n"
2311 " \"pageid\" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL\n"
2312 ");\n"
2313 "\n"
2314 "CREATE TABLE \"mlinks\" (\n"
2315 " \"sec\" TEXT NOT NULL,\n"
2316 " \"arch\" TEXT NOT NULL,\n"
2317 " \"name\" TEXT NOT NULL,\n"
2318 " \"pageid\" INTEGER NOT NULL REFERENCES mpages(pageid) "
2319 "ON DELETE CASCADE\n"
2320 ");\n"
2321 "CREATE INDEX mlinks_pageid_idx ON mlinks (pageid);\n"
2322 "\n"
2323 "CREATE TABLE \"names\" (\n"
2324 " \"bits\" INTEGER NOT NULL,\n"
2325 " \"name\" TEXT NOT NULL,\n"
2326 " \"pageid\" INTEGER NOT NULL REFERENCES mpages(pageid) "
2327 "ON DELETE CASCADE,\n"
2328 " UNIQUE (\"name\", \"pageid\") ON CONFLICT REPLACE\n"
2329 ");\n"
2330 "\n"
2331 "CREATE TABLE \"keys\" (\n"
2332 " \"bits\" INTEGER NOT NULL,\n"
2333 " \"key\" TEXT NOT NULL,\n"
2334 " \"pageid\" INTEGER NOT NULL REFERENCES mpages(pageid) "
2335 "ON DELETE CASCADE\n"
2336 ");\n"
2337 "CREATE INDEX keys_pageid_idx ON keys (pageid);\n";
2338
2339 if (SQLITE_OK != sqlite3_exec(db, sql, NULL, NULL, NULL)) {
2340 exitcode = (int)MANDOCLEVEL_SYSERR;
2341 say(MANDOC_DB, "%s", sqlite3_errmsg(db));
2342 sqlite3_close(db);
2343 return(0);
2344 }
2345
2346 prepare_statements:
2347 if (SQLITE_OK != sqlite3_exec(db,
2348 "PRAGMA foreign_keys = ON", NULL, NULL, NULL)) {
2349 exitcode = (int)MANDOCLEVEL_SYSERR;
2350 say(MANDOC_DB, "PRAGMA foreign_keys: %s",
2351 sqlite3_errmsg(db));
2352 sqlite3_close(db);
2353 return(0);
2354 }
2355
2356 sql = "DELETE FROM mpages WHERE pageid IN "
2357 "(SELECT pageid FROM mlinks WHERE "
2358 "sec=? AND arch=? AND name=?)";
2359 sqlite3_prepare_v2(db, sql, -1, &stmts[STMT_DELETE_PAGE], NULL);
2360 sql = "INSERT INTO mpages "
2361 "(desc,form) VALUES (?,?)";
2362 sqlite3_prepare_v2(db, sql, -1, &stmts[STMT_INSERT_PAGE], NULL);
2363 sql = "INSERT INTO mlinks "
2364 "(sec,arch,name,pageid) VALUES (?,?,?,?)";
2365 sqlite3_prepare_v2(db, sql, -1, &stmts[STMT_INSERT_LINK], NULL);
2366 sql = "SELECT bits FROM names where pageid = ?";
2367 sqlite3_prepare_v2(db, sql, -1, &stmts[STMT_SELECT_NAME], NULL);
2368 sql = "INSERT INTO names "
2369 "(bits,name,pageid) VALUES (?,?,?)";
2370 sqlite3_prepare_v2(db, sql, -1, &stmts[STMT_INSERT_NAME], NULL);
2371 sql = "INSERT INTO keys "
2372 "(bits,key,pageid) VALUES (?,?,?)";
2373 sqlite3_prepare_v2(db, sql, -1, &stmts[STMT_INSERT_KEY], NULL);
2374
2375 #ifndef __APPLE__
2376 /*
2377 * When opening a new database, we can turn off
2378 * synchronous mode for much better performance.
2379 */
2380
2381 if (real && SQLITE_OK != sqlite3_exec(db,
2382 "PRAGMA synchronous = OFF", NULL, NULL, NULL)) {
2383 exitcode = (int)MANDOCLEVEL_SYSERR;
2384 say(MANDOC_DB, "PRAGMA synchronous: %s",
2385 sqlite3_errmsg(db));
2386 sqlite3_close(db);
2387 return(0);
2388 }
2389 #endif
2390
2391 return(1);
2392 }
2393
2394 static void *
2395 hash_calloc(size_t n, size_t sz, void *arg)
2396 {
2397
2398 return(mandoc_calloc(n, sz));
2399 }
2400
2401 static void *
2402 hash_alloc(size_t sz, void *arg)
2403 {
2404
2405 return(mandoc_malloc(sz));
2406 }
2407
2408 static void
2409 hash_free(void *p, void *arg)
2410 {
2411
2412 free(p);
2413 }
2414
2415 static int
2416 set_basedir(const char *targetdir, int report_baddir)
2417 {
2418 static char startdir[PATH_MAX];
2419 static int getcwd_status; /* 1 = ok, 2 = failure */
2420 static int chdir_status; /* 1 = changed directory */
2421 char *cp;
2422
2423 /*
2424 * Remember the original working directory, if possible.
2425 * This will be needed if the second or a later directory
2426 * on the command line is given as a relative path.
2427 * Do not error out if the current directory is not
2428 * searchable: Maybe it won't be needed after all.
2429 */
2430 if (0 == getcwd_status) {
2431 if (NULL == getcwd(startdir, sizeof(startdir))) {
2432 getcwd_status = 2;
2433 (void)strlcpy(startdir, strerror(errno),
2434 sizeof(startdir));
2435 } else
2436 getcwd_status = 1;
2437 }
2438
2439 /*
2440 * We are leaving the old base directory.
2441 * Do not use it any longer, not even for messages.
2442 */
2443 *basedir = '\0';
2444
2445 /*
2446 * If and only if the directory was changed earlier and
2447 * the next directory to process is given as a relative path,
2448 * first go back, or bail out if that is impossible.
2449 */
2450 if (chdir_status && '/' != *targetdir) {
2451 if (2 == getcwd_status) {
2452 exitcode = (int)MANDOCLEVEL_SYSERR;
2453 say("", "getcwd: %s", startdir);
2454 return(0);
2455 }
2456 if (-1 == chdir(startdir)) {
2457 exitcode = (int)MANDOCLEVEL_SYSERR;
2458 say("", "&chdir %s", startdir);
2459 return(0);
2460 }
2461 }
2462
2463 /*
2464 * Always resolve basedir to the canonicalized absolute
2465 * pathname and append a trailing slash, such that
2466 * we can reliably check whether files are inside.
2467 */
2468 if (NULL == realpath(targetdir, basedir)) {
2469 if (report_baddir || errno != ENOENT) {
2470 exitcode = (int)MANDOCLEVEL_BADARG;
2471 say("", "&%s: realpath", targetdir);
2472 }
2473 return(0);
2474 } else if (-1 == chdir(basedir)) {
2475 if (report_baddir || errno != ENOENT) {
2476 exitcode = (int)MANDOCLEVEL_BADARG;
2477 say("", "&chdir");
2478 }
2479 return(0);
2480 }
2481 chdir_status = 1;
2482 cp = strchr(basedir, '\0');
2483 if ('/' != cp[-1]) {
2484 if (cp - basedir >= PATH_MAX - 1) {
2485 exitcode = (int)MANDOCLEVEL_SYSERR;
2486 say("", "Filename too long");
2487 return(0);
2488 }
2489 *cp++ = '/';
2490 *cp = '\0';
2491 }
2492 return(1);
2493 }
2494
2495 static void
2496 say(const char *file, const char *format, ...)
2497 {
2498 va_list ap;
2499 int use_errno;
2500
2501 if ('\0' != *basedir)
2502 fprintf(stderr, "%s", basedir);
2503 if ('\0' != *basedir && '\0' != *file)
2504 fputc('/', stderr);
2505 if ('\0' != *file)
2506 fprintf(stderr, "%s", file);
2507
2508 use_errno = 1;
2509 if (NULL != format) {
2510 switch (*format) {
2511 case '&':
2512 format++;
2513 break;
2514 case '\0':
2515 format = NULL;
2516 break;
2517 default:
2518 use_errno = 0;
2519 break;
2520 }
2521 }
2522 if (NULL != format) {
2523 if ('\0' != *basedir || '\0' != *file)
2524 fputs(": ", stderr);
2525 va_start(ap, format);
2526 vfprintf(stderr, format, ap);
2527 va_end(ap);
2528 }
2529 if (use_errno) {
2530 if ('\0' != *basedir || '\0' != *file || NULL != format)
2531 fputs(": ", stderr);
2532 perror(NULL);
2533 } else
2534 fputc('\n', stderr);
2535 }