1 /* $Id: mansearch.c,v 1.77 2017/08/22 17:50:11 schwarze Exp $ */
3 * Copyright (c) 2012 Kristaps Dzonsons <kristaps@bsd.lv>
4 * Copyright (c) 2013-2017 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.
21 #include <sys/types.h>
40 #include "mandoc_aux.h"
41 #include "mandoc_ohash.h"
43 #include "mansearch.h"
48 struct dbm_match match; /* Match type and expression. */
49 uint64_t bits; /* Type mask. */
50 /* Used for OR and AND groups: */
51 struct expr *next; /* Next child in the parent group. */
52 struct expr *child; /* First child in this group. */
53 enum { EXPR_TERM, EXPR_OR, EXPR_AND } type;
56 const char *const mansearch_keynames[KEY_MAX] = {
57 "arch", "sec", "Xr", "Ar", "Fa", "Fl", "Dv", "Fn",
58 "Ic", "Pa", "Cm", "Li", "Em", "Cd", "Va", "Ft",
59 "Tn", "Er", "Ev", "Sy", "Sh", "In", "Ss", "Ox",
60 "An", "Mt", "St", "Bx", "At", "Nx", "Fx", "Lk",
61 "Ms", "Bsx", "Dx", "Rs", "Vt", "Lb", "Nm", "Nd"
65 static struct ohash *manmerge(struct expr *, struct ohash *);
66 static struct ohash *manmerge_term(struct expr *, struct ohash *);
67 static struct ohash *manmerge_or(struct expr *, struct ohash *);
68 static struct ohash *manmerge_and(struct expr *, struct ohash *);
69 static char *buildnames(const struct dbm_page *);
70 static char *buildoutput(size_t, struct dbm_page *);
71 static size_t lstlen(const char *, size_t);
72 static void lstcat(char *, size_t *, const char *, const char *);
73 static int lstmatch(const char *, const char *);
74 static struct expr *exprcomp(const struct mansearch *,
75 int, char *[], int *);
76 static struct expr *expr_and(const struct mansearch *,
77 int, char *[], int *);
78 static struct expr *exprterm(const struct mansearch *,
79 int, char *[], int *);
80 static void exprfree(struct expr *);
81 static int manpage_compare(const void *, const void *);
85 mansearch(const struct mansearch *search,
86 const struct manpaths *paths,
87 int argc, char *argv[],
88 struct manpage **res, size_t *sz)
93 struct dbm_page *page;
94 struct manpage *mpage;
96 size_t cur, i, maxres, outkey;
98 int argi, chdir_status, getcwd_status, im;
101 if ((e = exprcomp(search, argc, argv, &argi)) == NULL) {
111 if (search->outkey != NULL)
112 for (im = 0; im < KEY_MAX; im++)
113 if (0 == strcasecmp(search->outkey,
114 mansearch_keynames[im])) {
120 * Remember the original working directory, if possible.
121 * This will be needed if the second or a later directory
122 * is given as a relative path.
123 * Do not error out if the current directory is not
124 * searchable: Maybe it won't be needed after all.
127 if (getcwd(buf, PATH_MAX) == NULL) {
129 (void)strlcpy(buf, strerror(errno), sizeof(buf));
134 * Loop over the directories (containing databases) for us to
136 * Don't let missing/bad databases/directories phase us.
137 * In each, try to open the resident database and, if it opens,
138 * scan it for our match expression.
142 for (i = 0; i < paths->sz; i++) {
143 if (chdir_status && paths->paths[i][0] != '/') {
144 if ( ! getcwd_status) {
145 warnx("%s: getcwd: %s", paths->paths[i], buf);
147 } else if (chdir(buf) == -1) {
152 if (chdir(paths->paths[i]) == -1) {
153 warn("%s", paths->paths[i]);
158 if (dbm_open(MANDOC_DB) == -1) {
160 warn("%s/%s", paths->paths[i], MANDOC_DB);
164 if ((htab = manmerge(e, NULL)) == NULL) {
169 for (rp = ohash_first(htab, &slot); rp != NULL;
170 rp = ohash_next(htab, &slot)) {
171 page = dbm_page_get(rp->page);
173 if (lstmatch(search->sec, page->sect) == 0 ||
174 lstmatch(search->arch, page->arch) == 0 ||
175 (search->argmode == ARG_NAME &&
176 rp->bits <= (int32_t)(NAME_SYN & NAME_MASK)))
183 if (cur + 1 > maxres) {
185 *res = mandoc_reallocarray(*res,
186 maxres, sizeof(**res));
189 mandoc_asprintf(&mpage->file, "%s/%s",
190 paths->paths[i], page->file + 1);
191 if (access(chdir_status ? page->file + 1 :
192 mpage->file, R_OK) == -1) {
193 warn("%s", mpage->file);
194 warnx("outdated mandoc.db contains "
195 "bogus %s entry, run makewhatis %s",
196 page->file + 1, paths->paths[i]);
201 mpage->names = buildnames(page);
202 mpage->output = buildoutput(outkey, page);
204 mpage->bits = rp->bits;
205 mpage->sec = *page->sect - '0';
206 if (mpage->sec < 0 || mpage->sec > 9)
208 mpage->form = *page->file;
217 * In man(1) mode, prefer matches in earlier trees
218 * over matches in later trees.
221 if (cur && search->firstmatch)
225 qsort(*res, cur, sizeof(struct manpage), manpage_compare);
226 if (chdir_status && getcwd_status && chdir(buf) == -1)
230 return res != NULL || cur;
234 * Merge the results for the expression tree rooted at e
235 * into the the result list htab.
237 static struct ohash *
238 manmerge(struct expr *e, struct ohash *htab)
242 return manmerge_term(e, htab);
244 return manmerge_or(e->child, htab);
246 return manmerge_and(e->child, htab);
252 static struct ohash *
253 manmerge_term(struct expr *e, struct ohash *htab)
255 struct dbm_res res, *rp;
261 htab = mandoc_malloc(sizeof(*htab));
262 mandoc_ohash_init(htab, 4, offsetof(struct dbm_res, page));
265 for (im = 0, ib = 1; im < KEY_MAX; im++, ib <<= 1) {
266 if ((e->bits & ib) == 0)
271 dbm_page_byarch(&e->match);
274 dbm_page_bysect(&e->match);
277 dbm_page_byname(&e->match);
280 dbm_page_bydesc(&e->match);
283 dbm_page_bymacro(im - 2, &e->match);
288 * When hashing for deduplication, use the unique
289 * page ID itself instead of a hash function;
290 * that is quite efficient.
294 res = dbm_page_next();
297 slot = ohash_lookup_memory(htab,
298 (char *)&res, sizeof(res.page), res.page);
299 if ((rp = ohash_find(htab, slot)) != NULL) {
300 rp->bits |= res.bits;
303 rp = mandoc_malloc(sizeof(*rp));
305 ohash_insert(htab, slot, rp);
311 static struct ohash *
312 manmerge_or(struct expr *e, struct ohash *htab)
315 htab = manmerge(e, htab);
321 static struct ohash *
322 manmerge_and(struct expr *e, struct ohash *htab)
324 struct ohash *hand, *h1, *h2;
326 unsigned int slot1, slot2;
328 /* Evaluate the first term of the AND clause. */
330 hand = manmerge(e, NULL);
332 while ((e = e->next) != NULL) {
334 /* Evaluate the next term and prepare for ANDing. */
336 h2 = manmerge(e, NULL);
337 if (ohash_entries(h2) < ohash_entries(hand)) {
342 hand = mandoc_malloc(sizeof(*hand));
343 mandoc_ohash_init(hand, 4, offsetof(struct dbm_res, page));
345 /* Keep all pages that are in both result sets. */
347 for (res = ohash_first(h1, &slot1); res != NULL;
348 res = ohash_next(h1, &slot1)) {
349 if (ohash_find(h2, ohash_lookup_memory(h2,
350 (char *)res, sizeof(res->page),
354 ohash_insert(hand, ohash_lookup_memory(hand,
355 (char *)res, sizeof(res->page),
359 /* Discard the merged results. */
361 for (res = ohash_first(h2, &slot2); res != NULL;
362 res = ohash_next(h2, &slot2))
370 /* Merge the result of the AND into htab. */
375 for (res = ohash_first(hand, &slot1); res != NULL;
376 res = ohash_next(hand, &slot1)) {
377 slot2 = ohash_lookup_memory(htab,
378 (char *)res, sizeof(res->page), res->page);
379 if (ohash_find(htab, slot2) == NULL)
380 ohash_insert(htab, slot2, res);
385 /* Discard the merged result. */
393 mansearch_free(struct manpage *res, size_t sz)
397 for (i = 0; i < sz; i++) {
406 manpage_compare(const void *vp1, const void *vp2)
408 const struct manpage *mp1, *mp2;
409 const char *cp1, *cp2;
415 if ((diff = mp2->bits - mp1->bits) ||
416 (diff = mp1->sec - mp2->sec))
419 /* Fall back to alphabetic ordering of names. */
420 sz1 = strcspn(mp1->names, "(");
421 sz2 = strcspn(mp2->names, "(");
424 if ((diff = strncasecmp(mp1->names, mp2->names, sz1)))
427 /* For identical names and sections, prefer arch-dependent. */
428 cp1 = strchr(mp1->names + sz1, '/');
429 cp2 = strchr(mp2->names + sz2, '/');
430 return cp1 != NULL && cp2 != NULL ? strcasecmp(cp1, cp2) :
431 cp1 != NULL ? -1 : cp2 != NULL ? 1 : 0;
435 buildnames(const struct dbm_page *page)
440 sz = lstlen(page->name, 2) + 1 + lstlen(page->sect, 2) +
441 (page->arch == NULL ? 0 : 1 + lstlen(page->arch, 2)) + 2;
442 buf = mandoc_malloc(sz);
444 lstcat(buf, &i, page->name, ", ");
446 lstcat(buf, &i, page->sect, ", ");
447 if (page->arch != NULL) {
449 lstcat(buf, &i, page->arch, ", ");
458 * Count the buffer space needed to print the NUL-terminated
459 * list of NUL-terminated strings, when printing sep separator
460 * characters between strings.
463 lstlen(const char *cp, size_t sep)
467 for (sz = 0; *cp != '\0'; cp++) {
469 /* Skip names appearing only in the SYNOPSIS. */
470 if (*cp <= (char)(NAME_SYN & NAME_MASK)) {
476 /* Skip name class markers. */
480 /* Print a separator before each but the first string. */
484 /* Copy one string. */
485 while (*cp != '\0') {
494 * Print the NUL-terminated list of NUL-terminated strings
495 * into the buffer, seperating strings with sep.
498 lstcat(char *buf, size_t *i, const char *cp, const char *sep)
503 for (i_start = *i; *cp != '\0'; cp++) {
505 /* Skip names appearing only in the SYNOPSIS. */
506 if (*cp <= (char)(NAME_SYN & NAME_MASK)) {
512 /* Skip name class markers. */
516 /* Print a separator before each but the first string. */
523 /* Copy one string. */
531 * Return 1 if the string *want occurs in any of the strings
532 * in the NUL-terminated string list *have, or 0 otherwise.
533 * If either argument is NULL or empty, assume no filtering
534 * is desired and return 1.
537 lstmatch(const char *want, const char *have)
539 if (want == NULL || have == NULL || *have == '\0')
541 while (*have != '\0') {
542 if (strcasestr(have, want) != NULL)
544 have = strchr(have, '\0') + 1;
550 * Build a list of values taken by the macro im in the manual page.
553 buildoutput(size_t im, struct dbm_page *page)
555 const char *oldoutput, *sep, *input;
556 char *output, *newoutput, *value;
561 return mandoc_strdup(page->desc);
579 sz = lstlen(input, 3) + 1;
580 output = mandoc_malloc(sz);
582 lstcat(output, &i, input, " # ");
589 dbm_macro_bypage(im - 2, page->addr);
590 while ((value = dbm_macro_next()) != NULL) {
591 if (output == NULL) {
598 mandoc_asprintf(&newoutput, "%s%s%s", oldoutput, sep, value);
606 * Compile a set of string tokens into an expression.
607 * Tokens in "argv" are assumed to be individual expression atoms (e.g.,
608 * "(", "foo=bar", etc.).
611 exprcomp(const struct mansearch *search, int argc, char *argv[], int *argi)
613 struct expr *parent, *child;
614 int needterm, nested;
616 if ((nested = *argi) == argc)
619 parent = child = NULL;
620 while (*argi < argc) {
621 if (strcmp(")", argv[*argi]) == 0) {
623 warnx("missing term "
624 "before closing parenthesis");
628 warnx("ignoring unmatched right parenthesis");
632 if (strcmp("-o", argv[*argi]) == 0) {
635 warnx("ignoring -o after %s",
638 warnx("ignoring initial -o");
646 child = expr_and(search, argc, argv, argi);
649 if (parent == NULL) {
650 parent = mandoc_calloc(1, sizeof(*parent));
651 parent->type = EXPR_OR;
653 parent->child = child;
655 child->next = expr_and(search, argc, argv, argi);
658 if (needterm && *argi)
659 warnx("ignoring trailing %s", argv[*argi - 1]);
660 return parent == NULL ? child : parent;
664 expr_and(const struct mansearch *search, int argc, char *argv[], int *argi)
666 struct expr *parent, *child;
670 parent = child = NULL;
671 while (*argi < argc) {
672 if (strcmp(")", argv[*argi]) == 0) {
674 warnx("missing term "
675 "before closing parenthesis");
679 if (strcmp("-o", argv[*argi]) == 0)
681 if (strcmp("-a", argv[*argi]) == 0) {
684 warnx("ignoring -a after %s",
687 warnx("ignoring initial -a");
696 child = exprterm(search, argc, argv, argi);
702 if (parent == NULL) {
703 parent = mandoc_calloc(1, sizeof(*parent));
704 parent->type = EXPR_AND;
706 parent->child = child;
708 child->next = exprterm(search, argc, argv, argi);
709 if (child->next != NULL) {
714 if (needterm && *argi)
715 warnx("ignoring trailing %s", argv[*argi - 1]);
716 return parent == NULL ? child : parent;
720 exprterm(const struct mansearch *search, int argc, char *argv[], int *argi)
728 if (strcmp("(", argv[*argi]) == 0) {
730 e = exprcomp(search, argc, argv, argi);
732 assert(strcmp(")", argv[*argi]) == 0);
735 warnx("unclosed parenthesis");
739 if (strcmp("-i", argv[*argi]) == 0 && *argi + 1 < argc) {
745 e = mandoc_calloc(1, sizeof(*e));
751 if (search->argmode == ARG_NAME) {
753 e->match.type = DBM_EXACT;
754 e->match.str = argv[(*argi)++];
759 * Separate macro keys from search string.
760 * If needed, request regular expression handling.
763 if (search->argmode == ARG_WORD) {
765 e->match.type = DBM_REGEX;
767 mandoc_asprintf(&val, "[[:<:]]%s[[:>:]]", argv[*argi]);
769 mandoc_asprintf(&val, "\\<%s\\>", argv[*argi]);
771 mandoc_asprintf(&val,
772 "(^|[^a-zA-Z01-9_])%s([^a-zA-Z01-9_]|$)", argv[*argi]);
775 } else if ((val = strpbrk(argv[*argi], "=~")) == NULL) {
776 e->bits = TYPE_Nm | TYPE_Nd;
777 e->match.type = DBM_SUB;
778 e->match.str = argv[*argi];
780 if (val == argv[*argi])
781 e->bits = TYPE_Nm | TYPE_Nd;
783 e->match.type = DBM_SUB;
784 e->match.str = val + 1;
786 e->match.type = DBM_REGEX;
788 if (strstr(argv[*argi], "arch") != NULL)
792 /* Compile regular expressions. */
794 if (e->match.type == DBM_REGEX) {
795 e->match.re = mandoc_malloc(sizeof(*e->match.re));
796 irc = regcomp(e->match.re, val,
797 REG_EXTENDED | REG_NOSUB | (cs ? 0 : REG_ICASE));
799 regerror(irc, e->match.re, errbuf, sizeof(errbuf));
800 warnx("regcomp /%s/: %s", val, errbuf);
802 if (search->argmode == ARG_WORD)
818 * Parse out all possible fields.
819 * If the field doesn't resolve, bail.
822 while (NULL != (key = strsep(&argv[*argi], ","))) {
825 for (i = 0, iterbit = 1; i < KEY_MAX; i++, iterbit <<= 1) {
826 if (0 == strcasecmp(key, mansearch_keynames[i])) {
832 if (strcasecmp(key, "any"))
833 warnx("treating unknown key "
834 "\"%s\" as \"any\"", key);
844 exprfree(struct expr *e)
848 if (e->child != NULL)