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