]>
git.cameronkatri.com Git - mandoc.git/blob - mansearch.c
1 /* $Id: mansearch.c,v 1.63 2015/11/26 07:42:11 schwarze Exp $ */
3 * Copyright (c) 2012 Kristaps Dzonsons <kristaps@bsd.lv>
4 * Copyright (c) 2013, 2014, 2015 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>
41 #ifndef SQLITE_DETERMINISTIC
42 #define SQLITE_DETERMINISTIC 0
46 #include "mandoc_aux.h"
47 #include "mandoc_ohash.h"
49 #include "mansearch.h"
51 extern int mansearch_keymax
;
52 extern const char *const mansearch_keynames
[];
54 #define SQL_BIND_TEXT(_db, _s, _i, _v) \
55 do { if (SQLITE_OK != sqlite3_bind_text \
56 ((_s), (_i)++, (_v), -1, SQLITE_STATIC)) \
57 errx((int)MANDOCLEVEL_SYSERR, "%s", sqlite3_errmsg((_db))); \
59 #define SQL_BIND_INT64(_db, _s, _i, _v) \
60 do { if (SQLITE_OK != sqlite3_bind_int64 \
61 ((_s), (_i)++, (_v))) \
62 errx((int)MANDOCLEVEL_SYSERR, "%s", sqlite3_errmsg((_db))); \
64 #define SQL_BIND_BLOB(_db, _s, _i, _v) \
65 do { if (SQLITE_OK != sqlite3_bind_blob \
66 ((_s), (_i)++, (&_v), sizeof(_v), SQLITE_STATIC)) \
67 errx((int)MANDOCLEVEL_SYSERR, "%s", sqlite3_errmsg((_db))); \
71 regex_t regexp
; /* compiled regexp, if applicable */
72 const char *substr
; /* to search for, if applicable */
73 struct expr
*next
; /* next in sequence */
74 uint64_t bits
; /* type-mask */
75 int equal
; /* equality, not subsring match */
76 int open
; /* opening parentheses before */
77 int and; /* logical AND before */
78 int close
; /* closing parentheses after */
82 uint64_t pageid
; /* identifier in database */
83 uint64_t bits
; /* name type mask */
84 char *desc
; /* manual page description */
85 int form
; /* bit field: formatted, zipped? */
88 static void buildnames(const struct mansearch
*,
89 struct manpage
*, sqlite3
*,
90 sqlite3_stmt
*, uint64_t,
91 const char *, int form
);
92 static char *buildoutput(sqlite3
*, sqlite3_stmt
*,
94 static struct expr
*exprcomp(const struct mansearch
*,
96 static void exprfree(struct expr
*);
97 static struct expr
*exprterm(const struct mansearch
*, char *, int);
98 static int manpage_compare(const void *, const void *);
99 static void sql_append(char **sql
, size_t *sz
,
100 const char *newstr
, int count
);
101 static void sql_match(sqlite3_context
*context
,
102 int argc
, sqlite3_value
**argv
);
103 static void sql_regexp(sqlite3_context
*context
,
104 int argc
, sqlite3_value
**argv
);
105 static char *sql_statement(const struct expr
*);
109 mansearch_setup(int start
)
111 static void *pagecache
;
114 #define PC_PAGESIZE 1280
115 #define PC_NUMPAGES 256
118 if (NULL
!= pagecache
) {
119 warnx("pagecache already enabled");
120 return (int)MANDOCLEVEL_BADARG
;
123 pagecache
= mmap(NULL
, PC_PAGESIZE
* PC_NUMPAGES
,
124 PROT_READ
| PROT_WRITE
,
125 MAP_SHARED
| MAP_ANON
, -1, 0);
127 if (MAP_FAILED
== pagecache
) {
130 return (int)MANDOCLEVEL_SYSERR
;
133 c
= sqlite3_config(SQLITE_CONFIG_PAGECACHE
,
134 pagecache
, PC_PAGESIZE
, PC_NUMPAGES
);
137 return (int)MANDOCLEVEL_OK
;
139 warnx("pagecache: %s", sqlite3_errstr(c
));
141 } else if (NULL
== pagecache
) {
142 warnx("pagecache missing");
143 return (int)MANDOCLEVEL_BADARG
;
146 if (-1 == munmap(pagecache
, PC_PAGESIZE
* PC_NUMPAGES
)) {
149 return (int)MANDOCLEVEL_SYSERR
;
153 return (int)MANDOCLEVEL_OK
;
157 mansearch(const struct mansearch
*search
,
158 const struct manpaths
*paths
,
159 int argc
, char *argv
[],
160 struct manpage
**res
, size_t *sz
)
163 uint64_t outbit
, iterbit
;
166 struct manpage
*mpage
;
169 sqlite3_stmt
*s
, *s2
;
173 size_t i
, j
, cur
, maxres
;
174 int c
, chdir_status
, getcwd_status
, indexbit
;
176 if (argc
== 0 || (e
= exprcomp(search
, argc
, argv
)) == NULL
) {
184 if (NULL
!= search
->outkey
) {
186 for (indexbit
= 0, iterbit
= 1;
187 indexbit
< mansearch_keymax
;
188 indexbit
++, iterbit
<<= 1) {
189 if (0 == strcasecmp(search
->outkey
,
190 mansearch_keynames
[indexbit
])) {
199 * Remember the original working directory, if possible.
200 * This will be needed if the second or a later directory
201 * is given as a relative path.
202 * Do not error out if the current directory is not
203 * searchable: Maybe it won't be needed after all.
206 if (getcwd(buf
, PATH_MAX
) == NULL
) {
208 (void)strlcpy(buf
, strerror(errno
), sizeof(buf
));
212 sql
= sql_statement(e
);
215 * Loop over the directories (containing databases) for us to
217 * Don't let missing/bad databases/directories phase us.
218 * In each, try to open the resident database and, if it opens,
219 * scan it for our match expression.
223 for (i
= 0; i
< paths
->sz
; i
++) {
224 if (chdir_status
&& paths
->paths
[i
][0] != '/') {
225 if ( ! getcwd_status
) {
226 warnx("%s: getcwd: %s", paths
->paths
[i
], buf
);
228 } else if (chdir(buf
) == -1) {
233 if (chdir(paths
->paths
[i
]) == -1) {
234 perror(paths
->paths
[i
]);
239 c
= sqlite3_open_v2(MANDOC_DB
, &db
,
240 SQLITE_OPEN_READONLY
, NULL
);
242 if (SQLITE_OK
!= c
) {
243 warn("%s/%s", paths
->paths
[i
], MANDOC_DB
);
249 * Define the SQL functions for substring
250 * and regular expression matching.
253 c
= sqlite3_create_function(db
, "match", 2,
254 SQLITE_UTF8
| SQLITE_DETERMINISTIC
,
255 NULL
, sql_match
, NULL
, NULL
);
256 assert(SQLITE_OK
== c
);
257 c
= sqlite3_create_function(db
, "regexp", 2,
258 SQLITE_UTF8
| SQLITE_DETERMINISTIC
,
259 NULL
, sql_regexp
, NULL
, NULL
);
260 assert(SQLITE_OK
== c
);
263 c
= sqlite3_prepare_v2(db
, sql
, -1, &s
, NULL
);
265 errx((int)MANDOCLEVEL_SYSERR
,
266 "%s", sqlite3_errmsg(db
));
268 for (ep
= e
; NULL
!= ep
; ep
= ep
->next
) {
269 if (NULL
== ep
->substr
) {
270 SQL_BIND_BLOB(db
, s
, j
, ep
->regexp
);
272 SQL_BIND_TEXT(db
, s
, j
, ep
->substr
);
273 if (0 == ((TYPE_Nd
| TYPE_Nm
) & ep
->bits
))
274 SQL_BIND_INT64(db
, s
, j
, ep
->bits
);
277 mandoc_ohash_init(&htab
, 4, offsetof(struct match
, pageid
));
280 * Hash each entry on its [unique] document identifier.
281 * This is a uint64_t.
282 * Instead of using a hash function, simply convert the
283 * uint64_t to a uint32_t, the hash value's type.
284 * This gives good performance and preserves the
285 * distribution of buckets in the table.
287 while (SQLITE_ROW
== (c
= sqlite3_step(s
))) {
288 pageid
= sqlite3_column_int64(s
, 2);
289 idx
= ohash_lookup_memory(&htab
,
290 (char *)&pageid
, sizeof(uint64_t),
293 if (NULL
!= ohash_find(&htab
, idx
))
296 mp
= mandoc_calloc(1, sizeof(struct match
));
298 mp
->form
= sqlite3_column_int(s
, 1);
299 mp
->bits
= sqlite3_column_int64(s
, 3);
300 if (TYPE_Nd
== outbit
)
301 mp
->desc
= mandoc_strdup((const char *)
302 sqlite3_column_text(s
, 0));
303 ohash_insert(&htab
, idx
, mp
);
306 if (SQLITE_DONE
!= c
)
307 warnx("%s", sqlite3_errmsg(db
));
311 c
= sqlite3_prepare_v2(db
,
312 "SELECT sec, arch, name, pageid FROM mlinks "
313 "WHERE pageid=? ORDER BY sec, arch, name",
316 errx((int)MANDOCLEVEL_SYSERR
,
317 "%s", sqlite3_errmsg(db
));
319 c
= sqlite3_prepare_v2(db
,
320 "SELECT bits, key, pageid FROM keys "
321 "WHERE pageid=? AND bits & ?",
324 errx((int)MANDOCLEVEL_SYSERR
,
325 "%s", sqlite3_errmsg(db
));
327 for (mp
= ohash_first(&htab
, &idx
);
329 mp
= ohash_next(&htab
, &idx
)) {
330 if (cur
+ 1 > maxres
) {
332 *res
= mandoc_reallocarray(*res
,
333 maxres
, sizeof(struct manpage
));
337 mpage
->bits
= mp
->bits
;
339 mpage
->form
= mp
->form
;
340 buildnames(search
, mpage
, db
, s
, mp
->pageid
,
341 paths
->paths
[i
], mp
->form
);
342 if (mpage
->names
!= NULL
) {
343 mpage
->output
= TYPE_Nd
& outbit
?
345 buildoutput(db
, s2
, mp
->pageid
, outbit
) :
353 sqlite3_finalize(s2
);
358 * In man(1) mode, prefer matches in earlier trees
359 * over matches in later trees.
362 if (cur
&& search
->firstmatch
)
365 qsort(*res
, cur
, sizeof(struct manpage
), manpage_compare
);
366 if (chdir_status
&& getcwd_status
&& chdir(buf
) == -1)
375 mansearch_free(struct manpage
*res
, size_t sz
)
379 for (i
= 0; i
< sz
; i
++) {
388 manpage_compare(const void *vp1
, const void *vp2
)
390 const struct manpage
*mp1
, *mp2
;
395 return (diff
= mp2
->bits
- mp1
->bits
) ? diff
:
396 (diff
= mp1
->sec
- mp2
->sec
) ? diff
:
397 strcasecmp(mp1
->names
, mp2
->names
);
401 buildnames(const struct mansearch
*search
, struct manpage
*mpage
,
402 sqlite3
*db
, sqlite3_stmt
*s
,
403 uint64_t pageid
, const char *path
, int form
)
406 char *firstname
, *newnames
, *prevsec
, *prevarch
;
407 const char *oldnames
, *sep1
, *name
, *sec
, *sep2
, *arch
, *fsec
;
413 firstname
= prevsec
= prevarch
= NULL
;
415 SQL_BIND_INT64(db
, s
, i
, pageid
);
416 while (SQLITE_ROW
== (c
= sqlite3_step(s
))) {
418 /* Decide whether we already have some names. */
420 if (NULL
== mpage
->names
) {
424 oldnames
= mpage
->names
;
428 /* Fetch the next name, rejecting sec/arch mismatches. */
430 sec
= (const char *)sqlite3_column_text(s
, 0);
431 if (search
->sec
!= NULL
&& strcasecmp(sec
, search
->sec
))
433 arch
= (const char *)sqlite3_column_text(s
, 1);
434 if (search
->arch
!= NULL
&& *arch
!= '\0' &&
435 strcasecmp(arch
, search
->arch
))
437 name
= (const char *)sqlite3_column_text(s
, 2);
439 /* Remember the first section found. */
441 if (9 < mpage
->sec
&& '1' <= *sec
&& '9' >= *sec
)
442 mpage
->sec
= (*sec
- '1') + 1;
444 /* If the section changed, append the old one. */
446 if (NULL
!= prevsec
&&
447 (strcmp(sec
, prevsec
) ||
448 strcmp(arch
, prevarch
))) {
449 sep2
= '\0' == *prevarch
? "" : "/";
450 mandoc_asprintf(&newnames
, "%s(%s%s%s)",
451 oldnames
, prevsec
, sep2
, prevarch
);
453 oldnames
= mpage
->names
= newnames
;
456 prevsec
= prevarch
= NULL
;
459 /* Save the new section, to append it later. */
461 if (NULL
== prevsec
) {
462 prevsec
= mandoc_strdup(sec
);
463 prevarch
= mandoc_strdup(arch
);
466 /* Append the new name. */
468 mandoc_asprintf(&newnames
, "%s%s%s",
469 oldnames
, sep1
, name
);
471 mpage
->names
= newnames
;
473 /* Also save the first file name encountered. */
475 if (mpage
->file
!= NULL
)
478 if (form
& FORM_SRC
) {
485 sep2
= *arch
== '\0' ? "" : "/";
486 mandoc_asprintf(&mpage
->file
, "%s/%s%s%s%s/%s.%s",
487 path
, sep1
, sec
, sep2
, arch
, name
, fsec
);
488 if (access(mpage
->file
, R_OK
) != -1)
491 /* Handle unusual file name extensions. */
493 if (firstname
== NULL
)
494 firstname
= mpage
->file
;
497 mandoc_asprintf(&mpage
->file
, "%s/%s%s%s%s/%s.*",
498 path
, sep1
, sec
, sep2
, arch
, name
);
499 globres
= glob(mpage
->file
, 0, NULL
, &globinfo
);
501 mpage
->file
= globres
? NULL
:
502 mandoc_strdup(*globinfo
.gl_pathv
);
505 if (c
!= SQLITE_DONE
)
506 warnx("%s", sqlite3_errmsg(db
));
509 /* If none of the files is usable, use the first name. */
511 if (mpage
->file
== NULL
)
512 mpage
->file
= firstname
;
513 else if (mpage
->file
!= firstname
)
516 /* Append one final section to the names. */
518 if (prevsec
!= NULL
) {
519 sep2
= *prevarch
== '\0' ? "" : "/";
520 mandoc_asprintf(&newnames
, "%s(%s%s%s)",
521 mpage
->names
, prevsec
, sep2
, prevarch
);
523 mpage
->names
= newnames
;
530 buildoutput(sqlite3
*db
, sqlite3_stmt
*s
, uint64_t pageid
, uint64_t outbit
)
532 char *output
, *newoutput
;
533 const char *oldoutput
, *sep1
, *data
;
539 SQL_BIND_INT64(db
, s
, i
, pageid
);
540 SQL_BIND_INT64(db
, s
, i
, outbit
);
541 while (SQLITE_ROW
== (c
= sqlite3_step(s
))) {
542 if (NULL
== output
) {
549 data
= (const char *)sqlite3_column_text(s
, 1);
550 mandoc_asprintf(&newoutput
, "%s%s%s",
551 oldoutput
, sep1
, data
);
555 if (SQLITE_DONE
!= c
)
556 warnx("%s", sqlite3_errmsg(db
));
562 * Implement substring match as an application-defined SQL function.
563 * Using the SQL LIKE or GLOB operators instead would be a bad idea
564 * because that would require escaping metacharacters in the string
565 * being searched for.
568 sql_match(sqlite3_context
*context
, int argc
, sqlite3_value
**argv
)
572 sqlite3_result_int(context
, NULL
!= strcasestr(
573 (const char *)sqlite3_value_text(argv
[1]),
574 (const char *)sqlite3_value_text(argv
[0])));
578 * Implement regular expression match
579 * as an application-defined SQL function.
582 sql_regexp(sqlite3_context
*context
, int argc
, sqlite3_value
**argv
)
586 sqlite3_result_int(context
, !regexec(
587 (regex_t
*)sqlite3_value_blob(argv
[0]),
588 (const char *)sqlite3_value_text(argv
[1]),
593 sql_append(char **sql
, size_t *sz
, const char *newstr
, int count
)
597 newsz
= 1 < count
? (size_t)count
: strlen(newstr
);
598 *sql
= mandoc_realloc(*sql
, *sz
+ newsz
+ 1);
600 memset(*sql
+ *sz
, *newstr
, (size_t)count
);
602 memcpy(*sql
+ *sz
, newstr
, newsz
);
608 * Prepare the search SQL statement.
611 sql_statement(const struct expr
*e
)
617 sql
= mandoc_strdup(e
->equal
?
618 "SELECT desc, form, pageid, bits "
619 "FROM mpages NATURAL JOIN names WHERE " :
620 "SELECT desc, form, pageid, 0 FROM mpages WHERE ");
623 for (needop
= 0; NULL
!= e
; e
= e
->next
) {
625 sql_append(&sql
, &sz
, " AND ", 1);
627 sql_append(&sql
, &sz
, " OR ", 1);
629 sql_append(&sql
, &sz
, "(", e
->open
);
630 sql_append(&sql
, &sz
,
637 ? "pageid IN (SELECT pageid FROM names "
638 "WHERE name REGEXP ?)"
641 : "pageid IN (SELECT pageid FROM names "
642 "WHERE name MATCH ?)")
644 ? "pageid IN (SELECT pageid FROM keys "
645 "WHERE key REGEXP ? AND bits & ?)"
646 : "pageid IN (SELECT pageid FROM keys "
647 "WHERE key MATCH ? AND bits & ?)"), 1);
649 sql_append(&sql
, &sz
, ")", e
->close
);
657 * Compile a set of string tokens into an expression.
658 * Tokens in "argv" are assumed to be individual expression atoms (e.g.,
659 * "(", "foo=bar", etc.).
662 exprcomp(const struct mansearch
*search
, int argc
, char *argv
[])
665 int i
, toopen
, logic
, igncase
, toclose
;
666 struct expr
*first
, *prev
, *cur
, *next
;
669 logic
= igncase
= toopen
= toclose
= 0;
671 for (i
= 0; i
< argc
; i
++) {
672 if (0 == strcmp("(", argv
[i
])) {
678 } else if (0 == strcmp(")", argv
[i
])) {
679 if (toopen
|| logic
|| igncase
|| NULL
== cur
)
685 } else if (0 == strcmp("-a", argv
[i
])) {
686 if (toopen
|| logic
|| igncase
|| NULL
== cur
)
690 } else if (0 == strcmp("-o", argv
[i
])) {
691 if (toopen
|| logic
|| igncase
|| NULL
== cur
)
695 } else if (0 == strcmp("-i", argv
[i
])) {
701 next
= exprterm(search
, argv
[i
], !igncase
);
711 * Searching for descriptions must be split out
712 * because they are stored in the mpages table,
713 * not in the keys table.
716 for (mask
= TYPE_Nm
; mask
<= TYPE_Nd
; mask
<<= 1) {
717 if (mask
& cur
->bits
&& ~mask
& cur
->bits
) {
718 next
= mandoc_calloc(1,
719 sizeof(struct expr
));
720 memcpy(next
, cur
, sizeof(struct expr
));
728 prev
->and = (1 == logic
);
729 prev
->open
+= toopen
;
733 toopen
= logic
= igncase
= 0;
735 if ( ! (toopen
|| logic
|| igncase
|| toclose
))
745 exprterm(const struct mansearch
*search
, char *buf
, int cs
)
756 e
= mandoc_calloc(1, sizeof(struct expr
));
758 if (search
->argmode
== ARG_NAME
) {
766 * Separate macro keys from search string.
767 * If needed, request regular expression handling
768 * by setting e->substr to NULL.
771 if (search
->argmode
== ARG_WORD
) {
775 mandoc_asprintf(&val
, "[[:<:]]%s[[:>:]]", buf
);
777 mandoc_asprintf(&val
, "\\<%s\\>", buf
);
779 mandoc_asprintf(&val
,
780 "(^|[^a-zA-Z01-9_])%s([^a-zA-Z01-9_]|$)", buf
);
783 } else if ((val
= strpbrk(buf
, "=~")) == NULL
) {
784 e
->bits
= TYPE_Nm
| TYPE_Nd
;
788 e
->bits
= TYPE_Nm
| TYPE_Nd
;
792 if (NULL
!= strstr(buf
, "arch"))
796 /* Compile regular expressions. */
798 if (NULL
== e
->substr
) {
799 irc
= regcomp(&e
->regexp
, val
,
800 REG_EXTENDED
| REG_NOSUB
| (cs
? 0 : REG_ICASE
));
801 if (search
->argmode
== ARG_WORD
)
804 regerror(irc
, &e
->regexp
, errbuf
, sizeof(errbuf
));
805 warnx("regcomp: %s", errbuf
);
815 * Parse out all possible fields.
816 * If the field doesn't resolve, bail.
819 while (NULL
!= (key
= strsep(&buf
, ","))) {
822 for (i
= 0, iterbit
= 1;
823 i
< mansearch_keymax
;
824 i
++, iterbit
<<= 1) {
825 if (0 == strcasecmp(key
,
826 mansearch_keynames
[i
])) {
831 if (i
== mansearch_keymax
) {
832 if (strcasecmp(key
, "any")) {
844 exprfree(struct expr
*p
)