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