]>
git.cameronkatri.com Git - mandoc.git/blob - mansearch.c
1 /* $Id: mansearch.c,v 1.46 2014/08/21 20:29:07 schwarze Exp $ */
3 * Copyright (c) 2012 Kristaps Dzonsons <kristaps@bsd.lv>
4 * Copyright (c) 2013, 2014 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>
38 #include "compat_ohash.h"
41 #ifndef SQLITE_DETERMINISTIC
42 #define SQLITE_DETERMINISTIC 0
46 #include "mandoc_aux.h"
48 #include "mansearch.h"
50 extern int mansearch_keymax
;
51 extern const char *const mansearch_keynames
[];
53 #define SQL_BIND_TEXT(_db, _s, _i, _v) \
54 do { if (SQLITE_OK != sqlite3_bind_text \
55 ((_s), (_i)++, (_v), -1, SQLITE_STATIC)) \
56 fprintf(stderr, "%s\n", sqlite3_errmsg((_db))); \
58 #define SQL_BIND_INT64(_db, _s, _i, _v) \
59 do { if (SQLITE_OK != sqlite3_bind_int64 \
60 ((_s), (_i)++, (_v))) \
61 fprintf(stderr, "%s\n", sqlite3_errmsg((_db))); \
63 #define SQL_BIND_BLOB(_db, _s, _i, _v) \
64 do { if (SQLITE_OK != sqlite3_bind_blob \
65 ((_s), (_i)++, (&_v), sizeof(_v), SQLITE_STATIC)) \
66 fprintf(stderr, "%s\n", sqlite3_errmsg((_db))); \
70 regex_t regexp
; /* compiled regexp, if applicable */
71 const char *substr
; /* to search for, if applicable */
72 struct expr
*next
; /* next in sequence */
73 uint64_t bits
; /* type-mask */
74 int equal
; /* equality, not subsring match */
75 int open
; /* opening parentheses before */
76 int and; /* logical AND before */
77 int close
; /* closing parentheses after */
81 uint64_t pageid
; /* identifier in database */
82 char *desc
; /* manual page description */
83 int form
; /* 0 == catpage */
86 static void buildnames(struct manpage
*, sqlite3
*,
87 sqlite3_stmt
*, uint64_t,
88 const char *, int form
);
89 static char *buildoutput(sqlite3
*, sqlite3_stmt
*,
91 static void *hash_alloc(size_t, void *);
92 static void hash_free(void *, void *);
93 static void *hash_calloc(size_t, size_t, void *);
94 static struct expr
*exprcomp(const struct mansearch
*,
96 static void exprfree(struct expr
*);
97 static struct expr
*exprspec(struct expr
*, uint64_t,
98 const char *, const char *);
99 static struct expr
*exprterm(const struct mansearch
*, char *, int);
100 static int manpage_compare(const void *, const void *);
101 static void sql_append(char **sql
, size_t *sz
,
102 const char *newstr
, int count
);
103 static void sql_match(sqlite3_context
*context
,
104 int argc
, sqlite3_value
**argv
);
105 static void sql_regexp(sqlite3_context
*context
,
106 int argc
, sqlite3_value
**argv
);
107 static char *sql_statement(const struct expr
*);
111 mansearch_setup(int start
)
113 static void *pagecache
;
116 #define PC_PAGESIZE 1280
117 #define PC_NUMPAGES 256
120 if (NULL
!= pagecache
) {
121 fprintf(stderr
, "pagecache already enabled\n");
122 return((int)MANDOCLEVEL_BADARG
);
125 pagecache
= mmap(NULL
, PC_PAGESIZE
* PC_NUMPAGES
,
126 PROT_READ
| PROT_WRITE
,
127 MAP_SHARED
| MAP_ANON
, -1, 0);
129 if (MAP_FAILED
== pagecache
) {
132 return((int)MANDOCLEVEL_SYSERR
);
135 c
= sqlite3_config(SQLITE_CONFIG_PAGECACHE
,
136 pagecache
, PC_PAGESIZE
, PC_NUMPAGES
);
139 return((int)MANDOCLEVEL_OK
);
141 fprintf(stderr
, "pagecache: %s\n", sqlite3_errstr(c
));
143 } else if (NULL
== pagecache
) {
144 fprintf(stderr
, "pagecache missing\n");
145 return((int)MANDOCLEVEL_BADARG
);
148 if (-1 == munmap(pagecache
, PC_PAGESIZE
* PC_NUMPAGES
)) {
151 return((int)MANDOCLEVEL_SYSERR
);
155 return((int)MANDOCLEVEL_OK
);
159 mansearch(const struct mansearch
*search
,
160 const struct manpaths
*paths
,
161 int argc
, char *argv
[],
162 struct manpage
**res
, size_t *sz
)
164 int fd
, rc
, c
, indexbit
;
166 uint64_t outbit
, iterbit
;
169 struct manpage
*mpage
;
172 sqlite3_stmt
*s
, *s2
;
174 struct ohash_info info
;
177 size_t i
, j
, cur
, maxres
;
179 info
.calloc
= hash_calloc
;
180 info
.alloc
= hash_alloc
;
181 info
.free
= hash_free
;
182 info
.key_offset
= offsetof(struct match
, pageid
);
184 *sz
= cur
= maxres
= 0;
193 if (NULL
== (e
= exprcomp(search
, argc
, argv
)))
197 if (NULL
!= search
->outkey
) {
198 for (indexbit
= 0, iterbit
= 1;
199 indexbit
< mansearch_keymax
;
200 indexbit
++, iterbit
<<= 1) {
201 if (0 == strcasecmp(search
->outkey
,
202 mansearch_keynames
[indexbit
])) {
210 * Save a descriptor to the current working directory.
211 * Since pathnames in the "paths" variable might be relative,
212 * and we'll be chdir()ing into them, we need to keep a handle
213 * on our current directory from which to start the chdir().
216 if (NULL
== getcwd(buf
, PATH_MAX
)) {
219 } else if (-1 == (fd
= open(buf
, O_RDONLY
, 0))) {
224 sql
= sql_statement(e
);
227 * Loop over the directories (containing databases) for us to
229 * Don't let missing/bad databases/directories phase us.
230 * In each, try to open the resident database and, if it opens,
231 * scan it for our match expression.
234 for (i
= 0; i
< paths
->sz
; i
++) {
235 if (-1 == fchdir(fd
)) {
239 } else if (-1 == chdir(paths
->paths
[i
])) {
240 perror(paths
->paths
[i
]);
244 c
= sqlite3_open_v2(MANDOC_DB
, &db
,
245 SQLITE_OPEN_READONLY
, NULL
);
247 if (SQLITE_OK
!= c
) {
254 * Define the SQL functions for substring
255 * and regular expression matching.
258 c
= sqlite3_create_function(db
, "match", 2,
259 SQLITE_UTF8
| SQLITE_DETERMINISTIC
,
260 NULL
, sql_match
, NULL
, NULL
);
261 assert(SQLITE_OK
== c
);
262 c
= sqlite3_create_function(db
, "regexp", 2,
263 SQLITE_UTF8
| SQLITE_DETERMINISTIC
,
264 NULL
, sql_regexp
, NULL
, NULL
);
265 assert(SQLITE_OK
== c
);
268 c
= sqlite3_prepare_v2(db
, sql
, -1, &s
, NULL
);
270 fprintf(stderr
, "%s\n", sqlite3_errmsg(db
));
272 for (ep
= e
; NULL
!= ep
; ep
= ep
->next
) {
273 if (NULL
== ep
->substr
) {
274 SQL_BIND_BLOB(db
, s
, j
, ep
->regexp
);
276 SQL_BIND_TEXT(db
, s
, j
, ep
->substr
);
277 if (0 == ((TYPE_Nd
| TYPE_Nm
) & ep
->bits
))
278 SQL_BIND_INT64(db
, s
, j
, ep
->bits
);
281 memset(&htab
, 0, sizeof(struct ohash
));
282 ohash_init(&htab
, 4, &info
);
285 * Hash each entry on its [unique] document identifier.
286 * This is a uint64_t.
287 * Instead of using a hash function, simply convert the
288 * uint64_t to a uint32_t, the hash value's type.
289 * This gives good performance and preserves the
290 * distribution of buckets in the table.
292 while (SQLITE_ROW
== (c
= sqlite3_step(s
))) {
293 pageid
= sqlite3_column_int64(s
, 2);
294 idx
= ohash_lookup_memory(&htab
,
295 (char *)&pageid
, sizeof(uint64_t),
298 if (NULL
!= ohash_find(&htab
, idx
))
301 mp
= mandoc_calloc(1, sizeof(struct match
));
303 mp
->form
= sqlite3_column_int(s
, 1);
304 if (TYPE_Nd
== outbit
)
305 mp
->desc
= mandoc_strdup((const char *)
306 sqlite3_column_text(s
, 0));
307 ohash_insert(&htab
, idx
, mp
);
310 if (SQLITE_DONE
!= c
)
311 fprintf(stderr
, "%s\n", sqlite3_errmsg(db
));
315 c
= sqlite3_prepare_v2(db
,
316 "SELECT sec, arch, name, pageid FROM mlinks "
317 "WHERE pageid=? ORDER BY sec, arch, name",
320 fprintf(stderr
, "%s\n", sqlite3_errmsg(db
));
322 c
= sqlite3_prepare_v2(db
,
323 "SELECT bits, key, pageid FROM keys "
324 "WHERE pageid=? AND bits & ?",
327 fprintf(stderr
, "%s\n", sqlite3_errmsg(db
));
329 for (mp
= ohash_first(&htab
, &idx
);
331 mp
= ohash_next(&htab
, &idx
)) {
332 if (cur
+ 1 > maxres
) {
334 *res
= mandoc_reallocarray(*res
,
335 maxres
, sizeof(struct manpage
));
339 mpage
->form
= mp
->form
;
340 buildnames(mpage
, db
, s
, mp
->pageid
,
341 paths
->paths
[i
], mp
->form
);
342 mpage
->output
= TYPE_Nd
& outbit
?
344 buildoutput(db
, s2
, mp
->pageid
, outbit
) : NULL
;
351 sqlite3_finalize(s2
);
355 qsort(*res
, cur
, sizeof(struct manpage
), manpage_compare
);
359 if (-1 == fchdir(fd
))
370 mansearch_free(struct manpage
*res
, size_t sz
)
374 for (i
= 0; i
< sz
; i
++) {
383 manpage_compare(const void *vp1
, const void *vp2
)
385 const struct manpage
*mp1
, *mp2
;
390 diff
= mp1
->sec
- mp2
->sec
;
391 return(diff
? diff
: strcasecmp(mp1
->names
, mp2
->names
));
395 buildnames(struct manpage
*mpage
, sqlite3
*db
, sqlite3_stmt
*s
,
396 uint64_t pageid
, const char *path
, int form
)
398 char *newnames
, *prevsec
, *prevarch
;
399 const char *oldnames
, *sep1
, *name
, *sec
, *sep2
, *arch
, *fsec
;
405 prevsec
= prevarch
= NULL
;
407 SQL_BIND_INT64(db
, s
, i
, pageid
);
408 while (SQLITE_ROW
== (c
= sqlite3_step(s
))) {
410 /* Decide whether we already have some names. */
412 if (NULL
== mpage
->names
) {
416 oldnames
= mpage
->names
;
420 /* Fetch the next name. */
422 sec
= (const char *)sqlite3_column_text(s
, 0);
423 arch
= (const char *)sqlite3_column_text(s
, 1);
424 name
= (const char *)sqlite3_column_text(s
, 2);
426 /* Remember the first section found. */
428 if (9 < mpage
->sec
&& '1' <= *sec
&& '9' >= *sec
)
429 mpage
->sec
= (*sec
- '1') + 1;
431 /* If the section changed, append the old one. */
433 if (NULL
!= prevsec
&&
434 (strcmp(sec
, prevsec
) ||
435 strcmp(arch
, prevarch
))) {
436 sep2
= '\0' == *prevarch
? "" : "/";
437 mandoc_asprintf(&newnames
, "%s(%s%s%s)",
438 oldnames
, prevsec
, sep2
, prevarch
);
440 oldnames
= mpage
->names
= newnames
;
443 prevsec
= prevarch
= NULL
;
446 /* Save the new section, to append it later. */
448 if (NULL
== prevsec
) {
449 prevsec
= mandoc_strdup(sec
);
450 prevarch
= mandoc_strdup(arch
);
453 /* Append the new name. */
455 mandoc_asprintf(&newnames
, "%s%s%s",
456 oldnames
, sep1
, name
);
458 mpage
->names
= newnames
;
460 /* Also save the first file name encountered. */
462 if (NULL
!= mpage
->file
)
472 sep2
= '\0' == *arch
? "" : "/";
473 mandoc_asprintf(&mpage
->file
, "%s/%s%s%s%s/%s.%s",
474 path
, sep1
, sec
, sep2
, arch
, name
, fsec
);
476 if (SQLITE_DONE
!= c
)
477 fprintf(stderr
, "%s\n", sqlite3_errmsg(db
));
480 /* Append one final section to the names. */
482 if (NULL
!= prevsec
) {
483 sep2
= '\0' == *prevarch
? "" : "/";
484 mandoc_asprintf(&newnames
, "%s(%s%s%s)",
485 mpage
->names
, prevsec
, sep2
, prevarch
);
487 mpage
->names
= newnames
;
494 buildoutput(sqlite3
*db
, sqlite3_stmt
*s
, uint64_t pageid
, uint64_t outbit
)
496 char *output
, *newoutput
;
497 const char *oldoutput
, *sep1
, *data
;
503 SQL_BIND_INT64(db
, s
, i
, pageid
);
504 SQL_BIND_INT64(db
, s
, i
, outbit
);
505 while (SQLITE_ROW
== (c
= sqlite3_step(s
))) {
506 if (NULL
== output
) {
513 data
= (const char *)sqlite3_column_text(s
, 1);
514 mandoc_asprintf(&newoutput
, "%s%s%s",
515 oldoutput
, sep1
, data
);
519 if (SQLITE_DONE
!= c
)
520 fprintf(stderr
, "%s\n", sqlite3_errmsg(db
));
526 * Implement substring match as an application-defined SQL function.
527 * Using the SQL LIKE or GLOB operators instead would be a bad idea
528 * because that would require escaping metacharacters in the string
529 * being searched for.
532 sql_match(sqlite3_context
*context
, int argc
, sqlite3_value
**argv
)
536 sqlite3_result_int(context
, NULL
!= strcasestr(
537 (const char *)sqlite3_value_text(argv
[1]),
538 (const char *)sqlite3_value_text(argv
[0])));
542 * Implement regular expression match
543 * as an application-defined SQL function.
546 sql_regexp(sqlite3_context
*context
, int argc
, sqlite3_value
**argv
)
550 sqlite3_result_int(context
, !regexec(
551 (regex_t
*)sqlite3_value_blob(argv
[0]),
552 (const char *)sqlite3_value_text(argv
[1]),
557 sql_append(char **sql
, size_t *sz
, const char *newstr
, int count
)
561 newsz
= 1 < count
? (size_t)count
: strlen(newstr
);
562 *sql
= mandoc_realloc(*sql
, *sz
+ newsz
+ 1);
564 memset(*sql
+ *sz
, *newstr
, (size_t)count
);
566 memcpy(*sql
+ *sz
, newstr
, newsz
);
572 * Prepare the search SQL statement.
575 sql_statement(const struct expr
*e
)
582 "SELECT desc, form, pageid FROM mpages WHERE ");
585 for (needop
= 0; NULL
!= e
; e
= e
->next
) {
587 sql_append(&sql
, &sz
, " AND ", 1);
589 sql_append(&sql
, &sz
, " OR ", 1);
591 sql_append(&sql
, &sz
, "(", e
->open
);
592 sql_append(&sql
, &sz
,
599 ? "pageid IN (SELECT pageid FROM names "
600 "WHERE name REGEXP ?)"
602 ? "pageid IN (SELECT pageid FROM names "
604 : "pageid IN (SELECT pageid FROM names "
605 "WHERE name MATCH ?)")
607 ? "pageid IN (SELECT pageid FROM keys "
608 "WHERE key REGEXP ? AND bits & ?)"
609 : "pageid IN (SELECT pageid FROM keys "
610 "WHERE key MATCH ? AND bits & ?)"), 1);
612 sql_append(&sql
, &sz
, ")", e
->close
);
620 * Compile a set of string tokens into an expression.
621 * Tokens in "argv" are assumed to be individual expression atoms (e.g.,
622 * "(", "foo=bar", etc.).
625 exprcomp(const struct mansearch
*search
, int argc
, char *argv
[])
628 int i
, toopen
, logic
, igncase
, toclose
;
629 struct expr
*first
, *prev
, *cur
, *next
;
632 logic
= igncase
= toclose
= 0;
633 toopen
= NULL
!= search
->sec
|| NULL
!= search
->arch
;
635 for (i
= 0; i
< argc
; i
++) {
636 if (0 == strcmp("(", argv
[i
])) {
642 } else if (0 == strcmp(")", argv
[i
])) {
643 if (toopen
|| logic
|| igncase
|| NULL
== cur
)
649 } else if (0 == strcmp("-a", argv
[i
])) {
650 if (toopen
|| logic
|| igncase
|| NULL
== cur
)
654 } else if (0 == strcmp("-o", argv
[i
])) {
655 if (toopen
|| logic
|| igncase
|| NULL
== cur
)
659 } else if (0 == strcmp("-i", argv
[i
])) {
665 next
= exprterm(search
, argv
[i
], !igncase
);
675 * Searching for descriptions must be split out
676 * because they are stored in the mpages table,
677 * not in the keys table.
680 for (mask
= TYPE_Nm
; mask
<= TYPE_Nd
; mask
<<= 1) {
681 if (mask
& cur
->bits
&& ~mask
& cur
->bits
) {
682 next
= mandoc_calloc(1,
683 sizeof(struct expr
));
684 memcpy(next
, cur
, sizeof(struct expr
));
692 prev
->and = (1 == logic
);
693 prev
->open
+= toopen
;
697 toopen
= logic
= igncase
= 0;
699 if (toopen
|| logic
|| igncase
|| toclose
)
702 if (NULL
!= search
->sec
|| NULL
!= search
->arch
)
704 if (NULL
!= search
->arch
)
705 cur
= exprspec(cur
, TYPE_arch
, search
->arch
, "^(%s|any)$");
706 if (NULL
!= search
->sec
)
707 exprspec(cur
, TYPE_sec
, search
->sec
, "^%s$");
718 exprspec(struct expr
*cur
, uint64_t key
, const char *value
,
725 mandoc_asprintf(&cp
, format
, value
);
726 cur
->next
= mandoc_calloc(1, sizeof(struct expr
));
730 if (0 != (irc
= regcomp(&cur
->regexp
, cp
,
731 REG_EXTENDED
| REG_NOSUB
| REG_ICASE
))) {
732 regerror(irc
, &cur
->regexp
, errbuf
, sizeof(errbuf
));
733 fprintf(stderr
, "regcomp: %s\n", errbuf
);
741 exprterm(const struct mansearch
*search
, char *buf
, int cs
)
752 e
= mandoc_calloc(1, sizeof(struct expr
));
754 if (search
->argmode
== ARG_NAME
) {
762 * Separate macro keys from search string.
763 * If needed, request regular expression handling
764 * by setting e->substr to NULL.
767 if (search
->argmode
== ARG_WORD
) {
770 mandoc_asprintf(&val
, "[[:<:]]%s[[:>:]]", buf
);
772 } else if ((val
= strpbrk(buf
, "=~")) == NULL
) {
773 e
->bits
= TYPE_Nm
| TYPE_Nd
;
777 e
->bits
= TYPE_Nm
| TYPE_Nd
;
781 if (NULL
!= strstr(buf
, "arch"))
785 /* Compile regular expressions. */
787 if (NULL
== e
->substr
) {
788 irc
= regcomp(&e
->regexp
, val
,
789 REG_EXTENDED
| REG_NOSUB
| (cs
? 0 : REG_ICASE
));
790 if (search
->argmode
== ARG_WORD
)
793 regerror(irc
, &e
->regexp
, errbuf
, sizeof(errbuf
));
794 fprintf(stderr
, "regcomp: %s\n", errbuf
);
804 * Parse out all possible fields.
805 * If the field doesn't resolve, bail.
808 while (NULL
!= (key
= strsep(&buf
, ","))) {
811 for (i
= 0, iterbit
= 1;
812 i
< mansearch_keymax
;
813 i
++, iterbit
<<= 1) {
814 if (0 == strcasecmp(key
,
815 mansearch_keynames
[i
])) {
820 if (i
== mansearch_keymax
) {
821 if (strcasecmp(key
, "any")) {
833 exprfree(struct expr
*p
)
845 hash_calloc(size_t nmemb
, size_t sz
, void *arg
)
848 return(mandoc_calloc(nmemb
, sz
));
852 hash_alloc(size_t sz
, void *arg
)
855 return(mandoc_malloc(sz
));
859 hash_free(void *p
, void *arg
)