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