]>
git.cameronkatri.com Git - mandoc.git/blob - mansearch.c
1 /* $Id: mansearch.c,v 1.53 2015/01/20 18:21:18 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 AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR 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>
39 #include "compat_ohash.h"
42 #ifndef SQLITE_DETERMINISTIC
43 #define SQLITE_DETERMINISTIC 0
47 #include "mandoc_aux.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 fprintf(stderr, "%s\n", 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 fprintf(stderr, "%s\n", 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 fprintf(stderr, "%s\n", 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 void *hash_alloc(size_t, void *);
95 static void hash_free(void *, void *);
96 static void *hash_calloc(size_t, size_t, void *);
97 static struct expr
*exprcomp(const struct mansearch
*,
99 static void exprfree(struct expr
*);
100 static struct expr
*exprterm(const struct mansearch
*, char *, int);
101 static int manpage_compare(const void *, const void *);
102 static void sql_append(char **sql
, size_t *sz
,
103 const char *newstr
, int count
);
104 static void sql_match(sqlite3_context
*context
,
105 int argc
, sqlite3_value
**argv
);
106 static void sql_regexp(sqlite3_context
*context
,
107 int argc
, sqlite3_value
**argv
);
108 static char *sql_statement(const struct expr
*);
112 mansearch_setup(int start
)
114 static void *pagecache
;
117 #define PC_PAGESIZE 1280
118 #define PC_NUMPAGES 256
121 if (NULL
!= pagecache
) {
122 fprintf(stderr
, "pagecache already enabled\n");
123 return((int)MANDOCLEVEL_BADARG
);
126 pagecache
= mmap(NULL
, PC_PAGESIZE
* PC_NUMPAGES
,
127 PROT_READ
| PROT_WRITE
,
128 MAP_SHARED
| MAP_ANON
, -1, 0);
130 if (MAP_FAILED
== pagecache
) {
133 return((int)MANDOCLEVEL_SYSERR
);
136 c
= sqlite3_config(SQLITE_CONFIG_PAGECACHE
,
137 pagecache
, PC_PAGESIZE
, PC_NUMPAGES
);
140 return((int)MANDOCLEVEL_OK
);
142 fprintf(stderr
, "pagecache: %s\n", sqlite3_errstr(c
));
144 } else if (NULL
== pagecache
) {
145 fprintf(stderr
, "pagecache missing\n");
146 return((int)MANDOCLEVEL_BADARG
);
149 if (-1 == munmap(pagecache
, PC_PAGESIZE
* PC_NUMPAGES
)) {
152 return((int)MANDOCLEVEL_SYSERR
);
156 return((int)MANDOCLEVEL_OK
);
160 mansearch(const struct mansearch
*search
,
161 const struct manpaths
*paths
,
162 int argc
, char *argv
[],
163 struct manpage
**res
, size_t *sz
)
165 int fd
, rc
, c
, indexbit
;
167 uint64_t outbit
, iterbit
;
170 struct manpage
*mpage
;
173 sqlite3_stmt
*s
, *s2
;
175 struct ohash_info info
;
178 size_t i
, j
, cur
, maxres
;
180 info
.calloc
= hash_calloc
;
181 info
.alloc
= hash_alloc
;
182 info
.free
= hash_free
;
183 info
.key_offset
= offsetof(struct match
, pageid
);
185 *sz
= cur
= maxres
= 0;
194 if (NULL
== (e
= exprcomp(search
, argc
, argv
)))
198 if (NULL
!= search
->outkey
) {
199 for (indexbit
= 0, iterbit
= 1;
200 indexbit
< mansearch_keymax
;
201 indexbit
++, iterbit
<<= 1) {
202 if (0 == strcasecmp(search
->outkey
,
203 mansearch_keynames
[indexbit
])) {
211 * Save a descriptor to the current working directory.
212 * Since pathnames in the "paths" variable might be relative,
213 * and we'll be chdir()ing into them, we need to keep a handle
214 * on our current directory from which to start the chdir().
217 if (NULL
== getcwd(buf
, PATH_MAX
)) {
220 } else if (-1 == (fd
= open(buf
, O_RDONLY
, 0))) {
225 sql
= sql_statement(e
);
228 * Loop over the directories (containing databases) for us to
230 * Don't let missing/bad databases/directories phase us.
231 * In each, try to open the resident database and, if it opens,
232 * scan it for our match expression.
235 for (i
= 0; i
< paths
->sz
; i
++) {
236 if (-1 == fchdir(fd
)) {
240 } else if (-1 == chdir(paths
->paths
[i
])) {
241 perror(paths
->paths
[i
]);
245 c
= sqlite3_open_v2(MANDOC_DB
, &db
,
246 SQLITE_OPEN_READONLY
, NULL
);
248 if (SQLITE_OK
!= c
) {
249 fprintf(stderr
, "%s/%s: %s\n",
250 paths
->paths
[i
], MANDOC_DB
, strerror(errno
));
256 * Define the SQL functions for substring
257 * and regular expression matching.
260 c
= sqlite3_create_function(db
, "match", 2,
261 SQLITE_UTF8
| SQLITE_DETERMINISTIC
,
262 NULL
, sql_match
, NULL
, NULL
);
263 assert(SQLITE_OK
== c
);
264 c
= sqlite3_create_function(db
, "regexp", 2,
265 SQLITE_UTF8
| SQLITE_DETERMINISTIC
,
266 NULL
, sql_regexp
, NULL
, NULL
);
267 assert(SQLITE_OK
== c
);
270 c
= sqlite3_prepare_v2(db
, sql
, -1, &s
, NULL
);
272 fprintf(stderr
, "%s\n", sqlite3_errmsg(db
));
274 for (ep
= e
; NULL
!= ep
; ep
= ep
->next
) {
275 if (NULL
== ep
->substr
) {
276 SQL_BIND_BLOB(db
, s
, j
, ep
->regexp
);
278 SQL_BIND_TEXT(db
, s
, j
, ep
->substr
);
279 if (0 == ((TYPE_Nd
| TYPE_Nm
) & ep
->bits
))
280 SQL_BIND_INT64(db
, s
, j
, ep
->bits
);
283 memset(&htab
, 0, sizeof(struct ohash
));
284 ohash_init(&htab
, 4, &info
);
287 * Hash each entry on its [unique] document identifier.
288 * This is a uint64_t.
289 * Instead of using a hash function, simply convert the
290 * uint64_t to a uint32_t, the hash value's type.
291 * This gives good performance and preserves the
292 * distribution of buckets in the table.
294 while (SQLITE_ROW
== (c
= sqlite3_step(s
))) {
295 pageid
= sqlite3_column_int64(s
, 2);
296 idx
= ohash_lookup_memory(&htab
,
297 (char *)&pageid
, sizeof(uint64_t),
300 if (NULL
!= ohash_find(&htab
, idx
))
303 mp
= mandoc_calloc(1, sizeof(struct match
));
305 mp
->form
= sqlite3_column_int(s
, 1);
306 mp
->bits
= sqlite3_column_int64(s
, 3);
307 if (TYPE_Nd
== outbit
)
308 mp
->desc
= mandoc_strdup((const char *)
309 sqlite3_column_text(s
, 0));
310 ohash_insert(&htab
, idx
, mp
);
313 if (SQLITE_DONE
!= c
)
314 fprintf(stderr
, "%s\n", sqlite3_errmsg(db
));
318 c
= sqlite3_prepare_v2(db
,
319 "SELECT sec, arch, name, pageid FROM mlinks "
320 "WHERE pageid=? ORDER BY sec, arch, name",
323 fprintf(stderr
, "%s\n", sqlite3_errmsg(db
));
325 c
= sqlite3_prepare_v2(db
,
326 "SELECT bits, key, pageid FROM keys "
327 "WHERE pageid=? AND bits & ?",
330 fprintf(stderr
, "%s\n", sqlite3_errmsg(db
));
332 for (mp
= ohash_first(&htab
, &idx
);
334 mp
= ohash_next(&htab
, &idx
)) {
335 if (cur
+ 1 > maxres
) {
337 *res
= mandoc_reallocarray(*res
,
338 maxres
, sizeof(struct manpage
));
342 mpage
->bits
= mp
->bits
;
344 mpage
->form
= mp
->form
;
345 buildnames(search
, mpage
, db
, s
, mp
->pageid
,
346 paths
->paths
[i
], mp
->form
);
347 if (mpage
->names
!= NULL
) {
348 mpage
->output
= TYPE_Nd
& outbit
?
350 buildoutput(db
, s2
, mp
->pageid
, outbit
) :
358 sqlite3_finalize(s2
);
363 * In man(1) mode, prefer matches in earlier trees
364 * over matches in later trees.
367 if (cur
&& search
->firstmatch
)
370 qsort(*res
, cur
, sizeof(struct manpage
), manpage_compare
);
374 if (-1 == fchdir(fd
))
385 mansearch_free(struct manpage
*res
, size_t sz
)
389 for (i
= 0; i
< sz
; i
++) {
398 manpage_compare(const void *vp1
, const void *vp2
)
400 const struct manpage
*mp1
, *mp2
;
405 return( (diff
= mp2
->bits
- mp1
->bits
) ? diff
:
406 (diff
= mp1
->sec
- mp2
->sec
) ? diff
:
407 strcasecmp(mp1
->names
, mp2
->names
));
411 buildnames(const struct mansearch
*search
, struct manpage
*mpage
,
412 sqlite3
*db
, sqlite3_stmt
*s
,
413 uint64_t pageid
, const char *path
, int form
)
415 char *newnames
, *prevsec
, *prevarch
;
416 const char *oldnames
, *sep1
, *name
, *sec
, *sep2
, *arch
, *fsec
;
422 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
);
498 if (c
!= SQLITE_DONE
)
499 fprintf(stderr
, "%s\n", sqlite3_errmsg(db
));
502 /* Append one final section to the names. */
504 if (prevsec
!= NULL
) {
505 sep2
= *prevarch
== '\0' ? "" : "/";
506 mandoc_asprintf(&newnames
, "%s(%s%s%s)",
507 mpage
->names
, prevsec
, sep2
, prevarch
);
509 mpage
->names
= newnames
;
516 buildoutput(sqlite3
*db
, sqlite3_stmt
*s
, uint64_t pageid
, uint64_t outbit
)
518 char *output
, *newoutput
;
519 const char *oldoutput
, *sep1
, *data
;
525 SQL_BIND_INT64(db
, s
, i
, pageid
);
526 SQL_BIND_INT64(db
, s
, i
, outbit
);
527 while (SQLITE_ROW
== (c
= sqlite3_step(s
))) {
528 if (NULL
== output
) {
535 data
= (const char *)sqlite3_column_text(s
, 1);
536 mandoc_asprintf(&newoutput
, "%s%s%s",
537 oldoutput
, sep1
, data
);
541 if (SQLITE_DONE
!= c
)
542 fprintf(stderr
, "%s\n", sqlite3_errmsg(db
));
548 * Implement substring match as an application-defined SQL function.
549 * Using the SQL LIKE or GLOB operators instead would be a bad idea
550 * because that would require escaping metacharacters in the string
551 * being searched for.
554 sql_match(sqlite3_context
*context
, int argc
, sqlite3_value
**argv
)
558 sqlite3_result_int(context
, NULL
!= strcasestr(
559 (const char *)sqlite3_value_text(argv
[1]),
560 (const char *)sqlite3_value_text(argv
[0])));
564 * Implement regular expression match
565 * as an application-defined SQL function.
568 sql_regexp(sqlite3_context
*context
, int argc
, sqlite3_value
**argv
)
572 sqlite3_result_int(context
, !regexec(
573 (regex_t
*)sqlite3_value_blob(argv
[0]),
574 (const char *)sqlite3_value_text(argv
[1]),
579 sql_append(char **sql
, size_t *sz
, const char *newstr
, int count
)
583 newsz
= 1 < count
? (size_t)count
: strlen(newstr
);
584 *sql
= mandoc_realloc(*sql
, *sz
+ newsz
+ 1);
586 memset(*sql
+ *sz
, *newstr
, (size_t)count
);
588 memcpy(*sql
+ *sz
, newstr
, newsz
);
594 * Prepare the search SQL statement.
597 sql_statement(const struct expr
*e
)
603 sql
= mandoc_strdup(e
->equal
?
604 "SELECT desc, form, pageid, bits "
605 "FROM mpages NATURAL JOIN names WHERE " :
606 "SELECT desc, form, pageid, 0 FROM mpages WHERE ");
609 for (needop
= 0; NULL
!= e
; e
= e
->next
) {
611 sql_append(&sql
, &sz
, " AND ", 1);
613 sql_append(&sql
, &sz
, " OR ", 1);
615 sql_append(&sql
, &sz
, "(", e
->open
);
616 sql_append(&sql
, &sz
,
623 ? "pageid IN (SELECT pageid FROM names "
624 "WHERE name REGEXP ?)"
627 : "pageid IN (SELECT pageid FROM names "
628 "WHERE name MATCH ?)")
630 ? "pageid IN (SELECT pageid FROM keys "
631 "WHERE key REGEXP ? AND bits & ?)"
632 : "pageid IN (SELECT pageid FROM keys "
633 "WHERE key MATCH ? AND bits & ?)"), 1);
635 sql_append(&sql
, &sz
, ")", e
->close
);
643 * Compile a set of string tokens into an expression.
644 * Tokens in "argv" are assumed to be individual expression atoms (e.g.,
645 * "(", "foo=bar", etc.).
648 exprcomp(const struct mansearch
*search
, int argc
, char *argv
[])
651 int i
, toopen
, logic
, igncase
, toclose
;
652 struct expr
*first
, *prev
, *cur
, *next
;
655 logic
= igncase
= toopen
= toclose
= 0;
657 for (i
= 0; i
< argc
; i
++) {
658 if (0 == strcmp("(", argv
[i
])) {
664 } else if (0 == strcmp(")", argv
[i
])) {
665 if (toopen
|| logic
|| igncase
|| NULL
== cur
)
671 } else if (0 == strcmp("-a", argv
[i
])) {
672 if (toopen
|| logic
|| igncase
|| NULL
== cur
)
676 } else if (0 == strcmp("-o", argv
[i
])) {
677 if (toopen
|| logic
|| igncase
|| NULL
== cur
)
681 } else if (0 == strcmp("-i", argv
[i
])) {
687 next
= exprterm(search
, argv
[i
], !igncase
);
697 * Searching for descriptions must be split out
698 * because they are stored in the mpages table,
699 * not in the keys table.
702 for (mask
= TYPE_Nm
; mask
<= TYPE_Nd
; mask
<<= 1) {
703 if (mask
& cur
->bits
&& ~mask
& cur
->bits
) {
704 next
= mandoc_calloc(1,
705 sizeof(struct expr
));
706 memcpy(next
, cur
, sizeof(struct expr
));
714 prev
->and = (1 == logic
);
715 prev
->open
+= toopen
;
719 toopen
= logic
= igncase
= 0;
721 if ( ! (toopen
|| logic
|| igncase
|| toclose
))
731 exprterm(const struct mansearch
*search
, char *buf
, int cs
)
742 e
= mandoc_calloc(1, sizeof(struct expr
));
744 if (search
->argmode
== ARG_NAME
) {
752 * Separate macro keys from search string.
753 * If needed, request regular expression handling
754 * by setting e->substr to NULL.
757 if (search
->argmode
== ARG_WORD
) {
760 mandoc_asprintf(&val
, "[[:<:]]%s[[:>:]]", buf
);
762 } else if ((val
= strpbrk(buf
, "=~")) == NULL
) {
763 e
->bits
= TYPE_Nm
| TYPE_Nd
;
767 e
->bits
= TYPE_Nm
| TYPE_Nd
;
771 if (NULL
!= strstr(buf
, "arch"))
775 /* Compile regular expressions. */
777 if (NULL
== e
->substr
) {
778 irc
= regcomp(&e
->regexp
, val
,
779 REG_EXTENDED
| REG_NOSUB
| (cs
? 0 : REG_ICASE
));
780 if (search
->argmode
== ARG_WORD
)
783 regerror(irc
, &e
->regexp
, errbuf
, sizeof(errbuf
));
784 fprintf(stderr
, "regcomp: %s\n", errbuf
);
794 * Parse out all possible fields.
795 * If the field doesn't resolve, bail.
798 while (NULL
!= (key
= strsep(&buf
, ","))) {
801 for (i
= 0, iterbit
= 1;
802 i
< mansearch_keymax
;
803 i
++, iterbit
<<= 1) {
804 if (0 == strcasecmp(key
,
805 mansearch_keynames
[i
])) {
810 if (i
== mansearch_keymax
) {
811 if (strcasecmp(key
, "any")) {
823 exprfree(struct expr
*p
)
835 hash_calloc(size_t nmemb
, size_t sz
, void *arg
)
838 return(mandoc_calloc(nmemb
, sz
));
842 hash_alloc(size_t sz
, void *arg
)
845 return(mandoc_malloc(sz
));
849 hash_free(void *p
, void *arg
)