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