1 /* $Id: mandocdb.c,v 1.49.2.10 2013/11/21 01:53:48 schwarze Exp $ */
3 * Copyright (c) 2011, 2012 Kristaps Dzonsons <kristaps@bsd.lv>
4 * Copyright (c) 2011, 2012 Ingo Schwarze <schwarze@openbsd.org>
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.
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.
22 #include <sys/types.h>
37 #if defined(__APPLE__)
38 # include <libkern/OSByteOrder.h>
39 #elif defined(__linux__)
42 # include <sys/byteorder.h>
43 # include <sys/stat.h>
45 # include <sys/endian.h>
48 #if defined(__linux__) || defined(__sun)
60 #define MANDOC_BUFSZ BUFSIZ
61 #define MANDOC_SLOP 1024
63 #define MANDOC_SRC 0x1
64 #define MANDOC_FORM 0x2
66 /* Access to the mandoc database on disk. */
69 char idxn[PATH_MAX]; /* index db filename */
70 char dbn[PATH_MAX]; /* keyword db filename */
71 DB *idx; /* index recno database */
72 DB *db; /* keyword btree database */
75 /* Stack of temporarily unused index records. */
78 recno_t *stack; /* pointer to a malloc'ed array */
79 size_t size; /* number of allocated slots */
80 size_t cur; /* current number of empty records */
81 recno_t last; /* last record number in the index */
84 /* Tiny list for files. No need to bring in QUEUE. */
87 char *fname; /* heap-allocated */
92 struct of *next; /* NULL for last one */
93 struct of *first; /* first in list */
96 /* Buffer for storing growable data. */
100 size_t len; /* current length */
101 size_t size; /* total buffer size */
104 /* Operation we're going to perform. */
107 OP_DEFAULT = 0, /* new dbs from dir list or default config */
108 OP_CONFFILE, /* new databases from custom config file */
109 OP_UPDATE, /* delete/add entries in existing database */
110 OP_DELETE, /* delete entries from existing database */
111 OP_TEST /* change no databases, report potential problems */
114 #define MAN_ARGS DB *hash, \
117 const struct man_node *n
118 #define MDOC_ARGS DB *hash, \
121 const struct mdoc_node *n, \
122 const struct mdoc_meta *m
124 static void buf_appendmdoc(struct buf *,
125 const struct mdoc_node *, int);
126 static void buf_append(struct buf *, const char *);
127 static void buf_appendb(struct buf *,
128 const void *, size_t);
129 static void dbt_put(DB *, const char *, DBT *, DBT *);
130 static void hash_put(DB *, const struct buf *, uint64_t);
131 static void hash_reset(DB **);
132 static void index_merge(const struct of *, struct mparse *,
133 struct buf *, struct buf *, DB *,
134 struct mdb *, struct recs *);
135 static void index_prune(const struct of *, struct mdb *,
137 static void ofile_argbuild(int, char *[], struct of **,
139 static void ofile_dirbuild(const char *, const char *,
140 const char *, int, struct of **);
141 static void ofile_free(struct of *);
142 static void pformatted(DB *, struct buf *,
143 struct buf *, const struct of *);
144 static int pman_node(MAN_ARGS);
145 static void pmdoc_node(MDOC_ARGS);
146 static int pmdoc_head(MDOC_ARGS);
147 static int pmdoc_body(MDOC_ARGS);
148 static int pmdoc_Fd(MDOC_ARGS);
149 static int pmdoc_In(MDOC_ARGS);
150 static int pmdoc_Fn(MDOC_ARGS);
151 static int pmdoc_Nd(MDOC_ARGS);
152 static int pmdoc_Nm(MDOC_ARGS);
153 static int pmdoc_Sh(MDOC_ARGS);
154 static int pmdoc_St(MDOC_ARGS);
155 static int pmdoc_Xr(MDOC_ARGS);
157 #define MDOCF_CHILD 0x01 /* Automatically index child nodes. */
159 struct mdoc_handler {
160 int (*fp)(MDOC_ARGS); /* Optional handler. */
161 uint64_t mask; /* Set unless handler returns 0. */
162 int flags; /* For use by pmdoc_node. */
165 static const struct mdoc_handler mdocs[MDOC_MAX] = {
166 { NULL, 0, 0 }, /* Ap */
167 { NULL, 0, 0 }, /* Dd */
168 { NULL, 0, 0 }, /* Dt */
169 { NULL, 0, 0 }, /* Os */
170 { pmdoc_Sh, TYPE_Sh, MDOCF_CHILD }, /* Sh */
171 { pmdoc_head, TYPE_Ss, MDOCF_CHILD }, /* Ss */
172 { NULL, 0, 0 }, /* Pp */
173 { NULL, 0, 0 }, /* D1 */
174 { NULL, 0, 0 }, /* Dl */
175 { NULL, 0, 0 }, /* Bd */
176 { NULL, 0, 0 }, /* Ed */
177 { NULL, 0, 0 }, /* Bl */
178 { NULL, 0, 0 }, /* El */
179 { NULL, 0, 0 }, /* It */
180 { NULL, 0, 0 }, /* Ad */
181 { NULL, TYPE_An, MDOCF_CHILD }, /* An */
182 { NULL, TYPE_Ar, MDOCF_CHILD }, /* Ar */
183 { NULL, TYPE_Cd, MDOCF_CHILD }, /* Cd */
184 { NULL, TYPE_Cm, MDOCF_CHILD }, /* Cm */
185 { NULL, TYPE_Dv, MDOCF_CHILD }, /* Dv */
186 { NULL, TYPE_Er, MDOCF_CHILD }, /* Er */
187 { NULL, TYPE_Ev, MDOCF_CHILD }, /* Ev */
188 { NULL, 0, 0 }, /* Ex */
189 { NULL, TYPE_Fa, MDOCF_CHILD }, /* Fa */
190 { pmdoc_Fd, TYPE_In, 0 }, /* Fd */
191 { NULL, TYPE_Fl, MDOCF_CHILD }, /* Fl */
192 { pmdoc_Fn, 0, 0 }, /* Fn */
193 { NULL, TYPE_Ft, MDOCF_CHILD }, /* Ft */
194 { NULL, TYPE_Ic, MDOCF_CHILD }, /* Ic */
195 { pmdoc_In, TYPE_In, 0 }, /* In */
196 { NULL, TYPE_Li, MDOCF_CHILD }, /* Li */
197 { pmdoc_Nd, TYPE_Nd, MDOCF_CHILD }, /* Nd */
198 { pmdoc_Nm, TYPE_Nm, MDOCF_CHILD }, /* Nm */
199 { NULL, 0, 0 }, /* Op */
200 { NULL, 0, 0 }, /* Ot */
201 { NULL, TYPE_Pa, MDOCF_CHILD }, /* Pa */
202 { NULL, 0, 0 }, /* Rv */
203 { pmdoc_St, TYPE_St, 0 }, /* St */
204 { NULL, TYPE_Va, MDOCF_CHILD }, /* Va */
205 { pmdoc_body, TYPE_Va, MDOCF_CHILD }, /* Vt */
206 { pmdoc_Xr, TYPE_Xr, 0 }, /* Xr */
207 { NULL, 0, 0 }, /* %A */
208 { NULL, 0, 0 }, /* %B */
209 { NULL, 0, 0 }, /* %D */
210 { NULL, 0, 0 }, /* %I */
211 { NULL, 0, 0 }, /* %J */
212 { NULL, 0, 0 }, /* %N */
213 { NULL, 0, 0 }, /* %O */
214 { NULL, 0, 0 }, /* %P */
215 { NULL, 0, 0 }, /* %R */
216 { NULL, 0, 0 }, /* %T */
217 { NULL, 0, 0 }, /* %V */
218 { NULL, 0, 0 }, /* Ac */
219 { NULL, 0, 0 }, /* Ao */
220 { NULL, 0, 0 }, /* Aq */
221 { NULL, TYPE_At, MDOCF_CHILD }, /* At */
222 { NULL, 0, 0 }, /* Bc */
223 { NULL, 0, 0 }, /* Bf */
224 { NULL, 0, 0 }, /* Bo */
225 { NULL, 0, 0 }, /* Bq */
226 { NULL, TYPE_Bsx, MDOCF_CHILD }, /* Bsx */
227 { NULL, TYPE_Bx, MDOCF_CHILD }, /* Bx */
228 { NULL, 0, 0 }, /* Db */
229 { NULL, 0, 0 }, /* Dc */
230 { NULL, 0, 0 }, /* Do */
231 { NULL, 0, 0 }, /* Dq */
232 { NULL, 0, 0 }, /* Ec */
233 { NULL, 0, 0 }, /* Ef */
234 { NULL, TYPE_Em, MDOCF_CHILD }, /* Em */
235 { NULL, 0, 0 }, /* Eo */
236 { NULL, TYPE_Fx, MDOCF_CHILD }, /* Fx */
237 { NULL, TYPE_Ms, MDOCF_CHILD }, /* Ms */
238 { NULL, 0, 0 }, /* No */
239 { NULL, 0, 0 }, /* Ns */
240 { NULL, TYPE_Nx, MDOCF_CHILD }, /* Nx */
241 { NULL, TYPE_Ox, MDOCF_CHILD }, /* Ox */
242 { NULL, 0, 0 }, /* Pc */
243 { NULL, 0, 0 }, /* Pf */
244 { NULL, 0, 0 }, /* Po */
245 { NULL, 0, 0 }, /* Pq */
246 { NULL, 0, 0 }, /* Qc */
247 { NULL, 0, 0 }, /* Ql */
248 { NULL, 0, 0 }, /* Qo */
249 { NULL, 0, 0 }, /* Qq */
250 { NULL, 0, 0 }, /* Re */
251 { NULL, 0, 0 }, /* Rs */
252 { NULL, 0, 0 }, /* Sc */
253 { NULL, 0, 0 }, /* So */
254 { NULL, 0, 0 }, /* Sq */
255 { NULL, 0, 0 }, /* Sm */
256 { NULL, 0, 0 }, /* Sx */
257 { NULL, TYPE_Sy, MDOCF_CHILD }, /* Sy */
258 { NULL, TYPE_Tn, MDOCF_CHILD }, /* Tn */
259 { NULL, 0, 0 }, /* Ux */
260 { NULL, 0, 0 }, /* Xc */
261 { NULL, 0, 0 }, /* Xo */
262 { pmdoc_head, TYPE_Fn, 0 }, /* Fo */
263 { NULL, 0, 0 }, /* Fc */
264 { NULL, 0, 0 }, /* Oo */
265 { NULL, 0, 0 }, /* Oc */
266 { NULL, 0, 0 }, /* Bk */
267 { NULL, 0, 0 }, /* Ek */
268 { NULL, 0, 0 }, /* Bt */
269 { NULL, 0, 0 }, /* Hf */
270 { NULL, 0, 0 }, /* Fr */
271 { NULL, 0, 0 }, /* Ud */
272 { NULL, TYPE_Lb, MDOCF_CHILD }, /* Lb */
273 { NULL, 0, 0 }, /* Lp */
274 { NULL, TYPE_Lk, MDOCF_CHILD }, /* Lk */
275 { NULL, TYPE_Mt, MDOCF_CHILD }, /* Mt */
276 { NULL, 0, 0 }, /* Brq */
277 { NULL, 0, 0 }, /* Bro */
278 { NULL, 0, 0 }, /* Brc */
279 { NULL, 0, 0 }, /* %C */
280 { NULL, 0, 0 }, /* Es */
281 { NULL, 0, 0 }, /* En */
282 { NULL, TYPE_Dx, MDOCF_CHILD }, /* Dx */
283 { NULL, 0, 0 }, /* %Q */
284 { NULL, 0, 0 }, /* br */
285 { NULL, 0, 0 }, /* sp */
286 { NULL, 0, 0 }, /* %U */
287 { NULL, 0, 0 }, /* Ta */
290 static const char *progname;
291 static int use_all; /* Use all directories and files. */
292 static int verb; /* Output verbosity level. */
293 static int warnings; /* Potential problems in manuals. */
296 main(int argc, char *argv[])
298 struct mparse *mp; /* parse sequence */
299 struct manpaths dirs;
302 enum op op; /* current operation */
307 DB *hash; /* temporary keyword hashtable */
308 BTREEINFO info; /* btree configuration */
309 size_t sz1, sz2, ipath;
310 struct buf buf, /* keyword buffer */
311 dbuf; /* description buffer */
312 struct of *of; /* list of files for processing */
316 progname = strrchr(argv[0], '/');
317 if (progname == NULL)
322 memset(&dirs, 0, sizeof(struct manpaths));
323 memset(&mdb, 0, sizeof(struct mdb));
324 memset(&recs, 0, sizeof(struct recs));
332 while (-1 != (ch = getopt(argc, argv, "aC:d:tu:vW")))
340 "-C: conflicting options\n");
349 "-d: conflicting options\n");
356 dup2(STDOUT_FILENO, STDERR_FILENO);
359 "-t: conflicting options\n");
369 "-u: conflicting options\n");
388 if (OP_CONFFILE == op && argc > 0) {
389 fprintf(stderr, "-C: too many arguments\n");
393 memset(&info, 0, sizeof(BTREEINFO));
397 mp = mparse_alloc(MPARSE_AUTO, MANDOCLEVEL_FATAL, NULL, NULL, NULL);
399 memset(&buf, 0, sizeof(struct buf));
400 memset(&dbuf, 0, sizeof(struct buf));
402 buf.size = dbuf.size = MANDOC_BUFSZ;
404 buf.cp = mandoc_malloc(buf.size);
405 dbuf.cp = mandoc_malloc(dbuf.size);
408 ofile_argbuild(argc, argv, &of, NULL);
411 index_merge(of, mp, &dbuf, &buf, hash, &mdb, &recs);
415 if (OP_UPDATE == op || OP_DELETE == op) {
416 if (NULL == realpath(dir, pbuf)) {
418 exit((int)MANDOCLEVEL_BADARG);
420 if (strlcat(pbuf, "/", PATH_MAX) >= PATH_MAX) {
421 fprintf(stderr, "%s: path too long\n", pbuf);
422 exit((int)MANDOCLEVEL_BADARG);
425 strlcat(mdb.dbn, pbuf, PATH_MAX);
426 sz1 = strlcat(mdb.dbn, MANDOC_DB, PATH_MAX);
428 strlcat(mdb.idxn, pbuf, PATH_MAX);
429 sz2 = strlcat(mdb.idxn, MANDOC_IDX, PATH_MAX);
431 if (sz1 >= PATH_MAX || sz2 >= PATH_MAX) {
432 fprintf(stderr, "%s: path too long\n", mdb.idxn);
433 exit((int)MANDOCLEVEL_BADARG);
436 flags = O_CREAT | O_RDWR;
437 mdb.db = dbopen(mdb.dbn, flags, 0644, DB_BTREE, &info);
438 mdb.idx = dbopen(mdb.idxn, flags, 0644, DB_RECNO, NULL);
440 if (NULL == mdb.db) {
442 exit((int)MANDOCLEVEL_SYSERR);
443 } else if (NULL == mdb.idx) {
445 exit((int)MANDOCLEVEL_SYSERR);
448 ofile_argbuild(argc, argv, &of, pbuf);
453 index_prune(of, &mdb, &recs);
456 * Go to the root of the respective manual tree.
457 * This must work or no manuals may be found (they're
458 * indexed relative to the root).
461 if (OP_UPDATE == op) {
462 if (-1 == chdir(dir)) {
464 exit((int)MANDOCLEVEL_SYSERR);
466 index_merge(of, mp, &dbuf, &buf, hash,
474 * Configure the directories we're going to scan.
475 * If we have command-line arguments, use them.
476 * If not, we use man(1)'s method (see mandocdb.8).
480 dirs.paths = mandoc_calloc(argc, sizeof(char *));
482 for (i = 0; i < argc; i++) {
483 if (NULL == (cp = realpath(argv[i], pbuf))) {
487 dirs.paths[i] = mandoc_strdup(cp);
490 manpath_parse(&dirs, dir, NULL, NULL);
492 for (ipath = 0; ipath < dirs.sz; ipath++) {
495 * Go to the root of the respective manual tree.
496 * This must work or no manuals may be found:
497 * They are indexed relative to the root.
500 if (-1 == chdir(dirs.paths[ipath])) {
501 perror(dirs.paths[ipath]);
502 exit((int)MANDOCLEVEL_SYSERR);
505 /* Create a new database in two temporary files. */
507 flags = O_CREAT | O_EXCL | O_RDWR;
508 while (NULL == mdb.db) {
509 strlcpy(mdb.dbn, MANDOC_DB, PATH_MAX);
510 strlcat(mdb.dbn, ".XXXXXXXXXX", PATH_MAX);
511 if (NULL == mktemp(mdb.dbn)) {
513 exit((int)MANDOCLEVEL_SYSERR);
515 mdb.db = dbopen(mdb.dbn, flags, 0644,
517 if (NULL == mdb.db && EEXIST != errno) {
519 exit((int)MANDOCLEVEL_SYSERR);
522 while (NULL == mdb.idx) {
523 strlcpy(mdb.idxn, MANDOC_IDX, PATH_MAX);
524 strlcat(mdb.idxn, ".XXXXXXXXXX", PATH_MAX);
525 if (NULL == mktemp(mdb.idxn)) {
528 exit((int)MANDOCLEVEL_SYSERR);
530 mdb.idx = dbopen(mdb.idxn, flags, 0644,
532 if (NULL == mdb.idx && EEXIST != errno) {
535 exit((int)MANDOCLEVEL_SYSERR);
540 * Search for manuals and fill the new database.
543 ofile_dirbuild(".", "", "", 0, &of);
546 index_merge(of, mp, &dbuf, &buf, hash,
552 (*mdb.db->close)(mdb.db);
553 (*mdb.idx->close)(mdb.idx);
558 * Replace the old database with the new one.
559 * This is not perfectly atomic,
560 * but i cannot think of a better way.
563 if (-1 == rename(mdb.dbn, MANDOC_DB)) {
567 exit((int)MANDOCLEVEL_SYSERR);
569 if (-1 == rename(mdb.idxn, MANDOC_IDX)) {
574 exit((int)MANDOCLEVEL_SYSERR);
580 (*mdb.db->close)(mdb.db);
582 (*mdb.idx->close)(mdb.idx);
584 (*hash->close)(hash);
594 return(MANDOCLEVEL_OK);
598 "usage: %s [-avvv] [-C file] | dir ... | -t file ...\n"
599 " -d dir [file ...] | "
600 "-u dir [file ...]\n",
603 return((int)MANDOCLEVEL_BADARG);
607 index_merge(const struct of *of, struct mparse *mp,
608 struct buf *dbuf, struct buf *buf, DB *hash,
609 struct mdb *mdb, struct recs *recs)
614 DB *files; /* temporary file name table */
617 const char *fn, *msec, *march, *mtitle;
625 static char emptystring[] = "";
633 for (of = of->first; of; of = of->next) {
637 * Try interpreting the file as mdoc(7) or man(7)
638 * source code, unless it is already known to be
639 * formatted. Fall back to formatted mode.
646 if ((MANDOC_SRC & of->src_form ||
647 ! (MANDOC_FORM & of->src_form)) &&
648 MANDOCLEVEL_FATAL > mparse_readfd(mp, -1, fn))
649 mparse_result(mp, &mdoc, &man);
652 msec = mdoc_meta(mdoc)->msec;
653 march = mdoc_meta(mdoc)->arch;
656 mtitle = mdoc_meta(mdoc)->title;
657 } else if (NULL != man) {
658 msec = man_meta(man)->msec;
660 mtitle = man_meta(man)->title;
668 * Check whether the manual section given in a file
669 * agrees with the directory where the file is located.
670 * Some manuals have suffixes like (3p) on their
671 * section number either inside the file or in the
672 * directory name, some are linked into more than one
673 * section, like encrypt(1) = makekey(8). Do not skip
674 * manuals for such reasons.
681 if (strcasecmp(msec, of->sec))
682 fprintf(stderr, "%s: "
683 "section \"%s\" manual "
684 "in \"%s\" directory\n",
688 * Manual page directories exist for each kernel
689 * architecture as returned by machine(1).
690 * However, many manuals only depend on the
691 * application architecture as returned by arch(1).
692 * For example, some (2/ARM) manuals are shared
693 * across the "armish" and "zaurus" kernel
695 * A few manuals are even shared across completely
696 * different architectures, for example fdformat(1)
697 * on amd64, i386, sparc, and sparc64.
698 * Thus, warn about architecture mismatches,
699 * but don't skip manuals for this reason.
705 if (strcasecmp(march, of->arch))
706 fprintf(stderr, "%s: "
707 "architecture \"%s\" manual "
708 "in \"%s\" directory\n",
709 fn, march, of->arch);
712 * By default, skip a file if the title given
713 * in the file disagrees with the file name.
714 * Do not warn, this happens for all MLINKs.
719 if (strcasecmp(mtitle, of->title))
723 * Build a title string for the file. If it matches
724 * the location of the file, remember the title as
725 * found; else, remember it as missing.
730 buf_appendb(buf, mtitle, strlen(mtitle));
731 buf_appendb(buf, "(", 1);
732 buf_appendb(buf, msec, strlen(msec));
733 if ('\0' != *march) {
734 buf_appendb(buf, "/", 1);
735 buf_appendb(buf, march, strlen(march));
737 buf_appendb(buf, ")", 2);
738 for (p = buf->cp; '\0' != *p; p++)
739 *p = tolower((unsigned char)*p);
745 val.data = emptystring;
747 ch = (*files->get)(files, &key, &val, 0);
750 exit((int)MANDOCLEVEL_SYSERR);
752 val.data = (void *)fn;
753 val.size = strlen(fn) + 1;
757 if (NULL != val.data &&
758 (*files->put)(files, &key, &val, 0) < 0) {
760 exit((int)MANDOCLEVEL_SYSERR);
764 if (skip && !use_all)
768 * The index record value consists of a nil-terminated
769 * filename, a nil-terminated manual section, and a
770 * nil-terminated description. Use the actual
771 * location of the file, such that the user can find
772 * it with man(1). Since the description may not be
773 * set, we set a sentinel to see if we're going to
774 * write a nil byte in its place.
778 type = mdoc ? 'd' : (man ? 'a' : 'c');
779 buf_appendb(dbuf, &type, 1);
780 buf_appendb(dbuf, fn, strlen(fn) + 1);
781 buf_appendb(dbuf, of->sec, strlen(of->sec) + 1);
782 buf_appendb(dbuf, of->title, strlen(of->title) + 1);
783 buf_appendb(dbuf, of->arch, strlen(of->arch) + 1);
788 * Collect keyword/mask pairs.
789 * Each pair will become a new btree node.
794 pmdoc_node(hash, buf, dbuf,
795 mdoc_node(mdoc), mdoc_meta(mdoc));
797 pman_node(hash, buf, dbuf, man_node(man));
799 pformatted(hash, buf, dbuf, of);
801 /* Test mode, do not access any database. */
803 if (NULL == mdb->db || NULL == mdb->idx)
807 * Make sure the file name is always registered
808 * as an .Nm search key.
811 buf_append(buf, of->title);
812 hash_put(hash, buf, TYPE_Nm);
815 * Reclaim an empty index record, if available.
816 * Use its record number for all new btree nodes.
821 rec = recs->stack[(int)recs->cur];
822 } else if (recs->last > 0) {
827 vbuf[1] = htobe64(rec);
830 * Copy from the in-memory hashtable of pending
831 * keyword/mask pairs into the database.
835 while (0 == (ch = (*hash->seq)(hash, &key, &val, seq))) {
837 assert(sizeof(uint64_t) == val.size);
838 memcpy(&mask, val.data, val.size);
839 vbuf[0] = htobe64(mask);
840 val.size = sizeof(vbuf);
842 dbt_put(mdb->db, mdb->dbn, &key, &val);
848 exit((int)MANDOCLEVEL_SYSERR);
852 * Apply to the index. If we haven't had a description
853 * set, put an empty one in now.
857 buf_appendb(dbuf, "", 1);
860 key.size = sizeof(recno_t);
863 val.size = dbuf->len;
866 printf("%s: adding to index\n", fn);
868 dbt_put(mdb->idx, mdb->idxn, &key, &val);
872 * Iterate the remembered file titles and check that
873 * all files can be found by their main title.
878 while (0 == (*files->seq)(files, &key, &val, seq)) {
881 fprintf(stderr, "%s: probably "
882 "unreachable, title is %s\n",
883 (char *)val.data, (char *)key.data);
885 (*files->close)(files);
890 * Scan through all entries in the index file `idx' and prune those
891 * entries in `ofile'.
892 * Pruning consists of removing from `db', then invalidating the entry
893 * in `idx' (zeroing its value size).
896 index_prune(const struct of *ofile, struct mdb *mdb, struct recs *recs)
907 while (0 == (ch = (*mdb->idx->seq)(mdb->idx, &key, &val, seq))) {
909 assert(sizeof(recno_t) == key.size);
910 memcpy(&recs->last, key.data, key.size);
912 /* Deleted records are zero-sized. Skip them. */
918 * Make sure we're sane.
919 * Read past our mdoc/man/cat type to the next string,
920 * then make sure it's bounded by a NUL.
921 * Failing any of these, we go into our error handler.
924 fn = (char *)val.data + 1;
925 if (NULL == memchr(fn, '\0', val.size - 1))
929 * Search for the file in those we care about.
930 * XXX: build this into a tree. Too slow.
933 for (of = ofile->first; of; of = of->next)
934 if (0 == strcmp(fn, of->fname))
941 * Search through the keyword database, throwing out all
942 * references to our file.
946 while (0 == (ch = (*mdb->db->seq)(mdb->db,
947 &key, &val, sseq))) {
949 if (sizeof(vbuf) != val.size)
952 memcpy(vbuf, val.data, val.size);
953 if (recs->last != betoh64(vbuf[1]))
956 if ((ch = (*mdb->db->del)(mdb->db,
957 &key, R_CURSOR)) < 0)
963 exit((int)MANDOCLEVEL_SYSERR);
964 } else if (1 != ch) {
965 fprintf(stderr, "%s: corrupt database\n",
967 exit((int)MANDOCLEVEL_SYSERR);
971 printf("%s: deleting from index\n", fn);
974 ch = (*mdb->idx->put)(mdb->idx, &key, &val, R_CURSOR);
979 if (recs->cur >= recs->size) {
980 recs->size += MANDOC_SLOP;
981 recs->stack = mandoc_realloc(recs->stack,
982 recs->size * sizeof(recno_t));
985 recs->stack[(int)recs->cur] = recs->last;
991 exit((int)MANDOCLEVEL_SYSERR);
992 } else if (1 != ch) {
993 fprintf(stderr, "%s: corrupt index\n", mdb->idxn);
994 exit((int)MANDOCLEVEL_SYSERR);
1001 * Grow the buffer (if necessary) and copy in a binary string.
1004 buf_appendb(struct buf *buf, const void *cp, size_t sz)
1007 /* Overshoot by MANDOC_BUFSZ. */
1009 while (buf->len + sz >= buf->size) {
1010 buf->size = buf->len + sz + MANDOC_BUFSZ;
1011 buf->cp = mandoc_realloc(buf->cp, buf->size);
1014 memcpy(buf->cp + (int)buf->len, cp, sz);
1019 * Append a nil-terminated string to the buffer.
1020 * This can be invoked multiple times.
1021 * The buffer string will be nil-terminated.
1022 * If invoked multiple times, a space is put between strings.
1025 buf_append(struct buf *buf, const char *cp)
1029 if (0 == (sz = strlen(cp)))
1033 buf->cp[(int)buf->len - 1] = ' ';
1035 buf_appendb(buf, cp, sz + 1);
1039 * Recursively add all text from a given node.
1040 * This is optimised for general mdoc nodes in this context, which do
1041 * not consist of subexpressions and having a recursive call for n->next
1042 * would be wasteful.
1043 * The "f" variable should be 0 unless called from pmdoc_Nd for the
1044 * description buffer, which does not start at the beginning of the
1048 buf_appendmdoc(struct buf *buf, const struct mdoc_node *n, int f)
1051 for ( ; n; n = n->next) {
1053 buf_appendmdoc(buf, n->child, f);
1055 if (MDOC_TEXT == n->type && f) {
1057 buf_appendb(buf, n->string,
1058 strlen(n->string) + 1);
1059 } else if (MDOC_TEXT == n->type)
1060 buf_append(buf, n->string);
1070 if (NULL != (hash = *db))
1071 (*hash->close)(hash);
1073 *db = dbopen(NULL, O_CREAT|O_RDWR, 0644, DB_HASH, NULL);
1076 exit((int)MANDOCLEVEL_SYSERR);
1082 pmdoc_head(MDOC_ARGS)
1085 return(MDOC_HEAD == n->type);
1090 pmdoc_body(MDOC_ARGS)
1093 return(MDOC_BODY == n->type);
1100 const char *start, *end;
1103 if (SEC_SYNOPSIS != n->sec)
1105 if (NULL == (n = n->child) || MDOC_TEXT != n->type)
1109 * Only consider those `Fd' macro fields that begin with an
1110 * "inclusion" token (versus, e.g., #define).
1112 if (strcmp("#include", n->string))
1115 if (NULL == (n = n->next) || MDOC_TEXT != n->type)
1119 * Strip away the enclosing angle brackets and make sure we're
1124 if ('<' == *start || '"' == *start)
1127 if (0 == (sz = strlen(start)))
1130 end = &start[(int)sz - 1];
1131 if ('>' == *end || '"' == *end)
1134 assert(end >= start);
1136 buf_appendb(buf, start, (size_t)(end - start + 1));
1137 buf_appendb(buf, "", 1);
1146 if (NULL == n->child || MDOC_TEXT != n->child->type)
1149 buf_append(buf, n->child->string);
1157 struct mdoc_node *nn;
1162 if (NULL == nn || MDOC_TEXT != nn->type)
1165 /* .Fn "struct type *name" "char *arg" */
1167 cp = strrchr(nn->string, ' ');
1171 /* Strip away pointer symbol. */
1176 /* Store the function name. */
1178 buf_append(buf, cp);
1179 hash_put(hash, buf, TYPE_Fn);
1181 /* Store the function type. */
1183 if (nn->string < cp) {
1185 buf_appendb(buf, nn->string, cp - nn->string);
1186 buf_appendb(buf, "", 1);
1187 hash_put(hash, buf, TYPE_Ft);
1190 /* Store the arguments. */
1192 for (nn = nn->next; nn; nn = nn->next) {
1193 if (MDOC_TEXT != nn->type)
1196 buf_append(buf, nn->string);
1197 hash_put(hash, buf, TYPE_Fa);
1208 if (NULL == n->child || MDOC_TEXT != n->child->type)
1211 buf_append(buf, n->child->string);
1220 if (NULL == (n = n->child))
1223 buf_appendb(buf, n->string, strlen(n->string));
1225 if (NULL != (n = n->next)) {
1226 buf_appendb(buf, ".", 1);
1227 buf_appendb(buf, n->string, strlen(n->string) + 1);
1229 buf_appendb(buf, ".", 2);
1239 if (MDOC_BODY != n->type)
1242 buf_appendmdoc(dbuf, n->child, 1);
1251 if (SEC_NAME == n->sec)
1253 else if (SEC_SYNOPSIS != n->sec || MDOC_HEAD != n->type)
1256 if (NULL == n->child)
1257 buf_append(buf, m->name);
1267 return(SEC_CUSTOM == n->sec && MDOC_HEAD == n->type);
1271 hash_put(DB *db, const struct buf *buf, uint64_t mask)
1281 key.size = buf->len;
1283 if ((rc = (*db->get)(db, &key, &val, 0)) < 0) {
1285 exit((int)MANDOCLEVEL_SYSERR);
1286 } else if (0 == rc) {
1287 assert(sizeof(uint64_t) == val.size);
1288 memcpy(&oldmask, val.data, val.size);
1293 val.size = sizeof(uint64_t);
1295 if ((rc = (*db->put)(db, &key, &val, 0)) < 0) {
1297 exit((int)MANDOCLEVEL_SYSERR);
1302 dbt_put(DB *db, const char *dbn, DBT *key, DBT *val)
1308 if (0 == (*db->put)(db, key, val, 0))
1312 exit((int)MANDOCLEVEL_SYSERR);
1317 * Call out to per-macro handlers after clearing the persistent database
1318 * key. If the macro sets the database key, flush it to the database.
1321 pmdoc_node(MDOC_ARGS)
1340 * Both NULL handlers and handlers returning true
1341 * request using the data. Only skip the element
1342 * when the handler returns false.
1345 if (NULL != mdocs[n->tok].fp &&
1346 0 == (*mdocs[n->tok].fp)(hash, buf, dbuf, n, m))
1350 * For many macros, use the text from all children.
1351 * Set zero flags for macros not needing this.
1352 * In that case, the handler must fill the buffer.
1355 if (MDOCF_CHILD & mdocs[n->tok].flags)
1356 buf_appendmdoc(buf, n->child, 0);
1359 * Cover the most common case:
1360 * Automatically stage one string per element.
1361 * Set a zero mask for macros not needing this.
1362 * Additional staging can be done in the handler.
1365 if (mdocs[n->tok].mask)
1366 hash_put(hash, buf, mdocs[n->tok].mask);
1372 pmdoc_node(hash, buf, dbuf, n->child, m);
1373 pmdoc_node(hash, buf, dbuf, n->next, m);
1379 const struct man_node *head, *body;
1380 char *start, *sv, *title;
1387 * We're only searching for one thing: the first text child in
1388 * the BODY of a NAME section. Since we don't keep track of
1389 * sections in -man, run some hoops to find out whether we're in
1390 * the correct section or not.
1393 if (MAN_BODY == n->type && MAN_SH == n->tok) {
1395 assert(body->parent);
1396 if (NULL != (head = body->parent->head) &&
1397 1 == head->nchild &&
1398 NULL != (head = (head->child)) &&
1399 MAN_TEXT == head->type &&
1400 0 == strcmp(head->string, "NAME") &&
1401 NULL != (body = body->child) &&
1402 MAN_TEXT == body->type) {
1407 * Suck the entire NAME section into memory.
1408 * Yes, we might run away.
1409 * But too many manuals have big, spread-out
1410 * NAME sections over many lines.
1412 for ( ; NULL != body; body = body->next) {
1413 if (MAN_TEXT != body->type)
1415 if (0 == (sz = strlen(body->string)))
1417 title = mandoc_realloc
1418 (title, titlesz + sz + 1);
1419 memcpy(title + titlesz, body->string, sz);
1421 title[(int)titlesz - 1] = ' ';
1426 title = mandoc_realloc(title, titlesz + 1);
1427 title[(int)titlesz] = '\0';
1429 /* Skip leading space. */
1432 while (isspace((unsigned char)*sv))
1435 if (0 == (sz = strlen(sv))) {
1440 /* Erase trailing space. */
1442 start = &sv[sz - 1];
1443 while (start > sv && isspace((unsigned char)*start))
1454 * Go through a special heuristic dance here.
1455 * This is why -man manuals are great!
1456 * (I'm being sarcastic: my eyes are bleeding.)
1457 * Conventionally, one or more manual names are
1458 * comma-specified prior to a whitespace, then a
1459 * dash, then a description. Try to puzzle out
1460 * the name parts here.
1464 sz = strcspn(start, " ,");
1465 if ('\0' == start[(int)sz])
1469 buf_appendb(buf, start, sz);
1470 buf_appendb(buf, "", 1);
1472 hash_put(hash, buf, TYPE_Nm);
1474 if (' ' == start[(int)sz]) {
1475 start += (int)sz + 1;
1479 assert(',' == start[(int)sz]);
1480 start += (int)sz + 1;
1481 while (' ' == *start)
1488 buf_append(buf, start);
1493 while (isspace((unsigned char)*start))
1496 if (0 == strncmp(start, "-", 1))
1498 else if (0 == strncmp(start, "\\-\\-", 4))
1500 else if (0 == strncmp(start, "\\-", 2))
1502 else if (0 == strncmp(start, "\\(en", 4))
1504 else if (0 == strncmp(start, "\\(em", 4))
1507 while (' ' == *start)
1510 sz = strlen(start) + 1;
1511 buf_appendb(dbuf, start, sz);
1512 buf_appendb(buf, start, sz);
1514 hash_put(hash, buf, TYPE_Nd);
1519 for (n = n->child; n; n = n->next)
1520 if (pman_node(hash, buf, dbuf, n))
1527 * Parse a formatted manual page.
1528 * By necessity, this involves rather crude guesswork.
1531 pformatted(DB *hash, struct buf *buf,
1532 struct buf *dbuf, const struct of *of)
1535 char *line, *p, *title;
1536 size_t len, plen, titlesz;
1538 if (NULL == (stream = fopen(of->fname, "r"))) {
1545 * Always use the title derived from the filename up front,
1546 * do not even try to find it in the file. This also makes
1547 * sure we don't end up with an orphan index record, even if
1548 * the file content turns out to be completely unintelligible.
1552 buf_append(buf, of->title);
1553 hash_put(hash, buf, TYPE_Nm);
1555 /* Skip to first blank line. */
1557 while (NULL != (line = fgetln(stream, &len)))
1562 * Assume the first line that is not indented
1563 * is the first section header. Skip to it.
1566 while (NULL != (line = fgetln(stream, &len)))
1567 if ('\n' != *line && ' ' != *line)
1571 * Read up until the next section into a buffer.
1572 * Strip the leading and trailing newline from each read line,
1573 * appending a trailing space.
1574 * Ignore empty (whitespace-only) lines.
1580 while (NULL != (line = fgetln(stream, &len))) {
1581 if (' ' != *line || '\n' != line[(int)len - 1])
1583 while (len > 0 && isspace((unsigned char)*line)) {
1589 title = mandoc_realloc(title, titlesz + len);
1590 memcpy(title + titlesz, line, len);
1592 title[(int)titlesz - 1] = ' ';
1597 * If no page content can be found, or the input line
1598 * is already the next section header, or there is no
1599 * trailing newline, reuse the page title as the page
1603 if (NULL == title || '\0' == *title) {
1605 fprintf(stderr, "%s: cannot find NAME section\n",
1607 buf_appendb(dbuf, buf->cp, buf->size);
1608 hash_put(hash, buf, TYPE_Nd);
1614 title = mandoc_realloc(title, titlesz + 1);
1615 title[(int)titlesz] = '\0';
1618 * Skip to the first dash.
1619 * Use the remaining line as the description (no more than 70
1623 if (NULL != (p = strstr(title, "- "))) {
1624 for (p += 2; ' ' == *p || '\b' == *p; p++)
1625 /* Skip to next word. */ ;
1628 fprintf(stderr, "%s: no dash in title line\n",
1635 /* Strip backspace-encoding from line. */
1637 while (NULL != (line = memchr(p, '\b', plen))) {
1640 memmove(line, line + 1, plen--);
1643 memmove(line - 1, line + 1, plen - len);
1647 buf_appendb(dbuf, p, plen + 1);
1649 buf_appendb(buf, p, plen + 1);
1650 hash_put(hash, buf, TYPE_Nd);
1656 ofile_argbuild(int argc, char *argv[], struct of **of,
1657 const char *basedir)
1660 char pbuf[PATH_MAX];
1661 const char *sec, *arch, *title;
1666 for (i = 0; i < argc; i++) {
1667 if (NULL == (relpath = realpath(argv[i], pbuf))) {
1671 if (NULL != basedir) {
1672 if (strstr(pbuf, basedir) != pbuf) {
1673 fprintf(stderr, "%s: file outside "
1674 "base directory %s\n",
1678 relpath = pbuf + strlen(basedir);
1682 * Try to infer the manual section, architecture and
1683 * page title from the path, assuming it looks like
1684 * man*[/<arch>]/<title>.<section> or
1685 * cat<section>[/<arch>]/<title>.0
1688 if (strlcpy(buf, relpath, sizeof(buf)) >= sizeof(buf)) {
1689 fprintf(stderr, "%s: path too long\n", relpath);
1692 sec = arch = title = "";
1694 p = strrchr(buf, '\0');
1696 if ('\0' == *sec && '.' == *p) {
1700 src_form |= MANDOC_FORM;
1701 else if ('1' <= *sec && '9' >= *sec)
1702 src_form |= MANDOC_SRC;
1707 if ('\0' == *title) {
1712 if (0 == strncmp("man", p + 1, 3))
1713 src_form |= MANDOC_SRC;
1714 else if (0 == strncmp("cat", p + 1, 3))
1715 src_form |= MANDOC_FORM;
1720 if ('\0' == *title) {
1723 "%s: cannot deduce title "
1730 * Build the file structure.
1733 nof = mandoc_calloc(1, sizeof(struct of));
1734 nof->fname = mandoc_strdup(relpath);
1735 nof->sec = mandoc_strdup(sec);
1736 nof->arch = mandoc_strdup(arch);
1737 nof->title = mandoc_strdup(title);
1738 nof->src_form = src_form;
1741 * Add the structure to the list.
1748 nof->first = (*of)->first;
1756 * Recursively build up a list of files to parse.
1757 * We use this instead of ftw() and so on because I don't want global
1758 * variables hanging around.
1759 * This ignores the mandoc.db and mandoc.index files, but assumes that
1760 * everything else is a manual.
1761 * Pass in a pointer to a NULL structure for the first invocation.
1764 ofile_dirbuild(const char *dir, const char* psec, const char *parch,
1765 int p_src_form, struct of **of)
1773 const char *fn, *sec, *arch;
1774 char *p, *q, *suffix;
1779 if (NULL == (d = opendir(dir))) {
1785 while (NULL != (dp = readdir(d))) {
1791 src_form = p_src_form;
1794 stat(dp->d_name, &sb);
1795 if (S_IFDIR & sb.st_mode) {
1797 if (DT_DIR == dp->d_type) {
1803 * By default, only use directories called:
1804 * man<section>/[<arch>/] or
1805 * cat<section>/[<arch>/]
1809 if(0 == strncmp("man", fn, 3)) {
1810 src_form |= MANDOC_SRC;
1812 } else if (0 == strncmp("cat", fn, 3)) {
1813 src_form |= MANDOC_FORM;
1816 if (warnings) fprintf(stderr,
1817 "%s/%s: bad section\n",
1824 } else if ('\0' == *arch) {
1825 if (NULL != strchr(fn, '.')) {
1826 if (warnings) fprintf(stderr,
1827 "%s/%s: bad architecture\n",
1834 if (warnings) fprintf(stderr, "%s/%s: "
1835 "excessive subdirectory\n", dir, fn);
1841 strlcat(buf, dir, PATH_MAX);
1842 strlcat(buf, "/", PATH_MAX);
1843 sz = strlcat(buf, fn, PATH_MAX);
1845 if (PATH_MAX <= sz) {
1846 if (warnings) fprintf(stderr, "%s/%s: "
1847 "path too long\n", dir, fn);
1851 ofile_dirbuild(buf, sec, arch, src_form, of);
1856 if (0 == S_IFREG & sb.st_mode) {
1858 if (DT_REG != dp->d_type) {
1862 "%s/%s: not a regular file\n",
1866 if (!strcmp(MANDOC_DB, fn) || !strcmp(MANDOC_IDX, fn))
1868 if ('\0' == *psec) {
1871 "%s/%s: file outside section\n",
1878 * By default, skip files where the file name suffix
1879 * does not agree with the section directory
1880 * they are located in.
1883 suffix = strrchr(fn, '.');
1884 if (NULL == suffix) {
1887 "%s/%s: no filename suffix\n",
1891 } else if ((MANDOC_SRC & src_form &&
1892 strcmp(suffix + 1, psec)) ||
1893 (MANDOC_FORM & src_form &&
1894 strcmp(suffix + 1, "0"))) {
1897 "%s/%s: wrong filename suffix\n",
1901 if ('0' == suffix[1])
1902 src_form |= MANDOC_FORM;
1903 else if ('1' <= suffix[1] && '9' >= suffix[1])
1904 src_form |= MANDOC_SRC;
1908 * Skip formatted manuals if a source version is
1909 * available. Ignore the age: it is very unlikely
1910 * that people install newer formatted base manuals
1911 * when they used to have source manuals before,
1912 * and in ports, old manuals get removed on update.
1914 if (0 == use_all && MANDOC_FORM & src_form &&
1917 strlcat(buf, dir, PATH_MAX);
1918 p = strrchr(buf, '/');
1919 if ('\0' != *parch && NULL != p)
1920 for (p--; p > buf; p--)
1927 if (0 == strncmp("cat", p, 3))
1928 memcpy(p, "man", 3);
1929 strlcat(buf, "/", PATH_MAX);
1930 sz = strlcat(buf, fn, PATH_MAX);
1931 if (sz >= PATH_MAX) {
1932 if (warnings) fprintf(stderr,
1933 "%s/%s: path too long\n",
1937 q = strrchr(buf, '.');
1938 if (NULL != q && p < q++) {
1940 sz = strlcat(buf, psec, PATH_MAX);
1941 if (sz >= PATH_MAX) {
1942 if (warnings) fprintf(stderr,
1943 "%s/%s: path too long\n",
1947 if (0 == access(buf, R_OK))
1953 assert('.' == dir[0]);
1954 if ('/' == dir[1]) {
1955 strlcat(buf, dir + 2, PATH_MAX);
1956 strlcat(buf, "/", PATH_MAX);
1958 sz = strlcat(buf, fn, PATH_MAX);
1959 if (sz >= PATH_MAX) {
1960 if (warnings) fprintf(stderr,
1961 "%s/%s: path too long\n", dir, fn);
1965 nof = mandoc_calloc(1, sizeof(struct of));
1966 nof->fname = mandoc_strdup(buf);
1967 nof->sec = mandoc_strdup(psec);
1968 nof->arch = mandoc_strdup(parch);
1969 nof->src_form = src_form;
1972 * Remember the file name without the extension,
1973 * to be used as the page title in the database.
1978 nof->title = mandoc_strdup(fn);
1981 * Add the structure to the list.
1988 nof->first = (*of)->first;
1998 ofile_free(struct of *of)
2005 while (NULL != of) {