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