]>
git.cameronkatri.com Git - mandoc.git/blob - mansearch.c
1 /* $Id: mansearch.c,v 1.54 2015/02/27 16:02:10 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>
40 #include "compat_ohash.h"
43 #ifndef SQLITE_DETERMINISTIC
44 #define SQLITE_DETERMINISTIC 0
48 #include "mandoc_aux.h"
50 #include "mansearch.h"
52 extern int mansearch_keymax
;
53 extern const char *const mansearch_keynames
[];
55 #define SQL_BIND_TEXT(_db, _s, _i, _v) \
56 do { if (SQLITE_OK != sqlite3_bind_text \
57 ((_s), (_i)++, (_v), -1, SQLITE_STATIC)) \
58 fprintf(stderr, "%s\n", sqlite3_errmsg((_db))); \
60 #define SQL_BIND_INT64(_db, _s, _i, _v) \
61 do { if (SQLITE_OK != sqlite3_bind_int64 \
62 ((_s), (_i)++, (_v))) \
63 fprintf(stderr, "%s\n", sqlite3_errmsg((_db))); \
65 #define SQL_BIND_BLOB(_db, _s, _i, _v) \
66 do { if (SQLITE_OK != sqlite3_bind_blob \
67 ((_s), (_i)++, (&_v), sizeof(_v), SQLITE_STATIC)) \
68 fprintf(stderr, "%s\n", sqlite3_errmsg((_db))); \
72 regex_t regexp
; /* compiled regexp, if applicable */
73 const char *substr
; /* to search for, if applicable */
74 struct expr
*next
; /* next in sequence */
75 uint64_t bits
; /* type-mask */
76 int equal
; /* equality, not subsring match */
77 int open
; /* opening parentheses before */
78 int and; /* logical AND before */
79 int close
; /* closing parentheses after */
83 uint64_t pageid
; /* identifier in database */
84 uint64_t bits
; /* name type mask */
85 char *desc
; /* manual page description */
86 int form
; /* bit field: formatted, zipped? */
89 static void buildnames(const struct mansearch
*,
90 struct manpage
*, sqlite3
*,
91 sqlite3_stmt
*, uint64_t,
92 const char *, int form
);
93 static char *buildoutput(sqlite3
*, sqlite3_stmt
*,
95 static void *hash_alloc(size_t, void *);
96 static void hash_free(void *, void *);
97 static void *hash_calloc(size_t, size_t, void *);
98 static struct expr
*exprcomp(const struct mansearch
*,
100 static void exprfree(struct expr
*);
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(search
, mpage
, db
, s
, mp
->pageid
,
347 paths
->paths
[i
], mp
->form
);
348 if (mpage
->names
!= NULL
) {
349 mpage
->output
= TYPE_Nd
& outbit
?
351 buildoutput(db
, s2
, mp
->pageid
, outbit
) :
359 sqlite3_finalize(s2
);
364 * In man(1) mode, prefer matches in earlier trees
365 * over matches in later trees.
368 if (cur
&& search
->firstmatch
)
371 qsort(*res
, cur
, sizeof(struct manpage
), manpage_compare
);
375 if (-1 == fchdir(fd
))
386 mansearch_free(struct manpage
*res
, size_t sz
)
390 for (i
= 0; i
< sz
; i
++) {
399 manpage_compare(const void *vp1
, const void *vp2
)
401 const struct manpage
*mp1
, *mp2
;
406 return( (diff
= mp2
->bits
- mp1
->bits
) ? diff
:
407 (diff
= mp1
->sec
- mp2
->sec
) ? diff
:
408 strcasecmp(mp1
->names
, mp2
->names
));
412 buildnames(const struct mansearch
*search
, struct manpage
*mpage
,
413 sqlite3
*db
, sqlite3_stmt
*s
,
414 uint64_t pageid
, const char *path
, int form
)
417 char *firstname
, *newnames
, *prevsec
, *prevarch
;
418 const char *oldnames
, *sep1
, *name
, *sec
, *sep2
, *arch
, *fsec
;
424 firstname
= prevsec
= prevarch
= NULL
;
426 SQL_BIND_INT64(db
, s
, i
, pageid
);
427 while (SQLITE_ROW
== (c
= sqlite3_step(s
))) {
429 /* Decide whether we already have some names. */
431 if (NULL
== mpage
->names
) {
435 oldnames
= mpage
->names
;
439 /* Fetch the next name, rejecting sec/arch mismatches. */
441 sec
= (const char *)sqlite3_column_text(s
, 0);
442 if (search
->sec
!= NULL
&& strcasecmp(sec
, search
->sec
))
444 arch
= (const char *)sqlite3_column_text(s
, 1);
445 if (search
->arch
!= NULL
&& *arch
!= '\0' &&
446 strcasecmp(arch
, search
->arch
))
448 name
= (const char *)sqlite3_column_text(s
, 2);
450 /* Remember the first section found. */
452 if (9 < mpage
->sec
&& '1' <= *sec
&& '9' >= *sec
)
453 mpage
->sec
= (*sec
- '1') + 1;
455 /* If the section changed, append the old one. */
457 if (NULL
!= prevsec
&&
458 (strcmp(sec
, prevsec
) ||
459 strcmp(arch
, prevarch
))) {
460 sep2
= '\0' == *prevarch
? "" : "/";
461 mandoc_asprintf(&newnames
, "%s(%s%s%s)",
462 oldnames
, prevsec
, sep2
, prevarch
);
464 oldnames
= mpage
->names
= newnames
;
467 prevsec
= prevarch
= NULL
;
470 /* Save the new section, to append it later. */
472 if (NULL
== prevsec
) {
473 prevsec
= mandoc_strdup(sec
);
474 prevarch
= mandoc_strdup(arch
);
477 /* Append the new name. */
479 mandoc_asprintf(&newnames
, "%s%s%s",
480 oldnames
, sep1
, name
);
482 mpage
->names
= newnames
;
484 /* Also save the first file name encountered. */
486 if (mpage
->file
!= NULL
)
489 if (form
& FORM_SRC
) {
496 sep2
= *arch
== '\0' ? "" : "/";
497 mandoc_asprintf(&mpage
->file
, "%s/%s%s%s%s/%s.%s",
498 path
, sep1
, sec
, sep2
, arch
, name
, fsec
);
499 if (access(mpage
->file
, R_OK
) != -1)
502 /* Handle unusual file name extensions. */
504 if (firstname
== NULL
)
505 firstname
= mpage
->file
;
508 mandoc_asprintf(&mpage
->file
, "%s/%s%s%s%s/%s.*",
509 path
, sep1
, sec
, sep2
, arch
, name
);
510 globres
= glob(mpage
->file
, 0, NULL
, &globinfo
);
512 mpage
->file
= globres
? NULL
:
513 mandoc_strdup(*globinfo
.gl_pathv
);
516 if (c
!= SQLITE_DONE
)
517 fprintf(stderr
, "%s\n", sqlite3_errmsg(db
));
520 /* If none of the files is usable, use the first name. */
522 if (mpage
->file
== NULL
)
523 mpage
->file
= firstname
;
524 else if (mpage
->file
!= firstname
)
527 /* Append one final section to the names. */
529 if (prevsec
!= NULL
) {
530 sep2
= *prevarch
== '\0' ? "" : "/";
531 mandoc_asprintf(&newnames
, "%s(%s%s%s)",
532 mpage
->names
, prevsec
, sep2
, prevarch
);
534 mpage
->names
= newnames
;
541 buildoutput(sqlite3
*db
, sqlite3_stmt
*s
, uint64_t pageid
, uint64_t outbit
)
543 char *output
, *newoutput
;
544 const char *oldoutput
, *sep1
, *data
;
550 SQL_BIND_INT64(db
, s
, i
, pageid
);
551 SQL_BIND_INT64(db
, s
, i
, outbit
);
552 while (SQLITE_ROW
== (c
= sqlite3_step(s
))) {
553 if (NULL
== output
) {
560 data
= (const char *)sqlite3_column_text(s
, 1);
561 mandoc_asprintf(&newoutput
, "%s%s%s",
562 oldoutput
, sep1
, data
);
566 if (SQLITE_DONE
!= c
)
567 fprintf(stderr
, "%s\n", sqlite3_errmsg(db
));
573 * Implement substring match as an application-defined SQL function.
574 * Using the SQL LIKE or GLOB operators instead would be a bad idea
575 * because that would require escaping metacharacters in the string
576 * being searched for.
579 sql_match(sqlite3_context
*context
, int argc
, sqlite3_value
**argv
)
583 sqlite3_result_int(context
, NULL
!= strcasestr(
584 (const char *)sqlite3_value_text(argv
[1]),
585 (const char *)sqlite3_value_text(argv
[0])));
589 * Implement regular expression match
590 * as an application-defined SQL function.
593 sql_regexp(sqlite3_context
*context
, int argc
, sqlite3_value
**argv
)
597 sqlite3_result_int(context
, !regexec(
598 (regex_t
*)sqlite3_value_blob(argv
[0]),
599 (const char *)sqlite3_value_text(argv
[1]),
604 sql_append(char **sql
, size_t *sz
, const char *newstr
, int count
)
608 newsz
= 1 < count
? (size_t)count
: strlen(newstr
);
609 *sql
= mandoc_realloc(*sql
, *sz
+ newsz
+ 1);
611 memset(*sql
+ *sz
, *newstr
, (size_t)count
);
613 memcpy(*sql
+ *sz
, newstr
, newsz
);
619 * Prepare the search SQL statement.
622 sql_statement(const struct expr
*e
)
628 sql
= mandoc_strdup(e
->equal
?
629 "SELECT desc, form, pageid, bits "
630 "FROM mpages NATURAL JOIN names WHERE " :
631 "SELECT desc, form, pageid, 0 FROM mpages WHERE ");
634 for (needop
= 0; NULL
!= e
; e
= e
->next
) {
636 sql_append(&sql
, &sz
, " AND ", 1);
638 sql_append(&sql
, &sz
, " OR ", 1);
640 sql_append(&sql
, &sz
, "(", e
->open
);
641 sql_append(&sql
, &sz
,
648 ? "pageid IN (SELECT pageid FROM names "
649 "WHERE name REGEXP ?)"
652 : "pageid IN (SELECT pageid FROM names "
653 "WHERE name MATCH ?)")
655 ? "pageid IN (SELECT pageid FROM keys "
656 "WHERE key REGEXP ? AND bits & ?)"
657 : "pageid IN (SELECT pageid FROM keys "
658 "WHERE key MATCH ? AND bits & ?)"), 1);
660 sql_append(&sql
, &sz
, ")", e
->close
);
668 * Compile a set of string tokens into an expression.
669 * Tokens in "argv" are assumed to be individual expression atoms (e.g.,
670 * "(", "foo=bar", etc.).
673 exprcomp(const struct mansearch
*search
, int argc
, char *argv
[])
676 int i
, toopen
, logic
, igncase
, toclose
;
677 struct expr
*first
, *prev
, *cur
, *next
;
680 logic
= igncase
= toopen
= toclose
= 0;
682 for (i
= 0; i
< argc
; i
++) {
683 if (0 == strcmp("(", argv
[i
])) {
689 } else if (0 == strcmp(")", argv
[i
])) {
690 if (toopen
|| logic
|| igncase
|| NULL
== cur
)
696 } else if (0 == strcmp("-a", argv
[i
])) {
697 if (toopen
|| logic
|| igncase
|| NULL
== cur
)
701 } else if (0 == strcmp("-o", argv
[i
])) {
702 if (toopen
|| logic
|| igncase
|| NULL
== cur
)
706 } else if (0 == strcmp("-i", argv
[i
])) {
712 next
= exprterm(search
, argv
[i
], !igncase
);
722 * Searching for descriptions must be split out
723 * because they are stored in the mpages table,
724 * not in the keys table.
727 for (mask
= TYPE_Nm
; mask
<= TYPE_Nd
; mask
<<= 1) {
728 if (mask
& cur
->bits
&& ~mask
& cur
->bits
) {
729 next
= mandoc_calloc(1,
730 sizeof(struct expr
));
731 memcpy(next
, cur
, sizeof(struct expr
));
739 prev
->and = (1 == logic
);
740 prev
->open
+= toopen
;
744 toopen
= logic
= igncase
= 0;
746 if ( ! (toopen
|| logic
|| igncase
|| toclose
))
756 exprterm(const struct mansearch
*search
, char *buf
, int cs
)
767 e
= mandoc_calloc(1, sizeof(struct expr
));
769 if (search
->argmode
== ARG_NAME
) {
777 * Separate macro keys from search string.
778 * If needed, request regular expression handling
779 * by setting e->substr to NULL.
782 if (search
->argmode
== ARG_WORD
) {
785 mandoc_asprintf(&val
, "[[:<:]]%s[[:>:]]", buf
);
787 } else if ((val
= strpbrk(buf
, "=~")) == NULL
) {
788 e
->bits
= TYPE_Nm
| TYPE_Nd
;
792 e
->bits
= TYPE_Nm
| TYPE_Nd
;
796 if (NULL
!= strstr(buf
, "arch"))
800 /* Compile regular expressions. */
802 if (NULL
== e
->substr
) {
803 irc
= regcomp(&e
->regexp
, val
,
804 REG_EXTENDED
| REG_NOSUB
| (cs
? 0 : REG_ICASE
));
805 if (search
->argmode
== ARG_WORD
)
808 regerror(irc
, &e
->regexp
, errbuf
, sizeof(errbuf
));
809 fprintf(stderr
, "regcomp: %s\n", errbuf
);
819 * Parse out all possible fields.
820 * If the field doesn't resolve, bail.
823 while (NULL
!= (key
= strsep(&buf
, ","))) {
826 for (i
= 0, iterbit
= 1;
827 i
< mansearch_keymax
;
828 i
++, iterbit
<<= 1) {
829 if (0 == strcasecmp(key
,
830 mansearch_keynames
[i
])) {
835 if (i
== mansearch_keymax
) {
836 if (strcasecmp(key
, "any")) {
848 exprfree(struct expr
*p
)
860 hash_calloc(size_t nmemb
, size_t sz
, void *arg
)
863 return(mandoc_calloc(nmemb
, sz
));
867 hash_alloc(size_t sz
, void *arg
)
870 return(mandoc_malloc(sz
));
874 hash_free(void *p
, void *arg
)