Import mdocml-1.12.2
[dragonfly.git] / contrib / mdocml / mandocdb.c
1 /*      $Id: mandocdb.c,v 1.49.2.7 2013/10/02 21:03:26 schwarze Exp $ */
2 /*
3  * Copyright (c) 2011, 2012 Kristaps Dzonsons <kristaps@bsd.lv>
4  * Copyright (c) 2011, 2012 Ingo Schwarze <schwarze@openbsd.org>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 #ifdef HAVE_CONFIG_H
19 #include "config.h"
20 #endif
21
22 #include <sys/types.h>
23
24 #include <assert.h>
25 #include <ctype.h>
26 #include <dirent.h>
27 #include <errno.h>
28 #include <fcntl.h>
29 #include <getopt.h>
30 #include <limits.h>
31 #include <stdio.h>
32 #include <stdint.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <unistd.h>
36
37 #if defined(__linux__) || defined(__sun)
38 # include <endian.h>
39 # include <db_185.h>
40 #elif defined(__APPLE__)
41 # include <libkern/OSByteOrder.h>
42 # include <db.h>
43 #else
44 # include <sys/endian.h>
45 # include <db.h>
46 #endif
47
48 #if defined(__sun)
49 #include <sys/stat.h>
50 #endif
51
52 #include "man.h"
53 #include "mdoc.h"
54 #include "mandoc.h"
55 #include "mandocdb.h"
56 #include "manpath.h"
57
58 #define MANDOC_BUFSZ      BUFSIZ
59 #define MANDOC_SLOP       1024
60
61 #define MANDOC_SRC        0x1
62 #define MANDOC_FORM       0x2
63
64 /* Access to the mandoc database on disk. */
65
66 struct  mdb {
67         char              idxn[PATH_MAX]; /* index db filename */
68         char              dbn[PATH_MAX]; /* keyword db filename */
69         DB               *idx; /* index recno database */
70         DB               *db; /* keyword btree database */
71 };
72
73 /* Stack of temporarily unused index records. */
74
75 struct  recs {
76         recno_t          *stack; /* pointer to a malloc'ed array */
77         size_t            size; /* number of allocated slots */
78         size_t            cur; /* current number of empty records */
79         recno_t           last; /* last record number in the index */
80 };
81
82 /* Tiny list for files.  No need to bring in QUEUE. */
83
84 struct  of {
85         char             *fname; /* heap-allocated */
86         char             *sec;
87         char             *arch;
88         char             *title;
89         int               src_form;
90         struct of        *next; /* NULL for last one */
91         struct of        *first; /* first in list */
92 };
93
94 /* Buffer for storing growable data. */
95
96 struct  buf {
97         char             *cp;
98         size_t            len; /* current length */
99         size_t            size; /* total buffer size */
100 };
101
102 /* Operation we're going to perform. */
103
104 enum    op {
105         OP_DEFAULT = 0, /* new dbs from dir list or default config */
106         OP_CONFFILE, /* new databases from custom config file */
107         OP_UPDATE, /* delete/add entries in existing database */
108         OP_DELETE, /* delete entries from existing database */
109         OP_TEST /* change no databases, report potential problems */
110 };
111
112 #define MAN_ARGS          DB *hash, \
113                           struct buf *buf, \
114                           struct buf *dbuf, \
115                           const struct man_node *n
116 #define MDOC_ARGS         DB *hash, \
117                           struct buf *buf, \
118                           struct buf *dbuf, \
119                           const struct mdoc_node *n, \
120                           const struct mdoc_meta *m
121
122 static  void              buf_appendmdoc(struct buf *, 
123                                 const struct mdoc_node *, int);
124 static  void              buf_append(struct buf *, const char *);
125 static  void              buf_appendb(struct buf *, 
126                                 const void *, size_t);
127 static  void              dbt_put(DB *, const char *, DBT *, DBT *);
128 static  void              hash_put(DB *, const struct buf *, uint64_t);
129 static  void              hash_reset(DB **);
130 static  void              index_merge(const struct of *, struct mparse *,
131                                 struct buf *, struct buf *, DB *,
132                                 struct mdb *, struct recs *);
133 static  void              index_prune(const struct of *, struct mdb *,
134                                 struct recs *);
135 static  void              ofile_argbuild(int, char *[], struct of **,
136                                 const char *);
137 static  void              ofile_dirbuild(const char *, const char *,
138                                 const char *, int, struct of **);
139 static  void              ofile_free(struct of *);
140 static  void              pformatted(DB *, struct buf *, 
141                                 struct buf *, const struct of *);
142 static  int               pman_node(MAN_ARGS);
143 static  void              pmdoc_node(MDOC_ARGS);
144 static  int               pmdoc_head(MDOC_ARGS);
145 static  int               pmdoc_body(MDOC_ARGS);
146 static  int               pmdoc_Fd(MDOC_ARGS);
147 static  int               pmdoc_In(MDOC_ARGS);
148 static  int               pmdoc_Fn(MDOC_ARGS);
149 static  int               pmdoc_Nd(MDOC_ARGS);
150 static  int               pmdoc_Nm(MDOC_ARGS);
151 static  int               pmdoc_Sh(MDOC_ARGS);
152 static  int               pmdoc_St(MDOC_ARGS);
153 static  int               pmdoc_Xr(MDOC_ARGS);
154
155 #define MDOCF_CHILD       0x01  /* Automatically index child nodes. */
156
157 struct  mdoc_handler {
158         int             (*fp)(MDOC_ARGS);  /* Optional handler. */
159         uint64_t          mask;  /* Set unless handler returns 0. */
160         int               flags;  /* For use by pmdoc_node. */
161 };
162
163 static  const struct mdoc_handler mdocs[MDOC_MAX] = {
164         { NULL, 0, 0 },  /* Ap */
165         { NULL, 0, 0 },  /* Dd */
166         { NULL, 0, 0 },  /* Dt */
167         { NULL, 0, 0 },  /* Os */
168         { pmdoc_Sh, TYPE_Sh, MDOCF_CHILD }, /* Sh */
169         { pmdoc_head, TYPE_Ss, MDOCF_CHILD }, /* Ss */
170         { NULL, 0, 0 },  /* Pp */
171         { NULL, 0, 0 },  /* D1 */
172         { NULL, 0, 0 },  /* Dl */
173         { NULL, 0, 0 },  /* Bd */
174         { NULL, 0, 0 },  /* Ed */
175         { NULL, 0, 0 },  /* Bl */
176         { NULL, 0, 0 },  /* El */
177         { NULL, 0, 0 },  /* It */
178         { NULL, 0, 0 },  /* Ad */
179         { NULL, TYPE_An, MDOCF_CHILD },  /* An */
180         { NULL, TYPE_Ar, MDOCF_CHILD },  /* Ar */
181         { NULL, TYPE_Cd, MDOCF_CHILD },  /* Cd */
182         { NULL, TYPE_Cm, MDOCF_CHILD },  /* Cm */
183         { NULL, TYPE_Dv, MDOCF_CHILD },  /* Dv */
184         { NULL, TYPE_Er, MDOCF_CHILD },  /* Er */
185         { NULL, TYPE_Ev, MDOCF_CHILD },  /* Ev */
186         { NULL, 0, 0 },  /* Ex */
187         { NULL, TYPE_Fa, MDOCF_CHILD },  /* Fa */
188         { pmdoc_Fd, TYPE_In, 0 },  /* Fd */
189         { NULL, TYPE_Fl, MDOCF_CHILD },  /* Fl */
190         { pmdoc_Fn, 0, 0 },  /* Fn */
191         { NULL, TYPE_Ft, MDOCF_CHILD },  /* Ft */
192         { NULL, TYPE_Ic, MDOCF_CHILD },  /* Ic */
193         { pmdoc_In, TYPE_In, 0 },  /* In */
194         { NULL, TYPE_Li, MDOCF_CHILD },  /* Li */
195         { pmdoc_Nd, TYPE_Nd, MDOCF_CHILD },  /* Nd */
196         { pmdoc_Nm, TYPE_Nm, MDOCF_CHILD },  /* Nm */
197         { NULL, 0, 0 },  /* Op */
198         { NULL, 0, 0 },  /* Ot */
199         { NULL, TYPE_Pa, MDOCF_CHILD },  /* Pa */
200         { NULL, 0, 0 },  /* Rv */
201         { pmdoc_St, TYPE_St, 0 },  /* St */
202         { NULL, TYPE_Va, MDOCF_CHILD },  /* Va */
203         { pmdoc_body, TYPE_Va, MDOCF_CHILD },  /* Vt */
204         { pmdoc_Xr, TYPE_Xr, 0 },  /* Xr */
205         { NULL, 0, 0 },  /* %A */
206         { NULL, 0, 0 },  /* %B */
207         { NULL, 0, 0 },  /* %D */
208         { NULL, 0, 0 },  /* %I */
209         { NULL, 0, 0 },  /* %J */
210         { NULL, 0, 0 },  /* %N */
211         { NULL, 0, 0 },  /* %O */
212         { NULL, 0, 0 },  /* %P */
213         { NULL, 0, 0 },  /* %R */
214         { NULL, 0, 0 },  /* %T */
215         { NULL, 0, 0 },  /* %V */
216         { NULL, 0, 0 },  /* Ac */
217         { NULL, 0, 0 },  /* Ao */
218         { NULL, 0, 0 },  /* Aq */
219         { NULL, TYPE_At, MDOCF_CHILD },  /* At */
220         { NULL, 0, 0 },  /* Bc */
221         { NULL, 0, 0 },  /* Bf */
222         { NULL, 0, 0 },  /* Bo */
223         { NULL, 0, 0 },  /* Bq */
224         { NULL, TYPE_Bsx, MDOCF_CHILD },  /* Bsx */
225         { NULL, TYPE_Bx, MDOCF_CHILD },  /* Bx */
226         { NULL, 0, 0 },  /* Db */
227         { NULL, 0, 0 },  /* Dc */
228         { NULL, 0, 0 },  /* Do */
229         { NULL, 0, 0 },  /* Dq */
230         { NULL, 0, 0 },  /* Ec */
231         { NULL, 0, 0 },  /* Ef */
232         { NULL, TYPE_Em, MDOCF_CHILD },  /* Em */
233         { NULL, 0, 0 },  /* Eo */
234         { NULL, TYPE_Fx, MDOCF_CHILD },  /* Fx */
235         { NULL, TYPE_Ms, MDOCF_CHILD },  /* Ms */
236         { NULL, 0, 0 },  /* No */
237         { NULL, 0, 0 },  /* Ns */
238         { NULL, TYPE_Nx, MDOCF_CHILD },  /* Nx */
239         { NULL, TYPE_Ox, MDOCF_CHILD },  /* Ox */
240         { NULL, 0, 0 },  /* Pc */
241         { NULL, 0, 0 },  /* Pf */
242         { NULL, 0, 0 },  /* Po */
243         { NULL, 0, 0 },  /* Pq */
244         { NULL, 0, 0 },  /* Qc */
245         { NULL, 0, 0 },  /* Ql */
246         { NULL, 0, 0 },  /* Qo */
247         { NULL, 0, 0 },  /* Qq */
248         { NULL, 0, 0 },  /* Re */
249         { NULL, 0, 0 },  /* Rs */
250         { NULL, 0, 0 },  /* Sc */
251         { NULL, 0, 0 },  /* So */
252         { NULL, 0, 0 },  /* Sq */
253         { NULL, 0, 0 },  /* Sm */
254         { NULL, 0, 0 },  /* Sx */
255         { NULL, TYPE_Sy, MDOCF_CHILD },  /* Sy */
256         { NULL, TYPE_Tn, MDOCF_CHILD },  /* Tn */
257         { NULL, 0, 0 },  /* Ux */
258         { NULL, 0, 0 },  /* Xc */
259         { NULL, 0, 0 },  /* Xo */
260         { pmdoc_head, TYPE_Fn, 0 },  /* Fo */
261         { NULL, 0, 0 },  /* Fc */
262         { NULL, 0, 0 },  /* Oo */
263         { NULL, 0, 0 },  /* Oc */
264         { NULL, 0, 0 },  /* Bk */
265         { NULL, 0, 0 },  /* Ek */
266         { NULL, 0, 0 },  /* Bt */
267         { NULL, 0, 0 },  /* Hf */
268         { NULL, 0, 0 },  /* Fr */
269         { NULL, 0, 0 },  /* Ud */
270         { NULL, TYPE_Lb, MDOCF_CHILD },  /* Lb */
271         { NULL, 0, 0 },  /* Lp */
272         { NULL, TYPE_Lk, MDOCF_CHILD },  /* Lk */
273         { NULL, TYPE_Mt, MDOCF_CHILD },  /* Mt */
274         { NULL, 0, 0 },  /* Brq */
275         { NULL, 0, 0 },  /* Bro */
276         { NULL, 0, 0 },  /* Brc */
277         { NULL, 0, 0 },  /* %C */
278         { NULL, 0, 0 },  /* Es */
279         { NULL, 0, 0 },  /* En */
280         { NULL, TYPE_Dx, MDOCF_CHILD },  /* Dx */
281         { NULL, 0, 0 },  /* %Q */
282         { NULL, 0, 0 },  /* br */
283         { NULL, 0, 0 },  /* sp */
284         { NULL, 0, 0 },  /* %U */
285         { NULL, 0, 0 },  /* Ta */
286 };
287
288 static  const char       *progname;
289 static  int               use_all;  /* Use all directories and files. */
290 static  int               verb;  /* Output verbosity level. */
291 static  int               warnings;  /* Potential problems in manuals. */
292
293 int
294 main(int argc, char *argv[])
295 {
296         struct mparse   *mp; /* parse sequence */
297         struct manpaths  dirs;
298         struct mdb       mdb;
299         struct recs      recs;
300         enum op          op; /* current operation */
301         const char      *dir;
302         char            *cp;
303         char             pbuf[PATH_MAX];
304         int              ch, i, flags;
305         DB              *hash; /* temporary keyword hashtable */
306         BTREEINFO        info; /* btree configuration */
307         size_t           sz1, sz2, ipath;
308         struct buf       buf, /* keyword buffer */
309                          dbuf; /* description buffer */
310         struct of       *of; /* list of files for processing */
311         extern int       optind;
312         extern char     *optarg;
313
314         progname = strrchr(argv[0], '/');
315         if (progname == NULL)
316                 progname = argv[0];
317         else
318                 ++progname;
319
320         memset(&dirs, 0, sizeof(struct manpaths));
321         memset(&mdb, 0, sizeof(struct mdb));
322         memset(&recs, 0, sizeof(struct recs));
323
324         of = NULL;
325         mp = NULL;
326         hash = NULL;
327         op = OP_DEFAULT;
328         dir = NULL;
329
330         while (-1 != (ch = getopt(argc, argv, "aC:d:tu:vW")))
331                 switch (ch) {
332                 case ('a'):
333                         use_all = 1;
334                         break;
335                 case ('C'):
336                         if (op) {
337                                 fprintf(stderr,
338                                     "-C: conflicting options\n");
339                                 goto usage;
340                         }
341                         dir = optarg;
342                         op = OP_CONFFILE;
343                         break;
344                 case ('d'):
345                         if (op) {
346                                 fprintf(stderr,
347                                     "-d: conflicting options\n");
348                                 goto usage;
349                         }
350                         dir = optarg;
351                         op = OP_UPDATE;
352                         break;
353                 case ('t'):
354                         dup2(STDOUT_FILENO, STDERR_FILENO);
355                         if (op) {
356                                 fprintf(stderr,
357                                     "-t: conflicting options\n");
358                                 goto usage;
359                         }
360                         op = OP_TEST;
361                         use_all = 1;
362                         warnings = 1;
363                         break;
364                 case ('u'):
365                         if (op) {
366                                 fprintf(stderr,
367                                     "-u: conflicting options\n");
368                                 goto usage;
369                         }
370                         dir = optarg;
371                         op = OP_DELETE;
372                         break;
373                 case ('v'):
374                         verb++;
375                         break;
376                 case ('W'):
377                         warnings = 1;
378                         break;
379                 default:
380                         goto usage;
381                 }
382
383         argc -= optind;
384         argv += optind;
385
386         if (OP_CONFFILE == op && argc > 0) {
387                 fprintf(stderr, "-C: too many arguments\n");
388                 goto usage;
389         }
390
391         memset(&info, 0, sizeof(BTREEINFO));
392         info.lorder = 4321;
393         info.flags = R_DUP;
394
395         mp = mparse_alloc(MPARSE_AUTO, MANDOCLEVEL_FATAL, NULL, NULL, NULL);
396
397         memset(&buf, 0, sizeof(struct buf));
398         memset(&dbuf, 0, sizeof(struct buf));
399
400         buf.size = dbuf.size = MANDOC_BUFSZ;
401
402         buf.cp = mandoc_malloc(buf.size);
403         dbuf.cp = mandoc_malloc(dbuf.size);
404
405         if (OP_TEST == op) {
406                 ofile_argbuild(argc, argv, &of, NULL);
407                 if (NULL == of)
408                         goto out;
409                 index_merge(of, mp, &dbuf, &buf, hash, &mdb, &recs);
410                 goto out;
411         }
412
413         if (OP_UPDATE == op || OP_DELETE == op) {
414                 if (NULL == realpath(dir, pbuf)) {
415                         perror(dir);
416                         exit((int)MANDOCLEVEL_BADARG);
417                 }
418                 if (strlcat(pbuf, "/", PATH_MAX) >= PATH_MAX) {
419                         fprintf(stderr, "%s: path too long\n", pbuf);
420                         exit((int)MANDOCLEVEL_BADARG);
421                 }
422
423                 strlcat(mdb.dbn, pbuf, PATH_MAX);
424                 sz1 = strlcat(mdb.dbn, MANDOC_DB, PATH_MAX);
425
426                 strlcat(mdb.idxn, pbuf, PATH_MAX);
427                 sz2 = strlcat(mdb.idxn, MANDOC_IDX, PATH_MAX);
428
429                 if (sz1 >= PATH_MAX || sz2 >= PATH_MAX) {
430                         fprintf(stderr, "%s: path too long\n", mdb.idxn);
431                         exit((int)MANDOCLEVEL_BADARG);
432                 }
433
434                 flags = O_CREAT | O_RDWR;
435                 mdb.db = dbopen(mdb.dbn, flags, 0644, DB_BTREE, &info);
436                 mdb.idx = dbopen(mdb.idxn, flags, 0644, DB_RECNO, NULL);
437
438                 if (NULL == mdb.db) {
439                         perror(mdb.dbn);
440                         exit((int)MANDOCLEVEL_SYSERR);
441                 } else if (NULL == mdb.idx) {
442                         perror(mdb.idxn);
443                         exit((int)MANDOCLEVEL_SYSERR);
444                 }
445
446                 ofile_argbuild(argc, argv, &of, pbuf);
447
448                 if (NULL == of)
449                         goto out;
450
451                 index_prune(of, &mdb, &recs);
452
453                 /*
454                  * Go to the root of the respective manual tree.
455                  * This must work or no manuals may be found (they're
456                  * indexed relative to the root).
457                  */
458
459                 if (OP_UPDATE == op) {
460                         if (-1 == chdir(dir)) {
461                                 perror(dir);
462                                 exit((int)MANDOCLEVEL_SYSERR);
463                         }
464                         index_merge(of, mp, &dbuf, &buf, hash,
465                                         &mdb, &recs);
466                 }
467
468                 goto out;
469         }
470
471         /*
472          * Configure the directories we're going to scan.
473          * If we have command-line arguments, use them.
474          * If not, we use man(1)'s method (see mandocdb.8).
475          */
476
477         if (argc > 0) {
478                 dirs.paths = mandoc_calloc(argc, sizeof(char *));
479                 dirs.sz = argc;
480                 for (i = 0; i < argc; i++) {
481                         if (NULL == (cp = realpath(argv[i], pbuf))) {
482                                 perror(argv[i]);
483                                 goto out;
484                         }
485                         dirs.paths[i] = mandoc_strdup(cp);
486                 }
487         } else
488                 manpath_parse(&dirs, dir, NULL, NULL);
489
490         for (ipath = 0; ipath < dirs.sz; ipath++) {
491
492                 /*
493                  * Go to the root of the respective manual tree.
494                  * This must work or no manuals may be found:
495                  * They are indexed relative to the root.
496                  */
497
498                 if (-1 == chdir(dirs.paths[ipath])) {
499                         perror(dirs.paths[ipath]);
500                         exit((int)MANDOCLEVEL_SYSERR);
501                 }
502
503                 /* Create a new database in two temporary files. */
504
505                 flags = O_CREAT | O_EXCL | O_RDWR;
506                 while (NULL == mdb.db) {
507                         strlcpy(mdb.dbn, MANDOC_DB, PATH_MAX);
508                         strlcat(mdb.dbn, ".XXXXXXXXXX", PATH_MAX);
509                         if (NULL == mktemp(mdb.dbn)) {
510                                 perror(mdb.dbn);
511                                 exit((int)MANDOCLEVEL_SYSERR);
512                         }
513                         mdb.db = dbopen(mdb.dbn, flags, 0644,
514                                         DB_BTREE, &info);
515                         if (NULL == mdb.db && EEXIST != errno) {
516                                 perror(mdb.dbn);
517                                 exit((int)MANDOCLEVEL_SYSERR);
518                         }
519                 }
520                 while (NULL == mdb.idx) {
521                         strlcpy(mdb.idxn, MANDOC_IDX, PATH_MAX);
522                         strlcat(mdb.idxn, ".XXXXXXXXXX", PATH_MAX);
523                         if (NULL == mktemp(mdb.idxn)) {
524                                 perror(mdb.idxn);
525                                 unlink(mdb.dbn);
526                                 exit((int)MANDOCLEVEL_SYSERR);
527                         }
528                         mdb.idx = dbopen(mdb.idxn, flags, 0644,
529                                         DB_RECNO, NULL);
530                         if (NULL == mdb.idx && EEXIST != errno) {
531                                 perror(mdb.idxn);
532                                 unlink(mdb.dbn);
533                                 exit((int)MANDOCLEVEL_SYSERR);
534                         }
535                 }
536
537                 /*
538                  * Search for manuals and fill the new database.
539                  */
540
541                 ofile_dirbuild(".", "", "", 0, &of);
542
543                 if (NULL != of) {
544                         index_merge(of, mp, &dbuf, &buf, hash,
545                              &mdb, &recs);
546                         ofile_free(of);
547                         of = NULL;
548                 }
549
550                 (*mdb.db->close)(mdb.db);
551                 (*mdb.idx->close)(mdb.idx);
552                 mdb.db = NULL;
553                 mdb.idx = NULL;
554
555                 /*
556                  * Replace the old database with the new one.
557                  * This is not perfectly atomic,
558                  * but i cannot think of a better way.
559                  */
560
561                 if (-1 == rename(mdb.dbn, MANDOC_DB)) {
562                         perror(MANDOC_DB);
563                         unlink(mdb.dbn);
564                         unlink(mdb.idxn);
565                         exit((int)MANDOCLEVEL_SYSERR);
566                 }
567                 if (-1 == rename(mdb.idxn, MANDOC_IDX)) {
568                         perror(MANDOC_IDX);
569                         unlink(MANDOC_DB);
570                         unlink(MANDOC_IDX);
571                         unlink(mdb.idxn);
572                         exit((int)MANDOCLEVEL_SYSERR);
573                 }
574         }
575
576 out:
577         if (mdb.db)
578                 (*mdb.db->close)(mdb.db);
579         if (mdb.idx)
580                 (*mdb.idx->close)(mdb.idx);
581         if (hash)
582                 (*hash->close)(hash);
583         if (mp)
584                 mparse_free(mp);
585
586         manpath_free(&dirs);
587         ofile_free(of);
588         free(buf.cp);
589         free(dbuf.cp);
590         free(recs.stack);
591
592         return(MANDOCLEVEL_OK);
593
594 usage:
595         fprintf(stderr,
596                 "usage: %s [-avvv] [-C file] | dir ... | -t file ...\n"
597                 "                        -d dir [file ...] | "
598                 "-u dir [file ...]\n",
599                 progname);
600
601         return((int)MANDOCLEVEL_BADARG);
602 }
603
604 void
605 index_merge(const struct of *of, struct mparse *mp,
606                 struct buf *dbuf, struct buf *buf, DB *hash,
607                 struct mdb *mdb, struct recs *recs)
608 {
609         recno_t          rec;
610         int              ch, skip;
611         DBT              key, val;
612         DB              *files;  /* temporary file name table */
613         struct mdoc     *mdoc;
614         struct man      *man;
615         const char      *fn, *msec, *march, *mtitle;
616         char            *p;
617         uint64_t         mask;
618         size_t           sv;
619         unsigned         seq;
620         uint64_t         vbuf[2];
621         char             type;
622
623         if (warnings) {
624                 files = NULL;
625                 hash_reset(&files);
626         }
627
628         rec = 0;
629         for (of = of->first; of; of = of->next) {
630                 fn = of->fname;
631
632                 /*
633                  * Try interpreting the file as mdoc(7) or man(7)
634                  * source code, unless it is already known to be
635                  * formatted.  Fall back to formatted mode.
636                  */
637
638                 mparse_reset(mp);
639                 mdoc = NULL;
640                 man = NULL;
641
642                 if ((MANDOC_SRC & of->src_form ||
643                     ! (MANDOC_FORM & of->src_form)) &&
644                     MANDOCLEVEL_FATAL > mparse_readfd(mp, -1, fn))
645                         mparse_result(mp, &mdoc, &man);
646
647                 if (NULL != mdoc) {
648                         msec = mdoc_meta(mdoc)->msec;
649                         march = mdoc_meta(mdoc)->arch;
650                         if (NULL == march)
651                                 march = "";
652                         mtitle = mdoc_meta(mdoc)->title;
653                 } else if (NULL != man) {
654                         msec = man_meta(man)->msec;
655                         march = "";
656                         mtitle = man_meta(man)->title;
657                 } else {
658                         msec = of->sec;
659                         march = of->arch;
660                         mtitle = of->title;
661                 }
662
663                 /*
664                  * Check whether the manual section given in a file
665                  * agrees with the directory where the file is located.
666                  * Some manuals have suffixes like (3p) on their
667                  * section number either inside the file or in the
668                  * directory name, some are linked into more than one
669                  * section, like encrypt(1) = makekey(8).  Do not skip
670                  * manuals for such reasons.
671                  */
672
673                 skip = 0;
674                 assert(of->sec);
675                 assert(msec);
676                 if (warnings)
677                         if (strcasecmp(msec, of->sec))
678                                 fprintf(stderr, "%s: "
679                                         "section \"%s\" manual "
680                                         "in \"%s\" directory\n",
681                                         fn, msec, of->sec);
682
683                 /*
684                  * Manual page directories exist for each kernel
685                  * architecture as returned by machine(1).
686                  * However, many manuals only depend on the
687                  * application architecture as returned by arch(1).
688                  * For example, some (2/ARM) manuals are shared
689                  * across the "armish" and "zaurus" kernel
690                  * architectures.
691                  * A few manuals are even shared across completely
692                  * different architectures, for example fdformat(1)
693                  * on amd64, i386, sparc, and sparc64.
694                  * Thus, warn about architecture mismatches,
695                  * but don't skip manuals for this reason.
696                  */
697
698                 assert(of->arch);
699                 assert(march);
700                 if (warnings)
701                         if (strcasecmp(march, of->arch))
702                                 fprintf(stderr, "%s: "
703                                         "architecture \"%s\" manual "
704                                         "in \"%s\" directory\n",
705                                         fn, march, of->arch);
706
707                 /*
708                  * By default, skip a file if the title given
709                  * in the file disagrees with the file name.
710                  * Do not warn, this happens for all MLINKs.
711                  */
712
713                 assert(of->title);
714                 assert(mtitle);
715                 if (strcasecmp(mtitle, of->title))
716                         skip = 1;
717
718                 /*
719                  * Build a title string for the file.  If it matches
720                  * the location of the file, remember the title as
721                  * found; else, remember it as missing.
722                  */
723
724                 if (warnings) {
725                         buf->len = 0;
726                         buf_appendb(buf, mtitle, strlen(mtitle));
727                         buf_appendb(buf, "(", 1);
728                         buf_appendb(buf, msec, strlen(msec));
729                         if ('\0' != *march) {
730                                 buf_appendb(buf, "/", 1);
731                                 buf_appendb(buf, march, strlen(march));
732                         }
733                         buf_appendb(buf, ")", 2);
734                         for (p = buf->cp; '\0' != *p; p++)
735                                 *p = tolower(*p);
736                         key.data = buf->cp;
737                         key.size = buf->len;
738                         val.data = NULL;
739                         val.size = 0;
740                         if (0 == skip)
741                                 val.data = "";
742                         else {
743                                 ch = (*files->get)(files, &key, &val, 0);
744                                 if (ch < 0) {
745                                         perror("hash");
746                                         exit((int)MANDOCLEVEL_SYSERR);
747                                 } else if (ch > 0) {
748                                         val.data = (void *)fn;
749                                         val.size = strlen(fn) + 1;
750                                 } else
751                                         val.data = NULL;
752                         }
753                         if (NULL != val.data &&
754                             (*files->put)(files, &key, &val, 0) < 0) {
755                                 perror("hash");
756                                 exit((int)MANDOCLEVEL_SYSERR);
757                         }
758                 }
759
760                 if (skip && !use_all)
761                         continue;
762
763                 /*
764                  * The index record value consists of a nil-terminated
765                  * filename, a nil-terminated manual section, and a
766                  * nil-terminated description.  Use the actual
767                  * location of the file, such that the user can find
768                  * it with man(1).  Since the description may not be
769                  * set, we set a sentinel to see if we're going to
770                  * write a nil byte in its place.
771                  */
772
773                 dbuf->len = 0;
774                 type = mdoc ? 'd' : (man ? 'a' : 'c');
775                 buf_appendb(dbuf, &type, 1);
776                 buf_appendb(dbuf, fn, strlen(fn) + 1);
777                 buf_appendb(dbuf, of->sec, strlen(of->sec) + 1);
778                 buf_appendb(dbuf, of->title, strlen(of->title) + 1);
779                 buf_appendb(dbuf, of->arch, strlen(of->arch) + 1);
780
781                 sv = dbuf->len;
782
783                 /*
784                  * Collect keyword/mask pairs.
785                  * Each pair will become a new btree node.
786                  */
787
788                 hash_reset(&hash);
789                 if (mdoc)
790                         pmdoc_node(hash, buf, dbuf,
791                                 mdoc_node(mdoc), mdoc_meta(mdoc));
792                 else if (man)
793                         pman_node(hash, buf, dbuf, man_node(man));
794                 else
795                         pformatted(hash, buf, dbuf, of);
796
797                 /* Test mode, do not access any database. */
798
799                 if (NULL == mdb->db || NULL == mdb->idx)
800                         continue;
801
802                 /*
803                  * Make sure the file name is always registered
804                  * as an .Nm search key.
805                  */
806                 buf->len = 0;
807                 buf_append(buf, of->title);
808                 hash_put(hash, buf, TYPE_Nm);
809
810                 /*
811                  * Reclaim an empty index record, if available.
812                  * Use its record number for all new btree nodes.
813                  */
814
815                 if (recs->cur > 0) {
816                         recs->cur--;
817                         rec = recs->stack[(int)recs->cur];
818                 } else if (recs->last > 0) {
819                         rec = recs->last;
820                         recs->last = 0;
821                 } else
822                         rec++;
823                 vbuf[1] = htobe64(rec);
824
825                 /*
826                  * Copy from the in-memory hashtable of pending
827                  * keyword/mask pairs into the database.
828                  */
829
830                 seq = R_FIRST;
831                 while (0 == (ch = (*hash->seq)(hash, &key, &val, seq))) {
832                         seq = R_NEXT;
833                         assert(sizeof(uint64_t) == val.size);
834                         memcpy(&mask, val.data, val.size);
835                         vbuf[0] = htobe64(mask);
836                         val.size = sizeof(vbuf);
837                         val.data = &vbuf;
838                         dbt_put(mdb->db, mdb->dbn, &key, &val);
839                 }
840                 if (ch < 0) {
841                         perror("hash");
842                         unlink(mdb->dbn);
843                         unlink(mdb->idxn);
844                         exit((int)MANDOCLEVEL_SYSERR);
845                 }
846
847                 /*
848                  * Apply to the index.  If we haven't had a description
849                  * set, put an empty one in now.
850                  */
851
852                 if (dbuf->len == sv)
853                         buf_appendb(dbuf, "", 1);
854
855                 key.data = &rec;
856                 key.size = sizeof(recno_t);
857
858                 val.data = dbuf->cp;
859                 val.size = dbuf->len;
860
861                 if (verb)
862                         printf("%s: adding to index\n", fn);
863
864                 dbt_put(mdb->idx, mdb->idxn, &key, &val);
865         }
866
867         /*
868          * Iterate the remembered file titles and check that
869          * all files can be found by their main title.
870          */
871
872         if (warnings) {
873                 seq = R_FIRST;
874                 while (0 == (*files->seq)(files, &key, &val, seq)) {
875                         seq = R_NEXT;
876                         if (val.size)
877                                 fprintf(stderr, "%s: probably "
878                                     "unreachable, title is %s\n",
879                                     (char *)val.data, (char *)key.data);
880                 }
881                 (*files->close)(files);
882         }
883 }
884
885 /*
886  * Scan through all entries in the index file `idx' and prune those
887  * entries in `ofile'.
888  * Pruning consists of removing from `db', then invalidating the entry
889  * in `idx' (zeroing its value size).
890  */
891 static void
892 index_prune(const struct of *ofile, struct mdb *mdb, struct recs *recs)
893 {
894         const struct of *of;
895         const char      *fn;
896         uint64_t         vbuf[2];
897         unsigned         seq, sseq;
898         DBT              key, val;
899         int              ch;
900
901         recs->cur = 0;
902         seq = R_FIRST;
903         while (0 == (ch = (*mdb->idx->seq)(mdb->idx, &key, &val, seq))) {
904                 seq = R_NEXT;
905                 assert(sizeof(recno_t) == key.size);
906                 memcpy(&recs->last, key.data, key.size);
907
908                 /* Deleted records are zero-sized.  Skip them. */
909
910                 if (0 == val.size)
911                         goto cont;
912
913                 /*
914                  * Make sure we're sane.
915                  * Read past our mdoc/man/cat type to the next string,
916                  * then make sure it's bounded by a NUL.
917                  * Failing any of these, we go into our error handler.
918                  */
919
920                 fn = (char *)val.data + 1;
921                 if (NULL == memchr(fn, '\0', val.size - 1))
922                         break;
923
924                 /*
925                  * Search for the file in those we care about.
926                  * XXX: build this into a tree.  Too slow.
927                  */
928
929                 for (of = ofile->first; of; of = of->next)
930                         if (0 == strcmp(fn, of->fname))
931                                 break;
932
933                 if (NULL == of)
934                         continue;
935
936                 /*
937                  * Search through the keyword database, throwing out all
938                  * references to our file.
939                  */
940
941                 sseq = R_FIRST;
942                 while (0 == (ch = (*mdb->db->seq)(mdb->db,
943                                         &key, &val, sseq))) {
944                         sseq = R_NEXT;
945                         if (sizeof(vbuf) != val.size)
946                                 break;
947
948                         memcpy(vbuf, val.data, val.size);
949                         if (recs->last != betoh64(vbuf[1]))
950                                 continue;
951
952                         if ((ch = (*mdb->db->del)(mdb->db,
953                                         &key, R_CURSOR)) < 0)
954                                 break;
955                 }
956
957                 if (ch < 0) {
958                         perror(mdb->dbn);
959                         exit((int)MANDOCLEVEL_SYSERR);
960                 } else if (1 != ch) {
961                         fprintf(stderr, "%s: corrupt database\n",
962                                         mdb->dbn);
963                         exit((int)MANDOCLEVEL_SYSERR);
964                 }
965
966                 if (verb)
967                         printf("%s: deleting from index\n", fn);
968
969                 val.size = 0;
970                 ch = (*mdb->idx->put)(mdb->idx, &key, &val, R_CURSOR);
971
972                 if (ch < 0)
973                         break;
974 cont:
975                 if (recs->cur >= recs->size) {
976                         recs->size += MANDOC_SLOP;
977                         recs->stack = mandoc_realloc(recs->stack,
978                                         recs->size * sizeof(recno_t));
979                 }
980
981                 recs->stack[(int)recs->cur] = recs->last;
982                 recs->cur++;
983         }
984
985         if (ch < 0) {
986                 perror(mdb->idxn);
987                 exit((int)MANDOCLEVEL_SYSERR);
988         } else if (1 != ch) {
989                 fprintf(stderr, "%s: corrupt index\n", mdb->idxn);
990                 exit((int)MANDOCLEVEL_SYSERR);
991         }
992
993         recs->last++;
994 }
995
996 /*
997  * Grow the buffer (if necessary) and copy in a binary string.
998  */
999 static void
1000 buf_appendb(struct buf *buf, const void *cp, size_t sz)
1001 {
1002
1003         /* Overshoot by MANDOC_BUFSZ. */
1004
1005         while (buf->len + sz >= buf->size) {
1006                 buf->size = buf->len + sz + MANDOC_BUFSZ;
1007                 buf->cp = mandoc_realloc(buf->cp, buf->size);
1008         }
1009
1010         memcpy(buf->cp + (int)buf->len, cp, sz);
1011         buf->len += sz;
1012 }
1013
1014 /*
1015  * Append a nil-terminated string to the buffer.  
1016  * This can be invoked multiple times.  
1017  * The buffer string will be nil-terminated.
1018  * If invoked multiple times, a space is put between strings.
1019  */
1020 static void
1021 buf_append(struct buf *buf, const char *cp)
1022 {
1023         size_t           sz;
1024
1025         if (0 == (sz = strlen(cp)))
1026                 return;
1027
1028         if (buf->len)
1029                 buf->cp[(int)buf->len - 1] = ' ';
1030
1031         buf_appendb(buf, cp, sz + 1);
1032 }
1033
1034 /*
1035  * Recursively add all text from a given node.  
1036  * This is optimised for general mdoc nodes in this context, which do
1037  * not consist of subexpressions and having a recursive call for n->next
1038  * would be wasteful.
1039  * The "f" variable should be 0 unless called from pmdoc_Nd for the
1040  * description buffer, which does not start at the beginning of the
1041  * buffer.
1042  */
1043 static void
1044 buf_appendmdoc(struct buf *buf, const struct mdoc_node *n, int f)
1045 {
1046
1047         for ( ; n; n = n->next) {
1048                 if (n->child)
1049                         buf_appendmdoc(buf, n->child, f);
1050
1051                 if (MDOC_TEXT == n->type && f) {
1052                         f = 0;
1053                         buf_appendb(buf, n->string, 
1054                                         strlen(n->string) + 1);
1055                 } else if (MDOC_TEXT == n->type)
1056                         buf_append(buf, n->string);
1057
1058         }
1059 }
1060
1061 static void
1062 hash_reset(DB **db)
1063 {
1064         DB              *hash;
1065
1066         if (NULL != (hash = *db))
1067                 (*hash->close)(hash);
1068
1069         *db = dbopen(NULL, O_CREAT|O_RDWR, 0644, DB_HASH, NULL);
1070         if (NULL == *db) {
1071                 perror("hash");
1072                 exit((int)MANDOCLEVEL_SYSERR);
1073         }
1074 }
1075
1076 /* ARGSUSED */
1077 static int
1078 pmdoc_head(MDOC_ARGS)
1079 {
1080
1081         return(MDOC_HEAD == n->type);
1082 }
1083
1084 /* ARGSUSED */
1085 static int
1086 pmdoc_body(MDOC_ARGS)
1087 {
1088
1089         return(MDOC_BODY == n->type);
1090 }
1091
1092 /* ARGSUSED */
1093 static int
1094 pmdoc_Fd(MDOC_ARGS)
1095 {
1096         const char      *start, *end;
1097         size_t           sz;
1098
1099         if (SEC_SYNOPSIS != n->sec)
1100                 return(0);
1101         if (NULL == (n = n->child) || MDOC_TEXT != n->type)
1102                 return(0);
1103
1104         /*
1105          * Only consider those `Fd' macro fields that begin with an
1106          * "inclusion" token (versus, e.g., #define).
1107          */
1108         if (strcmp("#include", n->string))
1109                 return(0);
1110
1111         if (NULL == (n = n->next) || MDOC_TEXT != n->type)
1112                 return(0);
1113
1114         /*
1115          * Strip away the enclosing angle brackets and make sure we're
1116          * not zero-length.
1117          */
1118
1119         start = n->string;
1120         if ('<' == *start || '"' == *start)
1121                 start++;
1122
1123         if (0 == (sz = strlen(start)))
1124                 return(0);
1125
1126         end = &start[(int)sz - 1];
1127         if ('>' == *end || '"' == *end)
1128                 end--;
1129
1130         assert(end >= start);
1131
1132         buf_appendb(buf, start, (size_t)(end - start + 1));
1133         buf_appendb(buf, "", 1);
1134         return(1);
1135 }
1136
1137 /* ARGSUSED */
1138 static int
1139 pmdoc_In(MDOC_ARGS)
1140 {
1141
1142         if (NULL == n->child || MDOC_TEXT != n->child->type)
1143                 return(0);
1144
1145         buf_append(buf, n->child->string);
1146         return(1);
1147 }
1148
1149 /* ARGSUSED */
1150 static int
1151 pmdoc_Fn(MDOC_ARGS)
1152 {
1153         struct mdoc_node *nn;
1154         const char      *cp;
1155
1156         nn = n->child;
1157
1158         if (NULL == nn || MDOC_TEXT != nn->type)
1159                 return(0);
1160
1161         /* .Fn "struct type *name" "char *arg" */
1162
1163         cp = strrchr(nn->string, ' ');
1164         if (NULL == cp)
1165                 cp = nn->string;
1166
1167         /* Strip away pointer symbol. */
1168
1169         while ('*' == *cp)
1170                 cp++;
1171
1172         /* Store the function name. */
1173
1174         buf_append(buf, cp);
1175         hash_put(hash, buf, TYPE_Fn);
1176
1177         /* Store the function type. */
1178
1179         if (nn->string < cp) {
1180                 buf->len = 0;
1181                 buf_appendb(buf, nn->string, cp - nn->string);
1182                 buf_appendb(buf, "", 1);
1183                 hash_put(hash, buf, TYPE_Ft);
1184         }
1185
1186         /* Store the arguments. */
1187
1188         for (nn = nn->next; nn; nn = nn->next) {
1189                 if (MDOC_TEXT != nn->type)
1190                         continue;
1191                 buf->len = 0;
1192                 buf_append(buf, nn->string);
1193                 hash_put(hash, buf, TYPE_Fa);
1194         }
1195
1196         return(0);
1197 }
1198
1199 /* ARGSUSED */
1200 static int
1201 pmdoc_St(MDOC_ARGS)
1202 {
1203
1204         if (NULL == n->child || MDOC_TEXT != n->child->type)
1205                 return(0);
1206
1207         buf_append(buf, n->child->string);
1208         return(1);
1209 }
1210
1211 /* ARGSUSED */
1212 static int
1213 pmdoc_Xr(MDOC_ARGS)
1214 {
1215
1216         if (NULL == (n = n->child))
1217                 return(0);
1218
1219         buf_appendb(buf, n->string, strlen(n->string));
1220
1221         if (NULL != (n = n->next)) {
1222                 buf_appendb(buf, ".", 1);
1223                 buf_appendb(buf, n->string, strlen(n->string) + 1);
1224         } else
1225                 buf_appendb(buf, ".", 2);
1226
1227         return(1);
1228 }
1229
1230 /* ARGSUSED */
1231 static int
1232 pmdoc_Nd(MDOC_ARGS)
1233 {
1234
1235         if (MDOC_BODY != n->type)
1236                 return(0);
1237
1238         buf_appendmdoc(dbuf, n->child, 1);
1239         return(1);
1240 }
1241
1242 /* ARGSUSED */
1243 static int
1244 pmdoc_Nm(MDOC_ARGS)
1245 {
1246
1247         if (SEC_NAME == n->sec)
1248                 return(1);
1249         else if (SEC_SYNOPSIS != n->sec || MDOC_HEAD != n->type)
1250                 return(0);
1251
1252         if (NULL == n->child)
1253                 buf_append(buf, m->name);
1254
1255         return(1);
1256 }
1257
1258 /* ARGSUSED */
1259 static int
1260 pmdoc_Sh(MDOC_ARGS)
1261 {
1262
1263         return(SEC_CUSTOM == n->sec && MDOC_HEAD == n->type);
1264 }
1265
1266 static void
1267 hash_put(DB *db, const struct buf *buf, uint64_t mask)
1268 {
1269         uint64_t         oldmask;
1270         DBT              key, val;
1271         int              rc;
1272
1273         if (buf->len < 2)
1274                 return;
1275
1276         key.data = buf->cp;
1277         key.size = buf->len;
1278
1279         if ((rc = (*db->get)(db, &key, &val, 0)) < 0) {
1280                 perror("hash");
1281                 exit((int)MANDOCLEVEL_SYSERR);
1282         } else if (0 == rc) {
1283                 assert(sizeof(uint64_t) == val.size);
1284                 memcpy(&oldmask, val.data, val.size);
1285                 mask |= oldmask;
1286         }
1287
1288         val.data = &mask;
1289         val.size = sizeof(uint64_t); 
1290
1291         if ((rc = (*db->put)(db, &key, &val, 0)) < 0) {
1292                 perror("hash");
1293                 exit((int)MANDOCLEVEL_SYSERR);
1294         } 
1295 }
1296
1297 static void
1298 dbt_put(DB *db, const char *dbn, DBT *key, DBT *val)
1299 {
1300
1301         assert(key->size);
1302         assert(val->size);
1303
1304         if (0 == (*db->put)(db, key, val, 0))
1305                 return;
1306         
1307         perror(dbn);
1308         exit((int)MANDOCLEVEL_SYSERR);
1309         /* NOTREACHED */
1310 }
1311
1312 /*
1313  * Call out to per-macro handlers after clearing the persistent database
1314  * key.  If the macro sets the database key, flush it to the database.
1315  */
1316 static void
1317 pmdoc_node(MDOC_ARGS)
1318 {
1319
1320         if (NULL == n)
1321                 return;
1322
1323         switch (n->type) {
1324         case (MDOC_HEAD):
1325                 /* FALLTHROUGH */
1326         case (MDOC_BODY):
1327                 /* FALLTHROUGH */
1328         case (MDOC_TAIL):
1329                 /* FALLTHROUGH */
1330         case (MDOC_BLOCK):
1331                 /* FALLTHROUGH */
1332         case (MDOC_ELEM):
1333                 buf->len = 0;
1334
1335                 /*
1336                  * Both NULL handlers and handlers returning true
1337                  * request using the data.  Only skip the element
1338                  * when the handler returns false.
1339                  */
1340
1341                 if (NULL != mdocs[n->tok].fp &&
1342                     0 == (*mdocs[n->tok].fp)(hash, buf, dbuf, n, m))
1343                         break;
1344
1345                 /*
1346                  * For many macros, use the text from all children.
1347                  * Set zero flags for macros not needing this.
1348                  * In that case, the handler must fill the buffer.
1349                  */
1350
1351                 if (MDOCF_CHILD & mdocs[n->tok].flags)
1352                         buf_appendmdoc(buf, n->child, 0);
1353
1354                 /*
1355                  * Cover the most common case:
1356                  * Automatically stage one string per element.
1357                  * Set a zero mask for macros not needing this.
1358                  * Additional staging can be done in the handler.
1359                  */
1360
1361                 if (mdocs[n->tok].mask)
1362                         hash_put(hash, buf, mdocs[n->tok].mask);
1363                 break;
1364         default:
1365                 break;
1366         }
1367
1368         pmdoc_node(hash, buf, dbuf, n->child, m);
1369         pmdoc_node(hash, buf, dbuf, n->next, m);
1370 }
1371
1372 static int
1373 pman_node(MAN_ARGS)
1374 {
1375         const struct man_node *head, *body;
1376         char            *start, *sv, *title;
1377         size_t           sz, titlesz;
1378
1379         if (NULL == n)
1380                 return(0);
1381
1382         /*
1383          * We're only searching for one thing: the first text child in
1384          * the BODY of a NAME section.  Since we don't keep track of
1385          * sections in -man, run some hoops to find out whether we're in
1386          * the correct section or not.
1387          */
1388
1389         if (MAN_BODY == n->type && MAN_SH == n->tok) {
1390                 body = n;
1391                 assert(body->parent);
1392                 if (NULL != (head = body->parent->head) &&
1393                                 1 == head->nchild &&
1394                                 NULL != (head = (head->child)) &&
1395                                 MAN_TEXT == head->type &&
1396                                 0 == strcmp(head->string, "NAME") &&
1397                                 NULL != (body = body->child) &&
1398                                 MAN_TEXT == body->type) {
1399
1400                         title = NULL;
1401                         titlesz = 0;
1402                         /*
1403                          * Suck the entire NAME section into memory.
1404                          * Yes, we might run away.
1405                          * But too many manuals have big, spread-out
1406                          * NAME sections over many lines.
1407                          */
1408                         for ( ; NULL != body; body = body->next) {
1409                                 if (MAN_TEXT != body->type)
1410                                         break;
1411                                 if (0 == (sz = strlen(body->string)))
1412                                         continue;
1413                                 title = mandoc_realloc
1414                                         (title, titlesz + sz + 1);
1415                                 memcpy(title + titlesz, body->string, sz);
1416                                 titlesz += sz + 1;
1417                                 title[(int)titlesz - 1] = ' ';
1418                         }
1419                         if (NULL == title)
1420                                 return(0);
1421
1422                         title = mandoc_realloc(title, titlesz + 1);
1423                         title[(int)titlesz] = '\0';
1424
1425                         /* Skip leading space.  */
1426
1427                         sv = title;
1428                         while (isspace((unsigned char)*sv))
1429                                 sv++;
1430
1431                         if (0 == (sz = strlen(sv))) {
1432                                 free(title);
1433                                 return(0);
1434                         }
1435
1436                         /* Erase trailing space. */
1437
1438                         start = &sv[sz - 1];
1439                         while (start > sv && isspace((unsigned char)*start))
1440                                 *start-- = '\0';
1441
1442                         if (start == sv) {
1443                                 free(title);
1444                                 return(0);
1445                         }
1446
1447                         start = sv;
1448
1449                         /* 
1450                          * Go through a special heuristic dance here.
1451                          * This is why -man manuals are great!
1452                          * (I'm being sarcastic: my eyes are bleeding.)
1453                          * Conventionally, one or more manual names are
1454                          * comma-specified prior to a whitespace, then a
1455                          * dash, then a description.  Try to puzzle out
1456                          * the name parts here.
1457                          */
1458
1459                         for ( ;; ) {
1460                                 sz = strcspn(start, " ,");
1461                                 if ('\0' == start[(int)sz])
1462                                         break;
1463
1464                                 buf->len = 0;
1465                                 buf_appendb(buf, start, sz);
1466                                 buf_appendb(buf, "", 1);
1467
1468                                 hash_put(hash, buf, TYPE_Nm);
1469
1470                                 if (' ' == start[(int)sz]) {
1471                                         start += (int)sz + 1;
1472                                         break;
1473                                 }
1474
1475                                 assert(',' == start[(int)sz]);
1476                                 start += (int)sz + 1;
1477                                 while (' ' == *start)
1478                                         start++;
1479                         }
1480
1481                         buf->len = 0;
1482
1483                         if (sv == start) {
1484                                 buf_append(buf, start);
1485                                 free(title);
1486                                 return(1);
1487                         }
1488
1489                         while (isspace((unsigned char)*start))
1490                                 start++;
1491
1492                         if (0 == strncmp(start, "-", 1))
1493                                 start += 1;
1494                         else if (0 == strncmp(start, "\\-\\-", 4))
1495                                 start += 4;
1496                         else if (0 == strncmp(start, "\\-", 2))
1497                                 start += 2;
1498                         else if (0 == strncmp(start, "\\(en", 4))
1499                                 start += 4;
1500                         else if (0 == strncmp(start, "\\(em", 4))
1501                                 start += 4;
1502
1503                         while (' ' == *start)
1504                                 start++;
1505
1506                         sz = strlen(start) + 1;
1507                         buf_appendb(dbuf, start, sz);
1508                         buf_appendb(buf, start, sz);
1509
1510                         hash_put(hash, buf, TYPE_Nd);
1511                         free(title);
1512                 }
1513         }
1514
1515         for (n = n->child; n; n = n->next)
1516                 if (pman_node(hash, buf, dbuf, n))
1517                         return(1);
1518
1519         return(0);
1520 }
1521
1522 /*
1523  * Parse a formatted manual page.
1524  * By necessity, this involves rather crude guesswork.
1525  */
1526 static void
1527 pformatted(DB *hash, struct buf *buf, 
1528                 struct buf *dbuf, const struct of *of)
1529 {
1530         FILE            *stream;
1531         char            *line, *p, *title;
1532         size_t           len, plen, titlesz;
1533
1534         if (NULL == (stream = fopen(of->fname, "r"))) {
1535                 if (warnings)
1536                         perror(of->fname);
1537                 return;
1538         }
1539
1540         /*
1541          * Always use the title derived from the filename up front,
1542          * do not even try to find it in the file.  This also makes
1543          * sure we don't end up with an orphan index record, even if
1544          * the file content turns out to be completely unintelligible.
1545          */
1546
1547         buf->len = 0;
1548         buf_append(buf, of->title);
1549         hash_put(hash, buf, TYPE_Nm);
1550
1551         /* Skip to first blank line. */
1552
1553         while (NULL != (line = fgetln(stream, &len)))
1554                 if ('\n' == *line)
1555                         break;
1556
1557         /*
1558          * Assume the first line that is not indented
1559          * is the first section header.  Skip to it.
1560          */
1561
1562         while (NULL != (line = fgetln(stream, &len)))
1563                 if ('\n' != *line && ' ' != *line)
1564                         break;
1565         
1566         /*
1567          * Read up until the next section into a buffer.
1568          * Strip the leading and trailing newline from each read line,
1569          * appending a trailing space.
1570          * Ignore empty (whitespace-only) lines.
1571          */
1572
1573         titlesz = 0;
1574         title = NULL;
1575
1576         while (NULL != (line = fgetln(stream, &len))) {
1577                 if (' ' != *line || '\n' != line[(int)len - 1])
1578                         break;
1579                 while (len > 0 && isspace((unsigned char)*line)) {
1580                         line++;
1581                         len--;
1582                 }
1583                 if (1 == len)
1584                         continue;
1585                 title = mandoc_realloc(title, titlesz + len);
1586                 memcpy(title + titlesz, line, len);
1587                 titlesz += len;
1588                 title[(int)titlesz - 1] = ' ';
1589         }
1590
1591
1592         /*
1593          * If no page content can be found, or the input line
1594          * is already the next section header, or there is no
1595          * trailing newline, reuse the page title as the page
1596          * description.
1597          */
1598
1599         if (NULL == title || '\0' == *title) {
1600                 if (warnings)
1601                         fprintf(stderr, "%s: cannot find NAME section\n",
1602                                         of->fname);
1603                 buf_appendb(dbuf, buf->cp, buf->size);
1604                 hash_put(hash, buf, TYPE_Nd);
1605                 fclose(stream);
1606                 free(title);
1607                 return;
1608         }
1609
1610         title = mandoc_realloc(title, titlesz + 1);
1611         title[(int)titlesz] = '\0';
1612
1613         /*
1614          * Skip to the first dash.
1615          * Use the remaining line as the description (no more than 70
1616          * bytes).
1617          */
1618
1619         if (NULL != (p = strstr(title, "- "))) {
1620                 for (p += 2; ' ' == *p || '\b' == *p; p++)
1621                         /* Skip to next word. */ ;
1622         } else {
1623                 if (warnings)
1624                         fprintf(stderr, "%s: no dash in title line\n",
1625                                         of->fname);
1626                 p = title;
1627         }
1628
1629         plen = strlen(p);
1630
1631         /* Strip backspace-encoding from line. */
1632
1633         while (NULL != (line = memchr(p, '\b', plen))) {
1634                 len = line - p;
1635                 if (0 == len) {
1636                         memmove(line, line + 1, plen--);
1637                         continue;
1638                 } 
1639                 memmove(line - 1, line + 1, plen - len);
1640                 plen -= 2;
1641         }
1642
1643         buf_appendb(dbuf, p, plen + 1);
1644         buf->len = 0;
1645         buf_appendb(buf, p, plen + 1);
1646         hash_put(hash, buf, TYPE_Nd);
1647         fclose(stream);
1648         free(title);
1649 }
1650
1651 static void
1652 ofile_argbuild(int argc, char *argv[], struct of **of,
1653                 const char *basedir)
1654 {
1655         char             buf[PATH_MAX];
1656         char             pbuf[PATH_MAX];
1657         const char      *sec, *arch, *title;
1658         char            *relpath, *p;
1659         int              i, src_form;
1660         struct of       *nof;
1661
1662         for (i = 0; i < argc; i++) {
1663                 if (NULL == (relpath = realpath(argv[i], pbuf))) {
1664                         perror(argv[i]);
1665                         continue;
1666                 }
1667                 if (NULL != basedir) {
1668                         if (strstr(pbuf, basedir) != pbuf) {
1669                                 fprintf(stderr, "%s: file outside "
1670                                     "base directory %s\n",
1671                                     pbuf, basedir);
1672                                 continue;
1673                         }
1674                         relpath = pbuf + strlen(basedir);
1675                 }
1676
1677                 /*
1678                  * Try to infer the manual section, architecture and
1679                  * page title from the path, assuming it looks like
1680                  *   man*[/<arch>]/<title>.<section>   or
1681                  *   cat<section>[/<arch>]/<title>.0
1682                  */
1683
1684                 if (strlcpy(buf, relpath, sizeof(buf)) >= sizeof(buf)) {
1685                         fprintf(stderr, "%s: path too long\n", relpath);
1686                         continue;
1687                 }
1688                 sec = arch = title = "";
1689                 src_form = 0;
1690                 p = strrchr(buf, '\0');
1691                 while (p-- > buf) {
1692                         if ('\0' == *sec && '.' == *p) {
1693                                 sec = p + 1;
1694                                 *p = '\0';
1695                                 if ('0' == *sec)
1696                                         src_form |= MANDOC_FORM;
1697                                 else if ('1' <= *sec && '9' >= *sec)
1698                                         src_form |= MANDOC_SRC;
1699                                 continue;
1700                         }
1701                         if ('/' != *p)
1702                                 continue;
1703                         if ('\0' == *title) {
1704                                 title = p + 1;
1705                                 *p = '\0';
1706                                 continue;
1707                         }
1708                         if (0 == strncmp("man", p + 1, 3))
1709                                 src_form |= MANDOC_SRC;
1710                         else if (0 == strncmp("cat", p + 1, 3))
1711                                 src_form |= MANDOC_FORM;
1712                         else
1713                                 arch = p + 1;
1714                         break;
1715                 }
1716                 if ('\0' == *title) {
1717                         if (warnings)
1718                                 fprintf(stderr,
1719                                     "%s: cannot deduce title "
1720                                     "from filename\n",
1721                                     relpath);
1722                         title = buf;
1723                 }
1724
1725                 /*
1726                  * Build the file structure.
1727                  */
1728
1729                 nof = mandoc_calloc(1, sizeof(struct of));
1730                 nof->fname = mandoc_strdup(relpath);
1731                 nof->sec = mandoc_strdup(sec);
1732                 nof->arch = mandoc_strdup(arch);
1733                 nof->title = mandoc_strdup(title);
1734                 nof->src_form = src_form;
1735
1736                 /*
1737                  * Add the structure to the list.
1738                  */
1739
1740                 if (NULL == *of) {
1741                         *of = nof;
1742                         (*of)->first = nof;
1743                 } else {
1744                         nof->first = (*of)->first;
1745                         (*of)->next = nof;
1746                         *of = nof;
1747                 }
1748         }
1749 }
1750
1751 /*
1752  * Recursively build up a list of files to parse.
1753  * We use this instead of ftw() and so on because I don't want global
1754  * variables hanging around.
1755  * This ignores the mandoc.db and mandoc.index files, but assumes that
1756  * everything else is a manual.
1757  * Pass in a pointer to a NULL structure for the first invocation.
1758  */
1759 static void
1760 ofile_dirbuild(const char *dir, const char* psec, const char *parch,
1761                 int p_src_form, struct of **of)
1762 {
1763         char             buf[PATH_MAX];
1764 #if defined(__sun)
1765         struct stat      sb;
1766 #endif
1767         size_t           sz;
1768         DIR             *d;
1769         const char      *fn, *sec, *arch;
1770         char            *p, *q, *suffix;
1771         struct of       *nof;
1772         struct dirent   *dp;
1773         int              src_form;
1774
1775         if (NULL == (d = opendir(dir))) {
1776                 if (warnings)
1777                         perror(dir);
1778                 return;
1779         }
1780
1781         while (NULL != (dp = readdir(d))) {
1782                 fn = dp->d_name;
1783
1784                 if ('.' == *fn)
1785                         continue;
1786
1787                 src_form = p_src_form;
1788
1789 #if defined(__sun)
1790                 stat(dp->d_name, &sb);
1791                 if (S_IFDIR & sb.st_mode) {
1792 #else
1793                 if (DT_DIR == dp->d_type) {
1794 #endif
1795                         sec = psec;
1796                         arch = parch;
1797
1798                         /*
1799                          * By default, only use directories called:
1800                          *   man<section>/[<arch>/]   or
1801                          *   cat<section>/[<arch>/]
1802                          */
1803
1804                         if ('\0' == *sec) {
1805                                 if(0 == strncmp("man", fn, 3)) {
1806                                         src_form |= MANDOC_SRC;
1807                                         sec = fn + 3;
1808                                 } else if (0 == strncmp("cat", fn, 3)) {
1809                                         src_form |= MANDOC_FORM;
1810                                         sec = fn + 3;
1811                                 } else {
1812                                         if (warnings) fprintf(stderr,
1813                                             "%s/%s: bad section\n",
1814                                             dir, fn);
1815                                         if (use_all)
1816                                                 sec = fn;
1817                                         else
1818                                                 continue;
1819                                 }
1820                         } else if ('\0' == *arch) {
1821                                 if (NULL != strchr(fn, '.')) {
1822                                         if (warnings) fprintf(stderr,
1823                                             "%s/%s: bad architecture\n",
1824                                             dir, fn);
1825                                         if (0 == use_all)
1826                                                 continue;
1827                                 }
1828                                 arch = fn;
1829                         } else {
1830                                 if (warnings) fprintf(stderr, "%s/%s: "
1831                                     "excessive subdirectory\n", dir, fn);
1832                                 if (0 == use_all)
1833                                         continue;
1834                         }
1835
1836                         buf[0] = '\0';
1837                         strlcat(buf, dir, PATH_MAX);
1838                         strlcat(buf, "/", PATH_MAX);
1839                         sz = strlcat(buf, fn, PATH_MAX);
1840
1841                         if (PATH_MAX <= sz) {
1842                                 if (warnings) fprintf(stderr, "%s/%s: "
1843                                     "path too long\n", dir, fn);
1844                                 continue;
1845                         }
1846
1847                         ofile_dirbuild(buf, sec, arch, src_form, of);
1848                         continue;
1849                 }
1850
1851 #if defined(__sun)
1852                 if (0 == S_IFREG & sb.st_mode) {
1853 #else
1854                 if (DT_REG != dp->d_type) {
1855 #endif
1856                         if (warnings)
1857                                 fprintf(stderr,
1858                                     "%s/%s: not a regular file\n",
1859                                     dir, fn);
1860                         continue;
1861                 }
1862                 if (!strcmp(MANDOC_DB, fn) || !strcmp(MANDOC_IDX, fn))
1863                         continue;
1864                 if ('\0' == *psec) {
1865                         if (warnings)
1866                                 fprintf(stderr,
1867                                     "%s/%s: file outside section\n",
1868                                     dir, fn);
1869                         if (0 == use_all)
1870                                 continue;
1871                 }
1872
1873                 /*
1874                  * By default, skip files where the file name suffix
1875                  * does not agree with the section directory
1876                  * they are located in.
1877                  */
1878
1879                 suffix = strrchr(fn, '.');
1880                 if (NULL == suffix) {
1881                         if (warnings)
1882                                 fprintf(stderr,
1883                                     "%s/%s: no filename suffix\n",
1884                                     dir, fn);
1885                         if (0 == use_all)
1886                                 continue;
1887                 } else if ((MANDOC_SRC & src_form &&
1888                                 strcmp(suffix + 1, psec)) ||
1889                             (MANDOC_FORM & src_form &&
1890                                 strcmp(suffix + 1, "0"))) {
1891                         if (warnings)
1892                                 fprintf(stderr,
1893                                     "%s/%s: wrong filename suffix\n",
1894                                     dir, fn);
1895                         if (0 == use_all)
1896                                 continue;
1897                         if ('0' == suffix[1])
1898                                 src_form |= MANDOC_FORM;
1899                         else if ('1' <= suffix[1] && '9' >= suffix[1])
1900                                 src_form |= MANDOC_SRC;
1901                 }
1902
1903                 /*
1904                  * Skip formatted manuals if a source version is
1905                  * available.  Ignore the age: it is very unlikely
1906                  * that people install newer formatted base manuals
1907                  * when they used to have source manuals before,
1908                  * and in ports, old manuals get removed on update.
1909                  */
1910                 if (0 == use_all && MANDOC_FORM & src_form &&
1911                                 '\0' != *psec) {
1912                         buf[0] = '\0';
1913                         strlcat(buf, dir, PATH_MAX);
1914                         p = strrchr(buf, '/');
1915                         if ('\0' != *parch && NULL != p)
1916                                 for (p--; p > buf; p--)
1917                                         if ('/' == *p)
1918                                                 break;
1919                         if (NULL == p)
1920                                 p = buf;
1921                         else
1922                                 p++;
1923                         if (0 == strncmp("cat", p, 3))
1924                                 memcpy(p, "man", 3);
1925                         strlcat(buf, "/", PATH_MAX);
1926                         sz = strlcat(buf, fn, PATH_MAX);
1927                         if (sz >= PATH_MAX) {
1928                                 if (warnings) fprintf(stderr,
1929                                     "%s/%s: path too long\n",
1930                                     dir, fn);
1931                                 continue;
1932                         }
1933                         q = strrchr(buf, '.');
1934                         if (NULL != q && p < q++) {
1935                                 *q = '\0';
1936                                 sz = strlcat(buf, psec, PATH_MAX);
1937                                 if (sz >= PATH_MAX) {
1938                                         if (warnings) fprintf(stderr,
1939                                             "%s/%s: path too long\n",
1940                                             dir, fn);
1941                                         continue;
1942                                 }
1943                                 if (0 == access(buf, R_OK))
1944                                         continue;
1945                         }
1946                 }
1947
1948                 buf[0] = '\0';
1949                 assert('.' == dir[0]);
1950                 if ('/' == dir[1]) {
1951                         strlcat(buf, dir + 2, PATH_MAX);
1952                         strlcat(buf, "/", PATH_MAX);
1953                 }
1954                 sz = strlcat(buf, fn, PATH_MAX);
1955                 if (sz >= PATH_MAX) {
1956                         if (warnings) fprintf(stderr,
1957                             "%s/%s: path too long\n", dir, fn);
1958                         continue;
1959                 }
1960
1961                 nof = mandoc_calloc(1, sizeof(struct of));
1962                 nof->fname = mandoc_strdup(buf);
1963                 nof->sec = mandoc_strdup(psec);
1964                 nof->arch = mandoc_strdup(parch);
1965                 nof->src_form = src_form;
1966
1967                 /*
1968                  * Remember the file name without the extension,
1969                  * to be used as the page title in the database.
1970                  */
1971
1972                 if (NULL != suffix)
1973                         *suffix = '\0';
1974                 nof->title = mandoc_strdup(fn);
1975
1976                 /*
1977                  * Add the structure to the list.
1978                  */
1979
1980                 if (NULL == *of) {
1981                         *of = nof;
1982                         (*of)->first = nof;
1983                 } else {
1984                         nof->first = (*of)->first;
1985                         (*of)->next = nof;
1986                         *of = nof;
1987                 }
1988         }
1989
1990         closedir(d);
1991 }
1992
1993 static void
1994 ofile_free(struct of *of)
1995 {
1996         struct of       *nof;
1997
1998         if (NULL != of)
1999                 of = of->first;
2000
2001         while (NULL != of) {
2002                 nof = of->next;
2003                 free(of->fname);
2004                 free(of->sec);
2005                 free(of->arch);
2006                 free(of->title);
2007                 free(of);
2008                 of = nof;
2009         }
2010 }