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