]>
git.cameronkatri.com Git - mandoc.git/blob - mansearch.c
1 /* $Id: mansearch.c,v 1.50 2014/11/18 01:15:21 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 uint64_t bits
; /* name type mask */
83 char *desc
; /* manual page description */
84 int form
; /* bit field: formatted, zipped? */
87 static void buildnames(struct manpage
*, sqlite3
*,
88 sqlite3_stmt
*, uint64_t,
89 const char *, int form
);
90 static char *buildoutput(sqlite3
*, sqlite3_stmt
*,
92 static void *hash_alloc(size_t, void *);
93 static void hash_free(void *, void *);
94 static void *hash_calloc(size_t, size_t, void *);
95 static struct expr
*exprcomp(const struct mansearch
*,
97 static void exprfree(struct expr
*);
98 static struct expr
*exprspec(struct expr
*, uint64_t,
99 const char *, const char *);
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
) {
255 * Define the SQL functions for substring
256 * and regular expression matching.
259 c
= sqlite3_create_function(db
, "match", 2,
260 SQLITE_UTF8
| SQLITE_DETERMINISTIC
,
261 NULL
, sql_match
, NULL
, NULL
);
262 assert(SQLITE_OK
== c
);
263 c
= sqlite3_create_function(db
, "regexp", 2,
264 SQLITE_UTF8
| SQLITE_DETERMINISTIC
,
265 NULL
, sql_regexp
, NULL
, NULL
);
266 assert(SQLITE_OK
== c
);
269 c
= sqlite3_prepare_v2(db
, sql
, -1, &s
, NULL
);
271 fprintf(stderr
, "%s\n", sqlite3_errmsg(db
));
273 for (ep
= e
; NULL
!= ep
; ep
= ep
->next
) {
274 if (NULL
== ep
->substr
) {
275 SQL_BIND_BLOB(db
, s
, j
, ep
->regexp
);
277 SQL_BIND_TEXT(db
, s
, j
, ep
->substr
);
278 if (0 == ((TYPE_Nd
| TYPE_Nm
) & ep
->bits
))
279 SQL_BIND_INT64(db
, s
, j
, ep
->bits
);
282 memset(&htab
, 0, sizeof(struct ohash
));
283 ohash_init(&htab
, 4, &info
);
286 * Hash each entry on its [unique] document identifier.
287 * This is a uint64_t.
288 * Instead of using a hash function, simply convert the
289 * uint64_t to a uint32_t, the hash value's type.
290 * This gives good performance and preserves the
291 * distribution of buckets in the table.
293 while (SQLITE_ROW
== (c
= sqlite3_step(s
))) {
294 pageid
= sqlite3_column_int64(s
, 2);
295 idx
= ohash_lookup_memory(&htab
,
296 (char *)&pageid
, sizeof(uint64_t),
299 if (NULL
!= ohash_find(&htab
, idx
))
302 mp
= mandoc_calloc(1, sizeof(struct match
));
304 mp
->form
= sqlite3_column_int(s
, 1);
305 mp
->bits
= sqlite3_column_int64(s
, 3);
306 if (TYPE_Nd
== outbit
)
307 mp
->desc
= mandoc_strdup((const char *)
308 sqlite3_column_text(s
, 0));
309 ohash_insert(&htab
, idx
, mp
);
312 if (SQLITE_DONE
!= c
)
313 fprintf(stderr
, "%s\n", sqlite3_errmsg(db
));
317 c
= sqlite3_prepare_v2(db
,
318 "SELECT sec, arch, name, pageid FROM mlinks "
319 "WHERE pageid=? ORDER BY sec, arch, name",
322 fprintf(stderr
, "%s\n", sqlite3_errmsg(db
));
324 c
= sqlite3_prepare_v2(db
,
325 "SELECT bits, key, pageid FROM keys "
326 "WHERE pageid=? AND bits & ?",
329 fprintf(stderr
, "%s\n", sqlite3_errmsg(db
));
331 for (mp
= ohash_first(&htab
, &idx
);
333 mp
= ohash_next(&htab
, &idx
)) {
334 if (cur
+ 1 > maxres
) {
336 *res
= mandoc_reallocarray(*res
,
337 maxres
, sizeof(struct manpage
));
341 mpage
->bits
= mp
->bits
;
343 mpage
->form
= mp
->form
;
344 buildnames(mpage
, db
, s
, mp
->pageid
,
345 paths
->paths
[i
], mp
->form
);
346 mpage
->output
= TYPE_Nd
& outbit
?
348 buildoutput(db
, s2
, mp
->pageid
, outbit
) : NULL
;
355 sqlite3_finalize(s2
);
360 * In man(1) mode, prefer matches in earlier trees
361 * over matches in later trees.
364 if (cur
&& search
->firstmatch
)
367 qsort(*res
, cur
, sizeof(struct manpage
), manpage_compare
);
371 if (-1 == fchdir(fd
))
382 mansearch_free(struct manpage
*res
, size_t sz
)
386 for (i
= 0; i
< sz
; i
++) {
395 manpage_compare(const void *vp1
, const void *vp2
)
397 const struct manpage
*mp1
, *mp2
;
402 return( (diff
= mp2
->bits
- mp1
->bits
) ? diff
:
403 (diff
= mp1
->sec
- mp2
->sec
) ? diff
:
404 strcasecmp(mp1
->names
, mp2
->names
));
408 buildnames(struct manpage
*mpage
, sqlite3
*db
, sqlite3_stmt
*s
,
409 uint64_t pageid
, const char *path
, int form
)
411 char *newnames
, *prevsec
, *prevarch
;
412 const char *oldnames
, *sep1
, *name
, *sec
, *sep2
, *arch
, *fsec
;
419 prevsec
= prevarch
= NULL
;
421 SQL_BIND_INT64(db
, s
, i
, pageid
);
422 while (SQLITE_ROW
== (c
= sqlite3_step(s
))) {
424 /* Decide whether we already have some names. */
426 if (NULL
== mpage
->names
) {
430 oldnames
= mpage
->names
;
434 /* Fetch the next name. */
436 sec
= (const char *)sqlite3_column_text(s
, 0);
437 arch
= (const char *)sqlite3_column_text(s
, 1);
438 name
= (const char *)sqlite3_column_text(s
, 2);
440 /* Remember the first section found. */
442 if (9 < mpage
->sec
&& '1' <= *sec
&& '9' >= *sec
)
443 mpage
->sec
= (*sec
- '1') + 1;
445 /* If the section changed, append the old one. */
447 if (NULL
!= prevsec
&&
448 (strcmp(sec
, prevsec
) ||
449 strcmp(arch
, prevarch
))) {
450 sep2
= '\0' == *prevarch
? "" : "/";
451 mandoc_asprintf(&newnames
, "%s(%s%s%s)",
452 oldnames
, prevsec
, sep2
, prevarch
);
454 oldnames
= mpage
->names
= newnames
;
457 prevsec
= prevarch
= NULL
;
460 /* Save the new section, to append it later. */
462 if (NULL
== prevsec
) {
463 prevsec
= mandoc_strdup(sec
);
464 prevarch
= mandoc_strdup(arch
);
467 /* Append the new name. */
469 mandoc_asprintf(&newnames
, "%s%s%s",
470 oldnames
, sep1
, name
);
472 mpage
->names
= newnames
;
474 /* Also save the first file name encountered. */
476 if (NULL
!= mpage
->file
)
479 if (form
& FORM_SRC
) {
490 sep2
= '\0' == *arch
? "" : "/";
491 mandoc_asprintf(&mpage
->file
, "%s/%s%s%s%s/%s.%s%s",
492 path
, sep1
, sec
, sep2
, arch
, name
, fsec
, gzip
);
494 if (SQLITE_DONE
!= c
)
495 fprintf(stderr
, "%s\n", sqlite3_errmsg(db
));
498 /* Append one final section to the names. */
500 if (NULL
!= prevsec
) {
501 sep2
= '\0' == *prevarch
? "" : "/";
502 mandoc_asprintf(&newnames
, "%s(%s%s%s)",
503 mpage
->names
, prevsec
, sep2
, prevarch
);
505 mpage
->names
= newnames
;
512 buildoutput(sqlite3
*db
, sqlite3_stmt
*s
, uint64_t pageid
, uint64_t outbit
)
514 char *output
, *newoutput
;
515 const char *oldoutput
, *sep1
, *data
;
521 SQL_BIND_INT64(db
, s
, i
, pageid
);
522 SQL_BIND_INT64(db
, s
, i
, outbit
);
523 while (SQLITE_ROW
== (c
= sqlite3_step(s
))) {
524 if (NULL
== output
) {
531 data
= (const char *)sqlite3_column_text(s
, 1);
532 mandoc_asprintf(&newoutput
, "%s%s%s",
533 oldoutput
, sep1
, data
);
537 if (SQLITE_DONE
!= c
)
538 fprintf(stderr
, "%s\n", sqlite3_errmsg(db
));
544 * Implement substring match as an application-defined SQL function.
545 * Using the SQL LIKE or GLOB operators instead would be a bad idea
546 * because that would require escaping metacharacters in the string
547 * being searched for.
550 sql_match(sqlite3_context
*context
, int argc
, sqlite3_value
**argv
)
554 sqlite3_result_int(context
, NULL
!= strcasestr(
555 (const char *)sqlite3_value_text(argv
[1]),
556 (const char *)sqlite3_value_text(argv
[0])));
560 * Implement regular expression match
561 * as an application-defined SQL function.
564 sql_regexp(sqlite3_context
*context
, int argc
, sqlite3_value
**argv
)
568 sqlite3_result_int(context
, !regexec(
569 (regex_t
*)sqlite3_value_blob(argv
[0]),
570 (const char *)sqlite3_value_text(argv
[1]),
575 sql_append(char **sql
, size_t *sz
, const char *newstr
, int count
)
579 newsz
= 1 < count
? (size_t)count
: strlen(newstr
);
580 *sql
= mandoc_realloc(*sql
, *sz
+ newsz
+ 1);
582 memset(*sql
+ *sz
, *newstr
, (size_t)count
);
584 memcpy(*sql
+ *sz
, newstr
, newsz
);
590 * Prepare the search SQL statement.
593 sql_statement(const struct expr
*e
)
599 sql
= mandoc_strdup(e
->equal
?
600 "SELECT desc, form, pageid, bits "
601 "FROM mpages NATURAL JOIN names WHERE " :
602 "SELECT desc, form, pageid, 0 FROM mpages WHERE ");
605 for (needop
= 0; NULL
!= e
; e
= e
->next
) {
607 sql_append(&sql
, &sz
, " AND ", 1);
609 sql_append(&sql
, &sz
, " OR ", 1);
611 sql_append(&sql
, &sz
, "(", e
->open
);
612 sql_append(&sql
, &sz
,
619 ? "pageid IN (SELECT pageid FROM names "
620 "WHERE name REGEXP ?)"
623 : "pageid IN (SELECT pageid FROM names "
624 "WHERE name MATCH ?)")
626 ? "pageid IN (SELECT pageid FROM keys "
627 "WHERE key REGEXP ? AND bits & ?)"
628 : "pageid IN (SELECT pageid FROM keys "
629 "WHERE key MATCH ? AND bits & ?)"), 1);
631 sql_append(&sql
, &sz
, ")", e
->close
);
639 * Compile a set of string tokens into an expression.
640 * Tokens in "argv" are assumed to be individual expression atoms (e.g.,
641 * "(", "foo=bar", etc.).
644 exprcomp(const struct mansearch
*search
, int argc
, char *argv
[])
647 int i
, toopen
, logic
, igncase
, toclose
;
648 struct expr
*first
, *prev
, *cur
, *next
;
651 logic
= igncase
= toclose
= 0;
652 toopen
= NULL
!= search
->sec
|| NULL
!= search
->arch
;
654 for (i
= 0; i
< argc
; i
++) {
655 if (0 == strcmp("(", argv
[i
])) {
661 } else if (0 == strcmp(")", argv
[i
])) {
662 if (toopen
|| logic
|| igncase
|| NULL
== cur
)
668 } else if (0 == strcmp("-a", argv
[i
])) {
669 if (toopen
|| logic
|| igncase
|| NULL
== cur
)
673 } else if (0 == strcmp("-o", argv
[i
])) {
674 if (toopen
|| logic
|| igncase
|| NULL
== cur
)
678 } else if (0 == strcmp("-i", argv
[i
])) {
684 next
= exprterm(search
, argv
[i
], !igncase
);
694 * Searching for descriptions must be split out
695 * because they are stored in the mpages table,
696 * not in the keys table.
699 for (mask
= TYPE_Nm
; mask
<= TYPE_Nd
; mask
<<= 1) {
700 if (mask
& cur
->bits
&& ~mask
& cur
->bits
) {
701 next
= mandoc_calloc(1,
702 sizeof(struct expr
));
703 memcpy(next
, cur
, sizeof(struct expr
));
711 prev
->and = (1 == logic
);
712 prev
->open
+= toopen
;
716 toopen
= logic
= igncase
= 0;
718 if (toopen
|| logic
|| igncase
|| toclose
)
721 if (NULL
!= search
->sec
|| NULL
!= search
->arch
)
723 if (NULL
!= search
->arch
)
724 cur
= exprspec(cur
, TYPE_arch
, search
->arch
, "^(%s|any)$");
725 if (NULL
!= search
->sec
)
726 exprspec(cur
, TYPE_sec
, search
->sec
, "^%s$");
737 exprspec(struct expr
*cur
, uint64_t key
, const char *value
,
744 mandoc_asprintf(&cp
, format
, value
);
745 cur
->next
= mandoc_calloc(1, sizeof(struct expr
));
749 if (0 != (irc
= regcomp(&cur
->regexp
, cp
,
750 REG_EXTENDED
| REG_NOSUB
| REG_ICASE
))) {
751 regerror(irc
, &cur
->regexp
, errbuf
, sizeof(errbuf
));
752 fprintf(stderr
, "regcomp: %s\n", errbuf
);
760 exprterm(const struct mansearch
*search
, char *buf
, int cs
)
771 e
= mandoc_calloc(1, sizeof(struct expr
));
773 if (search
->argmode
== ARG_NAME
) {
781 * Separate macro keys from search string.
782 * If needed, request regular expression handling
783 * by setting e->substr to NULL.
786 if (search
->argmode
== ARG_WORD
) {
789 mandoc_asprintf(&val
, "[[:<:]]%s[[:>:]]", buf
);
791 } else if ((val
= strpbrk(buf
, "=~")) == NULL
) {
792 e
->bits
= TYPE_Nm
| TYPE_Nd
;
796 e
->bits
= TYPE_Nm
| TYPE_Nd
;
800 if (NULL
!= strstr(buf
, "arch"))
804 /* Compile regular expressions. */
806 if (NULL
== e
->substr
) {
807 irc
= regcomp(&e
->regexp
, val
,
808 REG_EXTENDED
| REG_NOSUB
| (cs
? 0 : REG_ICASE
));
809 if (search
->argmode
== ARG_WORD
)
812 regerror(irc
, &e
->regexp
, errbuf
, sizeof(errbuf
));
813 fprintf(stderr
, "regcomp: %s\n", errbuf
);
823 * Parse out all possible fields.
824 * If the field doesn't resolve, bail.
827 while (NULL
!= (key
= strsep(&buf
, ","))) {
830 for (i
= 0, iterbit
= 1;
831 i
< mansearch_keymax
;
832 i
++, iterbit
<<= 1) {
833 if (0 == strcasecmp(key
,
834 mansearch_keynames
[i
])) {
839 if (i
== mansearch_keymax
) {
840 if (strcasecmp(key
, "any")) {
852 exprfree(struct expr
*p
)
864 hash_calloc(size_t nmemb
, size_t sz
, void *arg
)
867 return(mandoc_calloc(nmemb
, sz
));
871 hash_alloc(size_t sz
, void *arg
)
874 return(mandoc_malloc(sz
));
878 hash_free(void *p
, void *arg
)