]> git.cameronkatri.com Git - mandoc.git/blob - mansearch.c
Finally use __progname, err(3) and warn(3).
[mandoc.git] / mansearch.c
1 /* $Id: mansearch.c,v 1.59 2015/10/11 21:12:55 schwarze Exp $ */
2 /*
3 * Copyright (c) 2012 Kristaps Dzonsons <kristaps@bsd.lv>
4 * Copyright (c) 2013, 2014, 2015 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 #include <err.h>
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <getopt.h>
28 #include <glob.h>
29 #include <limits.h>
30 #include <regex.h>
31 #include <stdio.h>
32 #include <stdint.h>
33 #include <stddef.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <unistd.h>
37
38 #if HAVE_OHASH
39 #include <ohash.h>
40 #else
41 #include "compat_ohash.h"
42 #endif
43 #include <sqlite3.h>
44 #ifndef SQLITE_DETERMINISTIC
45 #define SQLITE_DETERMINISTIC 0
46 #endif
47
48 #include "mandoc.h"
49 #include "mandoc_aux.h"
50 #include "manconf.h"
51 #include "mansearch.h"
52
53 extern int mansearch_keymax;
54 extern const char *const mansearch_keynames[];
55
56 #define SQL_BIND_TEXT(_db, _s, _i, _v) \
57 do { if (SQLITE_OK != sqlite3_bind_text \
58 ((_s), (_i)++, (_v), -1, SQLITE_STATIC)) \
59 warnx("%s", sqlite3_errmsg((_db))); \
60 } while (0)
61 #define SQL_BIND_INT64(_db, _s, _i, _v) \
62 do { if (SQLITE_OK != sqlite3_bind_int64 \
63 ((_s), (_i)++, (_v))) \
64 warnx("%s", sqlite3_errmsg((_db))); \
65 } while (0)
66 #define SQL_BIND_BLOB(_db, _s, _i, _v) \
67 do { if (SQLITE_OK != sqlite3_bind_blob \
68 ((_s), (_i)++, (&_v), sizeof(_v), SQLITE_STATIC)) \
69 warnx("%s", sqlite3_errmsg((_db))); \
70 } while (0)
71
72 struct expr {
73 regex_t regexp; /* compiled regexp, if applicable */
74 const char *substr; /* to search for, if applicable */
75 struct expr *next; /* next in sequence */
76 uint64_t bits; /* type-mask */
77 int equal; /* equality, not subsring match */
78 int open; /* opening parentheses before */
79 int and; /* logical AND before */
80 int close; /* closing parentheses after */
81 };
82
83 struct match {
84 uint64_t pageid; /* identifier in database */
85 uint64_t bits; /* name type mask */
86 char *desc; /* manual page description */
87 int form; /* bit field: formatted, zipped? */
88 };
89
90 static void buildnames(const struct mansearch *,
91 struct manpage *, sqlite3 *,
92 sqlite3_stmt *, uint64_t,
93 const char *, int form);
94 static char *buildoutput(sqlite3 *, sqlite3_stmt *,
95 uint64_t, uint64_t);
96 static void *hash_alloc(size_t, void *);
97 static void hash_free(void *, void *);
98 static void *hash_calloc(size_t, size_t, void *);
99 static struct expr *exprcomp(const struct mansearch *,
100 int, char *[]);
101 static void exprfree(struct expr *);
102 static struct expr *exprterm(const struct mansearch *, char *, int);
103 static int manpage_compare(const void *, const void *);
104 static void sql_append(char **sql, size_t *sz,
105 const char *newstr, int count);
106 static void sql_match(sqlite3_context *context,
107 int argc, sqlite3_value **argv);
108 static void sql_regexp(sqlite3_context *context,
109 int argc, sqlite3_value **argv);
110 static char *sql_statement(const struct expr *);
111
112
113 int
114 mansearch_setup(int start)
115 {
116 static void *pagecache;
117 int c;
118
119 #define PC_PAGESIZE 1280
120 #define PC_NUMPAGES 256
121
122 if (start) {
123 if (NULL != pagecache) {
124 warnx("pagecache already enabled");
125 return (int)MANDOCLEVEL_BADARG;
126 }
127
128 pagecache = mmap(NULL, PC_PAGESIZE * PC_NUMPAGES,
129 PROT_READ | PROT_WRITE,
130 MAP_SHARED | MAP_ANON, -1, 0);
131
132 if (MAP_FAILED == pagecache) {
133 perror("mmap");
134 pagecache = NULL;
135 return (int)MANDOCLEVEL_SYSERR;
136 }
137
138 c = sqlite3_config(SQLITE_CONFIG_PAGECACHE,
139 pagecache, PC_PAGESIZE, PC_NUMPAGES);
140
141 if (SQLITE_OK == c)
142 return (int)MANDOCLEVEL_OK;
143
144 warnx("pagecache: %s", sqlite3_errstr(c));
145
146 } else if (NULL == pagecache) {
147 warnx("pagecache missing");
148 return (int)MANDOCLEVEL_BADARG;
149 }
150
151 if (-1 == munmap(pagecache, PC_PAGESIZE * PC_NUMPAGES)) {
152 perror("munmap");
153 pagecache = NULL;
154 return (int)MANDOCLEVEL_SYSERR;
155 }
156
157 pagecache = NULL;
158 return (int)MANDOCLEVEL_OK;
159 }
160
161 int
162 mansearch(const struct mansearch *search,
163 const struct manpaths *paths,
164 int argc, char *argv[],
165 struct manpage **res, size_t *sz)
166 {
167 int64_t pageid;
168 uint64_t outbit, iterbit;
169 char buf[PATH_MAX];
170 char *sql;
171 struct manpage *mpage;
172 struct expr *e, *ep;
173 sqlite3 *db;
174 sqlite3_stmt *s, *s2;
175 struct match *mp;
176 struct ohash_info info;
177 struct ohash htab;
178 unsigned int idx;
179 size_t i, j, cur, maxres;
180 int c, chdir_status, getcwd_status, indexbit;
181
182 if (argc == 0 || (e = exprcomp(search, argc, argv)) == NULL) {
183 *sz = 0;
184 return 0;
185 }
186
187 info.calloc = hash_calloc;
188 info.alloc = hash_alloc;
189 info.free = hash_free;
190 info.key_offset = offsetof(struct match, pageid);
191
192 cur = maxres = 0;
193 *res = NULL;
194
195 if (NULL != search->outkey) {
196 outbit = TYPE_Nd;
197 for (indexbit = 0, iterbit = 1;
198 indexbit < mansearch_keymax;
199 indexbit++, iterbit <<= 1) {
200 if (0 == strcasecmp(search->outkey,
201 mansearch_keynames[indexbit])) {
202 outbit = iterbit;
203 break;
204 }
205 }
206 } else
207 outbit = 0;
208
209 /*
210 * Remember the original working directory, if possible.
211 * This will be needed if the second or a later directory
212 * is given as a relative path.
213 * Do not error out if the current directory is not
214 * searchable: Maybe it won't be needed after all.
215 */
216
217 if (getcwd(buf, PATH_MAX) == NULL) {
218 getcwd_status = 0;
219 (void)strlcpy(buf, strerror(errno), sizeof(buf));
220 } else
221 getcwd_status = 1;
222
223 sql = sql_statement(e);
224
225 /*
226 * Loop over the directories (containing databases) for us to
227 * search.
228 * Don't let missing/bad databases/directories phase us.
229 * In each, try to open the resident database and, if it opens,
230 * scan it for our match expression.
231 */
232
233 chdir_status = 0;
234 for (i = 0; i < paths->sz; i++) {
235 if (chdir_status && paths->paths[i][0] != '/') {
236 if ( ! getcwd_status) {
237 warnx("%s: getcwd: %s", paths->paths[i], buf);
238 continue;
239 } else if (chdir(buf) == -1) {
240 perror(buf);
241 continue;
242 }
243 }
244 if (chdir(paths->paths[i]) == -1) {
245 perror(paths->paths[i]);
246 continue;
247 }
248 chdir_status = 1;
249
250 c = sqlite3_open_v2(MANDOC_DB, &db,
251 SQLITE_OPEN_READONLY, NULL);
252
253 if (SQLITE_OK != c) {
254 warn("%s/%s", paths->paths[i], MANDOC_DB);
255 sqlite3_close(db);
256 continue;
257 }
258
259 /*
260 * Define the SQL functions for substring
261 * and regular expression matching.
262 */
263
264 c = sqlite3_create_function(db, "match", 2,
265 SQLITE_UTF8 | SQLITE_DETERMINISTIC,
266 NULL, sql_match, NULL, NULL);
267 assert(SQLITE_OK == c);
268 c = sqlite3_create_function(db, "regexp", 2,
269 SQLITE_UTF8 | SQLITE_DETERMINISTIC,
270 NULL, sql_regexp, NULL, NULL);
271 assert(SQLITE_OK == c);
272
273 j = 1;
274 c = sqlite3_prepare_v2(db, sql, -1, &s, NULL);
275 if (SQLITE_OK != c)
276 warnx("%s", sqlite3_errmsg(db));
277
278 for (ep = e; NULL != ep; ep = ep->next) {
279 if (NULL == ep->substr) {
280 SQL_BIND_BLOB(db, s, j, ep->regexp);
281 } else
282 SQL_BIND_TEXT(db, s, j, ep->substr);
283 if (0 == ((TYPE_Nd | TYPE_Nm) & ep->bits))
284 SQL_BIND_INT64(db, s, j, ep->bits);
285 }
286
287 memset(&htab, 0, sizeof(struct ohash));
288 ohash_init(&htab, 4, &info);
289
290 /*
291 * Hash each entry on its [unique] document identifier.
292 * This is a uint64_t.
293 * Instead of using a hash function, simply convert the
294 * uint64_t to a uint32_t, the hash value's type.
295 * This gives good performance and preserves the
296 * distribution of buckets in the table.
297 */
298 while (SQLITE_ROW == (c = sqlite3_step(s))) {
299 pageid = sqlite3_column_int64(s, 2);
300 idx = ohash_lookup_memory(&htab,
301 (char *)&pageid, sizeof(uint64_t),
302 (uint32_t)pageid);
303
304 if (NULL != ohash_find(&htab, idx))
305 continue;
306
307 mp = mandoc_calloc(1, sizeof(struct match));
308 mp->pageid = pageid;
309 mp->form = sqlite3_column_int(s, 1);
310 mp->bits = sqlite3_column_int64(s, 3);
311 if (TYPE_Nd == outbit)
312 mp->desc = mandoc_strdup((const char *)
313 sqlite3_column_text(s, 0));
314 ohash_insert(&htab, idx, mp);
315 }
316
317 if (SQLITE_DONE != c)
318 warnx("%s", sqlite3_errmsg(db));
319
320 sqlite3_finalize(s);
321
322 c = sqlite3_prepare_v2(db,
323 "SELECT sec, arch, name, pageid FROM mlinks "
324 "WHERE pageid=? ORDER BY sec, arch, name",
325 -1, &s, NULL);
326 if (SQLITE_OK != c)
327 warnx("%s", sqlite3_errmsg(db));
328
329 c = sqlite3_prepare_v2(db,
330 "SELECT bits, key, pageid FROM keys "
331 "WHERE pageid=? AND bits & ?",
332 -1, &s2, NULL);
333 if (SQLITE_OK != c)
334 warnx("%s", sqlite3_errmsg(db));
335
336 for (mp = ohash_first(&htab, &idx);
337 NULL != mp;
338 mp = ohash_next(&htab, &idx)) {
339 if (cur + 1 > maxres) {
340 maxres += 1024;
341 *res = mandoc_reallocarray(*res,
342 maxres, sizeof(struct manpage));
343 }
344 mpage = *res + cur;
345 mpage->ipath = i;
346 mpage->bits = mp->bits;
347 mpage->sec = 10;
348 mpage->form = mp->form;
349 buildnames(search, mpage, db, s, mp->pageid,
350 paths->paths[i], mp->form);
351 if (mpage->names != NULL) {
352 mpage->output = TYPE_Nd & outbit ?
353 mp->desc : outbit ?
354 buildoutput(db, s2, mp->pageid, outbit) :
355 NULL;
356 cur++;
357 }
358 free(mp);
359 }
360
361 sqlite3_finalize(s);
362 sqlite3_finalize(s2);
363 sqlite3_close(db);
364 ohash_delete(&htab);
365
366 /*
367 * In man(1) mode, prefer matches in earlier trees
368 * over matches in later trees.
369 */
370
371 if (cur && search->firstmatch)
372 break;
373 }
374 qsort(*res, cur, sizeof(struct manpage), manpage_compare);
375 if (chdir_status && getcwd_status && chdir(buf) == -1)
376 perror(buf);
377 exprfree(e);
378 free(sql);
379 *sz = cur;
380 return 1;
381 }
382
383 void
384 mansearch_free(struct manpage *res, size_t sz)
385 {
386 size_t i;
387
388 for (i = 0; i < sz; i++) {
389 free(res[i].file);
390 free(res[i].names);
391 free(res[i].output);
392 }
393 free(res);
394 }
395
396 static int
397 manpage_compare(const void *vp1, const void *vp2)
398 {
399 const struct manpage *mp1, *mp2;
400 int diff;
401
402 mp1 = vp1;
403 mp2 = vp2;
404 return (diff = mp2->bits - mp1->bits) ? diff :
405 (diff = mp1->sec - mp2->sec) ? diff :
406 strcasecmp(mp1->names, mp2->names);
407 }
408
409 static void
410 buildnames(const struct mansearch *search, struct manpage *mpage,
411 sqlite3 *db, sqlite3_stmt *s,
412 uint64_t pageid, const char *path, int form)
413 {
414 glob_t globinfo;
415 char *firstname, *newnames, *prevsec, *prevarch;
416 const char *oldnames, *sep1, *name, *sec, *sep2, *arch, *fsec;
417 size_t i;
418 int c, globres;
419
420 mpage->file = NULL;
421 mpage->names = NULL;
422 firstname = prevsec = prevarch = NULL;
423 i = 1;
424 SQL_BIND_INT64(db, s, i, pageid);
425 while (SQLITE_ROW == (c = sqlite3_step(s))) {
426
427 /* Decide whether we already have some names. */
428
429 if (NULL == mpage->names) {
430 oldnames = "";
431 sep1 = "";
432 } else {
433 oldnames = mpage->names;
434 sep1 = ", ";
435 }
436
437 /* Fetch the next name, rejecting sec/arch mismatches. */
438
439 sec = (const char *)sqlite3_column_text(s, 0);
440 if (search->sec != NULL && strcasecmp(sec, search->sec))
441 continue;
442 arch = (const char *)sqlite3_column_text(s, 1);
443 if (search->arch != NULL && *arch != '\0' &&
444 strcasecmp(arch, search->arch))
445 continue;
446 name = (const char *)sqlite3_column_text(s, 2);
447
448 /* Remember the first section found. */
449
450 if (9 < mpage->sec && '1' <= *sec && '9' >= *sec)
451 mpage->sec = (*sec - '1') + 1;
452
453 /* If the section changed, append the old one. */
454
455 if (NULL != prevsec &&
456 (strcmp(sec, prevsec) ||
457 strcmp(arch, prevarch))) {
458 sep2 = '\0' == *prevarch ? "" : "/";
459 mandoc_asprintf(&newnames, "%s(%s%s%s)",
460 oldnames, prevsec, sep2, prevarch);
461 free(mpage->names);
462 oldnames = mpage->names = newnames;
463 free(prevsec);
464 free(prevarch);
465 prevsec = prevarch = NULL;
466 }
467
468 /* Save the new section, to append it later. */
469
470 if (NULL == prevsec) {
471 prevsec = mandoc_strdup(sec);
472 prevarch = mandoc_strdup(arch);
473 }
474
475 /* Append the new name. */
476
477 mandoc_asprintf(&newnames, "%s%s%s",
478 oldnames, sep1, name);
479 free(mpage->names);
480 mpage->names = newnames;
481
482 /* Also save the first file name encountered. */
483
484 if (mpage->file != NULL)
485 continue;
486
487 if (form & FORM_SRC) {
488 sep1 = "man";
489 fsec = sec;
490 } else {
491 sep1 = "cat";
492 fsec = "0";
493 }
494 sep2 = *arch == '\0' ? "" : "/";
495 mandoc_asprintf(&mpage->file, "%s/%s%s%s%s/%s.%s",
496 path, sep1, sec, sep2, arch, name, fsec);
497 if (access(mpage->file, R_OK) != -1)
498 continue;
499
500 /* Handle unusual file name extensions. */
501
502 if (firstname == NULL)
503 firstname = mpage->file;
504 else
505 free(mpage->file);
506 mandoc_asprintf(&mpage->file, "%s/%s%s%s%s/%s.*",
507 path, sep1, sec, sep2, arch, name);
508 globres = glob(mpage->file, 0, NULL, &globinfo);
509 free(mpage->file);
510 mpage->file = globres ? NULL :
511 mandoc_strdup(*globinfo.gl_pathv);
512 globfree(&globinfo);
513 }
514 if (c != SQLITE_DONE)
515 warnx("%s", sqlite3_errmsg(db));
516 sqlite3_reset(s);
517
518 /* If none of the files is usable, use the first name. */
519
520 if (mpage->file == NULL)
521 mpage->file = firstname;
522 else if (mpage->file != firstname)
523 free(firstname);
524
525 /* Append one final section to the names. */
526
527 if (prevsec != NULL) {
528 sep2 = *prevarch == '\0' ? "" : "/";
529 mandoc_asprintf(&newnames, "%s(%s%s%s)",
530 mpage->names, prevsec, sep2, prevarch);
531 free(mpage->names);
532 mpage->names = newnames;
533 free(prevsec);
534 free(prevarch);
535 }
536 }
537
538 static char *
539 buildoutput(sqlite3 *db, sqlite3_stmt *s, uint64_t pageid, uint64_t outbit)
540 {
541 char *output, *newoutput;
542 const char *oldoutput, *sep1, *data;
543 size_t i;
544 int c;
545
546 output = NULL;
547 i = 1;
548 SQL_BIND_INT64(db, s, i, pageid);
549 SQL_BIND_INT64(db, s, i, outbit);
550 while (SQLITE_ROW == (c = sqlite3_step(s))) {
551 if (NULL == output) {
552 oldoutput = "";
553 sep1 = "";
554 } else {
555 oldoutput = output;
556 sep1 = " # ";
557 }
558 data = (const char *)sqlite3_column_text(s, 1);
559 mandoc_asprintf(&newoutput, "%s%s%s",
560 oldoutput, sep1, data);
561 free(output);
562 output = newoutput;
563 }
564 if (SQLITE_DONE != c)
565 warnx("%s", sqlite3_errmsg(db));
566 sqlite3_reset(s);
567 return output;
568 }
569
570 /*
571 * Implement substring match as an application-defined SQL function.
572 * Using the SQL LIKE or GLOB operators instead would be a bad idea
573 * because that would require escaping metacharacters in the string
574 * being searched for.
575 */
576 static void
577 sql_match(sqlite3_context *context, int argc, sqlite3_value **argv)
578 {
579
580 assert(2 == argc);
581 sqlite3_result_int(context, NULL != strcasestr(
582 (const char *)sqlite3_value_text(argv[1]),
583 (const char *)sqlite3_value_text(argv[0])));
584 }
585
586 /*
587 * Implement regular expression match
588 * as an application-defined SQL function.
589 */
590 static void
591 sql_regexp(sqlite3_context *context, int argc, sqlite3_value **argv)
592 {
593
594 assert(2 == argc);
595 sqlite3_result_int(context, !regexec(
596 (regex_t *)sqlite3_value_blob(argv[0]),
597 (const char *)sqlite3_value_text(argv[1]),
598 0, NULL, 0));
599 }
600
601 static void
602 sql_append(char **sql, size_t *sz, const char *newstr, int count)
603 {
604 size_t newsz;
605
606 newsz = 1 < count ? (size_t)count : strlen(newstr);
607 *sql = mandoc_realloc(*sql, *sz + newsz + 1);
608 if (1 < count)
609 memset(*sql + *sz, *newstr, (size_t)count);
610 else
611 memcpy(*sql + *sz, newstr, newsz);
612 *sz += newsz;
613 (*sql)[*sz] = '\0';
614 }
615
616 /*
617 * Prepare the search SQL statement.
618 */
619 static char *
620 sql_statement(const struct expr *e)
621 {
622 char *sql;
623 size_t sz;
624 int needop;
625
626 sql = mandoc_strdup(e->equal ?
627 "SELECT desc, form, pageid, bits "
628 "FROM mpages NATURAL JOIN names WHERE " :
629 "SELECT desc, form, pageid, 0 FROM mpages WHERE ");
630 sz = strlen(sql);
631
632 for (needop = 0; NULL != e; e = e->next) {
633 if (e->and)
634 sql_append(&sql, &sz, " AND ", 1);
635 else if (needop)
636 sql_append(&sql, &sz, " OR ", 1);
637 if (e->open)
638 sql_append(&sql, &sz, "(", e->open);
639 sql_append(&sql, &sz,
640 TYPE_Nd & e->bits
641 ? (NULL == e->substr
642 ? "desc REGEXP ?"
643 : "desc MATCH ?")
644 : TYPE_Nm == e->bits
645 ? (NULL == e->substr
646 ? "pageid IN (SELECT pageid FROM names "
647 "WHERE name REGEXP ?)"
648 : e->equal
649 ? "name = ? "
650 : "pageid IN (SELECT pageid FROM names "
651 "WHERE name MATCH ?)")
652 : (NULL == e->substr
653 ? "pageid IN (SELECT pageid FROM keys "
654 "WHERE key REGEXP ? AND bits & ?)"
655 : "pageid IN (SELECT pageid FROM keys "
656 "WHERE key MATCH ? AND bits & ?)"), 1);
657 if (e->close)
658 sql_append(&sql, &sz, ")", e->close);
659 needop = 1;
660 }
661
662 return sql;
663 }
664
665 /*
666 * Compile a set of string tokens into an expression.
667 * Tokens in "argv" are assumed to be individual expression atoms (e.g.,
668 * "(", "foo=bar", etc.).
669 */
670 static struct expr *
671 exprcomp(const struct mansearch *search, int argc, char *argv[])
672 {
673 uint64_t mask;
674 int i, toopen, logic, igncase, toclose;
675 struct expr *first, *prev, *cur, *next;
676
677 first = cur = NULL;
678 logic = igncase = toopen = toclose = 0;
679
680 for (i = 0; i < argc; i++) {
681 if (0 == strcmp("(", argv[i])) {
682 if (igncase)
683 goto fail;
684 toopen++;
685 toclose++;
686 continue;
687 } else if (0 == strcmp(")", argv[i])) {
688 if (toopen || logic || igncase || NULL == cur)
689 goto fail;
690 cur->close++;
691 if (0 > --toclose)
692 goto fail;
693 continue;
694 } else if (0 == strcmp("-a", argv[i])) {
695 if (toopen || logic || igncase || NULL == cur)
696 goto fail;
697 logic = 1;
698 continue;
699 } else if (0 == strcmp("-o", argv[i])) {
700 if (toopen || logic || igncase || NULL == cur)
701 goto fail;
702 logic = 2;
703 continue;
704 } else if (0 == strcmp("-i", argv[i])) {
705 if (igncase)
706 goto fail;
707 igncase = 1;
708 continue;
709 }
710 next = exprterm(search, argv[i], !igncase);
711 if (NULL == next)
712 goto fail;
713 if (NULL == first)
714 first = next;
715 else
716 cur->next = next;
717 prev = cur = next;
718
719 /*
720 * Searching for descriptions must be split out
721 * because they are stored in the mpages table,
722 * not in the keys table.
723 */
724
725 for (mask = TYPE_Nm; mask <= TYPE_Nd; mask <<= 1) {
726 if (mask & cur->bits && ~mask & cur->bits) {
727 next = mandoc_calloc(1,
728 sizeof(struct expr));
729 memcpy(next, cur, sizeof(struct expr));
730 prev->open = 1;
731 cur->bits = mask;
732 cur->next = next;
733 cur = next;
734 cur->bits &= ~mask;
735 }
736 }
737 prev->and = (1 == logic);
738 prev->open += toopen;
739 if (cur != prev)
740 cur->close = 1;
741
742 toopen = logic = igncase = 0;
743 }
744 if ( ! (toopen || logic || igncase || toclose))
745 return first;
746
747 fail:
748 if (NULL != first)
749 exprfree(first);
750 return NULL;
751 }
752
753 static struct expr *
754 exprterm(const struct mansearch *search, char *buf, int cs)
755 {
756 char errbuf[BUFSIZ];
757 struct expr *e;
758 char *key, *val;
759 uint64_t iterbit;
760 int i, irc;
761
762 if ('\0' == *buf)
763 return NULL;
764
765 e = mandoc_calloc(1, sizeof(struct expr));
766
767 if (search->argmode == ARG_NAME) {
768 e->bits = TYPE_Nm;
769 e->substr = buf;
770 e->equal = 1;
771 return e;
772 }
773
774 /*
775 * Separate macro keys from search string.
776 * If needed, request regular expression handling
777 * by setting e->substr to NULL.
778 */
779
780 if (search->argmode == ARG_WORD) {
781 e->bits = TYPE_Nm;
782 e->substr = NULL;
783 mandoc_asprintf(&val, "[[:<:]]%s[[:>:]]", buf);
784 cs = 0;
785 } else if ((val = strpbrk(buf, "=~")) == NULL) {
786 e->bits = TYPE_Nm | TYPE_Nd;
787 e->substr = buf;
788 } else {
789 if (val == buf)
790 e->bits = TYPE_Nm | TYPE_Nd;
791 if ('=' == *val)
792 e->substr = val + 1;
793 *val++ = '\0';
794 if (NULL != strstr(buf, "arch"))
795 cs = 0;
796 }
797
798 /* Compile regular expressions. */
799
800 if (NULL == e->substr) {
801 irc = regcomp(&e->regexp, val,
802 REG_EXTENDED | REG_NOSUB | (cs ? 0 : REG_ICASE));
803 if (search->argmode == ARG_WORD)
804 free(val);
805 if (irc) {
806 regerror(irc, &e->regexp, errbuf, sizeof(errbuf));
807 warnx("regcomp: %s", errbuf);
808 free(e);
809 return NULL;
810 }
811 }
812
813 if (e->bits)
814 return e;
815
816 /*
817 * Parse out all possible fields.
818 * If the field doesn't resolve, bail.
819 */
820
821 while (NULL != (key = strsep(&buf, ","))) {
822 if ('\0' == *key)
823 continue;
824 for (i = 0, iterbit = 1;
825 i < mansearch_keymax;
826 i++, iterbit <<= 1) {
827 if (0 == strcasecmp(key,
828 mansearch_keynames[i])) {
829 e->bits |= iterbit;
830 break;
831 }
832 }
833 if (i == mansearch_keymax) {
834 if (strcasecmp(key, "any")) {
835 free(e);
836 return NULL;
837 }
838 e->bits |= ~0ULL;
839 }
840 }
841
842 return e;
843 }
844
845 static void
846 exprfree(struct expr *p)
847 {
848 struct expr *pp;
849
850 while (NULL != p) {
851 pp = p->next;
852 free(p);
853 p = pp;
854 }
855 }
856
857 static void *
858 hash_calloc(size_t nmemb, size_t sz, void *arg)
859 {
860
861 return mandoc_calloc(nmemb, sz);
862 }
863
864 static void *
865 hash_alloc(size_t sz, void *arg)
866 {
867
868 return mandoc_malloc(sz);
869 }
870
871 static void
872 hash_free(void *p, void *arg)
873 {
874
875 free(p);
876 }