]> git.cameronkatri.com Git - mandoc.git/blob - mansearch.c
The .Dd and .TH macros must interrupt .ce, too;
[mandoc.git] / mansearch.c
1 /* $OpenBSD: mansearch.c,v 1.50 2016/07/09 15:23:36 schwarze Exp $ */
2 /*
3 * Copyright (c) 2012 Kristaps Dzonsons <kristaps@bsd.lv>
4 * Copyright (c) 2013-2017 Ingo Schwarze <schwarze@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE 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.
17 */
18 #include "config.h"
19
20 #include <sys/mman.h>
21 #include <sys/types.h>
22
23 #include <assert.h>
24 #if HAVE_ERR
25 #include <err.h>
26 #endif
27 #include <errno.h>
28 #include <fcntl.h>
29 #include <glob.h>
30 #include <limits.h>
31 #include <regex.h>
32 #include <stdio.h>
33 #include <stdint.h>
34 #include <stddef.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <unistd.h>
38
39 #include "mandoc.h"
40 #include "mandoc_aux.h"
41 #include "mandoc_ohash.h"
42 #include "manconf.h"
43 #include "mansearch.h"
44 #include "dbm.h"
45
46 struct expr {
47 /* Used for terms: */
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;
54 };
55
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"
62 };
63
64
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 *);
82
83
84 int
85 mansearch(const struct mansearch *search,
86 const struct manpaths *paths,
87 int argc, char *argv[],
88 struct manpage **res, size_t *sz)
89 {
90 char buf[PATH_MAX];
91 struct dbm_res *rp;
92 struct expr *e;
93 struct dbm_page *page;
94 struct manpage *mpage;
95 struct ohash *htab;
96 size_t cur, i, maxres, outkey;
97 unsigned int slot;
98 int argi, chdir_status, getcwd_status, im;
99
100 argi = 0;
101 if ((e = exprcomp(search, argc, argv, &argi)) == NULL) {
102 *sz = 0;
103 return 0;
104 }
105
106 cur = maxres = 0;
107 if (res != NULL)
108 *res = NULL;
109
110 outkey = KEY_Nd;
111 if (search->outkey != NULL)
112 for (im = 0; im < KEY_MAX; im++)
113 if (0 == strcasecmp(search->outkey,
114 mansearch_keynames[im])) {
115 outkey = im;
116 break;
117 }
118
119 /*
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.
125 */
126
127 if (getcwd(buf, PATH_MAX) == NULL) {
128 getcwd_status = 0;
129 (void)strlcpy(buf, strerror(errno), sizeof(buf));
130 } else
131 getcwd_status = 1;
132
133 /*
134 * Loop over the directories (containing databases) for us to
135 * search.
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.
139 */
140
141 chdir_status = 0;
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);
146 continue;
147 } else if (chdir(buf) == -1) {
148 warn("%s", buf);
149 continue;
150 }
151 }
152 if (chdir(paths->paths[i]) == -1) {
153 warn("%s", paths->paths[i]);
154 continue;
155 }
156 chdir_status = 1;
157
158 if (dbm_open(MANDOC_DB) == -1) {
159 if (errno != ENOENT)
160 warn("%s/%s", paths->paths[i], MANDOC_DB);
161 continue;
162 }
163
164 if ((htab = manmerge(e, NULL)) == NULL) {
165 dbm_close();
166 continue;
167 }
168
169 for (rp = ohash_first(htab, &slot); rp != NULL;
170 rp = ohash_next(htab, &slot)) {
171 page = dbm_page_get(rp->page);
172
173 if (lstmatch(search->sec, page->sect) == 0 ||
174 lstmatch(search->arch, page->arch) == 0)
175 continue;
176
177 if (res == NULL) {
178 cur = 1;
179 break;
180 }
181 if (cur + 1 > maxres) {
182 maxres += 1024;
183 *res = mandoc_reallocarray(*res,
184 maxres, sizeof(**res));
185 }
186 mpage = *res + cur;
187 mandoc_asprintf(&mpage->file, "%s/%s",
188 paths->paths[i], page->file + 1);
189 mpage->names = buildnames(page);
190 mpage->output = buildoutput(outkey, page);
191 mpage->ipath = i;
192 mpage->bits = rp->bits;
193 mpage->sec = *page->sect - '0';
194 if (mpage->sec < 0 || mpage->sec > 9)
195 mpage->sec = 10;
196 mpage->form = *page->file;
197 free(rp);
198 cur++;
199 }
200 ohash_delete(htab);
201 free(htab);
202 dbm_close();
203
204 /*
205 * In man(1) mode, prefer matches in earlier trees
206 * over matches in later trees.
207 */
208
209 if (cur && search->firstmatch)
210 break;
211 }
212 if (res != NULL)
213 qsort(*res, cur, sizeof(struct manpage), manpage_compare);
214 if (chdir_status && getcwd_status && chdir(buf) == -1)
215 warn("%s", buf);
216 exprfree(e);
217 *sz = cur;
218 return res != NULL || cur;
219 }
220
221 /*
222 * Merge the results for the expression tree rooted at e
223 * into the the result list htab.
224 */
225 static struct ohash *
226 manmerge(struct expr *e, struct ohash *htab)
227 {
228 switch (e->type) {
229 case EXPR_TERM:
230 return manmerge_term(e, htab);
231 case EXPR_OR:
232 return manmerge_or(e->child, htab);
233 case EXPR_AND:
234 return manmerge_and(e->child, htab);
235 default:
236 abort();
237 }
238 }
239
240 static struct ohash *
241 manmerge_term(struct expr *e, struct ohash *htab)
242 {
243 struct dbm_res res, *rp;
244 uint64_t ib;
245 unsigned int slot;
246 int im;
247
248 if (htab == NULL) {
249 htab = mandoc_malloc(sizeof(*htab));
250 mandoc_ohash_init(htab, 4, offsetof(struct dbm_res, page));
251 }
252
253 for (im = 0, ib = 1; im < KEY_MAX; im++, ib <<= 1) {
254 if ((e->bits & ib) == 0)
255 continue;
256
257 switch (ib) {
258 case TYPE_arch:
259 dbm_page_byarch(&e->match);
260 break;
261 case TYPE_sec:
262 dbm_page_bysect(&e->match);
263 break;
264 case TYPE_Nm:
265 dbm_page_byname(&e->match);
266 break;
267 case TYPE_Nd:
268 dbm_page_bydesc(&e->match);
269 break;
270 default:
271 dbm_page_bymacro(im - 2, &e->match);
272 break;
273 }
274
275 /*
276 * When hashing for deduplication, use the unique
277 * page ID itself instead of a hash function;
278 * that is quite efficient.
279 */
280
281 for (;;) {
282 res = dbm_page_next();
283 if (res.page == -1)
284 break;
285 slot = ohash_lookup_memory(htab,
286 (char *)&res, sizeof(res.page), res.page);
287 if ((rp = ohash_find(htab, slot)) != NULL) {
288 rp->bits |= res.bits;
289 continue;
290 }
291 rp = mandoc_malloc(sizeof(*rp));
292 *rp = res;
293 ohash_insert(htab, slot, rp);
294 }
295 }
296 return htab;
297 }
298
299 static struct ohash *
300 manmerge_or(struct expr *e, struct ohash *htab)
301 {
302 while (e != NULL) {
303 htab = manmerge(e, htab);
304 e = e->next;
305 }
306 return htab;
307 }
308
309 static struct ohash *
310 manmerge_and(struct expr *e, struct ohash *htab)
311 {
312 struct ohash *hand, *h1, *h2;
313 struct dbm_res *res;
314 unsigned int slot1, slot2;
315
316 /* Evaluate the first term of the AND clause. */
317
318 hand = manmerge(e, NULL);
319
320 while ((e = e->next) != NULL) {
321
322 /* Evaluate the next term and prepare for ANDing. */
323
324 h2 = manmerge(e, NULL);
325 if (ohash_entries(h2) < ohash_entries(hand)) {
326 h1 = h2;
327 h2 = hand;
328 } else
329 h1 = hand;
330 hand = mandoc_malloc(sizeof(*hand));
331 mandoc_ohash_init(hand, 4, offsetof(struct dbm_res, page));
332
333 /* Keep all pages that are in both result sets. */
334
335 for (res = ohash_first(h1, &slot1); res != NULL;
336 res = ohash_next(h1, &slot1)) {
337 if (ohash_find(h2, ohash_lookup_memory(h2,
338 (char *)res, sizeof(res->page),
339 res->page)) == NULL)
340 free(res);
341 else
342 ohash_insert(hand, ohash_lookup_memory(hand,
343 (char *)res, sizeof(res->page),
344 res->page), res);
345 }
346
347 /* Discard the merged results. */
348
349 for (res = ohash_first(h2, &slot2); res != NULL;
350 res = ohash_next(h2, &slot2))
351 free(res);
352 ohash_delete(h2);
353 free(h2);
354 ohash_delete(h1);
355 free(h1);
356 }
357
358 /* Merge the result of the AND into htab. */
359
360 if (htab == NULL)
361 return hand;
362
363 for (res = ohash_first(hand, &slot1); res != NULL;
364 res = ohash_next(hand, &slot1)) {
365 slot2 = ohash_lookup_memory(htab,
366 (char *)res, sizeof(res->page), res->page);
367 if (ohash_find(htab, slot2) == NULL)
368 ohash_insert(htab, slot2, res);
369 else
370 free(res);
371 }
372
373 /* Discard the merged result. */
374
375 ohash_delete(hand);
376 free(hand);
377 return htab;
378 }
379
380 void
381 mansearch_free(struct manpage *res, size_t sz)
382 {
383 size_t i;
384
385 for (i = 0; i < sz; i++) {
386 free(res[i].file);
387 free(res[i].names);
388 free(res[i].output);
389 }
390 free(res);
391 }
392
393 static int
394 manpage_compare(const void *vp1, const void *vp2)
395 {
396 const struct manpage *mp1, *mp2;
397 int diff;
398
399 mp1 = vp1;
400 mp2 = vp2;
401 return (diff = mp2->bits - mp1->bits) ? diff :
402 (diff = mp1->sec - mp2->sec) ? diff :
403 strcasecmp(mp1->names, mp2->names);
404 }
405
406 static char *
407 buildnames(const struct dbm_page *page)
408 {
409 char *buf;
410 size_t i, sz;
411
412 sz = lstlen(page->name, 2) + 1 + lstlen(page->sect, 2) +
413 (page->arch == NULL ? 0 : 1 + lstlen(page->arch, 2)) + 2;
414 buf = mandoc_malloc(sz);
415 i = 0;
416 lstcat(buf, &i, page->name, ", ");
417 buf[i++] = '(';
418 lstcat(buf, &i, page->sect, ", ");
419 if (page->arch != NULL) {
420 buf[i++] = '/';
421 lstcat(buf, &i, page->arch, ", ");
422 }
423 buf[i++] = ')';
424 buf[i++] = '\0';
425 assert(i == sz);
426 return buf;
427 }
428
429 /*
430 * Count the buffer space needed to print the NUL-terminated
431 * list of NUL-terminated strings, when printing sep separator
432 * characters between strings.
433 */
434 static size_t
435 lstlen(const char *cp, size_t sep)
436 {
437 size_t sz;
438
439 for (sz = 0;; sz++) {
440 if (cp[0] == '\0') {
441 if (cp[1] == '\0')
442 break;
443 sz += sep - 1;
444 } else if (cp[0] < ' ')
445 sz--;
446 cp++;
447 }
448 return sz;
449 }
450
451 /*
452 * Print the NUL-terminated list of NUL-terminated strings
453 * into the buffer, seperating strings with sep.
454 */
455 static void
456 lstcat(char *buf, size_t *i, const char *cp, const char *sep)
457 {
458 const char *s;
459
460 for (;;) {
461 if (cp[0] == '\0') {
462 if (cp[1] == '\0')
463 break;
464 s = sep;
465 while (*s != '\0')
466 buf[(*i)++] = *s++;
467 } else if (cp[0] >= ' ')
468 buf[(*i)++] = cp[0];
469 cp++;
470 }
471 }
472
473 /*
474 * Return 1 if the string *want occurs in any of the strings
475 * in the NUL-terminated string list *have, or 0 otherwise.
476 * If either argument is NULL or empty, assume no filtering
477 * is desired and return 1.
478 */
479 static int
480 lstmatch(const char *want, const char *have)
481 {
482 if (want == NULL || have == NULL || *have == '\0')
483 return 1;
484 while (*have != '\0') {
485 if (strcasestr(have, want) != NULL)
486 return 1;
487 have = strchr(have, '\0') + 1;
488 }
489 return 0;
490 }
491
492 /*
493 * Build a list of values taken by the macro im in the manual page.
494 */
495 static char *
496 buildoutput(size_t im, struct dbm_page *page)
497 {
498 const char *oldoutput, *sep, *input;
499 char *output, *newoutput, *value;
500 size_t sz, i;
501
502 switch (im) {
503 case KEY_Nd:
504 return mandoc_strdup(page->desc);
505 case KEY_Nm:
506 input = page->name;
507 break;
508 case KEY_sec:
509 input = page->sect;
510 break;
511 case KEY_arch:
512 input = page->arch;
513 if (input == NULL)
514 input = "all\0";
515 break;
516 default:
517 input = NULL;
518 break;
519 }
520
521 if (input != NULL) {
522 sz = lstlen(input, 3) + 1;
523 output = mandoc_malloc(sz);
524 i = 0;
525 lstcat(output, &i, input, " # ");
526 output[i++] = '\0';
527 assert(i == sz);
528 return output;
529 }
530
531 output = NULL;
532 dbm_macro_bypage(im - 2, page->addr);
533 while ((value = dbm_macro_next()) != NULL) {
534 if (output == NULL) {
535 oldoutput = "";
536 sep = "";
537 } else {
538 oldoutput = output;
539 sep = " # ";
540 }
541 mandoc_asprintf(&newoutput, "%s%s%s", oldoutput, sep, value);
542 free(output);
543 output = newoutput;
544 }
545 return output;
546 }
547
548 /*
549 * Compile a set of string tokens into an expression.
550 * Tokens in "argv" are assumed to be individual expression atoms (e.g.,
551 * "(", "foo=bar", etc.).
552 */
553 static struct expr *
554 exprcomp(const struct mansearch *search, int argc, char *argv[], int *argi)
555 {
556 struct expr *parent, *child;
557 int needterm, nested;
558
559 if ((nested = *argi) == argc)
560 return NULL;
561 needterm = 1;
562 parent = child = NULL;
563 while (*argi < argc) {
564 if (strcmp(")", argv[*argi]) == 0) {
565 if (needterm)
566 warnx("missing term "
567 "before closing parenthesis");
568 needterm = 0;
569 if (nested)
570 break;
571 warnx("ignoring unmatched right parenthesis");
572 ++*argi;
573 continue;
574 }
575 if (strcmp("-o", argv[*argi]) == 0) {
576 if (needterm) {
577 if (*argi > 0)
578 warnx("ignoring -o after %s",
579 argv[*argi - 1]);
580 else
581 warnx("ignoring initial -o");
582 }
583 needterm = 1;
584 ++*argi;
585 continue;
586 }
587 needterm = 0;
588 if (child == NULL) {
589 child = expr_and(search, argc, argv, argi);
590 continue;
591 }
592 if (parent == NULL) {
593 parent = mandoc_calloc(1, sizeof(*parent));
594 parent->type = EXPR_OR;
595 parent->next = NULL;
596 parent->child = child;
597 }
598 child->next = expr_and(search, argc, argv, argi);
599 child = child->next;
600 }
601 if (needterm && *argi)
602 warnx("ignoring trailing %s", argv[*argi - 1]);
603 return parent == NULL ? child : parent;
604 }
605
606 static struct expr *
607 expr_and(const struct mansearch *search, int argc, char *argv[], int *argi)
608 {
609 struct expr *parent, *child;
610 int needterm;
611
612 needterm = 1;
613 parent = child = NULL;
614 while (*argi < argc) {
615 if (strcmp(")", argv[*argi]) == 0) {
616 if (needterm)
617 warnx("missing term "
618 "before closing parenthesis");
619 needterm = 0;
620 break;
621 }
622 if (strcmp("-o", argv[*argi]) == 0)
623 break;
624 if (strcmp("-a", argv[*argi]) == 0) {
625 if (needterm) {
626 if (*argi > 0)
627 warnx("ignoring -a after %s",
628 argv[*argi - 1]);
629 else
630 warnx("ignoring initial -a");
631 }
632 needterm = 1;
633 ++*argi;
634 continue;
635 }
636 if (needterm == 0)
637 break;
638 if (child == NULL) {
639 child = exprterm(search, argc, argv, argi);
640 if (child != NULL)
641 needterm = 0;
642 continue;
643 }
644 needterm = 0;
645 if (parent == NULL) {
646 parent = mandoc_calloc(1, sizeof(*parent));
647 parent->type = EXPR_AND;
648 parent->next = NULL;
649 parent->child = child;
650 }
651 child->next = exprterm(search, argc, argv, argi);
652 if (child->next != NULL) {
653 child = child->next;
654 needterm = 0;
655 }
656 }
657 if (needterm && *argi)
658 warnx("ignoring trailing %s", argv[*argi - 1]);
659 return parent == NULL ? child : parent;
660 }
661
662 static struct expr *
663 exprterm(const struct mansearch *search, int argc, char *argv[], int *argi)
664 {
665 char errbuf[BUFSIZ];
666 struct expr *e;
667 char *key, *val;
668 uint64_t iterbit;
669 int cs, i, irc;
670
671 if (strcmp("(", argv[*argi]) == 0) {
672 ++*argi;
673 e = exprcomp(search, argc, argv, argi);
674 if (*argi < argc) {
675 assert(strcmp(")", argv[*argi]) == 0);
676 ++*argi;
677 } else
678 warnx("unclosed parenthesis");
679 return e;
680 }
681
682 if (strcmp("-i", argv[*argi]) == 0 && *argi + 1 < argc) {
683 cs = 0;
684 ++*argi;
685 } else
686 cs = 1;
687
688 e = mandoc_calloc(1, sizeof(*e));
689 e->type = EXPR_TERM;
690 e->bits = 0;
691 e->next = NULL;
692 e->child = NULL;
693
694 if (search->argmode == ARG_NAME) {
695 e->bits = TYPE_Nm;
696 e->match.type = DBM_EXACT;
697 e->match.str = argv[(*argi)++];
698 return e;
699 }
700
701 /*
702 * Separate macro keys from search string.
703 * If needed, request regular expression handling.
704 */
705
706 if (search->argmode == ARG_WORD) {
707 e->bits = TYPE_Nm;
708 e->match.type = DBM_REGEX;
709 #if HAVE_REWB_BSD
710 mandoc_asprintf(&val, "[[:<:]]%s[[:>:]]", argv[*argi]);
711 #elif HAVE_REWB_SYSV
712 mandoc_asprintf(&val, "\\<%s\\>", argv[*argi]);
713 #else
714 mandoc_asprintf(&val,
715 "(^|[^a-zA-Z01-9_])%s([^a-zA-Z01-9_]|$)", argv[*argi]);
716 #endif
717 cs = 0;
718 } else if ((val = strpbrk(argv[*argi], "=~")) == NULL) {
719 e->bits = TYPE_Nm | TYPE_Nd;
720 e->match.type = DBM_SUB;
721 e->match.str = argv[*argi];
722 } else {
723 if (val == argv[*argi])
724 e->bits = TYPE_Nm | TYPE_Nd;
725 if (*val == '=') {
726 e->match.type = DBM_SUB;
727 e->match.str = val + 1;
728 } else
729 e->match.type = DBM_REGEX;
730 *val++ = '\0';
731 if (strstr(argv[*argi], "arch") != NULL)
732 cs = 0;
733 }
734
735 /* Compile regular expressions. */
736
737 if (e->match.type == DBM_REGEX) {
738 e->match.re = mandoc_malloc(sizeof(*e->match.re));
739 irc = regcomp(e->match.re, val,
740 REG_EXTENDED | REG_NOSUB | (cs ? 0 : REG_ICASE));
741 if (irc) {
742 regerror(irc, e->match.re, errbuf, sizeof(errbuf));
743 warnx("regcomp /%s/: %s", val, errbuf);
744 }
745 if (search->argmode == ARG_WORD)
746 free(val);
747 if (irc) {
748 free(e->match.re);
749 free(e);
750 ++*argi;
751 return NULL;
752 }
753 }
754
755 if (e->bits) {
756 ++*argi;
757 return e;
758 }
759
760 /*
761 * Parse out all possible fields.
762 * If the field doesn't resolve, bail.
763 */
764
765 while (NULL != (key = strsep(&argv[*argi], ","))) {
766 if ('\0' == *key)
767 continue;
768 for (i = 0, iterbit = 1; i < KEY_MAX; i++, iterbit <<= 1) {
769 if (0 == strcasecmp(key, mansearch_keynames[i])) {
770 e->bits |= iterbit;
771 break;
772 }
773 }
774 if (i == KEY_MAX) {
775 if (strcasecmp(key, "any"))
776 warnx("treating unknown key "
777 "\"%s\" as \"any\"", key);
778 e->bits |= ~0ULL;
779 }
780 }
781
782 ++*argi;
783 return e;
784 }
785
786 static void
787 exprfree(struct expr *e)
788 {
789 if (e->next != NULL)
790 exprfree(e->next);
791 if (e->child != NULL)
792 exprfree(e->child);
793 free(e);
794 }