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 mlink *mlinks; /* singly linked list */
107 int form; /* format from file content */
112 char file[PATH_MAX]; /* filename rel. to manpath */
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 struct mpage *mpage; /* parent */
119 int dform; /* format from directory */
120 int fform; /* format from file name suffix */
121 int gzip; /* filename has a .gz suffix */
125 STMT_DELETE_PAGE = 0, /* delete mpage */
126 STMT_INSERT_PAGE, /* insert mpage */
127 STMT_INSERT_LINK, /* insert mlink */
128 STMT_INSERT_NAME, /* insert name */
129 STMT_SELECT_NAME, /* retrieve existing name flags */
130 STMT_INSERT_KEY, /* insert parsed key */
134 typedef int (*mdoc_fp)(struct mpage *, const struct roff_meta *,
135 const struct roff_node *);
137 struct mdoc_handler {
138 mdoc_fp fp; /* optional handler */
139 uint64_t mask; /* set unless handler returns 0 */
142 static void dbclose(int);
143 static void dbadd(struct mpage *);
144 static void dbadd_mlink(const struct mlink *mlink);
145 static void dbadd_mlink_name(const struct mlink *mlink);
146 static int dbopen(int);
147 static void dbprune(void);
148 static void filescan(const char *);
149 static void mlink_add(struct mlink *, const struct stat *);
150 static void mlink_check(struct mpage *, struct mlink *);
151 static void mlink_free(struct mlink *);
152 static void mlinks_undupe(struct mpage *);
153 static void mpages_free(void);
154 static void mpages_merge(struct mparse *);
155 static void names_check(void);
156 static void parse_cat(struct mpage *, int);
157 static void parse_man(struct mpage *, const struct roff_meta *,
158 const struct roff_node *);
159 static void parse_mdoc(struct mpage *, const struct roff_meta *,
160 const struct roff_node *);
161 static int parse_mdoc_head(struct mpage *, const struct roff_meta *,
162 const struct roff_node *);
163 static int parse_mdoc_Fd(struct mpage *, const struct roff_meta *,
164 const struct roff_node *);
165 static void parse_mdoc_fname(struct mpage *, const struct roff_node *);
166 static int parse_mdoc_Fn(struct mpage *, const struct roff_meta *,
167 const struct roff_node *);
168 static int parse_mdoc_Fo(struct mpage *, const struct roff_meta *,
169 const struct roff_node *);
170 static int parse_mdoc_Nd(struct mpage *, const struct roff_meta *,
171 const struct roff_node *);
172 static int parse_mdoc_Nm(struct mpage *, const struct roff_meta *,
173 const struct roff_node *);
174 static int parse_mdoc_Sh(struct mpage *, const struct roff_meta *,
175 const struct roff_node *);
176 static int parse_mdoc_Va(struct mpage *, const struct roff_meta *,
177 const struct roff_node *);
178 static int parse_mdoc_Xr(struct mpage *, const struct roff_meta *,
179 const struct roff_node *);
180 static void putkey(const struct mpage *, char *, uint64_t);
181 static void putkeys(const struct mpage *, char *, size_t, uint64_t);
182 static void putmdockey(const struct mpage *,
183 const struct roff_node *, uint64_t);
184 static int render_string(char **, size_t *);
185 static void say(const char *, const char *, ...);
186 static int set_basedir(const char *, int);
187 static int treescan(void);
188 static size_t utf8(unsigned int, char [7]);
190 static char tempfilename[32];
191 static int nodb; /* no database changes */
192 static int mparse_options; /* abort the parse early */
193 static int use_all; /* use all found files */
194 static int debug; /* print what we're doing */
195 static int warnings; /* warn about crap */
196 static int write_utf8; /* write UTF-8 output; else ASCII */
197 static int exitcode; /* to be returned by main */
198 static enum op op; /* operational mode */
199 static char basedir[PATH_MAX]; /* current base directory */
200 static struct ohash mpages; /* table of distinct manual pages */
201 static struct ohash mlinks; /* table of directory entries */
202 static struct ohash names; /* table of all names */
203 static struct ohash strings; /* table of all strings */
204 static sqlite3 *db = NULL; /* current database */
205 static sqlite3_stmt *stmts[STMT__MAX]; /* current statements */
206 static uint64_t name_mask;
208 static const struct mdoc_handler mdocs[MDOC_MAX] = {
209 { NULL, 0 }, /* Ap */
210 { NULL, 0 }, /* Dd */
211 { NULL, 0 }, /* Dt */
212 { NULL, 0 }, /* Os */
213 { parse_mdoc_Sh, TYPE_Sh }, /* Sh */
214 { parse_mdoc_head, TYPE_Ss }, /* Ss */
215 { NULL, 0 }, /* Pp */
216 { NULL, 0 }, /* D1 */
217 { NULL, 0 }, /* Dl */
218 { NULL, 0 }, /* Bd */
219 { NULL, 0 }, /* Ed */
220 { NULL, 0 }, /* Bl */
221 { NULL, 0 }, /* El */
222 { NULL, 0 }, /* It */
223 { NULL, 0 }, /* Ad */
224 { NULL, TYPE_An }, /* An */
225 { NULL, TYPE_Ar }, /* Ar */
226 { NULL, TYPE_Cd }, /* Cd */
227 { NULL, TYPE_Cm }, /* Cm */
228 { NULL, TYPE_Dv }, /* Dv */
229 { NULL, TYPE_Er }, /* Er */
230 { NULL, TYPE_Ev }, /* Ev */
231 { NULL, 0 }, /* Ex */
232 { NULL, TYPE_Fa }, /* Fa */
233 { parse_mdoc_Fd, 0 }, /* Fd */
234 { NULL, TYPE_Fl }, /* Fl */
235 { parse_mdoc_Fn, 0 }, /* Fn */
236 { NULL, TYPE_Ft }, /* Ft */
237 { NULL, TYPE_Ic }, /* Ic */
238 { NULL, TYPE_In }, /* In */
239 { NULL, TYPE_Li }, /* Li */
240 { parse_mdoc_Nd, 0 }, /* Nd */
241 { parse_mdoc_Nm, 0 }, /* Nm */
242 { NULL, 0 }, /* Op */
243 { NULL, 0 }, /* Ot */
244 { NULL, TYPE_Pa }, /* Pa */
245 { NULL, 0 }, /* Rv */
246 { NULL, TYPE_St }, /* St */
247 { parse_mdoc_Va, TYPE_Va }, /* Va */
248 { parse_mdoc_Va, TYPE_Vt }, /* Vt */
249 { parse_mdoc_Xr, 0 }, /* Xr */
250 { NULL, 0 }, /* %A */
251 { NULL, 0 }, /* %B */
252 { NULL, 0 }, /* %D */
253 { NULL, 0 }, /* %I */
254 { NULL, 0 }, /* %J */
255 { NULL, 0 }, /* %N */
256 { NULL, 0 }, /* %O */
257 { NULL, 0 }, /* %P */
258 { NULL, 0 }, /* %R */
259 { NULL, 0 }, /* %T */
260 { NULL, 0 }, /* %V */
261 { NULL, 0 }, /* Ac */
262 { NULL, 0 }, /* Ao */
263 { NULL, 0 }, /* Aq */
264 { NULL, TYPE_At }, /* At */
265 { NULL, 0 }, /* Bc */
266 { NULL, 0 }, /* Bf */
267 { NULL, 0 }, /* Bo */
268 { NULL, 0 }, /* Bq */
269 { NULL, TYPE_Bsx }, /* Bsx */
270 { NULL, TYPE_Bx }, /* Bx */
271 { NULL, 0 }, /* Db */
272 { NULL, 0 }, /* Dc */
273 { NULL, 0 }, /* Do */
274 { NULL, 0 }, /* Dq */
275 { NULL, 0 }, /* Ec */
276 { NULL, 0 }, /* Ef */
277 { NULL, TYPE_Em }, /* Em */
278 { NULL, 0 }, /* Eo */
279 { NULL, TYPE_Fx }, /* Fx */
280 { NULL, TYPE_Ms }, /* Ms */
281 { NULL, 0 }, /* No */
282 { NULL, 0 }, /* Ns */
283 { NULL, TYPE_Nx }, /* Nx */
284 { NULL, TYPE_Ox }, /* Ox */
285 { NULL, 0 }, /* Pc */
286 { NULL, 0 }, /* Pf */
287 { NULL, 0 }, /* Po */
288 { NULL, 0 }, /* Pq */
289 { NULL, 0 }, /* Qc */
290 { NULL, 0 }, /* Ql */
291 { NULL, 0 }, /* Qo */
292 { NULL, 0 }, /* Qq */
293 { NULL, 0 }, /* Re */
294 { NULL, 0 }, /* Rs */
295 { NULL, 0 }, /* Sc */
296 { NULL, 0 }, /* So */
297 { NULL, 0 }, /* Sq */
298 { NULL, 0 }, /* Sm */
299 { NULL, 0 }, /* Sx */
300 { NULL, TYPE_Sy }, /* Sy */
301 { NULL, TYPE_Tn }, /* Tn */
302 { NULL, 0 }, /* Ux */
303 { NULL, 0 }, /* Xc */
304 { NULL, 0 }, /* Xo */
305 { parse_mdoc_Fo, 0 }, /* Fo */
306 { NULL, 0 }, /* Fc */
307 { NULL, 0 }, /* Oo */
308 { NULL, 0 }, /* Oc */
309 { NULL, 0 }, /* Bk */
310 { NULL, 0 }, /* Ek */
311 { NULL, 0 }, /* Bt */
312 { NULL, 0 }, /* Hf */
313 { NULL, 0 }, /* Fr */
314 { NULL, 0 }, /* Ud */
315 { NULL, TYPE_Lb }, /* Lb */
316 { NULL, 0 }, /* Lp */
317 { NULL, TYPE_Lk }, /* Lk */
318 { NULL, TYPE_Mt }, /* Mt */
319 { NULL, 0 }, /* Brq */
320 { NULL, 0 }, /* Bro */
321 { NULL, 0 }, /* Brc */
322 { NULL, 0 }, /* %C */
323 { NULL, 0 }, /* Es */
324 { NULL, 0 }, /* En */
325 { NULL, TYPE_Dx }, /* Dx */
326 { NULL, 0 }, /* %Q */
327 { NULL, 0 }, /* br */
328 { NULL, 0 }, /* sp */
329 { NULL, 0 }, /* %U */
330 { NULL, 0 }, /* Ta */
331 { NULL, 0 }, /* ll */
336 mandocdb(int argc, char *argv[])
340 const char *path_arg, *progname;
345 if (pledge("stdio rpath wpath cpath fattr flock proc exec", NULL) == -1) {
347 return (int)MANDOCLEVEL_SYSERR;
351 #if HAVE_SANDBOX_INIT
352 if (sandbox_init(kSBXProfileNoInternet, SANDBOX_NAMED, NULL) == -1) {
353 warnx("sandbox_init");
354 return (int)MANDOCLEVEL_SYSERR;
358 memset(&conf, 0, sizeof(conf));
359 memset(stmts, 0, STMT__MAX * sizeof(sqlite3_stmt *));
362 * We accept a few different invocations.
363 * The CHECKOP macro makes sure that invocation styles don't
364 * clobber each other.
366 #define CHECKOP(_op, _ch) do \
367 if (OP_DEFAULT != (_op)) { \
368 warnx("-%c: Conflicting option", (_ch)); \
370 } while (/*CONSTCOND*/0)
375 while (-1 != (ch = getopt(argc, argv, "aC:Dd:npQT:tu:v")))
400 mparse_options |= MPARSE_QUICK;
403 if (strcmp(optarg, "utf8")) {
404 warnx("-T%s: Unsupported output format",
412 dup2(STDOUT_FILENO, STDERR_FILENO);
422 /* Compatibility with espie@'s makewhatis. */
433 if (pledge("stdio rpath", NULL) == -1) {
435 return (int)MANDOCLEVEL_SYSERR;
440 if (OP_CONFFILE == op && argc > 0) {
441 warnx("-C: Too many arguments");
445 exitcode = (int)MANDOCLEVEL_OK;
447 mp = mparse_alloc(mparse_options, MANDOCLEVEL_BADARG, NULL, NULL);
448 mandoc_ohash_init(&mpages, 6, offsetof(struct mpage, inodev));
449 mandoc_ohash_init(&mlinks, 6, offsetof(struct mlink, file));
451 if (OP_UPDATE == op || OP_DELETE == op || OP_TEST == op) {
454 * Most of these deal with a specific directory.
455 * Jump into that directory first.
457 if (OP_TEST != op && 0 == set_basedir(path_arg, 1))
462 * The existing database is usable. Process
463 * all files specified on the command-line.
467 if (pledge("stdio rpath wpath cpath fattr flock", NULL) == -1) {
469 exitcode = (int)MANDOCLEVEL_SYSERR;
475 for (i = 0; i < argc; i++)
481 * Database missing or corrupt.
482 * Recreate from scratch.
484 exitcode = (int)MANDOCLEVEL_OK;
493 dbclose(OP_DEFAULT == op ? 0 : 1);
496 * If we have arguments, use them as our manpaths.
497 * If we don't, grok from manpath(1) or however else
498 * manconf_parse() wants to do it.
501 conf.manpath.paths = mandoc_reallocarray(NULL,
502 argc, sizeof(char *));
503 conf.manpath.sz = (size_t)argc;
504 for (i = 0; i < argc; i++)
505 conf.manpath.paths[i] = mandoc_strdup(argv[i]);
507 manconf_parse(&conf, path_arg, NULL, NULL);
509 if (conf.manpath.sz == 0) {
510 exitcode = (int)MANDOCLEVEL_BADARG;
511 say("", "Empty manpath");
515 * First scan the tree rooted at a base directory, then
516 * build a new database and finally move it into place.
517 * Ignore zero-length directories and strip trailing
520 for (j = 0; j < conf.manpath.sz; j++) {
521 sz = strlen(conf.manpath.paths[j]);
522 if (sz && conf.manpath.paths[j][sz - 1] == '/')
523 conf.manpath.paths[j][--sz] = '\0';
528 mandoc_ohash_init(&mpages, 6,
529 offsetof(struct mpage, inodev));
530 mandoc_ohash_init(&mlinks, 6,
531 offsetof(struct mlink, file));
534 if ( ! set_basedir(conf.manpath.paths[j], argc > 0))
542 if (warnings && !nodb &&
543 ! (MPARSE_QUICK & mparse_options))
547 if (j + 1 < conf.manpath.sz) {
549 ohash_delete(&mpages);
550 ohash_delete(&mlinks);
559 ohash_delete(&mpages);
560 ohash_delete(&mlinks);
563 progname = getprogname();
564 fprintf(stderr, "usage: %s [-aDnpQ] [-C file] [-Tutf8]\n"
565 " %s [-aDnpQ] [-Tutf8] dir ...\n"
566 " %s [-DnpQ] [-Tutf8] -d dir [file ...]\n"
567 " %s [-Dnp] -u dir [file ...]\n"
568 " %s [-Q] -t file ...\n",
569 progname, progname, progname, progname, progname);
571 return (int)MANDOCLEVEL_BADARG;
575 * Scan a directory tree rooted at "basedir" for manpages.
576 * We use fts(), scanning directory parts along the way for clues to our
577 * section and architecture.
579 * If use_all has been specified, grok all files.
580 * If not, sanitise paths to the following:
582 * [./]man*[/<arch>]/<name>.<section>
584 * [./]cat<section>[/<arch>]/<name>.0
586 * TODO: accommodate for multi-language directories.
596 char *dsec, *arch, *fsec, *cp;
601 argv[1] = (char *)NULL;
603 f = fts_open((char * const *)argv,
604 FTS_PHYSICAL | FTS_NOCHDIR, NULL);
606 exitcode = (int)MANDOCLEVEL_SYSERR;
607 say("", "&fts_open");
614 while ((ff = fts_read(f)) != NULL) {
615 path = ff->fts_path + 2;
616 switch (ff->fts_info) {
619 * Symbolic links require various sanity checks,
620 * then get handled just like regular files.
623 if (realpath(path, buf) == NULL) {
625 say(path, "&realpath");
628 if (strstr(buf, basedir) != buf
630 && strstr(buf, HOMEBREWDIR) != buf
633 if (warnings) say("",
634 "%s: outside base directory", buf);
637 /* Use logical inode to avoid mpages dupe. */
638 if (stat(path, ff->fts_statp) == -1) {
646 * If we're a regular file, add an mlink by using the
647 * stored directory data and handling the filename.
650 if ( ! strcmp(path, MANDOC_DB))
652 if ( ! use_all && ff->fts_level < 2) {
654 say(path, "Extraneous file");
659 while (fsec == NULL) {
660 fsec = strrchr(ff->fts_name, '.');
661 if (fsec == NULL || strcmp(fsec+1, "gz"))
671 "No filename suffix");
674 } else if ( ! strcmp(++fsec, "html")) {
676 say(path, "Skip html");
678 } else if ( ! strcmp(fsec, "ps")) {
680 say(path, "Skip ps");
682 } else if ( ! strcmp(fsec, "pdf")) {
684 say(path, "Skip pdf");
686 } else if ( ! use_all &&
687 ((dform == FORM_SRC &&
688 strncmp(fsec, dsec, strlen(dsec))) ||
689 (dform == FORM_CAT && strcmp(fsec, "0")))) {
691 say(path, "Wrong filename suffix");
696 mlink = mandoc_calloc(1, sizeof(struct mlink));
697 if (strlcpy(mlink->file, path,
698 sizeof(mlink->file)) >=
699 sizeof(mlink->file)) {
700 say(path, "Filename too long");
704 mlink->dform = dform;
707 mlink->name = ff->fts_name;
710 mlink_add(mlink, ff->fts_statp);
719 say(path, "Not a regular file");
723 switch (ff->fts_level) {
725 /* Ignore the root directory. */
729 * This might contain manX/ or catX/.
730 * Try to infer this from the name.
731 * If we're not in use_all, enforce it.
734 if (ff->fts_info == FTS_DP) {
740 if ( ! strncmp(cp, "man", 3)) {
743 } else if ( ! strncmp(cp, "cat", 3)) {
751 if (dsec != NULL || use_all)
755 say(path, "Unknown directory part");
756 fts_set(f, ff, FTS_SKIP);
760 * Possibly our architecture.
761 * If we're descending, keep tabs on it.
763 if (ff->fts_info != FTS_DP && dsec != NULL)
769 if (ff->fts_info == FTS_DP || use_all)
772 say(path, "Extraneous directory part");
773 fts_set(f, ff, FTS_SKIP);
783 * Add a file to the mlinks table.
784 * Do not verify that it's a "valid" looking manpage (we'll do that
787 * Try to infer the manual section, architecture, and page name from the
788 * path, assuming it looks like
790 * [./]man*[/<arch>]/<name>.<section>
792 * [./]cat<section>[/<arch>]/<name>.0
794 * See treescan() for the fts(3) version of this.
797 filescan(const char *file)
806 if (0 == strncmp(file, "./", 2))
810 * We have to do lstat(2) before realpath(3) loses
811 * the information whether this is a symbolic link.
812 * We need to know that because for symbolic links,
813 * we want to use the orginal file name, while for
814 * regular files, we want to use the real path.
816 if (-1 == lstat(file, &st)) {
817 exitcode = (int)MANDOCLEVEL_BADARG;
820 } else if (0 == ((S_IFREG | S_IFLNK) & st.st_mode)) {
821 exitcode = (int)MANDOCLEVEL_BADARG;
822 say(file, "Not a regular file");
827 * We have to resolve the file name to the real path
828 * in any case for the base directory check.
830 if (NULL == realpath(file, buf)) {
831 exitcode = (int)MANDOCLEVEL_BADARG;
832 say(file, "&realpath");
838 else if (strstr(buf, basedir) == buf)
839 start = buf + strlen(basedir);
841 else if (strstr(buf, HOMEBREWDIR) == buf)
845 exitcode = (int)MANDOCLEVEL_BADARG;
846 say("", "%s: outside base directory", buf);
851 * Now we are sure the file is inside our tree.
852 * If it is a symbolic link, ignore the real path
853 * and use the original name.
854 * This implies passing stuff like "cat1/../man1/foo.1"
855 * on the command line won't work. So don't do that.
856 * Note the stat(2) can still fail if the link target
859 if (S_IFLNK & st.st_mode) {
860 if (-1 == stat(buf, &st)) {
861 exitcode = (int)MANDOCLEVEL_BADARG;
865 if (strlcpy(buf, file, sizeof(buf)) >= sizeof(buf)) {
866 say(file, "Filename too long");
870 if (OP_TEST != op && strstr(buf, basedir) == buf)
871 start += strlen(basedir);
874 mlink = mandoc_calloc(1, sizeof(struct mlink));
875 mlink->dform = FORM_NONE;
876 if (strlcpy(mlink->file, start, sizeof(mlink->file)) >=
877 sizeof(mlink->file)) {
878 say(start, "Filename too long");
884 * First try to guess our directory structure.
885 * If we find a separator, try to look for man* or cat*.
886 * If we find one of these and what's underneath is a directory,
887 * assume it's an architecture.
889 if (NULL != (p = strchr(start, '/'))) {
891 if (0 == strncmp(start, "man", 3)) {
892 mlink->dform = FORM_SRC;
893 mlink->dsec = start + 3;
894 } else if (0 == strncmp(start, "cat", 3)) {
895 mlink->dform = FORM_CAT;
896 mlink->dsec = start + 3;
900 if (NULL != mlink->dsec && NULL != (p = strchr(start, '/'))) {
908 * Now check the file suffix.
909 * Suffix of `.0' indicates a catpage, `.1-9' is a manpage.
911 p = strrchr(start, '\0');
912 while (p-- > start && '/' != *p && '.' != *p)
921 * Now try to parse the name.
922 * Use the filename portion of the path.
925 if (NULL != (p = strrchr(start, '/'))) {
929 mlink_add(mlink, &st);
933 mlink_add(struct mlink *mlink, const struct stat *st)
935 struct inodev inodev;
939 assert(NULL != mlink->file);
941 mlink->dsec = mandoc_strdup(mlink->dsec ? mlink->dsec : "");
942 mlink->arch = mandoc_strdup(mlink->arch ? mlink->arch : "");
943 mlink->name = mandoc_strdup(mlink->name ? mlink->name : "");
944 mlink->fsec = mandoc_strdup(mlink->fsec ? mlink->fsec : "");
946 if ('0' == *mlink->fsec) {
948 mlink->fsec = mandoc_strdup(mlink->dsec);
949 mlink->fform = FORM_CAT;
950 } else if ('1' <= *mlink->fsec && '9' >= *mlink->fsec)
951 mlink->fform = FORM_SRC;
953 mlink->fform = FORM_NONE;
955 slot = ohash_qlookup(&mlinks, mlink->file);
956 assert(NULL == ohash_find(&mlinks, slot));
957 ohash_insert(&mlinks, slot, mlink);
959 memset(&inodev, 0, sizeof(inodev)); /* Clear padding. */
960 inodev.st_ino = st->st_ino;
961 inodev.st_dev = st->st_dev;
962 slot = ohash_lookup_memory(&mpages, (char *)&inodev,
963 sizeof(struct inodev), inodev.st_ino);
964 mpage = ohash_find(&mpages, slot);
966 mpage = mandoc_calloc(1, sizeof(struct mpage));
967 mpage->inodev.st_ino = inodev.st_ino;
968 mpage->inodev.st_dev = inodev.st_dev;
969 ohash_insert(&mpages, slot, mpage);
971 mlink->next = mpage->mlinks;
972 mpage->mlinks = mlink;
973 mlink->mpage = mpage;
977 mlink_free(struct mlink *mlink)
994 mpage = ohash_first(&mpages, &slot);
995 while (NULL != mpage) {
996 while (NULL != (mlink = mpage->mlinks)) {
997 mpage->mlinks = mlink->next;
1005 mpage = ohash_next(&mpages, &slot);
1010 * For each mlink to the mpage, check whether the path looks like
1011 * it is formatted, and if it does, check whether a source manual
1012 * exists by the same name, ignoring the suffix.
1013 * If both conditions hold, drop the mlink.
1016 mlinks_undupe(struct mpage *mpage)
1019 struct mlink **prev;
1020 struct mlink *mlink;
1023 mpage->form = FORM_CAT;
1024 prev = &mpage->mlinks;
1025 while (NULL != (mlink = *prev)) {
1026 if (FORM_CAT != mlink->dform) {
1027 mpage->form = FORM_NONE;
1030 (void)strlcpy(buf, mlink->file, sizeof(buf));
1031 bufp = strstr(buf, "cat");
1032 assert(NULL != bufp);
1033 memcpy(bufp, "man", 3);
1034 if (NULL != (bufp = strrchr(buf, '.')))
1036 (void)strlcat(buf, mlink->dsec, sizeof(buf));
1037 if (NULL == ohash_find(&mlinks,
1038 ohash_qlookup(&mlinks, buf)))
1041 say(mlink->file, "Man source exists: %s", buf);
1044 *prev = mlink->next;
1048 prev = &(*prev)->next;
1053 mlink_check(struct mpage *mpage, struct mlink *mlink)
1059 * Check whether the manual section given in a file
1060 * agrees with the directory where the file is located.
1061 * Some manuals have suffixes like (3p) on their
1062 * section number either inside the file or in the
1063 * directory name, some are linked into more than one
1064 * section, like encrypt(1) = makekey(8).
1067 if (FORM_SRC == mpage->form &&
1068 strcasecmp(mpage->sec, mlink->dsec))
1069 say(mlink->file, "Section \"%s\" manual in %s directory",
1070 mpage->sec, mlink->dsec);
1073 * Manual page directories exist for each kernel
1074 * architecture as returned by machine(1).
1075 * However, many manuals only depend on the
1076 * application architecture as returned by arch(1).
1077 * For example, some (2/ARM) manuals are shared
1078 * across the "armish" and "zaurus" kernel
1080 * A few manuals are even shared across completely
1081 * different architectures, for example fdformat(1)
1082 * on amd64, i386, sparc, and sparc64.
1085 if (strcasecmp(mpage->arch, mlink->arch))
1086 say(mlink->file, "Architecture \"%s\" manual in "
1087 "\"%s\" directory", mpage->arch, mlink->arch);
1091 * parse_cat() doesn't set NAME_TITLE yet.
1094 if (FORM_CAT == mpage->form)
1098 * Check whether this mlink
1099 * appears as a name in the NAME section.
1102 slot = ohash_qlookup(&names, mlink->name);
1103 str = ohash_find(&names, slot);
1104 assert(NULL != str);
1105 if ( ! (NAME_TITLE & str->mask))
1106 say(mlink->file, "Name missing in NAME section");
1110 * Run through the files in the global vector "mpages"
1111 * and add them to the database specified in "basedir".
1113 * This handles the parsing scheme itself, using the cues of directory
1114 * and filename to determine whether the file is parsable or not.
1117 mpages_merge(struct mparse *mp)
1120 struct mpage *mpage, *mpage_dest;
1121 struct mlink *mlink, *mlink_dest;
1122 struct roff_man *man;
1129 SQL_EXEC("BEGIN TRANSACTION");
1131 mpage = ohash_first(&mpages, &pslot);
1132 while (mpage != NULL) {
1133 mlinks_undupe(mpage);
1134 if ((mlink = mpage->mlinks) == NULL) {
1135 mpage = ohash_next(&mpages, &pslot);
1139 name_mask = NAME_MASK;
1140 mandoc_ohash_init(&names, 4, offsetof(struct str, key));
1141 mandoc_ohash_init(&strings, 6, offsetof(struct str, key));
1146 if ((fd = mparse_open(mp, mlink->file)) == -1) {
1147 say(mlink->file, "&open");
1152 * Interpret the file as mdoc(7) or man(7) source
1153 * code, unless it is known to be formatted.
1155 if (mlink->dform != FORM_CAT || mlink->fform != FORM_CAT) {
1156 mparse_readfd(mp, fd, mlink->file);
1158 mparse_result(mp, &man, &sodest);
1161 if (sodest != NULL) {
1162 mlink_dest = ohash_find(&mlinks,
1163 ohash_qlookup(&mlinks, sodest));
1164 if (mlink_dest == NULL) {
1165 mandoc_asprintf(&cp, "%s.gz", sodest);
1166 mlink_dest = ohash_find(&mlinks,
1167 ohash_qlookup(&mlinks, cp));
1170 if (mlink_dest != NULL) {
1172 /* The .so target exists. */
1174 mpage_dest = mlink_dest->mpage;
1176 mlink->mpage = mpage_dest;
1179 * If the target was already
1180 * processed, add the links
1181 * to the database now.
1182 * Otherwise, this will
1183 * happen when we come
1187 if (mpage_dest->pageid)
1188 dbadd_mlink_name(mlink);
1190 if (mlink->next == NULL)
1192 mlink = mlink->next;
1195 /* Move all links to the target. */
1197 mlink->next = mlink_dest->next;
1198 mlink_dest->next = mpage->mlinks;
1199 mpage->mlinks = NULL;
1202 } else if (man != NULL && man->macroset == MACROSET_MDOC) {
1204 mpage->form = FORM_SRC;
1205 mpage->sec = man->meta.msec;
1206 mpage->sec = mandoc_strdup(
1207 mpage->sec == NULL ? "" : mpage->sec);
1208 mpage->arch = man->meta.arch;
1209 mpage->arch = mandoc_strdup(
1210 mpage->arch == NULL ? "" : mpage->arch);
1211 mpage->title = mandoc_strdup(man->meta.title);
1212 } else if (man != NULL && man->macroset == MACROSET_MAN) {
1214 mpage->form = FORM_SRC;
1215 mpage->sec = mandoc_strdup(man->meta.msec);
1216 mpage->arch = mandoc_strdup(mlink->arch);
1217 mpage->title = mandoc_strdup(man->meta.title);
1219 mpage->form = FORM_CAT;
1220 mpage->sec = mandoc_strdup(mlink->dsec);
1221 mpage->arch = mandoc_strdup(mlink->arch);
1222 mpage->title = mandoc_strdup(mlink->name);
1224 putkey(mpage, mpage->sec, TYPE_sec);
1225 if (*mpage->arch != '\0')
1226 putkey(mpage, mpage->arch, TYPE_arch);
1228 for ( ; mlink != NULL; mlink = mlink->next) {
1229 if ('\0' != *mlink->dsec)
1230 putkey(mpage, mlink->dsec, TYPE_sec);
1231 if ('\0' != *mlink->fsec)
1232 putkey(mpage, mlink->fsec, TYPE_sec);
1233 putkey(mpage, '\0' == *mlink->arch ?
1234 any : mlink->arch, TYPE_arch);
1235 putkey(mpage, mlink->name, NAME_FILE);
1238 assert(mpage->desc == NULL);
1239 if (man != NULL && man->macroset == MACROSET_MDOC)
1240 parse_mdoc(mpage, &man->meta, man->first);
1241 else if (man != NULL)
1242 parse_man(mpage, &man->meta, man->first);
1244 parse_cat(mpage, fd);
1245 if (mpage->desc == NULL)
1246 mpage->desc = mandoc_strdup(mpage->mlinks->name);
1248 if (warnings && !use_all)
1249 for (mlink = mpage->mlinks; mlink;
1250 mlink = mlink->next)
1251 mlink_check(mpage, mlink);
1254 mlink = mpage->mlinks;
1257 ohash_delete(&strings);
1258 ohash_delete(&names);
1259 mpage = ohash_next(&mpages, &pslot);
1263 SQL_EXEC("END TRANSACTION");
1270 const char *name, *sec, *arch, *key;
1272 sqlite3_prepare_v2(db,
1273 "SELECT name, sec, arch, key FROM ("
1274 "SELECT name AS key, pageid FROM names "
1275 "WHERE bits & ? AND NOT EXISTS ("
1276 "SELECT pageid FROM mlinks "
1277 "WHERE mlinks.pageid == names.pageid "
1278 "AND mlinks.name == names.name"
1281 "SELECT sec, arch, name, pageid FROM mlinks "
1283 ") USING (pageid);",
1286 if (sqlite3_bind_int64(stmt, 1, NAME_TITLE) != SQLITE_OK)
1287 say("", "%s", sqlite3_errmsg(db));
1289 while (sqlite3_step(stmt) == SQLITE_ROW) {
1290 name = (const char *)sqlite3_column_text(stmt, 0);
1291 sec = (const char *)sqlite3_column_text(stmt, 1);
1292 arch = (const char *)sqlite3_column_text(stmt, 2);
1293 key = (const char *)sqlite3_column_text(stmt, 3);
1294 say("", "%s(%s%s%s) lacks mlink \"%s\"", name, sec,
1295 '\0' == *arch ? "" : "/",
1296 '\0' == *arch ? "" : arch, key);
1298 sqlite3_finalize(stmt);
1302 parse_cat(struct mpage *mpage, int fd)
1305 char *line, *p, *title;
1306 size_t linesz, plen, titlesz;
1310 stream = (-1 == fd) ?
1311 fopen(mpage->mlinks->file, "r") :
1313 if (NULL == stream) {
1317 say(mpage->mlinks->file, "&fopen");
1324 /* Skip to first blank line. */
1326 while (getline(&line, &linesz, stream) != -1)
1331 * Assume the first line that is not indented
1332 * is the first section header. Skip to it.
1335 while (getline(&line, &linesz, stream) != -1)
1336 if (*line != '\n' && *line != ' ')
1340 * Read up until the next section into a buffer.
1341 * Strip the leading and trailing newline from each read line,
1342 * appending a trailing space.
1343 * Ignore empty (whitespace-only) lines.
1349 while ((len = getline(&line, &linesz, stream)) != -1) {
1353 while (isspace((unsigned char)line[offs]))
1355 if (line[offs] == '\0')
1357 title = mandoc_realloc(title, titlesz + len - offs);
1358 memcpy(title + titlesz, line + offs, len - offs);
1359 titlesz += len - offs;
1360 title[titlesz - 1] = ' ';
1365 * If no page content can be found, or the input line
1366 * is already the next section header, or there is no
1367 * trailing newline, reuse the page title as the page
1371 if (NULL == title || '\0' == *title) {
1373 say(mpage->mlinks->file,
1374 "Cannot find NAME section");
1380 title[titlesz - 1] = '\0';
1383 * Skip to the first dash.
1384 * Use the remaining line as the description (no more than 70
1388 if (NULL != (p = strstr(title, "- "))) {
1389 for (p += 2; ' ' == *p || '\b' == *p; p++)
1390 /* Skip to next word. */ ;
1393 say(mpage->mlinks->file,
1394 "No dash in title line");
1400 /* Strip backspace-encoding from line. */
1402 while (NULL != (line = memchr(p, '\b', plen))) {
1405 memmove(line, line + 1, plen--);
1408 memmove(line - 1, line + 1, plen - len);
1412 mpage->desc = mandoc_strdup(p);
1418 * Put a type/word pair into the word database for this particular file.
1421 putkey(const struct mpage *mpage, char *value, uint64_t type)
1425 assert(NULL != value);
1426 if (TYPE_arch == type)
1427 for (cp = value; *cp; cp++)
1428 if (isupper((unsigned char)*cp))
1429 *cp = _tolower((unsigned char)*cp);
1430 putkeys(mpage, value, strlen(value), type);
1434 * Grok all nodes at or below a certain mdoc node into putkey().
1437 putmdockey(const struct mpage *mpage,
1438 const struct roff_node *n, uint64_t m)
1441 for ( ; NULL != n; n = n->next) {
1442 if (NULL != n->child)
1443 putmdockey(mpage, n->child, m);
1444 if (n->type == ROFFT_TEXT)
1445 putkey(mpage, n->string, m);
1450 parse_man(struct mpage *mpage, const struct roff_meta *meta,
1451 const struct roff_node *n)
1453 const struct roff_node *head, *body;
1454 char *start, *title;
1462 * We're only searching for one thing: the first text child in
1463 * the BODY of a NAME section. Since we don't keep track of
1464 * sections in -man, run some hoops to find out whether we're in
1465 * the correct section or not.
1468 if (n->type == ROFFT_BODY && n->tok == MAN_SH) {
1470 if ((head = body->parent->head) != NULL &&
1471 (head = head->child) != NULL &&
1472 head->next == NULL &&
1473 head->type == ROFFT_TEXT &&
1474 strcmp(head->string, "NAME") == 0 &&
1475 body->child != NULL) {
1478 * Suck the entire NAME section into memory.
1479 * Yes, we might run away.
1480 * But too many manuals have big, spread-out
1481 * NAME sections over many lines.
1485 deroff(&title, body);
1490 * Go through a special heuristic dance here.
1491 * Conventionally, one or more manual names are
1492 * comma-specified prior to a whitespace, then a
1493 * dash, then a description. Try to puzzle out
1494 * the name parts here.
1499 sz = strcspn(start, " ,");
1500 if ('\0' == start[sz])
1507 * Assume a stray trailing comma in the
1508 * name list if a name begins with a dash.
1511 if ('-' == start[0] ||
1512 ('\\' == start[0] && '-' == start[1]))
1515 putkey(mpage, start, NAME_TITLE);
1516 if ( ! (mpage->name_head_done ||
1517 strcasecmp(start, meta->title))) {
1518 putkey(mpage, start, NAME_HEAD);
1519 mpage->name_head_done = 1;
1527 assert(',' == byte);
1529 while (' ' == *start)
1533 if (start == title) {
1534 putkey(mpage, start, NAME_TITLE);
1535 if ( ! (mpage->name_head_done ||
1536 strcasecmp(start, meta->title))) {
1537 putkey(mpage, start, NAME_HEAD);
1538 mpage->name_head_done = 1;
1544 while (isspace((unsigned char)*start))
1547 if (0 == strncmp(start, "-", 1))
1549 else if (0 == strncmp(start, "\\-\\-", 4))
1551 else if (0 == strncmp(start, "\\-", 2))
1553 else if (0 == strncmp(start, "\\(en", 4))
1555 else if (0 == strncmp(start, "\\(em", 4))
1558 while (' ' == *start)
1561 mpage->desc = mandoc_strdup(start);
1567 for (n = n->child; n; n = n->next) {
1568 if (NULL != mpage->desc)
1570 parse_man(mpage, meta, n);
1575 parse_mdoc(struct mpage *mpage, const struct roff_meta *meta,
1576 const struct roff_node *n)
1580 for (n = n->child; NULL != n; n = n->next) {
1587 if (NULL != mdocs[n->tok].fp)
1588 if (0 == (*mdocs[n->tok].fp)(mpage, meta, n))
1590 if (mdocs[n->tok].mask)
1591 putmdockey(mpage, n->child,
1592 mdocs[n->tok].mask);
1595 assert(n->type != ROFFT_ROOT);
1598 if (NULL != n->child)
1599 parse_mdoc(mpage, meta, n);
1604 parse_mdoc_Fd(struct mpage *mpage, const struct roff_meta *meta,
1605 const struct roff_node *n)
1610 if (SEC_SYNOPSIS != n->sec ||
1611 NULL == (n = n->child) ||
1612 n->type != ROFFT_TEXT)
1616 * Only consider those `Fd' macro fields that begin with an
1617 * "inclusion" token (versus, e.g., #define).
1620 if (strcmp("#include", n->string))
1623 if ((n = n->next) == NULL || n->type != ROFFT_TEXT)
1627 * Strip away the enclosing angle brackets and make sure we're
1632 if ('<' == *start || '"' == *start)
1635 if (0 == (sz = strlen(start)))
1638 end = &start[(int)sz - 1];
1639 if ('>' == *end || '"' == *end)
1643 putkeys(mpage, start, end - start + 1, TYPE_In);
1648 parse_mdoc_fname(struct mpage *mpage, const struct roff_node *n)
1653 if (n->type != ROFFT_TEXT)
1656 /* Skip function pointer punctuation. */
1659 while (*cp == '(' || *cp == '*')
1661 sz = strcspn(cp, "()");
1663 putkeys(mpage, cp, sz, TYPE_Fn);
1664 if (n->sec == SEC_SYNOPSIS)
1665 putkeys(mpage, cp, sz, NAME_SYN);
1669 parse_mdoc_Fn(struct mpage *mpage, const struct roff_meta *meta,
1670 const struct roff_node *n)
1673 if (n->child == NULL)
1676 parse_mdoc_fname(mpage, n->child);
1678 for (n = n->child->next; n != NULL; n = n->next)
1679 if (n->type == ROFFT_TEXT)
1680 putkey(mpage, n->string, TYPE_Fa);
1686 parse_mdoc_Fo(struct mpage *mpage, const struct roff_meta *meta,
1687 const struct roff_node *n)
1690 if (n->type != ROFFT_HEAD)
1693 if (n->child != NULL)
1694 parse_mdoc_fname(mpage, n->child);
1700 parse_mdoc_Va(struct mpage *mpage, const struct roff_meta *meta,
1701 const struct roff_node *n)
1705 if (n->type != ROFFT_ELEM && n->type != ROFFT_BODY)
1708 if (n->child != NULL &&
1709 n->child->next == NULL &&
1710 n->child->type == ROFFT_TEXT)
1716 putkey(mpage, cp, TYPE_Vt | (n->tok == MDOC_Va ||
1717 n->type == ROFFT_BODY ? TYPE_Va : 0));
1725 parse_mdoc_Xr(struct mpage *mpage, const struct roff_meta *meta,
1726 const struct roff_node *n)
1730 if (NULL == (n = n->child))
1733 if (NULL == n->next) {
1734 putkey(mpage, n->string, TYPE_Xr);
1738 mandoc_asprintf(&cp, "%s(%s)", n->string, n->next->string);
1739 putkey(mpage, cp, TYPE_Xr);
1745 parse_mdoc_Nd(struct mpage *mpage, const struct roff_meta *meta,
1746 const struct roff_node *n)
1749 if (n->type == ROFFT_BODY)
1750 deroff(&mpage->desc, n);
1755 parse_mdoc_Nm(struct mpage *mpage, const struct roff_meta *meta,
1756 const struct roff_node *n)
1759 if (SEC_NAME == n->sec)
1760 putmdockey(mpage, n->child, NAME_TITLE);
1761 else if (n->sec == SEC_SYNOPSIS && n->type == ROFFT_HEAD) {
1762 if (n->child == NULL)
1763 putkey(mpage, meta->name, NAME_SYN);
1765 putmdockey(mpage, n->child, NAME_SYN);
1767 if ( ! (mpage->name_head_done ||
1768 n->child == NULL || n->child->string == NULL ||
1769 strcasecmp(n->child->string, meta->title))) {
1770 putkey(mpage, n->child->string, ROFFT_HEAD);
1771 mpage->name_head_done = 1;
1777 parse_mdoc_Sh(struct mpage *mpage, const struct roff_meta *meta,
1778 const struct roff_node *n)
1781 return n->sec == SEC_CUSTOM && n->type == ROFFT_HEAD;
1785 parse_mdoc_head(struct mpage *mpage, const struct roff_meta *meta,
1786 const struct roff_node *n)
1789 return n->type == ROFFT_HEAD;
1793 * Add a string to the hash table for the current manual.
1794 * Each string has a bitmask telling which macros it belongs to.
1795 * When we finish the manual, we'll dump the table.
1798 putkeys(const struct mpage *mpage, char *cp, size_t sz, uint64_t v)
1809 mustfree = render_string(&cp, &sz);
1815 name_mask &= ~NAME_FIRST;
1817 say(mpage->mlinks->file,
1818 "Adding name %*s, bits=%d", sz, cp, v);
1822 for (i = 0; i < mansearch_keymax; i++)
1823 if ((uint64_t)1 << i & v)
1824 say(mpage->mlinks->file,
1825 "Adding key %s=%*s",
1826 mansearch_keynames[i], sz, cp);
1830 slot = ohash_qlookupi(htab, cp, &end);
1831 s = ohash_find(htab, slot);
1833 if (NULL != s && mpage == s->mpage) {
1836 } else if (NULL == s) {
1837 s = mandoc_calloc(1, sizeof(struct str) + sz + 1);
1838 memcpy(s->key, cp, sz);
1839 ohash_insert(htab, slot, s);
1849 * Take a Unicode codepoint and produce its UTF-8 encoding.
1850 * This isn't the best way to do this, but it works.
1851 * The magic numbers are from the UTF-8 packaging.
1852 * They're not as scary as they seem: read the UTF-8 spec for details.
1855 utf8(unsigned int cp, char out[7])
1860 if (cp <= 0x0000007F) {
1863 } else if (cp <= 0x000007FF) {
1865 out[0] = (cp >> 6 & 31) | 192;
1866 out[1] = (cp & 63) | 128;
1867 } else if (cp <= 0x0000FFFF) {
1869 out[0] = (cp >> 12 & 15) | 224;
1870 out[1] = (cp >> 6 & 63) | 128;
1871 out[2] = (cp & 63) | 128;
1872 } else if (cp <= 0x001FFFFF) {
1874 out[0] = (cp >> 18 & 7) | 240;
1875 out[1] = (cp >> 12 & 63) | 128;
1876 out[2] = (cp >> 6 & 63) | 128;
1877 out[3] = (cp & 63) | 128;
1878 } else if (cp <= 0x03FFFFFF) {
1880 out[0] = (cp >> 24 & 3) | 248;
1881 out[1] = (cp >> 18 & 63) | 128;
1882 out[2] = (cp >> 12 & 63) | 128;
1883 out[3] = (cp >> 6 & 63) | 128;
1884 out[4] = (cp & 63) | 128;
1885 } else if (cp <= 0x7FFFFFFF) {
1887 out[0] = (cp >> 30 & 1) | 252;
1888 out[1] = (cp >> 24 & 63) | 128;
1889 out[2] = (cp >> 18 & 63) | 128;
1890 out[3] = (cp >> 12 & 63) | 128;
1891 out[4] = (cp >> 6 & 63) | 128;
1892 out[5] = (cp & 63) | 128;
1901 * If the string contains escape sequences,
1902 * replace it with an allocated rendering and return 1,
1903 * such that the caller can free it after use.
1904 * Otherwise, do nothing and return 0.
1907 render_string(char **public, size_t *psz)
1909 const char *src, *scp, *addcp, *seq;
1911 size_t ssz, dsz, addsz;
1912 char utfbuf[7], res[6];
1913 int seqlen, unicode;
1917 res[2] = ASCII_NBRSP;
1918 res[3] = ASCII_HYPH;
1919 res[4] = ASCII_BREAK;
1922 src = scp = *public;
1927 while (scp < src + *psz) {
1929 /* Leave normal characters unchanged. */
1931 if (strchr(res, *scp) == NULL) {
1939 * Found something that requires replacing,
1940 * make sure we have a destination buffer.
1944 dst = mandoc_malloc(ssz + 1);
1946 memcpy(dst, src, dsz);
1949 /* Handle single-char special characters. */
1970 * Found an escape sequence.
1971 * Read past the slash, then parse it.
1972 * Ignore everything except characters.
1976 if (mandoc_escape(&scp, &seq, &seqlen) != ESCAPE_SPECIAL)
1980 * Render the special character
1981 * as either UTF-8 or ASCII.
1985 unicode = mchars_spec2cp(seq, seqlen);
1988 addsz = utf8(unicode, utfbuf);
1993 addcp = mchars_spec2str(seq, seqlen, &addsz);
1996 if (*addcp == ASCII_NBRSP) {
2002 /* Copy the rendered glyph into the stream. */
2005 dst = mandoc_realloc(dst, ssz + 1);
2006 memcpy(dst + dsz, addcp, addsz);
2014 /* Trim trailing whitespace and NUL-terminate. */
2016 while (*psz > 0 && (*public)[*psz - 1] == ' ')
2019 (*public)[*psz] = '\0';
2026 dbadd_mlink(const struct mlink *mlink)
2031 SQL_BIND_TEXT(stmts[STMT_INSERT_LINK], i, mlink->dsec);
2032 SQL_BIND_TEXT(stmts[STMT_INSERT_LINK], i, mlink->arch);
2033 SQL_BIND_TEXT(stmts[STMT_INSERT_LINK], i, mlink->name);
2034 SQL_BIND_INT64(stmts[STMT_INSERT_LINK], i, mlink->mpage->pageid);
2035 SQL_STEP(stmts[STMT_INSERT_LINK]);
2036 sqlite3_reset(stmts[STMT_INSERT_LINK]);
2040 dbadd_mlink_name(const struct mlink *mlink)
2048 SQL_BIND_INT64(stmts[STMT_SELECT_NAME], i, mlink->mpage->pageid);
2049 bits = NAME_FILE & NAME_MASK;
2050 if (sqlite3_step(stmts[STMT_SELECT_NAME]) == SQLITE_ROW) {
2051 bits |= sqlite3_column_int64(stmts[STMT_SELECT_NAME], 0);
2052 sqlite3_reset(stmts[STMT_SELECT_NAME]);
2056 SQL_BIND_INT64(stmts[STMT_INSERT_NAME], i, bits);
2057 SQL_BIND_TEXT(stmts[STMT_INSERT_NAME], i, mlink->name);
2058 SQL_BIND_INT64(stmts[STMT_INSERT_NAME], i, mlink->mpage->pageid);
2059 SQL_STEP(stmts[STMT_INSERT_NAME]);
2060 sqlite3_reset(stmts[STMT_INSERT_NAME]);
2064 * Flush the current page's terms (and their bits) into the database.
2065 * Wrap the entire set of additions in a transaction to make sqlite be a
2067 * Also, handle escape sequences at the last possible moment.
2070 dbadd(struct mpage *mpage)
2072 struct mlink *mlink;
2079 mlink = mpage->mlinks;
2082 for (key = ohash_first(&names, &slot); NULL != key;
2083 key = ohash_next(&names, &slot))
2085 for (key = ohash_first(&strings, &slot); NULL != key;
2086 key = ohash_next(&strings, &slot))
2090 while (NULL != mlink) {
2091 fputs(mlink->name, stdout);
2092 if (NULL == mlink->next ||
2093 strcmp(mlink->dsec, mlink->next->dsec) ||
2094 strcmp(mlink->fsec, mlink->next->fsec) ||
2095 strcmp(mlink->arch, mlink->next->arch)) {
2097 if ('\0' == *mlink->dsec)
2098 fputs(mlink->fsec, stdout);
2100 fputs(mlink->dsec, stdout);
2101 if ('\0' != *mlink->arch)
2102 printf("/%s", mlink->arch);
2105 mlink = mlink->next;
2107 fputs(", ", stdout);
2109 printf(" - %s\n", mpage->desc);
2114 say(mlink->file, "Adding to database");
2118 mustfree = render_string(&cp, &i);
2120 SQL_BIND_TEXT(stmts[STMT_INSERT_PAGE], i, cp);
2121 SQL_BIND_INT(stmts[STMT_INSERT_PAGE], i, mpage->form);
2122 SQL_STEP(stmts[STMT_INSERT_PAGE]);
2123 mpage->pageid = sqlite3_last_insert_rowid(db);
2124 sqlite3_reset(stmts[STMT_INSERT_PAGE]);
2128 while (NULL != mlink) {
2130 mlink = mlink->next;
2132 mlink = mpage->mlinks;
2134 for (key = ohash_first(&names, &slot); NULL != key;
2135 key = ohash_next(&names, &slot)) {
2136 assert(key->mpage == mpage);
2138 SQL_BIND_INT64(stmts[STMT_INSERT_NAME], i, key->mask);
2139 SQL_BIND_TEXT(stmts[STMT_INSERT_NAME], i, key->key);
2140 SQL_BIND_INT64(stmts[STMT_INSERT_NAME], i, mpage->pageid);
2141 SQL_STEP(stmts[STMT_INSERT_NAME]);
2142 sqlite3_reset(stmts[STMT_INSERT_NAME]);
2145 for (key = ohash_first(&strings, &slot); NULL != key;
2146 key = ohash_next(&strings, &slot)) {
2147 assert(key->mpage == mpage);
2149 SQL_BIND_INT64(stmts[STMT_INSERT_KEY], i, key->mask);
2150 SQL_BIND_TEXT(stmts[STMT_INSERT_KEY], i, key->key);
2151 SQL_BIND_INT64(stmts[STMT_INSERT_KEY], i, mpage->pageid);
2152 SQL_STEP(stmts[STMT_INSERT_KEY]);
2153 sqlite3_reset(stmts[STMT_INSERT_KEY]);
2161 struct mpage *mpage;
2162 struct mlink *mlink;
2167 SQL_EXEC("BEGIN TRANSACTION");
2169 for (mpage = ohash_first(&mpages, &slot); NULL != mpage;
2170 mpage = ohash_next(&mpages, &slot)) {
2171 mlink = mpage->mlinks;
2173 say(mlink->file, "Deleting from database");
2176 for ( ; NULL != mlink; mlink = mlink->next) {
2178 SQL_BIND_TEXT(stmts[STMT_DELETE_PAGE],
2180 SQL_BIND_TEXT(stmts[STMT_DELETE_PAGE],
2182 SQL_BIND_TEXT(stmts[STMT_DELETE_PAGE],
2184 SQL_STEP(stmts[STMT_DELETE_PAGE]);
2185 sqlite3_reset(stmts[STMT_DELETE_PAGE]);
2190 SQL_EXEC("END TRANSACTION");
2194 * Close an existing database and its prepared statements.
2195 * If "real" is not set, rename the temporary file into the real one.
2207 for (i = 0; i < STMT__MAX; i++) {
2208 sqlite3_finalize(stmts[i]);
2218 if ('\0' == *tempfilename) {
2219 if (-1 == rename(MANDOC_DB "~", MANDOC_DB)) {
2220 exitcode = (int)MANDOCLEVEL_SYSERR;
2221 say(MANDOC_DB, "&rename");
2226 switch (child = fork()) {
2228 exitcode = (int)MANDOCLEVEL_SYSERR;
2229 say("", "&fork cmp");
2232 execlp("cmp", "cmp", "-s",
2233 tempfilename, MANDOC_DB, (char *)NULL);
2234 say("", "&exec cmp");
2239 if (-1 == waitpid(child, &status, 0)) {
2240 exitcode = (int)MANDOCLEVEL_SYSERR;
2241 say("", "&wait cmp");
2242 } else if (WIFSIGNALED(status)) {
2243 exitcode = (int)MANDOCLEVEL_SYSERR;
2244 say("", "cmp died from signal %d", WTERMSIG(status));
2245 } else if (WEXITSTATUS(status)) {
2246 exitcode = (int)MANDOCLEVEL_SYSERR;
2248 "Data changed, but cannot replace database");
2251 *strrchr(tempfilename, '/') = '\0';
2252 switch (child = fork()) {
2254 exitcode = (int)MANDOCLEVEL_SYSERR;
2255 say("", "&fork rm");
2258 execlp("rm", "rm", "-rf", tempfilename, (char *)NULL);
2259 say("", "&exec rm");
2260 exit((int)MANDOCLEVEL_SYSERR);
2264 if (-1 == waitpid(child, &status, 0)) {
2265 exitcode = (int)MANDOCLEVEL_SYSERR;
2266 say("", "&wait rm");
2267 } else if (WIFSIGNALED(status) || WEXITSTATUS(status)) {
2268 exitcode = (int)MANDOCLEVEL_SYSERR;
2269 say("", "%s: Cannot remove temporary directory",
2275 * This is straightforward stuff.
2276 * Open a database connection to a "temporary" database, then open a set
2277 * of prepared statements we'll use over and over again.
2278 * If "real" is set, we use the existing database; if not, we truncate a
2280 * Must be matched by dbclose().
2291 *tempfilename = '\0';
2292 ofl = SQLITE_OPEN_READWRITE;
2295 rc = sqlite3_open_v2(MANDOC_DB, &db, ofl, NULL);
2296 if (SQLITE_OK != rc) {
2297 exitcode = (int)MANDOCLEVEL_SYSERR;
2298 if (SQLITE_CANTOPEN != rc)
2299 say(MANDOC_DB, "%s", sqlite3_errstr(rc));
2302 goto prepare_statements;
2305 ofl |= SQLITE_OPEN_CREATE | SQLITE_OPEN_EXCLUSIVE;
2307 remove(MANDOC_DB "~");
2308 rc = sqlite3_open_v2(MANDOC_DB "~", &db, ofl, NULL);
2309 if (SQLITE_OK == rc)
2311 if (MPARSE_QUICK & mparse_options) {
2312 exitcode = (int)MANDOCLEVEL_SYSERR;
2313 say(MANDOC_DB "~", "%s", sqlite3_errstr(rc));
2317 (void)strlcpy(tempfilename, "/tmp/mandocdb.XXXXXX",
2318 sizeof(tempfilename));
2319 if (NULL == mkdtemp(tempfilename)) {
2320 exitcode = (int)MANDOCLEVEL_SYSERR;
2321 say("", "&%s", tempfilename);
2324 (void)strlcat(tempfilename, "/" MANDOC_DB,
2325 sizeof(tempfilename));
2326 rc = sqlite3_open_v2(tempfilename, &db, ofl, NULL);
2327 if (SQLITE_OK != rc) {
2328 exitcode = (int)MANDOCLEVEL_SYSERR;
2329 say("", "%s: %s", tempfilename, sqlite3_errstr(rc));
2334 sql = "CREATE TABLE \"mpages\" (\n"
2335 " \"desc\" TEXT NOT NULL,\n"
2336 " \"form\" INTEGER NOT NULL,\n"
2337 " \"pageid\" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL\n"
2340 "CREATE TABLE \"mlinks\" (\n"
2341 " \"sec\" TEXT NOT NULL,\n"
2342 " \"arch\" TEXT NOT NULL,\n"
2343 " \"name\" TEXT NOT NULL,\n"
2344 " \"pageid\" INTEGER NOT NULL REFERENCES mpages(pageid) "
2345 "ON DELETE CASCADE\n"
2347 "CREATE INDEX mlinks_pageid_idx ON mlinks (pageid);\n"
2349 "CREATE TABLE \"names\" (\n"
2350 " \"bits\" INTEGER NOT NULL,\n"
2351 " \"name\" TEXT NOT NULL,\n"
2352 " \"pageid\" INTEGER NOT NULL REFERENCES mpages(pageid) "
2353 "ON DELETE CASCADE,\n"
2354 " UNIQUE (\"name\", \"pageid\") ON CONFLICT REPLACE\n"
2357 "CREATE TABLE \"keys\" (\n"
2358 " \"bits\" INTEGER NOT NULL,\n"
2359 " \"key\" TEXT NOT NULL,\n"
2360 " \"pageid\" INTEGER NOT NULL REFERENCES mpages(pageid) "
2361 "ON DELETE CASCADE\n"
2363 "CREATE INDEX keys_pageid_idx ON keys (pageid);\n";
2365 if (SQLITE_OK != sqlite3_exec(db, sql, NULL, NULL, NULL)) {
2366 exitcode = (int)MANDOCLEVEL_SYSERR;
2367 say(MANDOC_DB, "%s", sqlite3_errmsg(db));
2373 if (SQLITE_OK != sqlite3_exec(db,
2374 "PRAGMA foreign_keys = ON", NULL, NULL, NULL)) {
2375 exitcode = (int)MANDOCLEVEL_SYSERR;
2376 say(MANDOC_DB, "PRAGMA foreign_keys: %s",
2377 sqlite3_errmsg(db));
2382 sql = "DELETE FROM mpages WHERE pageid IN "
2383 "(SELECT pageid FROM mlinks WHERE "
2384 "sec=? AND arch=? AND name=?)";
2385 sqlite3_prepare_v2(db, sql, -1, &stmts[STMT_DELETE_PAGE], NULL);
2386 sql = "INSERT INTO mpages "
2387 "(desc,form) VALUES (?,?)";
2388 sqlite3_prepare_v2(db, sql, -1, &stmts[STMT_INSERT_PAGE], NULL);
2389 sql = "INSERT INTO mlinks "
2390 "(sec,arch,name,pageid) VALUES (?,?,?,?)";
2391 sqlite3_prepare_v2(db, sql, -1, &stmts[STMT_INSERT_LINK], NULL);
2392 sql = "SELECT bits FROM names where pageid = ?";
2393 sqlite3_prepare_v2(db, sql, -1, &stmts[STMT_SELECT_NAME], NULL);
2394 sql = "INSERT INTO names "
2395 "(bits,name,pageid) VALUES (?,?,?)";
2396 sqlite3_prepare_v2(db, sql, -1, &stmts[STMT_INSERT_NAME], NULL);
2397 sql = "INSERT INTO keys "
2398 "(bits,key,pageid) VALUES (?,?,?)";
2399 sqlite3_prepare_v2(db, sql, -1, &stmts[STMT_INSERT_KEY], NULL);
2403 * When opening a new database, we can turn off
2404 * synchronous mode for much better performance.
2407 if (real && SQLITE_OK != sqlite3_exec(db,
2408 "PRAGMA synchronous = OFF", NULL, NULL, NULL)) {
2409 exitcode = (int)MANDOCLEVEL_SYSERR;
2410 say(MANDOC_DB, "PRAGMA synchronous: %s",
2411 sqlite3_errmsg(db));
2421 set_basedir(const char *targetdir, int report_baddir)
2423 static char startdir[PATH_MAX];
2424 static int getcwd_status; /* 1 = ok, 2 = failure */
2425 static int chdir_status; /* 1 = changed directory */
2429 * Remember the original working directory, if possible.
2430 * This will be needed if the second or a later directory
2431 * on the command line is given as a relative path.
2432 * Do not error out if the current directory is not
2433 * searchable: Maybe it won't be needed after all.
2435 if (0 == getcwd_status) {
2436 if (NULL == getcwd(startdir, sizeof(startdir))) {
2438 (void)strlcpy(startdir, strerror(errno),
2445 * We are leaving the old base directory.
2446 * Do not use it any longer, not even for messages.
2451 * If and only if the directory was changed earlier and
2452 * the next directory to process is given as a relative path,
2453 * first go back, or bail out if that is impossible.
2455 if (chdir_status && '/' != *targetdir) {
2456 if (2 == getcwd_status) {
2457 exitcode = (int)MANDOCLEVEL_SYSERR;
2458 say("", "getcwd: %s", startdir);
2461 if (-1 == chdir(startdir)) {
2462 exitcode = (int)MANDOCLEVEL_SYSERR;
2463 say("", "&chdir %s", startdir);
2469 * Always resolve basedir to the canonicalized absolute
2470 * pathname and append a trailing slash, such that
2471 * we can reliably check whether files are inside.
2473 if (NULL == realpath(targetdir, basedir)) {
2474 if (report_baddir || errno != ENOENT) {
2475 exitcode = (int)MANDOCLEVEL_BADARG;
2476 say("", "&%s: realpath", targetdir);
2479 } else if (-1 == chdir(basedir)) {
2480 if (report_baddir || errno != ENOENT) {
2481 exitcode = (int)MANDOCLEVEL_BADARG;
2487 cp = strchr(basedir, '\0');
2488 if ('/' != cp[-1]) {
2489 if (cp - basedir >= PATH_MAX - 1) {
2490 exitcode = (int)MANDOCLEVEL_SYSERR;
2491 say("", "Filename too long");
2501 say(const char *file, const char *format, ...)
2506 if ('\0' != *basedir)
2507 fprintf(stderr, "%s", basedir);
2508 if ('\0' != *basedir && '\0' != *file)
2511 fprintf(stderr, "%s", file);
2514 if (NULL != format) {
2527 if (NULL != format) {
2528 if ('\0' != *basedir || '\0' != *file)
2529 fputs(": ", stderr);
2530 va_start(ap, format);
2531 vfprintf(stderr, format, ap);
2535 if ('\0' != *basedir || '\0' != *file || NULL != format)
2536 fputs(": ", stderr);
2539 fputc('\n', stderr);