]>
git.cameronkatri.com Git - mandoc.git/blob - mansearch.c
1 /* $Id: mansearch.c,v 1.59 2015/10/11 21:12:55 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 #include "compat_ohash.h"
44 #ifndef SQLITE_DETERMINISTIC
45 #define SQLITE_DETERMINISTIC 0
49 #include "mandoc_aux.h"
51 #include "mansearch.h"
53 extern int mansearch_keymax
;
54 extern const char *const mansearch_keynames
[];
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))); \
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))); \
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))); \
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 */
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? */
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
*,
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
*,
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
*);
114 mansearch_setup(int start
)
116 static void *pagecache
;
119 #define PC_PAGESIZE 1280
120 #define PC_NUMPAGES 256
123 if (NULL
!= pagecache
) {
124 warnx("pagecache already enabled");
125 return (int)MANDOCLEVEL_BADARG
;
128 pagecache
= mmap(NULL
, PC_PAGESIZE
* PC_NUMPAGES
,
129 PROT_READ
| PROT_WRITE
,
130 MAP_SHARED
| MAP_ANON
, -1, 0);
132 if (MAP_FAILED
== pagecache
) {
135 return (int)MANDOCLEVEL_SYSERR
;
138 c
= sqlite3_config(SQLITE_CONFIG_PAGECACHE
,
139 pagecache
, PC_PAGESIZE
, PC_NUMPAGES
);
142 return (int)MANDOCLEVEL_OK
;
144 warnx("pagecache: %s", sqlite3_errstr(c
));
146 } else if (NULL
== pagecache
) {
147 warnx("pagecache missing");
148 return (int)MANDOCLEVEL_BADARG
;
151 if (-1 == munmap(pagecache
, PC_PAGESIZE
* PC_NUMPAGES
)) {
154 return (int)MANDOCLEVEL_SYSERR
;
158 return (int)MANDOCLEVEL_OK
;
162 mansearch(const struct mansearch
*search
,
163 const struct manpaths
*paths
,
164 int argc
, char *argv
[],
165 struct manpage
**res
, size_t *sz
)
168 uint64_t outbit
, iterbit
;
171 struct manpage
*mpage
;
174 sqlite3_stmt
*s
, *s2
;
176 struct ohash_info info
;
179 size_t i
, j
, cur
, maxres
;
180 int c
, chdir_status
, getcwd_status
, indexbit
;
182 if (argc
== 0 || (e
= exprcomp(search
, argc
, argv
)) == NULL
) {
187 info
.calloc
= hash_calloc
;
188 info
.alloc
= hash_alloc
;
189 info
.free
= hash_free
;
190 info
.key_offset
= offsetof(struct match
, pageid
);
195 if (NULL
!= search
->outkey
) {
197 for (indexbit
= 0, iterbit
= 1;
198 indexbit
< mansearch_keymax
;
199 indexbit
++, iterbit
<<= 1) {
200 if (0 == strcasecmp(search
->outkey
,
201 mansearch_keynames
[indexbit
])) {
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.
217 if (getcwd(buf
, PATH_MAX
) == NULL
) {
219 (void)strlcpy(buf
, strerror(errno
), sizeof(buf
));
223 sql
= sql_statement(e
);
226 * Loop over the directories (containing databases) for us to
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.
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
);
239 } else if (chdir(buf
) == -1) {
244 if (chdir(paths
->paths
[i
]) == -1) {
245 perror(paths
->paths
[i
]);
250 c
= sqlite3_open_v2(MANDOC_DB
, &db
,
251 SQLITE_OPEN_READONLY
, NULL
);
253 if (SQLITE_OK
!= c
) {
254 warn("%s/%s", paths
->paths
[i
], MANDOC_DB
);
260 * Define the SQL functions for substring
261 * and regular expression matching.
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
);
274 c
= sqlite3_prepare_v2(db
, sql
, -1, &s
, NULL
);
276 warnx("%s", sqlite3_errmsg(db
));
278 for (ep
= e
; NULL
!= ep
; ep
= ep
->next
) {
279 if (NULL
== ep
->substr
) {
280 SQL_BIND_BLOB(db
, s
, j
, ep
->regexp
);
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
);
287 memset(&htab
, 0, sizeof(struct ohash
));
288 ohash_init(&htab
, 4, &info
);
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.
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),
304 if (NULL
!= ohash_find(&htab
, idx
))
307 mp
= mandoc_calloc(1, sizeof(struct match
));
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
);
317 if (SQLITE_DONE
!= c
)
318 warnx("%s", sqlite3_errmsg(db
));
322 c
= sqlite3_prepare_v2(db
,
323 "SELECT sec, arch, name, pageid FROM mlinks "
324 "WHERE pageid=? ORDER BY sec, arch, name",
327 warnx("%s", sqlite3_errmsg(db
));
329 c
= sqlite3_prepare_v2(db
,
330 "SELECT bits, key, pageid FROM keys "
331 "WHERE pageid=? AND bits & ?",
334 warnx("%s", sqlite3_errmsg(db
));
336 for (mp
= ohash_first(&htab
, &idx
);
338 mp
= ohash_next(&htab
, &idx
)) {
339 if (cur
+ 1 > maxres
) {
341 *res
= mandoc_reallocarray(*res
,
342 maxres
, sizeof(struct manpage
));
346 mpage
->bits
= mp
->bits
;
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
?
354 buildoutput(db
, s2
, mp
->pageid
, outbit
) :
362 sqlite3_finalize(s2
);
367 * In man(1) mode, prefer matches in earlier trees
368 * over matches in later trees.
371 if (cur
&& search
->firstmatch
)
374 qsort(*res
, cur
, sizeof(struct manpage
), manpage_compare
);
375 if (chdir_status
&& getcwd_status
&& chdir(buf
) == -1)
384 mansearch_free(struct manpage
*res
, size_t sz
)
388 for (i
= 0; i
< sz
; i
++) {
397 manpage_compare(const void *vp1
, const void *vp2
)
399 const struct manpage
*mp1
, *mp2
;
404 return (diff
= mp2
->bits
- mp1
->bits
) ? diff
:
405 (diff
= mp1
->sec
- mp2
->sec
) ? diff
:
406 strcasecmp(mp1
->names
, mp2
->names
);
410 buildnames(const struct mansearch
*search
, struct manpage
*mpage
,
411 sqlite3
*db
, sqlite3_stmt
*s
,
412 uint64_t pageid
, const char *path
, int form
)
415 char *firstname
, *newnames
, *prevsec
, *prevarch
;
416 const char *oldnames
, *sep1
, *name
, *sec
, *sep2
, *arch
, *fsec
;
422 firstname
= prevsec
= prevarch
= NULL
;
424 SQL_BIND_INT64(db
, s
, i
, pageid
);
425 while (SQLITE_ROW
== (c
= sqlite3_step(s
))) {
427 /* Decide whether we already have some names. */
429 if (NULL
== mpage
->names
) {
433 oldnames
= mpage
->names
;
437 /* Fetch the next name, rejecting sec/arch mismatches. */
439 sec
= (const char *)sqlite3_column_text(s
, 0);
440 if (search
->sec
!= NULL
&& strcasecmp(sec
, search
->sec
))
442 arch
= (const char *)sqlite3_column_text(s
, 1);
443 if (search
->arch
!= NULL
&& *arch
!= '\0' &&
444 strcasecmp(arch
, search
->arch
))
446 name
= (const char *)sqlite3_column_text(s
, 2);
448 /* Remember the first section found. */
450 if (9 < mpage
->sec
&& '1' <= *sec
&& '9' >= *sec
)
451 mpage
->sec
= (*sec
- '1') + 1;
453 /* If the section changed, append the old one. */
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
);
462 oldnames
= mpage
->names
= newnames
;
465 prevsec
= prevarch
= NULL
;
468 /* Save the new section, to append it later. */
470 if (NULL
== prevsec
) {
471 prevsec
= mandoc_strdup(sec
);
472 prevarch
= mandoc_strdup(arch
);
475 /* Append the new name. */
477 mandoc_asprintf(&newnames
, "%s%s%s",
478 oldnames
, sep1
, name
);
480 mpage
->names
= newnames
;
482 /* Also save the first file name encountered. */
484 if (mpage
->file
!= NULL
)
487 if (form
& FORM_SRC
) {
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)
500 /* Handle unusual file name extensions. */
502 if (firstname
== NULL
)
503 firstname
= 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
);
510 mpage
->file
= globres
? NULL
:
511 mandoc_strdup(*globinfo
.gl_pathv
);
514 if (c
!= SQLITE_DONE
)
515 warnx("%s", sqlite3_errmsg(db
));
518 /* If none of the files is usable, use the first name. */
520 if (mpage
->file
== NULL
)
521 mpage
->file
= firstname
;
522 else if (mpage
->file
!= firstname
)
525 /* Append one final section to the names. */
527 if (prevsec
!= NULL
) {
528 sep2
= *prevarch
== '\0' ? "" : "/";
529 mandoc_asprintf(&newnames
, "%s(%s%s%s)",
530 mpage
->names
, prevsec
, sep2
, prevarch
);
532 mpage
->names
= newnames
;
539 buildoutput(sqlite3
*db
, sqlite3_stmt
*s
, uint64_t pageid
, uint64_t outbit
)
541 char *output
, *newoutput
;
542 const char *oldoutput
, *sep1
, *data
;
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
) {
558 data
= (const char *)sqlite3_column_text(s
, 1);
559 mandoc_asprintf(&newoutput
, "%s%s%s",
560 oldoutput
, sep1
, data
);
564 if (SQLITE_DONE
!= c
)
565 warnx("%s", sqlite3_errmsg(db
));
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.
577 sql_match(sqlite3_context
*context
, int argc
, sqlite3_value
**argv
)
581 sqlite3_result_int(context
, NULL
!= strcasestr(
582 (const char *)sqlite3_value_text(argv
[1]),
583 (const char *)sqlite3_value_text(argv
[0])));
587 * Implement regular expression match
588 * as an application-defined SQL function.
591 sql_regexp(sqlite3_context
*context
, int argc
, sqlite3_value
**argv
)
595 sqlite3_result_int(context
, !regexec(
596 (regex_t
*)sqlite3_value_blob(argv
[0]),
597 (const char *)sqlite3_value_text(argv
[1]),
602 sql_append(char **sql
, size_t *sz
, const char *newstr
, int count
)
606 newsz
= 1 < count
? (size_t)count
: strlen(newstr
);
607 *sql
= mandoc_realloc(*sql
, *sz
+ newsz
+ 1);
609 memset(*sql
+ *sz
, *newstr
, (size_t)count
);
611 memcpy(*sql
+ *sz
, newstr
, newsz
);
617 * Prepare the search SQL statement.
620 sql_statement(const struct expr
*e
)
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 ");
632 for (needop
= 0; NULL
!= e
; e
= e
->next
) {
634 sql_append(&sql
, &sz
, " AND ", 1);
636 sql_append(&sql
, &sz
, " OR ", 1);
638 sql_append(&sql
, &sz
, "(", e
->open
);
639 sql_append(&sql
, &sz
,
646 ? "pageid IN (SELECT pageid FROM names "
647 "WHERE name REGEXP ?)"
650 : "pageid IN (SELECT pageid FROM names "
651 "WHERE name MATCH ?)")
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);
658 sql_append(&sql
, &sz
, ")", e
->close
);
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.).
671 exprcomp(const struct mansearch
*search
, int argc
, char *argv
[])
674 int i
, toopen
, logic
, igncase
, toclose
;
675 struct expr
*first
, *prev
, *cur
, *next
;
678 logic
= igncase
= toopen
= toclose
= 0;
680 for (i
= 0; i
< argc
; i
++) {
681 if (0 == strcmp("(", argv
[i
])) {
687 } else if (0 == strcmp(")", argv
[i
])) {
688 if (toopen
|| logic
|| igncase
|| NULL
== cur
)
694 } else if (0 == strcmp("-a", argv
[i
])) {
695 if (toopen
|| logic
|| igncase
|| NULL
== cur
)
699 } else if (0 == strcmp("-o", argv
[i
])) {
700 if (toopen
|| logic
|| igncase
|| NULL
== cur
)
704 } else if (0 == strcmp("-i", argv
[i
])) {
710 next
= exprterm(search
, argv
[i
], !igncase
);
720 * Searching for descriptions must be split out
721 * because they are stored in the mpages table,
722 * not in the keys table.
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
));
737 prev
->and = (1 == logic
);
738 prev
->open
+= toopen
;
742 toopen
= logic
= igncase
= 0;
744 if ( ! (toopen
|| logic
|| igncase
|| toclose
))
754 exprterm(const struct mansearch
*search
, char *buf
, int cs
)
765 e
= mandoc_calloc(1, sizeof(struct expr
));
767 if (search
->argmode
== ARG_NAME
) {
775 * Separate macro keys from search string.
776 * If needed, request regular expression handling
777 * by setting e->substr to NULL.
780 if (search
->argmode
== ARG_WORD
) {
783 mandoc_asprintf(&val
, "[[:<:]]%s[[:>:]]", buf
);
785 } else if ((val
= strpbrk(buf
, "=~")) == NULL
) {
786 e
->bits
= TYPE_Nm
| TYPE_Nd
;
790 e
->bits
= TYPE_Nm
| TYPE_Nd
;
794 if (NULL
!= strstr(buf
, "arch"))
798 /* Compile regular expressions. */
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
)
806 regerror(irc
, &e
->regexp
, errbuf
, sizeof(errbuf
));
807 warnx("regcomp: %s", errbuf
);
817 * Parse out all possible fields.
818 * If the field doesn't resolve, bail.
821 while (NULL
!= (key
= strsep(&buf
, ","))) {
824 for (i
= 0, iterbit
= 1;
825 i
< mansearch_keymax
;
826 i
++, iterbit
<<= 1) {
827 if (0 == strcasecmp(key
,
828 mansearch_keynames
[i
])) {
833 if (i
== mansearch_keymax
) {
834 if (strcasecmp(key
, "any")) {
846 exprfree(struct expr
*p
)
858 hash_calloc(size_t nmemb
, size_t sz
, void *arg
)
861 return mandoc_calloc(nmemb
, sz
);
865 hash_alloc(size_t sz
, void *arg
)
868 return mandoc_malloc(sz
);
872 hash_free(void *p
, void *arg
)