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