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