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