1 /* $Id: mandocdb.c,v 1.218 2016/07/12 05:18:38 kristaps Exp $ */
3 * Copyright (c) 2011, 2012 Kristaps Dzonsons <kristaps@bsd.lv>
4 * Copyright (c) 2011-2016 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 AUTHORS DISCLAIM ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS 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.
20 #include <sys/types.h>
34 #include "compat_fts.h"
49 #include "mandoc_aux.h"
50 #include "mandoc_ohash.h"
56 #include "mansearch.h"
58 extern int mansearch_keymax;
59 extern const char *const mansearch_keynames[];
61 #define SQL_EXEC(_v) \
62 if (SQLITE_OK != sqlite3_exec(db, (_v), NULL, NULL, NULL)) \
63 say("", "%s: %s", (_v), sqlite3_errmsg(db))
64 #define SQL_BIND_TEXT(_s, _i, _v) \
65 if (SQLITE_OK != sqlite3_bind_text \
66 ((_s), (_i)++, (_v), -1, SQLITE_STATIC)) \
67 say(mlink->file, "%s", sqlite3_errmsg(db))
68 #define SQL_BIND_INT(_s, _i, _v) \
69 if (SQLITE_OK != sqlite3_bind_int \
70 ((_s), (_i)++, (_v))) \
71 say(mlink->file, "%s", sqlite3_errmsg(db))
72 #define SQL_BIND_INT64(_s, _i, _v) \
73 if (SQLITE_OK != sqlite3_bind_int64 \
74 ((_s), (_i)++, (_v))) \
75 say(mlink->file, "%s", sqlite3_errmsg(db))
76 #define SQL_STEP(_s) \
77 if (SQLITE_DONE != sqlite3_step((_s))) \
78 say(mlink->file, "%s", sqlite3_errmsg(db))
81 OP_DEFAULT = 0, /* new dbs from dir list or default config */
82 OP_CONFFILE, /* new databases from custom config file */
83 OP_UPDATE, /* delete/add entries in existing database */
84 OP_DELETE, /* delete entries from existing database */
85 OP_TEST /* change no databases, report potential problems */
89 const struct mpage *mpage; /* if set, the owning parse */
90 uint64_t mask; /* bitmask in sequence */
91 char key[]; /* rendered text */
100 struct inodev inodev; /* used for hashing routine */
101 int64_t pageid; /* pageid in mpages SQL table */
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 mpage *next; /* singly linked list */
107 struct mlink *mlinks; /* singly linked list */
108 int form; /* format from file content */
113 char file[PATH_MAX]; /* filename rel. to manpath */
114 char *dsec; /* section from directory */
115 char *arch; /* architecture from directory */
116 char *name; /* name from file name (not empty) */
117 char *fsec; /* section from file name suffix */
118 struct mlink *next; /* singly linked list */
119 struct mpage *mpage; /* parent */
120 int dform; /* format from directory */
121 int fform; /* format from file name suffix */
122 int gzip; /* filename has a .gz suffix */
126 STMT_DELETE_PAGE = 0, /* delete mpage */
127 STMT_INSERT_PAGE, /* insert mpage */
128 STMT_INSERT_LINK, /* insert mlink */
129 STMT_INSERT_NAME, /* insert name */
130 STMT_SELECT_NAME, /* retrieve existing name flags */
131 STMT_INSERT_KEY, /* insert parsed key */
135 typedef int (*mdoc_fp)(struct mpage *, const struct roff_meta *,
136 const struct roff_node *);
138 struct mdoc_handler {
139 mdoc_fp fp; /* optional handler */
140 uint64_t mask; /* set unless handler returns 0 */
143 static void dbclose(int);
144 static void dbadd(struct mpage *);
145 static void dbadd_mlink(const struct mlink *mlink);
146 static void dbadd_mlink_name(const struct mlink *mlink);
147 static int dbopen(int);
148 static void dbprune(void);
149 static void filescan(const char *);
150 static int fts_compare(const FTSENT *const *, const FTSENT *const *);
151 static void mlink_add(struct mlink *, const struct stat *);
152 static void mlink_check(struct mpage *, struct mlink *);
153 static void mlink_free(struct mlink *);
154 static void mlinks_undupe(struct mpage *);
155 static void mpages_free(void);
156 static void mpages_merge(struct mparse *);
157 static void names_check(void);
158 static void parse_cat(struct mpage *, int);
159 static void parse_man(struct mpage *, const struct roff_meta *,
160 const struct roff_node *);
161 static void parse_mdoc(struct mpage *, const struct roff_meta *,
162 const struct roff_node *);
163 static int parse_mdoc_head(struct mpage *, const struct roff_meta *,
164 const struct roff_node *);
165 static int parse_mdoc_Fd(struct mpage *, const struct roff_meta *,
166 const struct roff_node *);
167 static void parse_mdoc_fname(struct mpage *, const struct roff_node *);
168 static int parse_mdoc_Fn(struct mpage *, const struct roff_meta *,
169 const struct roff_node *);
170 static int parse_mdoc_Fo(struct mpage *, const struct roff_meta *,
171 const struct roff_node *);
172 static int parse_mdoc_Nd(struct mpage *, const struct roff_meta *,
173 const struct roff_node *);
174 static int parse_mdoc_Nm(struct mpage *, const struct roff_meta *,
175 const struct roff_node *);
176 static int parse_mdoc_Sh(struct mpage *, const struct roff_meta *,
177 const struct roff_node *);
178 static int parse_mdoc_Va(struct mpage *, const struct roff_meta *,
179 const struct roff_node *);
180 static int parse_mdoc_Xr(struct mpage *, const struct roff_meta *,
181 const struct roff_node *);
182 static void putkey(const struct mpage *, char *, uint64_t);
183 static void putkeys(const struct mpage *, char *, size_t, uint64_t);
184 static void putmdockey(const struct mpage *,
185 const struct roff_node *, uint64_t);
186 static int render_string(char **, size_t *);
187 static void say(const char *, const char *, ...);
188 static int set_basedir(const char *, int);
189 static int treescan(void);
190 static size_t utf8(unsigned int, char [7]);
192 static char tempfilename[32];
193 static int nodb; /* no database changes */
194 static int mparse_options; /* abort the parse early */
195 static int use_all; /* use all found files */
196 static int debug; /* print what we're doing */
197 static int warnings; /* warn about crap */
198 static int write_utf8; /* write UTF-8 output; else ASCII */
199 static int exitcode; /* to be returned by main */
200 static enum op op; /* operational mode */
201 static char basedir[PATH_MAX]; /* current base directory */
202 static struct ohash mpages; /* table of distinct manual pages */
203 static struct ohash mlinks; /* table of directory entries */
204 static struct ohash names; /* table of all names */
205 static struct ohash strings; /* table of all strings */
206 static sqlite3 *db = NULL; /* current database */
207 static sqlite3_stmt *stmts[STMT__MAX]; /* current statements */
208 static uint64_t name_mask;
209 static struct mpage *mpage_head;
211 static const struct mdoc_handler mdocs[MDOC_MAX] = {
212 { NULL, 0 }, /* Ap */
213 { NULL, 0 }, /* Dd */
214 { NULL, 0 }, /* Dt */
215 { NULL, 0 }, /* Os */
216 { parse_mdoc_Sh, TYPE_Sh }, /* Sh */
217 { parse_mdoc_head, TYPE_Ss }, /* Ss */
218 { NULL, 0 }, /* Pp */
219 { NULL, 0 }, /* D1 */
220 { NULL, 0 }, /* Dl */
221 { NULL, 0 }, /* Bd */
222 { NULL, 0 }, /* Ed */
223 { NULL, 0 }, /* Bl */
224 { NULL, 0 }, /* El */
225 { NULL, 0 }, /* It */
226 { NULL, 0 }, /* Ad */
227 { NULL, TYPE_An }, /* An */
228 { NULL, TYPE_Ar }, /* Ar */
229 { NULL, TYPE_Cd }, /* Cd */
230 { NULL, TYPE_Cm }, /* Cm */
231 { NULL, TYPE_Dv }, /* Dv */
232 { NULL, TYPE_Er }, /* Er */
233 { NULL, TYPE_Ev }, /* Ev */
234 { NULL, 0 }, /* Ex */
235 { NULL, TYPE_Fa }, /* Fa */
236 { parse_mdoc_Fd, 0 }, /* Fd */
237 { NULL, TYPE_Fl }, /* Fl */
238 { parse_mdoc_Fn, 0 }, /* Fn */
239 { NULL, TYPE_Ft }, /* Ft */
240 { NULL, TYPE_Ic }, /* Ic */
241 { NULL, TYPE_In }, /* In */
242 { NULL, TYPE_Li }, /* Li */
243 { parse_mdoc_Nd, 0 }, /* Nd */
244 { parse_mdoc_Nm, 0 }, /* Nm */
245 { NULL, 0 }, /* Op */
246 { NULL, 0 }, /* Ot */
247 { NULL, TYPE_Pa }, /* Pa */
248 { NULL, 0 }, /* Rv */
249 { NULL, TYPE_St }, /* St */
250 { parse_mdoc_Va, TYPE_Va }, /* Va */
251 { parse_mdoc_Va, TYPE_Vt }, /* Vt */
252 { parse_mdoc_Xr, 0 }, /* Xr */
253 { NULL, 0 }, /* %A */
254 { NULL, 0 }, /* %B */
255 { NULL, 0 }, /* %D */
256 { NULL, 0 }, /* %I */
257 { NULL, 0 }, /* %J */
258 { NULL, 0 }, /* %N */
259 { NULL, 0 }, /* %O */
260 { NULL, 0 }, /* %P */
261 { NULL, 0 }, /* %R */
262 { NULL, 0 }, /* %T */
263 { NULL, 0 }, /* %V */
264 { NULL, 0 }, /* Ac */
265 { NULL, 0 }, /* Ao */
266 { NULL, 0 }, /* Aq */
267 { NULL, TYPE_At }, /* At */
268 { NULL, 0 }, /* Bc */
269 { NULL, 0 }, /* Bf */
270 { NULL, 0 }, /* Bo */
271 { NULL, 0 }, /* Bq */
272 { NULL, TYPE_Bsx }, /* Bsx */
273 { NULL, TYPE_Bx }, /* Bx */
274 { NULL, 0 }, /* Db */
275 { NULL, 0 }, /* Dc */
276 { NULL, 0 }, /* Do */
277 { NULL, 0 }, /* Dq */
278 { NULL, 0 }, /* Ec */
279 { NULL, 0 }, /* Ef */
280 { NULL, TYPE_Em }, /* Em */
281 { NULL, 0 }, /* Eo */
282 { NULL, TYPE_Fx }, /* Fx */
283 { NULL, TYPE_Ms }, /* Ms */
284 { NULL, 0 }, /* No */
285 { NULL, 0 }, /* Ns */
286 { NULL, TYPE_Nx }, /* Nx */
287 { NULL, TYPE_Ox }, /* Ox */
288 { NULL, 0 }, /* Pc */
289 { NULL, 0 }, /* Pf */
290 { NULL, 0 }, /* Po */
291 { NULL, 0 }, /* Pq */
292 { NULL, 0 }, /* Qc */
293 { NULL, 0 }, /* Ql */
294 { NULL, 0 }, /* Qo */
295 { NULL, 0 }, /* Qq */
296 { NULL, 0 }, /* Re */
297 { NULL, 0 }, /* Rs */
298 { NULL, 0 }, /* Sc */
299 { NULL, 0 }, /* So */
300 { NULL, 0 }, /* Sq */
301 { NULL, 0 }, /* Sm */
302 { NULL, 0 }, /* Sx */
303 { NULL, TYPE_Sy }, /* Sy */
304 { NULL, TYPE_Tn }, /* Tn */
305 { NULL, 0 }, /* Ux */
306 { NULL, 0 }, /* Xc */
307 { NULL, 0 }, /* Xo */
308 { parse_mdoc_Fo, 0 }, /* Fo */
309 { NULL, 0 }, /* Fc */
310 { NULL, 0 }, /* Oo */
311 { NULL, 0 }, /* Oc */
312 { NULL, 0 }, /* Bk */
313 { NULL, 0 }, /* Ek */
314 { NULL, 0 }, /* Bt */
315 { NULL, 0 }, /* Hf */
316 { NULL, 0 }, /* Fr */
317 { NULL, 0 }, /* Ud */
318 { NULL, TYPE_Lb }, /* Lb */
319 { NULL, 0 }, /* Lp */
320 { NULL, TYPE_Lk }, /* Lk */
321 { NULL, TYPE_Mt }, /* Mt */
322 { NULL, 0 }, /* Brq */
323 { NULL, 0 }, /* Bro */
324 { NULL, 0 }, /* Brc */
325 { NULL, 0 }, /* %C */
326 { NULL, 0 }, /* Es */
327 { NULL, 0 }, /* En */
328 { NULL, TYPE_Dx }, /* Dx */
329 { NULL, 0 }, /* %Q */
330 { NULL, 0 }, /* br */
331 { NULL, 0 }, /* sp */
332 { NULL, 0 }, /* %U */
333 { NULL, 0 }, /* Ta */
334 { NULL, 0 }, /* ll */
339 mandocdb(int argc, char *argv[])
343 const char *path_arg, *progname;
348 if (pledge("stdio rpath wpath cpath fattr flock proc exec", NULL) == -1) {
350 return (int)MANDOCLEVEL_SYSERR;
354 #if HAVE_SANDBOX_INIT
355 if (sandbox_init(kSBXProfileNoInternet, SANDBOX_NAMED, NULL) == -1) {
356 warnx("sandbox_init");
357 return (int)MANDOCLEVEL_SYSERR;
361 memset(&conf, 0, sizeof(conf));
362 memset(stmts, 0, STMT__MAX * sizeof(sqlite3_stmt *));
365 * We accept a few different invocations.
366 * The CHECKOP macro makes sure that invocation styles don't
367 * clobber each other.
369 #define CHECKOP(_op, _ch) do \
370 if (OP_DEFAULT != (_op)) { \
371 warnx("-%c: Conflicting option", (_ch)); \
373 } while (/*CONSTCOND*/0)
378 while (-1 != (ch = getopt(argc, argv, "aC:Dd:npQT:tu:v")))
403 mparse_options |= MPARSE_QUICK;
406 if (strcmp(optarg, "utf8")) {
407 warnx("-T%s: Unsupported output format",
415 dup2(STDOUT_FILENO, STDERR_FILENO);
425 /* Compatibility with espie@'s makewhatis. */
436 if (pledge("stdio rpath", NULL) == -1) {
438 return (int)MANDOCLEVEL_SYSERR;
443 if (OP_CONFFILE == op && argc > 0) {
444 warnx("-C: Too many arguments");
448 exitcode = (int)MANDOCLEVEL_OK;
450 mp = mparse_alloc(mparse_options, MANDOCLEVEL_BADARG, NULL, NULL);
451 mandoc_ohash_init(&mpages, 6, offsetof(struct mpage, inodev));
452 mandoc_ohash_init(&mlinks, 6, offsetof(struct mlink, file));
454 if (OP_UPDATE == op || OP_DELETE == op || OP_TEST == op) {
457 * Most of these deal with a specific directory.
458 * Jump into that directory first.
460 if (OP_TEST != op && 0 == set_basedir(path_arg, 1))
465 * The existing database is usable. Process
466 * all files specified on the command-line.
470 if (pledge("stdio rpath wpath cpath fattr flock", NULL) == -1) {
472 exitcode = (int)MANDOCLEVEL_SYSERR;
478 for (i = 0; i < argc; i++)
484 * Database missing or corrupt.
485 * Recreate from scratch.
487 exitcode = (int)MANDOCLEVEL_OK;
496 dbclose(OP_DEFAULT == op ? 0 : 1);
499 * If we have arguments, use them as our manpaths.
500 * If we don't, grok from manpath(1) or however else
501 * manconf_parse() wants to do it.
504 conf.manpath.paths = mandoc_reallocarray(NULL,
505 argc, sizeof(char *));
506 conf.manpath.sz = (size_t)argc;
507 for (i = 0; i < argc; i++)
508 conf.manpath.paths[i] = mandoc_strdup(argv[i]);
510 manconf_parse(&conf, path_arg, NULL, NULL);
512 if (conf.manpath.sz == 0) {
513 exitcode = (int)MANDOCLEVEL_BADARG;
514 say("", "Empty manpath");
518 * First scan the tree rooted at a base directory, then
519 * build a new database and finally move it into place.
520 * Ignore zero-length directories and strip trailing
523 for (j = 0; j < conf.manpath.sz; j++) {
524 sz = strlen(conf.manpath.paths[j]);
525 if (sz && conf.manpath.paths[j][sz - 1] == '/')
526 conf.manpath.paths[j][--sz] = '\0';
531 mandoc_ohash_init(&mpages, 6,
532 offsetof(struct mpage, inodev));
533 mandoc_ohash_init(&mlinks, 6,
534 offsetof(struct mlink, file));
537 if ( ! set_basedir(conf.manpath.paths[j], argc > 0))
545 if (warnings && !nodb &&
546 ! (MPARSE_QUICK & mparse_options))
550 if (j + 1 < conf.manpath.sz) {
552 ohash_delete(&mpages);
553 ohash_delete(&mlinks);
562 ohash_delete(&mpages);
563 ohash_delete(&mlinks);
566 progname = getprogname();
567 fprintf(stderr, "usage: %s [-aDnpQ] [-C file] [-Tutf8]\n"
568 " %s [-aDnpQ] [-Tutf8] dir ...\n"
569 " %s [-DnpQ] [-Tutf8] -d dir [file ...]\n"
570 " %s [-Dnp] -u dir [file ...]\n"
571 " %s [-Q] -t file ...\n",
572 progname, progname, progname, progname, progname);
574 return (int)MANDOCLEVEL_BADARG;
578 fts_compare(const FTSENT *const *a, const FTSENT *const *b)
582 * The mpage list is processed in the opposite order to which pages are
583 * added, so traverse the hierarchy in reverse alpha order, resulting
584 * in database inserts in alpha order. This is not required for correct
585 * operation, but is helpful when inspecting the database during
588 return -strcmp((*a)->fts_name, (*b)->fts_name);
592 * Scan a directory tree rooted at "basedir" for manpages.
593 * We use fts(), scanning directory parts along the way for clues to our
594 * section and architecture.
596 * If use_all has been specified, grok all files.
597 * If not, sanitise paths to the following:
599 * [./]man*[/<arch>]/<name>.<section>
601 * [./]cat<section>[/<arch>]/<name>.0
603 * TODO: accommodate for multi-language directories.
613 char *dsec, *arch, *fsec, *cp;
618 argv[1] = (char *)NULL;
620 f = fts_open((char * const *)argv, FTS_PHYSICAL | FTS_NOCHDIR,
623 exitcode = (int)MANDOCLEVEL_SYSERR;
624 say("", "&fts_open");
631 while ((ff = fts_read(f)) != NULL) {
632 path = ff->fts_path + 2;
633 switch (ff->fts_info) {
636 * Symbolic links require various sanity checks,
637 * then get handled just like regular files.
640 if (realpath(path, buf) == NULL) {
642 say(path, "&realpath");
645 if (strstr(buf, basedir) != buf
647 && strstr(buf, HOMEBREWDIR) != buf
650 if (warnings) say("",
651 "%s: outside base directory", buf);
654 /* Use logical inode to avoid mpages dupe. */
655 if (stat(path, ff->fts_statp) == -1) {
663 * If we're a regular file, add an mlink by using the
664 * stored directory data and handling the filename.
667 if ( ! strcmp(path, MANDOC_DB))
669 if ( ! use_all && ff->fts_level < 2) {
671 say(path, "Extraneous file");
676 while (fsec == NULL) {
677 fsec = strrchr(ff->fts_name, '.');
678 if (fsec == NULL || strcmp(fsec+1, "gz"))
688 "No filename suffix");
691 } else if ( ! strcmp(++fsec, "html")) {
693 say(path, "Skip html");
695 } else if ( ! strcmp(fsec, "ps")) {
697 say(path, "Skip ps");
699 } else if ( ! strcmp(fsec, "pdf")) {
701 say(path, "Skip pdf");
703 } else if ( ! use_all &&
704 ((dform == FORM_SRC &&
705 strncmp(fsec, dsec, strlen(dsec))) ||
706 (dform == FORM_CAT && strcmp(fsec, "0")))) {
708 say(path, "Wrong filename suffix");
713 mlink = mandoc_calloc(1, sizeof(struct mlink));
714 if (strlcpy(mlink->file, path,
715 sizeof(mlink->file)) >=
716 sizeof(mlink->file)) {
717 say(path, "Filename too long");
721 mlink->dform = dform;
724 mlink->name = ff->fts_name;
727 mlink_add(mlink, ff->fts_statp);
736 say(path, "Not a regular file");
740 switch (ff->fts_level) {
742 /* Ignore the root directory. */
746 * This might contain manX/ or catX/.
747 * Try to infer this from the name.
748 * If we're not in use_all, enforce it.
751 if (ff->fts_info == FTS_DP) {
757 if ( ! strncmp(cp, "man", 3)) {
760 } else if ( ! strncmp(cp, "cat", 3)) {
768 if (dsec != NULL || use_all)
772 say(path, "Unknown directory part");
773 fts_set(f, ff, FTS_SKIP);
777 * Possibly our architecture.
778 * If we're descending, keep tabs on it.
780 if (ff->fts_info != FTS_DP && dsec != NULL)
786 if (ff->fts_info == FTS_DP || use_all)
789 say(path, "Extraneous directory part");
790 fts_set(f, ff, FTS_SKIP);
800 * Add a file to the mlinks table.
801 * Do not verify that it's a "valid" looking manpage (we'll do that
804 * Try to infer the manual section, architecture, and page name from the
805 * path, assuming it looks like
807 * [./]man*[/<arch>]/<name>.<section>
809 * [./]cat<section>[/<arch>]/<name>.0
811 * See treescan() for the fts(3) version of this.
814 filescan(const char *file)
823 if (0 == strncmp(file, "./", 2))
827 * We have to do lstat(2) before realpath(3) loses
828 * the information whether this is a symbolic link.
829 * We need to know that because for symbolic links,
830 * we want to use the orginal file name, while for
831 * regular files, we want to use the real path.
833 if (-1 == lstat(file, &st)) {
834 exitcode = (int)MANDOCLEVEL_BADARG;
837 } else if (0 == ((S_IFREG | S_IFLNK) & st.st_mode)) {
838 exitcode = (int)MANDOCLEVEL_BADARG;
839 say(file, "Not a regular file");
844 * We have to resolve the file name to the real path
845 * in any case for the base directory check.
847 if (NULL == realpath(file, buf)) {
848 exitcode = (int)MANDOCLEVEL_BADARG;
849 say(file, "&realpath");
855 else if (strstr(buf, basedir) == buf)
856 start = buf + strlen(basedir);
858 else if (strstr(buf, HOMEBREWDIR) == buf)
862 exitcode = (int)MANDOCLEVEL_BADARG;
863 say("", "%s: outside base directory", buf);
868 * Now we are sure the file is inside our tree.
869 * If it is a symbolic link, ignore the real path
870 * and use the original name.
871 * This implies passing stuff like "cat1/../man1/foo.1"
872 * on the command line won't work. So don't do that.
873 * Note the stat(2) can still fail if the link target
876 if (S_IFLNK & st.st_mode) {
877 if (-1 == stat(buf, &st)) {
878 exitcode = (int)MANDOCLEVEL_BADARG;
882 if (strlcpy(buf, file, sizeof(buf)) >= sizeof(buf)) {
883 say(file, "Filename too long");
887 if (OP_TEST != op && strstr(buf, basedir) == buf)
888 start += strlen(basedir);
891 mlink = mandoc_calloc(1, sizeof(struct mlink));
892 mlink->dform = FORM_NONE;
893 if (strlcpy(mlink->file, start, sizeof(mlink->file)) >=
894 sizeof(mlink->file)) {
895 say(start, "Filename too long");
901 * First try to guess our directory structure.
902 * If we find a separator, try to look for man* or cat*.
903 * If we find one of these and what's underneath is a directory,
904 * assume it's an architecture.
906 if (NULL != (p = strchr(start, '/'))) {
908 if (0 == strncmp(start, "man", 3)) {
909 mlink->dform = FORM_SRC;
910 mlink->dsec = start + 3;
911 } else if (0 == strncmp(start, "cat", 3)) {
912 mlink->dform = FORM_CAT;
913 mlink->dsec = start + 3;
917 if (NULL != mlink->dsec && NULL != (p = strchr(start, '/'))) {
925 * Now check the file suffix.
926 * Suffix of `.0' indicates a catpage, `.1-9' is a manpage.
928 p = strrchr(start, '\0');
929 while (p-- > start && '/' != *p && '.' != *p)
938 * Now try to parse the name.
939 * Use the filename portion of the path.
942 if (NULL != (p = strrchr(start, '/'))) {
946 mlink_add(mlink, &st);
950 mlink_add(struct mlink *mlink, const struct stat *st)
952 struct inodev inodev;
956 assert(NULL != mlink->file);
958 mlink->dsec = mandoc_strdup(mlink->dsec ? mlink->dsec : "");
959 mlink->arch = mandoc_strdup(mlink->arch ? mlink->arch : "");
960 mlink->name = mandoc_strdup(mlink->name ? mlink->name : "");
961 mlink->fsec = mandoc_strdup(mlink->fsec ? mlink->fsec : "");
963 if ('0' == *mlink->fsec) {
965 mlink->fsec = mandoc_strdup(mlink->dsec);
966 mlink->fform = FORM_CAT;
967 } else if ('1' <= *mlink->fsec && '9' >= *mlink->fsec)
968 mlink->fform = FORM_SRC;
970 mlink->fform = FORM_NONE;
972 slot = ohash_qlookup(&mlinks, mlink->file);
973 assert(NULL == ohash_find(&mlinks, slot));
974 ohash_insert(&mlinks, slot, mlink);
976 memset(&inodev, 0, sizeof(inodev)); /* Clear padding. */
977 inodev.st_ino = st->st_ino;
978 inodev.st_dev = st->st_dev;
979 slot = ohash_lookup_memory(&mpages, (char *)&inodev,
980 sizeof(struct inodev), inodev.st_ino);
981 mpage = ohash_find(&mpages, slot);
983 mpage = mandoc_calloc(1, sizeof(struct mpage));
984 mpage->inodev.st_ino = inodev.st_ino;
985 mpage->inodev.st_dev = inodev.st_dev;
986 mpage->next = mpage_head;
988 ohash_insert(&mpages, slot, mpage);
990 mlink->next = mpage->mlinks;
991 mpage->mlinks = mlink;
992 mlink->mpage = mpage;
996 mlink_free(struct mlink *mlink)
1009 struct mpage *mpage;
1010 struct mlink *mlink;
1012 while (NULL != (mpage = mpage_head)) {
1013 while (NULL != (mlink = mpage->mlinks)) {
1014 mpage->mlinks = mlink->next;
1017 mpage_head = mpage->next;
1027 * For each mlink to the mpage, check whether the path looks like
1028 * it is formatted, and if it does, check whether a source manual
1029 * exists by the same name, ignoring the suffix.
1030 * If both conditions hold, drop the mlink.
1033 mlinks_undupe(struct mpage *mpage)
1036 struct mlink **prev;
1037 struct mlink *mlink;
1040 mpage->form = FORM_CAT;
1041 prev = &mpage->mlinks;
1042 while (NULL != (mlink = *prev)) {
1043 if (FORM_CAT != mlink->dform) {
1044 mpage->form = FORM_NONE;
1047 (void)strlcpy(buf, mlink->file, sizeof(buf));
1048 bufp = strstr(buf, "cat");
1049 assert(NULL != bufp);
1050 memcpy(bufp, "man", 3);
1051 if (NULL != (bufp = strrchr(buf, '.')))
1053 (void)strlcat(buf, mlink->dsec, sizeof(buf));
1054 if (NULL == ohash_find(&mlinks,
1055 ohash_qlookup(&mlinks, buf)))
1058 say(mlink->file, "Man source exists: %s", buf);
1061 *prev = mlink->next;
1065 prev = &(*prev)->next;
1070 mlink_check(struct mpage *mpage, struct mlink *mlink)
1076 * Check whether the manual section given in a file
1077 * agrees with the directory where the file is located.
1078 * Some manuals have suffixes like (3p) on their
1079 * section number either inside the file or in the
1080 * directory name, some are linked into more than one
1081 * section, like encrypt(1) = makekey(8).
1084 if (FORM_SRC == mpage->form &&
1085 strcasecmp(mpage->sec, mlink->dsec))
1086 say(mlink->file, "Section \"%s\" manual in %s directory",
1087 mpage->sec, mlink->dsec);
1090 * Manual page directories exist for each kernel
1091 * architecture as returned by machine(1).
1092 * However, many manuals only depend on the
1093 * application architecture as returned by arch(1).
1094 * For example, some (2/ARM) manuals are shared
1095 * across the "armish" and "zaurus" kernel
1097 * A few manuals are even shared across completely
1098 * different architectures, for example fdformat(1)
1099 * on amd64, i386, sparc, and sparc64.
1102 if (strcasecmp(mpage->arch, mlink->arch))
1103 say(mlink->file, "Architecture \"%s\" manual in "
1104 "\"%s\" directory", mpage->arch, mlink->arch);
1108 * parse_cat() doesn't set NAME_TITLE yet.
1111 if (FORM_CAT == mpage->form)
1115 * Check whether this mlink
1116 * appears as a name in the NAME section.
1119 slot = ohash_qlookup(&names, mlink->name);
1120 str = ohash_find(&names, slot);
1121 assert(NULL != str);
1122 if ( ! (NAME_TITLE & str->mask))
1123 say(mlink->file, "Name missing in NAME section");
1127 * Run through the files in the global vector "mpages"
1128 * and add them to the database specified in "basedir".
1130 * This handles the parsing scheme itself, using the cues of directory
1131 * and filename to determine whether the file is parsable or not.
1134 mpages_merge(struct mparse *mp)
1137 struct mpage *mpage, *mpage_dest;
1138 struct mlink *mlink, *mlink_dest;
1139 struct roff_man *man;
1145 SQL_EXEC("BEGIN TRANSACTION");
1147 for (mpage = mpage_head; mpage != NULL; mpage = mpage->next) {
1148 mlinks_undupe(mpage);
1149 if ((mlink = mpage->mlinks) == NULL)
1152 name_mask = NAME_MASK;
1153 mandoc_ohash_init(&names, 4, offsetof(struct str, key));
1154 mandoc_ohash_init(&strings, 6, offsetof(struct str, key));
1159 if ((fd = mparse_open(mp, mlink->file)) == -1) {
1160 say(mlink->file, "&open");
1165 * Interpret the file as mdoc(7) or man(7) source
1166 * code, unless it is known to be formatted.
1168 if (mlink->dform != FORM_CAT || mlink->fform != FORM_CAT) {
1169 mparse_readfd(mp, fd, mlink->file);
1171 mparse_result(mp, &man, &sodest);
1174 if (sodest != NULL) {
1175 mlink_dest = ohash_find(&mlinks,
1176 ohash_qlookup(&mlinks, sodest));
1177 if (mlink_dest == NULL) {
1178 mandoc_asprintf(&cp, "%s.gz", sodest);
1179 mlink_dest = ohash_find(&mlinks,
1180 ohash_qlookup(&mlinks, cp));
1183 if (mlink_dest != NULL) {
1185 /* The .so target exists. */
1187 mpage_dest = mlink_dest->mpage;
1189 mlink->mpage = mpage_dest;
1192 * If the target was already
1193 * processed, add the links
1194 * to the database now.
1195 * Otherwise, this will
1196 * happen when we come
1200 if (mpage_dest->pageid)
1201 dbadd_mlink_name(mlink);
1203 if (mlink->next == NULL)
1205 mlink = mlink->next;
1208 /* Move all links to the target. */
1210 mlink->next = mlink_dest->next;
1211 mlink_dest->next = mpage->mlinks;
1212 mpage->mlinks = NULL;
1215 } else if (man != NULL && man->macroset == MACROSET_MDOC) {
1217 mpage->form = FORM_SRC;
1218 mpage->sec = man->meta.msec;
1219 mpage->sec = mandoc_strdup(
1220 mpage->sec == NULL ? "" : mpage->sec);
1221 mpage->arch = man->meta.arch;
1222 mpage->arch = mandoc_strdup(
1223 mpage->arch == NULL ? "" : mpage->arch);
1224 mpage->title = mandoc_strdup(man->meta.title);
1225 } else if (man != NULL && man->macroset == MACROSET_MAN) {
1227 mpage->form = FORM_SRC;
1228 mpage->sec = mandoc_strdup(man->meta.msec);
1229 mpage->arch = mandoc_strdup(mlink->arch);
1230 mpage->title = mandoc_strdup(man->meta.title);
1232 mpage->form = FORM_CAT;
1233 mpage->sec = mandoc_strdup(mlink->dsec);
1234 mpage->arch = mandoc_strdup(mlink->arch);
1235 mpage->title = mandoc_strdup(mlink->name);
1237 putkey(mpage, mpage->sec, TYPE_sec);
1238 if (*mpage->arch != '\0')
1239 putkey(mpage, mpage->arch, TYPE_arch);
1241 for ( ; mlink != NULL; mlink = mlink->next) {
1242 if ('\0' != *mlink->dsec)
1243 putkey(mpage, mlink->dsec, TYPE_sec);
1244 if ('\0' != *mlink->fsec)
1245 putkey(mpage, mlink->fsec, TYPE_sec);
1246 putkey(mpage, '\0' == *mlink->arch ?
1247 any : mlink->arch, TYPE_arch);
1248 putkey(mpage, mlink->name, NAME_FILE);
1251 assert(mpage->desc == NULL);
1252 if (man != NULL && man->macroset == MACROSET_MDOC)
1253 parse_mdoc(mpage, &man->meta, man->first);
1254 else if (man != NULL)
1255 parse_man(mpage, &man->meta, man->first);
1257 parse_cat(mpage, fd);
1258 if (mpage->desc == NULL)
1259 mpage->desc = mandoc_strdup(mpage->mlinks->name);
1261 if (warnings && !use_all)
1262 for (mlink = mpage->mlinks; mlink;
1263 mlink = mlink->next)
1264 mlink_check(mpage, mlink);
1267 mlink = mpage->mlinks;
1270 ohash_delete(&strings);
1271 ohash_delete(&names);
1275 SQL_EXEC("END TRANSACTION");
1282 const char *name, *sec, *arch, *key;
1284 sqlite3_prepare_v2(db,
1285 "SELECT name, sec, arch, key FROM ("
1286 "SELECT name AS key, pageid FROM names "
1287 "WHERE bits & ? AND NOT EXISTS ("
1288 "SELECT pageid FROM mlinks "
1289 "WHERE mlinks.pageid == names.pageid "
1290 "AND mlinks.name == names.name"
1293 "SELECT sec, arch, name, pageid FROM mlinks "
1295 ") USING (pageid);",
1298 if (sqlite3_bind_int64(stmt, 1, NAME_TITLE) != SQLITE_OK)
1299 say("", "%s", sqlite3_errmsg(db));
1301 while (sqlite3_step(stmt) == SQLITE_ROW) {
1302 name = (const char *)sqlite3_column_text(stmt, 0);
1303 sec = (const char *)sqlite3_column_text(stmt, 1);
1304 arch = (const char *)sqlite3_column_text(stmt, 2);
1305 key = (const char *)sqlite3_column_text(stmt, 3);
1306 say("", "%s(%s%s%s) lacks mlink \"%s\"", name, sec,
1307 '\0' == *arch ? "" : "/",
1308 '\0' == *arch ? "" : arch, key);
1310 sqlite3_finalize(stmt);
1314 parse_cat(struct mpage *mpage, int fd)
1317 char *line, *p, *title;
1318 size_t linesz, plen, titlesz;
1322 stream = (-1 == fd) ?
1323 fopen(mpage->mlinks->file, "r") :
1325 if (NULL == stream) {
1329 say(mpage->mlinks->file, "&fopen");
1336 /* Skip to first blank line. */
1338 while (getline(&line, &linesz, stream) != -1)
1343 * Assume the first line that is not indented
1344 * is the first section header. Skip to it.
1347 while (getline(&line, &linesz, stream) != -1)
1348 if (*line != '\n' && *line != ' ')
1352 * Read up until the next section into a buffer.
1353 * Strip the leading and trailing newline from each read line,
1354 * appending a trailing space.
1355 * Ignore empty (whitespace-only) lines.
1361 while ((len = getline(&line, &linesz, stream)) != -1) {
1365 while (isspace((unsigned char)line[offs]))
1367 if (line[offs] == '\0')
1369 title = mandoc_realloc(title, titlesz + len - offs);
1370 memcpy(title + titlesz, line + offs, len - offs);
1371 titlesz += len - offs;
1372 title[titlesz - 1] = ' ';
1377 * If no page content can be found, or the input line
1378 * is already the next section header, or there is no
1379 * trailing newline, reuse the page title as the page
1383 if (NULL == title || '\0' == *title) {
1385 say(mpage->mlinks->file,
1386 "Cannot find NAME section");
1392 title[titlesz - 1] = '\0';
1395 * Skip to the first dash.
1396 * Use the remaining line as the description (no more than 70
1400 if (NULL != (p = strstr(title, "- "))) {
1401 for (p += 2; ' ' == *p || '\b' == *p; p++)
1402 /* Skip to next word. */ ;
1405 say(mpage->mlinks->file,
1406 "No dash in title line");
1412 /* Strip backspace-encoding from line. */
1414 while (NULL != (line = memchr(p, '\b', plen))) {
1417 memmove(line, line + 1, plen--);
1420 memmove(line - 1, line + 1, plen - len);
1424 mpage->desc = mandoc_strdup(p);
1430 * Put a type/word pair into the word database for this particular file.
1433 putkey(const struct mpage *mpage, char *value, uint64_t type)
1437 assert(NULL != value);
1438 if (TYPE_arch == type)
1439 for (cp = value; *cp; cp++)
1440 if (isupper((unsigned char)*cp))
1441 *cp = _tolower((unsigned char)*cp);
1442 putkeys(mpage, value, strlen(value), type);
1446 * Grok all nodes at or below a certain mdoc node into putkey().
1449 putmdockey(const struct mpage *mpage,
1450 const struct roff_node *n, uint64_t m)
1453 for ( ; NULL != n; n = n->next) {
1454 if (NULL != n->child)
1455 putmdockey(mpage, n->child, m);
1456 if (n->type == ROFFT_TEXT)
1457 putkey(mpage, n->string, m);
1462 parse_man(struct mpage *mpage, const struct roff_meta *meta,
1463 const struct roff_node *n)
1465 const struct roff_node *head, *body;
1466 char *start, *title;
1474 * We're only searching for one thing: the first text child in
1475 * the BODY of a NAME section. Since we don't keep track of
1476 * sections in -man, run some hoops to find out whether we're in
1477 * the correct section or not.
1480 if (n->type == ROFFT_BODY && n->tok == MAN_SH) {
1482 if ((head = body->parent->head) != NULL &&
1483 (head = head->child) != NULL &&
1484 head->next == NULL &&
1485 head->type == ROFFT_TEXT &&
1486 strcmp(head->string, "NAME") == 0 &&
1487 body->child != NULL) {
1490 * Suck the entire NAME section into memory.
1491 * Yes, we might run away.
1492 * But too many manuals have big, spread-out
1493 * NAME sections over many lines.
1497 deroff(&title, body);
1502 * Go through a special heuristic dance here.
1503 * Conventionally, one or more manual names are
1504 * comma-specified prior to a whitespace, then a
1505 * dash, then a description. Try to puzzle out
1506 * the name parts here.
1511 sz = strcspn(start, " ,");
1512 if ('\0' == start[sz])
1519 * Assume a stray trailing comma in the
1520 * name list if a name begins with a dash.
1523 if ('-' == start[0] ||
1524 ('\\' == start[0] && '-' == start[1]))
1527 putkey(mpage, start, NAME_TITLE);
1528 if ( ! (mpage->name_head_done ||
1529 strcasecmp(start, meta->title))) {
1530 putkey(mpage, start, NAME_HEAD);
1531 mpage->name_head_done = 1;
1539 assert(',' == byte);
1541 while (' ' == *start)
1545 if (start == title) {
1546 putkey(mpage, start, NAME_TITLE);
1547 if ( ! (mpage->name_head_done ||
1548 strcasecmp(start, meta->title))) {
1549 putkey(mpage, start, NAME_HEAD);
1550 mpage->name_head_done = 1;
1556 while (isspace((unsigned char)*start))
1559 if (0 == strncmp(start, "-", 1))
1561 else if (0 == strncmp(start, "\\-\\-", 4))
1563 else if (0 == strncmp(start, "\\-", 2))
1565 else if (0 == strncmp(start, "\\(en", 4))
1567 else if (0 == strncmp(start, "\\(em", 4))
1570 while (' ' == *start)
1573 mpage->desc = mandoc_strdup(start);
1579 for (n = n->child; n; n = n->next) {
1580 if (NULL != mpage->desc)
1582 parse_man(mpage, meta, n);
1587 parse_mdoc(struct mpage *mpage, const struct roff_meta *meta,
1588 const struct roff_node *n)
1592 for (n = n->child; NULL != n; n = n->next) {
1599 if (NULL != mdocs[n->tok].fp)
1600 if (0 == (*mdocs[n->tok].fp)(mpage, meta, n))
1602 if (mdocs[n->tok].mask)
1603 putmdockey(mpage, n->child,
1604 mdocs[n->tok].mask);
1607 assert(n->type != ROFFT_ROOT);
1610 if (NULL != n->child)
1611 parse_mdoc(mpage, meta, n);
1616 parse_mdoc_Fd(struct mpage *mpage, const struct roff_meta *meta,
1617 const struct roff_node *n)
1622 if (SEC_SYNOPSIS != n->sec ||
1623 NULL == (n = n->child) ||
1624 n->type != ROFFT_TEXT)
1628 * Only consider those `Fd' macro fields that begin with an
1629 * "inclusion" token (versus, e.g., #define).
1632 if (strcmp("#include", n->string))
1635 if ((n = n->next) == NULL || n->type != ROFFT_TEXT)
1639 * Strip away the enclosing angle brackets and make sure we're
1644 if ('<' == *start || '"' == *start)
1647 if (0 == (sz = strlen(start)))
1650 end = &start[(int)sz - 1];
1651 if ('>' == *end || '"' == *end)
1655 putkeys(mpage, start, end - start + 1, TYPE_In);
1660 parse_mdoc_fname(struct mpage *mpage, const struct roff_node *n)
1665 if (n->type != ROFFT_TEXT)
1668 /* Skip function pointer punctuation. */
1671 while (*cp == '(' || *cp == '*')
1673 sz = strcspn(cp, "()");
1675 putkeys(mpage, cp, sz, TYPE_Fn);
1676 if (n->sec == SEC_SYNOPSIS)
1677 putkeys(mpage, cp, sz, NAME_SYN);
1681 parse_mdoc_Fn(struct mpage *mpage, const struct roff_meta *meta,
1682 const struct roff_node *n)
1685 if (n->child == NULL)
1688 parse_mdoc_fname(mpage, n->child);
1690 for (n = n->child->next; n != NULL; n = n->next)
1691 if (n->type == ROFFT_TEXT)
1692 putkey(mpage, n->string, TYPE_Fa);
1698 parse_mdoc_Fo(struct mpage *mpage, const struct roff_meta *meta,
1699 const struct roff_node *n)
1702 if (n->type != ROFFT_HEAD)
1705 if (n->child != NULL)
1706 parse_mdoc_fname(mpage, n->child);
1712 parse_mdoc_Va(struct mpage *mpage, const struct roff_meta *meta,
1713 const struct roff_node *n)
1717 if (n->type != ROFFT_ELEM && n->type != ROFFT_BODY)
1720 if (n->child != NULL &&
1721 n->child->next == NULL &&
1722 n->child->type == ROFFT_TEXT)
1728 putkey(mpage, cp, TYPE_Vt | (n->tok == MDOC_Va ||
1729 n->type == ROFFT_BODY ? TYPE_Va : 0));
1737 parse_mdoc_Xr(struct mpage *mpage, const struct roff_meta *meta,
1738 const struct roff_node *n)
1742 if (NULL == (n = n->child))
1745 if (NULL == n->next) {
1746 putkey(mpage, n->string, TYPE_Xr);
1750 mandoc_asprintf(&cp, "%s(%s)", n->string, n->next->string);
1751 putkey(mpage, cp, TYPE_Xr);
1757 parse_mdoc_Nd(struct mpage *mpage, const struct roff_meta *meta,
1758 const struct roff_node *n)
1761 if (n->type == ROFFT_BODY)
1762 deroff(&mpage->desc, n);
1767 parse_mdoc_Nm(struct mpage *mpage, const struct roff_meta *meta,
1768 const struct roff_node *n)
1771 if (SEC_NAME == n->sec)
1772 putmdockey(mpage, n->child, NAME_TITLE);
1773 else if (n->sec == SEC_SYNOPSIS && n->type == ROFFT_HEAD) {
1774 if (n->child == NULL)
1775 putkey(mpage, meta->name, NAME_SYN);
1777 putmdockey(mpage, n->child, NAME_SYN);
1779 if ( ! (mpage->name_head_done ||
1780 n->child == NULL || n->child->string == NULL ||
1781 strcasecmp(n->child->string, meta->title))) {
1782 putkey(mpage, n->child->string, ROFFT_HEAD);
1783 mpage->name_head_done = 1;
1789 parse_mdoc_Sh(struct mpage *mpage, const struct roff_meta *meta,
1790 const struct roff_node *n)
1793 return n->sec == SEC_CUSTOM && n->type == ROFFT_HEAD;
1797 parse_mdoc_head(struct mpage *mpage, const struct roff_meta *meta,
1798 const struct roff_node *n)
1801 return n->type == ROFFT_HEAD;
1805 * Add a string to the hash table for the current manual.
1806 * Each string has a bitmask telling which macros it belongs to.
1807 * When we finish the manual, we'll dump the table.
1810 putkeys(const struct mpage *mpage, char *cp, size_t sz, uint64_t v)
1821 mustfree = render_string(&cp, &sz);
1827 name_mask &= ~NAME_FIRST;
1829 say(mpage->mlinks->file,
1830 "Adding name %*s, bits=%d", sz, cp, v);
1834 for (i = 0; i < mansearch_keymax; i++)
1835 if ((uint64_t)1 << i & v)
1836 say(mpage->mlinks->file,
1837 "Adding key %s=%*s",
1838 mansearch_keynames[i], sz, cp);
1842 slot = ohash_qlookupi(htab, cp, &end);
1843 s = ohash_find(htab, slot);
1845 if (NULL != s && mpage == s->mpage) {
1848 } else if (NULL == s) {
1849 s = mandoc_calloc(1, sizeof(struct str) + sz + 1);
1850 memcpy(s->key, cp, sz);
1851 ohash_insert(htab, slot, s);
1861 * Take a Unicode codepoint and produce its UTF-8 encoding.
1862 * This isn't the best way to do this, but it works.
1863 * The magic numbers are from the UTF-8 packaging.
1864 * They're not as scary as they seem: read the UTF-8 spec for details.
1867 utf8(unsigned int cp, char out[7])
1872 if (cp <= 0x0000007F) {
1875 } else if (cp <= 0x000007FF) {
1877 out[0] = (cp >> 6 & 31) | 192;
1878 out[1] = (cp & 63) | 128;
1879 } else if (cp <= 0x0000FFFF) {
1881 out[0] = (cp >> 12 & 15) | 224;
1882 out[1] = (cp >> 6 & 63) | 128;
1883 out[2] = (cp & 63) | 128;
1884 } else if (cp <= 0x001FFFFF) {
1886 out[0] = (cp >> 18 & 7) | 240;
1887 out[1] = (cp >> 12 & 63) | 128;
1888 out[2] = (cp >> 6 & 63) | 128;
1889 out[3] = (cp & 63) | 128;
1890 } else if (cp <= 0x03FFFFFF) {
1892 out[0] = (cp >> 24 & 3) | 248;
1893 out[1] = (cp >> 18 & 63) | 128;
1894 out[2] = (cp >> 12 & 63) | 128;
1895 out[3] = (cp >> 6 & 63) | 128;
1896 out[4] = (cp & 63) | 128;
1897 } else if (cp <= 0x7FFFFFFF) {
1899 out[0] = (cp >> 30 & 1) | 252;
1900 out[1] = (cp >> 24 & 63) | 128;
1901 out[2] = (cp >> 18 & 63) | 128;
1902 out[3] = (cp >> 12 & 63) | 128;
1903 out[4] = (cp >> 6 & 63) | 128;
1904 out[5] = (cp & 63) | 128;
1913 * If the string contains escape sequences,
1914 * replace it with an allocated rendering and return 1,
1915 * such that the caller can free it after use.
1916 * Otherwise, do nothing and return 0.
1919 render_string(char **public, size_t *psz)
1921 const char *src, *scp, *addcp, *seq;
1923 size_t ssz, dsz, addsz;
1924 char utfbuf[7], res[6];
1925 int seqlen, unicode;
1929 res[2] = ASCII_NBRSP;
1930 res[3] = ASCII_HYPH;
1931 res[4] = ASCII_BREAK;
1934 src = scp = *public;
1939 while (scp < src + *psz) {
1941 /* Leave normal characters unchanged. */
1943 if (strchr(res, *scp) == NULL) {
1951 * Found something that requires replacing,
1952 * make sure we have a destination buffer.
1956 dst = mandoc_malloc(ssz + 1);
1958 memcpy(dst, src, dsz);
1961 /* Handle single-char special characters. */
1982 * Found an escape sequence.
1983 * Read past the slash, then parse it.
1984 * Ignore everything except characters.
1988 if (mandoc_escape(&scp, &seq, &seqlen) != ESCAPE_SPECIAL)
1992 * Render the special character
1993 * as either UTF-8 or ASCII.
1997 unicode = mchars_spec2cp(seq, seqlen);
2000 addsz = utf8(unicode, utfbuf);
2005 addcp = mchars_spec2str(seq, seqlen, &addsz);
2008 if (*addcp == ASCII_NBRSP) {
2014 /* Copy the rendered glyph into the stream. */
2017 dst = mandoc_realloc(dst, ssz + 1);
2018 memcpy(dst + dsz, addcp, addsz);
2026 /* Trim trailing whitespace and NUL-terminate. */
2028 while (*psz > 0 && (*public)[*psz - 1] == ' ')
2031 (*public)[*psz] = '\0';
2038 dbadd_mlink(const struct mlink *mlink)
2043 SQL_BIND_TEXT(stmts[STMT_INSERT_LINK], i, mlink->dsec);
2044 SQL_BIND_TEXT(stmts[STMT_INSERT_LINK], i, mlink->arch);
2045 SQL_BIND_TEXT(stmts[STMT_INSERT_LINK], i, mlink->name);
2046 SQL_BIND_INT64(stmts[STMT_INSERT_LINK], i, mlink->mpage->pageid);
2047 SQL_STEP(stmts[STMT_INSERT_LINK]);
2048 sqlite3_reset(stmts[STMT_INSERT_LINK]);
2052 dbadd_mlink_name(const struct mlink *mlink)
2060 SQL_BIND_INT64(stmts[STMT_SELECT_NAME], i, mlink->mpage->pageid);
2061 bits = NAME_FILE & NAME_MASK;
2062 if (sqlite3_step(stmts[STMT_SELECT_NAME]) == SQLITE_ROW) {
2063 bits |= sqlite3_column_int64(stmts[STMT_SELECT_NAME], 0);
2064 sqlite3_reset(stmts[STMT_SELECT_NAME]);
2068 SQL_BIND_INT64(stmts[STMT_INSERT_NAME], i, bits);
2069 SQL_BIND_TEXT(stmts[STMT_INSERT_NAME], i, mlink->name);
2070 SQL_BIND_INT64(stmts[STMT_INSERT_NAME], i, mlink->mpage->pageid);
2071 SQL_STEP(stmts[STMT_INSERT_NAME]);
2072 sqlite3_reset(stmts[STMT_INSERT_NAME]);
2076 * Flush the current page's terms (and their bits) into the database.
2077 * Wrap the entire set of additions in a transaction to make sqlite be a
2079 * Also, handle escape sequences at the last possible moment.
2082 dbadd(struct mpage *mpage)
2084 struct mlink *mlink;
2091 mlink = mpage->mlinks;
2094 for (key = ohash_first(&names, &slot); NULL != key;
2095 key = ohash_next(&names, &slot))
2097 for (key = ohash_first(&strings, &slot); NULL != key;
2098 key = ohash_next(&strings, &slot))
2102 while (NULL != mlink) {
2103 fputs(mlink->name, stdout);
2104 if (NULL == mlink->next ||
2105 strcmp(mlink->dsec, mlink->next->dsec) ||
2106 strcmp(mlink->fsec, mlink->next->fsec) ||
2107 strcmp(mlink->arch, mlink->next->arch)) {
2109 if ('\0' == *mlink->dsec)
2110 fputs(mlink->fsec, stdout);
2112 fputs(mlink->dsec, stdout);
2113 if ('\0' != *mlink->arch)
2114 printf("/%s", mlink->arch);
2117 mlink = mlink->next;
2119 fputs(", ", stdout);
2121 printf(" - %s\n", mpage->desc);
2126 say(mlink->file, "Adding to database");
2130 mustfree = render_string(&cp, &i);
2132 SQL_BIND_TEXT(stmts[STMT_INSERT_PAGE], i, cp);
2133 SQL_BIND_INT(stmts[STMT_INSERT_PAGE], i, mpage->form);
2134 SQL_STEP(stmts[STMT_INSERT_PAGE]);
2135 mpage->pageid = sqlite3_last_insert_rowid(db);
2136 sqlite3_reset(stmts[STMT_INSERT_PAGE]);
2140 while (NULL != mlink) {
2142 mlink = mlink->next;
2144 mlink = mpage->mlinks;
2146 for (key = ohash_first(&names, &slot); NULL != key;
2147 key = ohash_next(&names, &slot)) {
2148 assert(key->mpage == mpage);
2150 SQL_BIND_INT64(stmts[STMT_INSERT_NAME], i, key->mask);
2151 SQL_BIND_TEXT(stmts[STMT_INSERT_NAME], i, key->key);
2152 SQL_BIND_INT64(stmts[STMT_INSERT_NAME], i, mpage->pageid);
2153 SQL_STEP(stmts[STMT_INSERT_NAME]);
2154 sqlite3_reset(stmts[STMT_INSERT_NAME]);
2157 for (key = ohash_first(&strings, &slot); NULL != key;
2158 key = ohash_next(&strings, &slot)) {
2159 assert(key->mpage == mpage);
2161 SQL_BIND_INT64(stmts[STMT_INSERT_KEY], i, key->mask);
2162 SQL_BIND_TEXT(stmts[STMT_INSERT_KEY], i, key->key);
2163 SQL_BIND_INT64(stmts[STMT_INSERT_KEY], i, mpage->pageid);
2164 SQL_STEP(stmts[STMT_INSERT_KEY]);
2165 sqlite3_reset(stmts[STMT_INSERT_KEY]);
2173 struct mpage *mpage;
2174 struct mlink *mlink;
2179 SQL_EXEC("BEGIN TRANSACTION");
2181 for (mpage = ohash_first(&mpages, &slot); NULL != mpage;
2182 mpage = ohash_next(&mpages, &slot)) {
2183 mlink = mpage->mlinks;
2185 say(mlink->file, "Deleting from database");
2188 for ( ; NULL != mlink; mlink = mlink->next) {
2190 SQL_BIND_TEXT(stmts[STMT_DELETE_PAGE],
2192 SQL_BIND_TEXT(stmts[STMT_DELETE_PAGE],
2194 SQL_BIND_TEXT(stmts[STMT_DELETE_PAGE],
2196 SQL_STEP(stmts[STMT_DELETE_PAGE]);
2197 sqlite3_reset(stmts[STMT_DELETE_PAGE]);
2202 SQL_EXEC("END TRANSACTION");
2206 * Close an existing database and its prepared statements.
2207 * If "real" is not set, rename the temporary file into the real one.
2219 for (i = 0; i < STMT__MAX; i++) {
2220 sqlite3_finalize(stmts[i]);
2230 if ('\0' == *tempfilename) {
2231 if (-1 == rename(MANDOC_DB "~", MANDOC_DB)) {
2232 exitcode = (int)MANDOCLEVEL_SYSERR;
2233 say(MANDOC_DB, "&rename");
2238 switch (child = fork()) {
2240 exitcode = (int)MANDOCLEVEL_SYSERR;
2241 say("", "&fork cmp");
2244 execlp("cmp", "cmp", "-s",
2245 tempfilename, MANDOC_DB, (char *)NULL);
2246 say("", "&exec cmp");
2251 if (-1 == waitpid(child, &status, 0)) {
2252 exitcode = (int)MANDOCLEVEL_SYSERR;
2253 say("", "&wait cmp");
2254 } else if (WIFSIGNALED(status)) {
2255 exitcode = (int)MANDOCLEVEL_SYSERR;
2256 say("", "cmp died from signal %d", WTERMSIG(status));
2257 } else if (WEXITSTATUS(status)) {
2258 exitcode = (int)MANDOCLEVEL_SYSERR;
2260 "Data changed, but cannot replace database");
2263 *strrchr(tempfilename, '/') = '\0';
2264 switch (child = fork()) {
2266 exitcode = (int)MANDOCLEVEL_SYSERR;
2267 say("", "&fork rm");
2270 execlp("rm", "rm", "-rf", tempfilename, (char *)NULL);
2271 say("", "&exec rm");
2272 exit((int)MANDOCLEVEL_SYSERR);
2276 if (-1 == waitpid(child, &status, 0)) {
2277 exitcode = (int)MANDOCLEVEL_SYSERR;
2278 say("", "&wait rm");
2279 } else if (WIFSIGNALED(status) || WEXITSTATUS(status)) {
2280 exitcode = (int)MANDOCLEVEL_SYSERR;
2281 say("", "%s: Cannot remove temporary directory",
2287 * This is straightforward stuff.
2288 * Open a database connection to a "temporary" database, then open a set
2289 * of prepared statements we'll use over and over again.
2290 * If "real" is set, we use the existing database; if not, we truncate a
2292 * Must be matched by dbclose().
2303 *tempfilename = '\0';
2304 ofl = SQLITE_OPEN_READWRITE;
2307 rc = sqlite3_open_v2(MANDOC_DB, &db, ofl, NULL);
2308 if (SQLITE_OK != rc) {
2309 exitcode = (int)MANDOCLEVEL_SYSERR;
2310 if (SQLITE_CANTOPEN != rc)
2311 say(MANDOC_DB, "%s", sqlite3_errstr(rc));
2314 goto prepare_statements;
2317 ofl |= SQLITE_OPEN_CREATE | SQLITE_OPEN_EXCLUSIVE;
2319 remove(MANDOC_DB "~");
2320 rc = sqlite3_open_v2(MANDOC_DB "~", &db, ofl, NULL);
2321 if (SQLITE_OK == rc)
2323 if (MPARSE_QUICK & mparse_options) {
2324 exitcode = (int)MANDOCLEVEL_SYSERR;
2325 say(MANDOC_DB "~", "%s", sqlite3_errstr(rc));
2329 (void)strlcpy(tempfilename, "/tmp/mandocdb.XXXXXX",
2330 sizeof(tempfilename));
2331 if (NULL == mkdtemp(tempfilename)) {
2332 exitcode = (int)MANDOCLEVEL_SYSERR;
2333 say("", "&%s", tempfilename);
2336 (void)strlcat(tempfilename, "/" MANDOC_DB,
2337 sizeof(tempfilename));
2338 rc = sqlite3_open_v2(tempfilename, &db, ofl, NULL);
2339 if (SQLITE_OK != rc) {
2340 exitcode = (int)MANDOCLEVEL_SYSERR;
2341 say("", "%s: %s", tempfilename, sqlite3_errstr(rc));
2346 sql = "CREATE TABLE \"mpages\" (\n"
2347 " \"desc\" TEXT NOT NULL,\n"
2348 " \"form\" INTEGER NOT NULL,\n"
2349 " \"pageid\" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL\n"
2352 "CREATE TABLE \"mlinks\" (\n"
2353 " \"sec\" TEXT NOT NULL,\n"
2354 " \"arch\" TEXT NOT NULL,\n"
2355 " \"name\" TEXT NOT NULL,\n"
2356 " \"pageid\" INTEGER NOT NULL REFERENCES mpages(pageid) "
2357 "ON DELETE CASCADE\n"
2359 "CREATE INDEX mlinks_pageid_idx ON mlinks (pageid);\n"
2361 "CREATE TABLE \"names\" (\n"
2362 " \"bits\" INTEGER NOT NULL,\n"
2363 " \"name\" TEXT NOT NULL,\n"
2364 " \"pageid\" INTEGER NOT NULL REFERENCES mpages(pageid) "
2365 "ON DELETE CASCADE,\n"
2366 " UNIQUE (\"name\", \"pageid\") ON CONFLICT REPLACE\n"
2369 "CREATE TABLE \"keys\" (\n"
2370 " \"bits\" INTEGER NOT NULL,\n"
2371 " \"key\" TEXT NOT NULL,\n"
2372 " \"pageid\" INTEGER NOT NULL REFERENCES mpages(pageid) "
2373 "ON DELETE CASCADE\n"
2375 "CREATE INDEX keys_pageid_idx ON keys (pageid);\n";
2377 if (SQLITE_OK != sqlite3_exec(db, sql, NULL, NULL, NULL)) {
2378 exitcode = (int)MANDOCLEVEL_SYSERR;
2379 say(MANDOC_DB, "%s", sqlite3_errmsg(db));
2385 if (SQLITE_OK != sqlite3_exec(db,
2386 "PRAGMA foreign_keys = ON", NULL, NULL, NULL)) {
2387 exitcode = (int)MANDOCLEVEL_SYSERR;
2388 say(MANDOC_DB, "PRAGMA foreign_keys: %s",
2389 sqlite3_errmsg(db));
2394 sql = "DELETE FROM mpages WHERE pageid IN "
2395 "(SELECT pageid FROM mlinks WHERE "
2396 "sec=? AND arch=? AND name=?)";
2397 sqlite3_prepare_v2(db, sql, -1, &stmts[STMT_DELETE_PAGE], NULL);
2398 sql = "INSERT INTO mpages "
2399 "(desc,form) VALUES (?,?)";
2400 sqlite3_prepare_v2(db, sql, -1, &stmts[STMT_INSERT_PAGE], NULL);
2401 sql = "INSERT INTO mlinks "
2402 "(sec,arch,name,pageid) VALUES (?,?,?,?)";
2403 sqlite3_prepare_v2(db, sql, -1, &stmts[STMT_INSERT_LINK], NULL);
2404 sql = "SELECT bits FROM names where pageid = ?";
2405 sqlite3_prepare_v2(db, sql, -1, &stmts[STMT_SELECT_NAME], NULL);
2406 sql = "INSERT INTO names "
2407 "(bits,name,pageid) VALUES (?,?,?)";
2408 sqlite3_prepare_v2(db, sql, -1, &stmts[STMT_INSERT_NAME], NULL);
2409 sql = "INSERT INTO keys "
2410 "(bits,key,pageid) VALUES (?,?,?)";
2411 sqlite3_prepare_v2(db, sql, -1, &stmts[STMT_INSERT_KEY], NULL);
2415 * When opening a new database, we can turn off
2416 * synchronous mode for much better performance.
2419 if (real && SQLITE_OK != sqlite3_exec(db,
2420 "PRAGMA synchronous = OFF", NULL, NULL, NULL)) {
2421 exitcode = (int)MANDOCLEVEL_SYSERR;
2422 say(MANDOC_DB, "PRAGMA synchronous: %s",
2423 sqlite3_errmsg(db));
2433 set_basedir(const char *targetdir, int report_baddir)
2435 static char startdir[PATH_MAX];
2436 static int getcwd_status; /* 1 = ok, 2 = failure */
2437 static int chdir_status; /* 1 = changed directory */
2441 * Remember the original working directory, if possible.
2442 * This will be needed if the second or a later directory
2443 * on the command line is given as a relative path.
2444 * Do not error out if the current directory is not
2445 * searchable: Maybe it won't be needed after all.
2447 if (0 == getcwd_status) {
2448 if (NULL == getcwd(startdir, sizeof(startdir))) {
2450 (void)strlcpy(startdir, strerror(errno),
2457 * We are leaving the old base directory.
2458 * Do not use it any longer, not even for messages.
2463 * If and only if the directory was changed earlier and
2464 * the next directory to process is given as a relative path,
2465 * first go back, or bail out if that is impossible.
2467 if (chdir_status && '/' != *targetdir) {
2468 if (2 == getcwd_status) {
2469 exitcode = (int)MANDOCLEVEL_SYSERR;
2470 say("", "getcwd: %s", startdir);
2473 if (-1 == chdir(startdir)) {
2474 exitcode = (int)MANDOCLEVEL_SYSERR;
2475 say("", "&chdir %s", startdir);
2481 * Always resolve basedir to the canonicalized absolute
2482 * pathname and append a trailing slash, such that
2483 * we can reliably check whether files are inside.
2485 if (NULL == realpath(targetdir, basedir)) {
2486 if (report_baddir || errno != ENOENT) {
2487 exitcode = (int)MANDOCLEVEL_BADARG;
2488 say("", "&%s: realpath", targetdir);
2491 } else if (-1 == chdir(basedir)) {
2492 if (report_baddir || errno != ENOENT) {
2493 exitcode = (int)MANDOCLEVEL_BADARG;
2499 cp = strchr(basedir, '\0');
2500 if ('/' != cp[-1]) {
2501 if (cp - basedir >= PATH_MAX - 1) {
2502 exitcode = (int)MANDOCLEVEL_SYSERR;
2503 say("", "Filename too long");
2513 say(const char *file, const char *format, ...)
2518 if ('\0' != *basedir)
2519 fprintf(stderr, "%s", basedir);
2520 if ('\0' != *basedir && '\0' != *file)
2523 fprintf(stderr, "%s", file);
2526 if (NULL != format) {
2539 if (NULL != format) {
2540 if ('\0' != *basedir || '\0' != *file)
2541 fputs(": ", stderr);
2542 va_start(ap, format);
2543 vfprintf(stderr, format, ap);
2547 if ('\0' != *basedir || '\0' != *file || NULL != format)
2548 fputs(": ", stderr);
2551 fputc('\n', stderr);