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