]>
git.cameronkatri.com Git - mandoc.git/blob - mansearch.c
1 /* $Id: mansearch.c,v 1.52 2014/12/06 01:23:24 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>
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(struct manpage
*, sqlite3
*,
89 sqlite3_stmt
*, uint64_t,
90 const char *, int form
);
91 static char *buildoutput(sqlite3
*, sqlite3_stmt
*,
93 static void *hash_alloc(size_t, void *);
94 static void hash_free(void *, void *);
95 static void *hash_calloc(size_t, size_t, void *);
96 static struct expr
*exprcomp(const struct mansearch
*,
98 static void exprfree(struct expr
*);
99 static struct expr
*exprspec(struct expr
*, uint64_t,
100 const char *, const char *);
101 static struct expr
*exprterm(const struct mansearch
*, char *, int);
102 static int manpage_compare(const void *, const void *);
103 static void sql_append(char **sql
, size_t *sz
,
104 const char *newstr
, int count
);
105 static void sql_match(sqlite3_context
*context
,
106 int argc
, sqlite3_value
**argv
);
107 static void sql_regexp(sqlite3_context
*context
,
108 int argc
, sqlite3_value
**argv
);
109 static char *sql_statement(const struct expr
*);
113 mansearch_setup(int start
)
115 static void *pagecache
;
118 #define PC_PAGESIZE 1280
119 #define PC_NUMPAGES 256
122 if (NULL
!= pagecache
) {
123 fprintf(stderr
, "pagecache already enabled\n");
124 return((int)MANDOCLEVEL_BADARG
);
127 pagecache
= mmap(NULL
, PC_PAGESIZE
* PC_NUMPAGES
,
128 PROT_READ
| PROT_WRITE
,
129 MAP_SHARED
| MAP_ANON
, -1, 0);
131 if (MAP_FAILED
== pagecache
) {
134 return((int)MANDOCLEVEL_SYSERR
);
137 c
= sqlite3_config(SQLITE_CONFIG_PAGECACHE
,
138 pagecache
, PC_PAGESIZE
, PC_NUMPAGES
);
141 return((int)MANDOCLEVEL_OK
);
143 fprintf(stderr
, "pagecache: %s\n", sqlite3_errstr(c
));
145 } else if (NULL
== pagecache
) {
146 fprintf(stderr
, "pagecache missing\n");
147 return((int)MANDOCLEVEL_BADARG
);
150 if (-1 == munmap(pagecache
, PC_PAGESIZE
* PC_NUMPAGES
)) {
153 return((int)MANDOCLEVEL_SYSERR
);
157 return((int)MANDOCLEVEL_OK
);
161 mansearch(const struct mansearch
*search
,
162 const struct manpaths
*paths
,
163 int argc
, char *argv
[],
164 struct manpage
**res
, size_t *sz
)
166 int fd
, rc
, c
, indexbit
;
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
;
181 info
.calloc
= hash_calloc
;
182 info
.alloc
= hash_alloc
;
183 info
.free
= hash_free
;
184 info
.key_offset
= offsetof(struct match
, pageid
);
186 *sz
= cur
= maxres
= 0;
195 if (NULL
== (e
= exprcomp(search
, argc
, argv
)))
199 if (NULL
!= search
->outkey
) {
200 for (indexbit
= 0, iterbit
= 1;
201 indexbit
< mansearch_keymax
;
202 indexbit
++, iterbit
<<= 1) {
203 if (0 == strcasecmp(search
->outkey
,
204 mansearch_keynames
[indexbit
])) {
212 * Save a descriptor to the current working directory.
213 * Since pathnames in the "paths" variable might be relative,
214 * and we'll be chdir()ing into them, we need to keep a handle
215 * on our current directory from which to start the chdir().
218 if (NULL
== getcwd(buf
, PATH_MAX
)) {
221 } else if (-1 == (fd
= open(buf
, O_RDONLY
, 0))) {
226 sql
= sql_statement(e
);
229 * Loop over the directories (containing databases) for us to
231 * Don't let missing/bad databases/directories phase us.
232 * In each, try to open the resident database and, if it opens,
233 * scan it for our match expression.
236 for (i
= 0; i
< paths
->sz
; i
++) {
237 if (-1 == fchdir(fd
)) {
241 } else if (-1 == chdir(paths
->paths
[i
])) {
242 perror(paths
->paths
[i
]);
246 c
= sqlite3_open_v2(MANDOC_DB
, &db
,
247 SQLITE_OPEN_READONLY
, NULL
);
249 if (SQLITE_OK
!= c
) {
250 fprintf(stderr
, "%s/%s: %s\n",
251 paths
->paths
[i
], MANDOC_DB
, strerror(errno
));
257 * Define the SQL functions for substring
258 * and regular expression matching.
261 c
= sqlite3_create_function(db
, "match", 2,
262 SQLITE_UTF8
| SQLITE_DETERMINISTIC
,
263 NULL
, sql_match
, NULL
, NULL
);
264 assert(SQLITE_OK
== c
);
265 c
= sqlite3_create_function(db
, "regexp", 2,
266 SQLITE_UTF8
| SQLITE_DETERMINISTIC
,
267 NULL
, sql_regexp
, NULL
, NULL
);
268 assert(SQLITE_OK
== c
);
271 c
= sqlite3_prepare_v2(db
, sql
, -1, &s
, NULL
);
273 fprintf(stderr
, "%s\n", sqlite3_errmsg(db
));
275 for (ep
= e
; NULL
!= ep
; ep
= ep
->next
) {
276 if (NULL
== ep
->substr
) {
277 SQL_BIND_BLOB(db
, s
, j
, ep
->regexp
);
279 SQL_BIND_TEXT(db
, s
, j
, ep
->substr
);
280 if (0 == ((TYPE_Nd
| TYPE_Nm
) & ep
->bits
))
281 SQL_BIND_INT64(db
, s
, j
, ep
->bits
);
284 memset(&htab
, 0, sizeof(struct ohash
));
285 ohash_init(&htab
, 4, &info
);
288 * Hash each entry on its [unique] document identifier.
289 * This is a uint64_t.
290 * Instead of using a hash function, simply convert the
291 * uint64_t to a uint32_t, the hash value's type.
292 * This gives good performance and preserves the
293 * distribution of buckets in the table.
295 while (SQLITE_ROW
== (c
= sqlite3_step(s
))) {
296 pageid
= sqlite3_column_int64(s
, 2);
297 idx
= ohash_lookup_memory(&htab
,
298 (char *)&pageid
, sizeof(uint64_t),
301 if (NULL
!= ohash_find(&htab
, idx
))
304 mp
= mandoc_calloc(1, sizeof(struct match
));
306 mp
->form
= sqlite3_column_int(s
, 1);
307 mp
->bits
= sqlite3_column_int64(s
, 3);
308 if (TYPE_Nd
== outbit
)
309 mp
->desc
= mandoc_strdup((const char *)
310 sqlite3_column_text(s
, 0));
311 ohash_insert(&htab
, idx
, mp
);
314 if (SQLITE_DONE
!= c
)
315 fprintf(stderr
, "%s\n", sqlite3_errmsg(db
));
319 c
= sqlite3_prepare_v2(db
,
320 "SELECT sec, arch, name, pageid FROM mlinks "
321 "WHERE pageid=? ORDER BY sec, arch, name",
324 fprintf(stderr
, "%s\n", sqlite3_errmsg(db
));
326 c
= sqlite3_prepare_v2(db
,
327 "SELECT bits, key, pageid FROM keys "
328 "WHERE pageid=? AND bits & ?",
331 fprintf(stderr
, "%s\n", sqlite3_errmsg(db
));
333 for (mp
= ohash_first(&htab
, &idx
);
335 mp
= ohash_next(&htab
, &idx
)) {
336 if (cur
+ 1 > maxres
) {
338 *res
= mandoc_reallocarray(*res
,
339 maxres
, sizeof(struct manpage
));
343 mpage
->bits
= mp
->bits
;
345 mpage
->form
= mp
->form
;
346 buildnames(mpage
, db
, s
, mp
->pageid
,
347 paths
->paths
[i
], mp
->form
);
348 mpage
->output
= TYPE_Nd
& outbit
?
350 buildoutput(db
, s2
, mp
->pageid
, outbit
) : NULL
;
357 sqlite3_finalize(s2
);
362 * In man(1) mode, prefer matches in earlier trees
363 * over matches in later trees.
366 if (cur
&& search
->firstmatch
)
369 qsort(*res
, cur
, sizeof(struct manpage
), manpage_compare
);
373 if (-1 == fchdir(fd
))
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(struct manpage
*mpage
, sqlite3
*db
, sqlite3_stmt
*s
,
411 uint64_t pageid
, const char *path
, int form
)
413 char *newnames
, *prevsec
, *prevarch
;
414 const char *oldnames
, *sep1
, *name
, *sec
, *sep2
, *arch
, *fsec
;
420 prevsec
= prevarch
= NULL
;
422 SQL_BIND_INT64(db
, s
, i
, pageid
);
423 while (SQLITE_ROW
== (c
= sqlite3_step(s
))) {
425 /* Decide whether we already have some names. */
427 if (NULL
== mpage
->names
) {
431 oldnames
= mpage
->names
;
435 /* Fetch the next name. */
437 sec
= (const char *)sqlite3_column_text(s
, 0);
438 arch
= (const char *)sqlite3_column_text(s
, 1);
439 name
= (const char *)sqlite3_column_text(s
, 2);
441 /* Remember the first section found. */
443 if (9 < mpage
->sec
&& '1' <= *sec
&& '9' >= *sec
)
444 mpage
->sec
= (*sec
- '1') + 1;
446 /* If the section changed, append the old one. */
448 if (NULL
!= prevsec
&&
449 (strcmp(sec
, prevsec
) ||
450 strcmp(arch
, prevarch
))) {
451 sep2
= '\0' == *prevarch
? "" : "/";
452 mandoc_asprintf(&newnames
, "%s(%s%s%s)",
453 oldnames
, prevsec
, sep2
, prevarch
);
455 oldnames
= mpage
->names
= newnames
;
458 prevsec
= prevarch
= NULL
;
461 /* Save the new section, to append it later. */
463 if (NULL
== prevsec
) {
464 prevsec
= mandoc_strdup(sec
);
465 prevarch
= mandoc_strdup(arch
);
468 /* Append the new name. */
470 mandoc_asprintf(&newnames
, "%s%s%s",
471 oldnames
, sep1
, name
);
473 mpage
->names
= newnames
;
475 /* Also save the first file name encountered. */
477 if (mpage
->file
!= NULL
)
480 if (form
& FORM_SRC
) {
487 sep2
= *arch
== '\0' ? "" : "/";
488 mandoc_asprintf(&mpage
->file
, "%s/%s%s%s%s/%s.%s",
489 path
, sep1
, sec
, sep2
, arch
, name
, fsec
);
491 if (c
!= SQLITE_DONE
)
492 fprintf(stderr
, "%s\n", sqlite3_errmsg(db
));
495 /* Append one final section to the names. */
497 if (prevsec
!= NULL
) {
498 sep2
= *prevarch
== '\0' ? "" : "/";
499 mandoc_asprintf(&newnames
, "%s(%s%s%s)",
500 mpage
->names
, prevsec
, sep2
, prevarch
);
502 mpage
->names
= newnames
;
509 buildoutput(sqlite3
*db
, sqlite3_stmt
*s
, uint64_t pageid
, uint64_t outbit
)
511 char *output
, *newoutput
;
512 const char *oldoutput
, *sep1
, *data
;
518 SQL_BIND_INT64(db
, s
, i
, pageid
);
519 SQL_BIND_INT64(db
, s
, i
, outbit
);
520 while (SQLITE_ROW
== (c
= sqlite3_step(s
))) {
521 if (NULL
== output
) {
528 data
= (const char *)sqlite3_column_text(s
, 1);
529 mandoc_asprintf(&newoutput
, "%s%s%s",
530 oldoutput
, sep1
, data
);
534 if (SQLITE_DONE
!= c
)
535 fprintf(stderr
, "%s\n", sqlite3_errmsg(db
));
541 * Implement substring match as an application-defined SQL function.
542 * Using the SQL LIKE or GLOB operators instead would be a bad idea
543 * because that would require escaping metacharacters in the string
544 * being searched for.
547 sql_match(sqlite3_context
*context
, int argc
, sqlite3_value
**argv
)
551 sqlite3_result_int(context
, NULL
!= strcasestr(
552 (const char *)sqlite3_value_text(argv
[1]),
553 (const char *)sqlite3_value_text(argv
[0])));
557 * Implement regular expression match
558 * as an application-defined SQL function.
561 sql_regexp(sqlite3_context
*context
, int argc
, sqlite3_value
**argv
)
565 sqlite3_result_int(context
, !regexec(
566 (regex_t
*)sqlite3_value_blob(argv
[0]),
567 (const char *)sqlite3_value_text(argv
[1]),
572 sql_append(char **sql
, size_t *sz
, const char *newstr
, int count
)
576 newsz
= 1 < count
? (size_t)count
: strlen(newstr
);
577 *sql
= mandoc_realloc(*sql
, *sz
+ newsz
+ 1);
579 memset(*sql
+ *sz
, *newstr
, (size_t)count
);
581 memcpy(*sql
+ *sz
, newstr
, newsz
);
587 * Prepare the search SQL statement.
590 sql_statement(const struct expr
*e
)
596 sql
= mandoc_strdup(e
->equal
?
597 "SELECT desc, form, pageid, bits "
598 "FROM mpages NATURAL JOIN names WHERE " :
599 "SELECT desc, form, pageid, 0 FROM mpages WHERE ");
602 for (needop
= 0; NULL
!= e
; e
= e
->next
) {
604 sql_append(&sql
, &sz
, " AND ", 1);
606 sql_append(&sql
, &sz
, " OR ", 1);
608 sql_append(&sql
, &sz
, "(", e
->open
);
609 sql_append(&sql
, &sz
,
616 ? "pageid IN (SELECT pageid FROM names "
617 "WHERE name REGEXP ?)"
620 : "pageid IN (SELECT pageid FROM names "
621 "WHERE name MATCH ?)")
623 ? "pageid IN (SELECT pageid FROM keys "
624 "WHERE key REGEXP ? AND bits & ?)"
625 : "pageid IN (SELECT pageid FROM keys "
626 "WHERE key MATCH ? AND bits & ?)"), 1);
628 sql_append(&sql
, &sz
, ")", e
->close
);
636 * Compile a set of string tokens into an expression.
637 * Tokens in "argv" are assumed to be individual expression atoms (e.g.,
638 * "(", "foo=bar", etc.).
641 exprcomp(const struct mansearch
*search
, int argc
, char *argv
[])
644 int i
, toopen
, logic
, igncase
, toclose
;
645 struct expr
*first
, *prev
, *cur
, *next
;
648 logic
= igncase
= toclose
= 0;
649 toopen
= NULL
!= search
->sec
|| NULL
!= search
->arch
;
651 for (i
= 0; i
< argc
; i
++) {
652 if (0 == strcmp("(", argv
[i
])) {
658 } else if (0 == strcmp(")", argv
[i
])) {
659 if (toopen
|| logic
|| igncase
|| NULL
== cur
)
665 } else if (0 == strcmp("-a", argv
[i
])) {
666 if (toopen
|| logic
|| igncase
|| NULL
== cur
)
670 } else if (0 == strcmp("-o", argv
[i
])) {
671 if (toopen
|| logic
|| igncase
|| NULL
== cur
)
675 } else if (0 == strcmp("-i", argv
[i
])) {
681 next
= exprterm(search
, argv
[i
], !igncase
);
691 * Searching for descriptions must be split out
692 * because they are stored in the mpages table,
693 * not in the keys table.
696 for (mask
= TYPE_Nm
; mask
<= TYPE_Nd
; mask
<<= 1) {
697 if (mask
& cur
->bits
&& ~mask
& cur
->bits
) {
698 next
= mandoc_calloc(1,
699 sizeof(struct expr
));
700 memcpy(next
, cur
, sizeof(struct expr
));
708 prev
->and = (1 == logic
);
709 prev
->open
+= toopen
;
713 toopen
= logic
= igncase
= 0;
715 if (toopen
|| logic
|| igncase
|| toclose
)
718 if (NULL
!= search
->sec
|| NULL
!= search
->arch
)
720 if (NULL
!= search
->arch
)
721 cur
= exprspec(cur
, TYPE_arch
, search
->arch
, "^(%s|any)$");
722 if (NULL
!= search
->sec
)
723 exprspec(cur
, TYPE_sec
, search
->sec
, "^%s$");
734 exprspec(struct expr
*cur
, uint64_t key
, const char *value
,
741 mandoc_asprintf(&cp
, format
, value
);
742 cur
->next
= mandoc_calloc(1, sizeof(struct expr
));
746 if (0 != (irc
= regcomp(&cur
->regexp
, cp
,
747 REG_EXTENDED
| REG_NOSUB
| REG_ICASE
))) {
748 regerror(irc
, &cur
->regexp
, errbuf
, sizeof(errbuf
));
749 fprintf(stderr
, "regcomp: %s\n", errbuf
);
757 exprterm(const struct mansearch
*search
, char *buf
, int cs
)
768 e
= mandoc_calloc(1, sizeof(struct expr
));
770 if (search
->argmode
== ARG_NAME
) {
778 * Separate macro keys from search string.
779 * If needed, request regular expression handling
780 * by setting e->substr to NULL.
783 if (search
->argmode
== ARG_WORD
) {
786 mandoc_asprintf(&val
, "[[:<:]]%s[[:>:]]", buf
);
788 } else if ((val
= strpbrk(buf
, "=~")) == NULL
) {
789 e
->bits
= TYPE_Nm
| TYPE_Nd
;
793 e
->bits
= TYPE_Nm
| TYPE_Nd
;
797 if (NULL
!= strstr(buf
, "arch"))
801 /* Compile regular expressions. */
803 if (NULL
== e
->substr
) {
804 irc
= regcomp(&e
->regexp
, val
,
805 REG_EXTENDED
| REG_NOSUB
| (cs
? 0 : REG_ICASE
));
806 if (search
->argmode
== ARG_WORD
)
809 regerror(irc
, &e
->regexp
, errbuf
, sizeof(errbuf
));
810 fprintf(stderr
, "regcomp: %s\n", errbuf
);
820 * Parse out all possible fields.
821 * If the field doesn't resolve, bail.
824 while (NULL
!= (key
= strsep(&buf
, ","))) {
827 for (i
= 0, iterbit
= 1;
828 i
< mansearch_keymax
;
829 i
++, iterbit
<<= 1) {
830 if (0 == strcasecmp(key
,
831 mansearch_keynames
[i
])) {
836 if (i
== mansearch_keymax
) {
837 if (strcasecmp(key
, "any")) {
849 exprfree(struct expr
*p
)
861 hash_calloc(size_t nmemb
, size_t sz
, void *arg
)
864 return(mandoc_calloc(nmemb
, sz
));
868 hash_alloc(size_t sz
, void *arg
)
871 return(mandoc_malloc(sz
));
875 hash_free(void *p
, void *arg
)