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