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