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