]>
git.cameronkatri.com Git - mandoc.git/blob - mansearch.c
1 /* $Id: mansearch.c,v 1.60 2015/10/13 15:53:05 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 AUTHORS DISCLAIM ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS 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 #ifndef SQLITE_DETERMINISTIC
40 #define SQLITE_DETERMINISTIC 0
44 #include "mandoc_aux.h"
45 #include "mandoc_ohash.h"
47 #include "mansearch.h"
49 extern int mansearch_keymax
;
50 extern const char *const mansearch_keynames
[];
52 #define SQL_BIND_TEXT(_db, _s, _i, _v) \
53 do { if (SQLITE_OK != sqlite3_bind_text \
54 ((_s), (_i)++, (_v), -1, SQLITE_STATIC)) \
55 warnx("%s", sqlite3_errmsg((_db))); \
57 #define SQL_BIND_INT64(_db, _s, _i, _v) \
58 do { if (SQLITE_OK != sqlite3_bind_int64 \
59 ((_s), (_i)++, (_v))) \
60 warnx("%s", sqlite3_errmsg((_db))); \
62 #define SQL_BIND_BLOB(_db, _s, _i, _v) \
63 do { if (SQLITE_OK != sqlite3_bind_blob \
64 ((_s), (_i)++, (&_v), sizeof(_v), SQLITE_STATIC)) \
65 warnx("%s", sqlite3_errmsg((_db))); \
69 regex_t regexp
; /* compiled regexp, if applicable */
70 const char *substr
; /* to search for, if applicable */
71 struct expr
*next
; /* next in sequence */
72 uint64_t bits
; /* type-mask */
73 int equal
; /* equality, not subsring match */
74 int open
; /* opening parentheses before */
75 int and; /* logical AND before */
76 int close
; /* closing parentheses after */
80 uint64_t pageid
; /* identifier in database */
81 uint64_t bits
; /* name type mask */
82 char *desc
; /* manual page description */
83 int form
; /* bit field: formatted, zipped? */
86 static void buildnames(const struct mansearch
*,
87 struct manpage
*, sqlite3
*,
88 sqlite3_stmt
*, uint64_t,
89 const char *, int form
);
90 static char *buildoutput(sqlite3
*, sqlite3_stmt
*,
92 static struct expr
*exprcomp(const struct mansearch
*,
94 static void exprfree(struct expr
*);
95 static struct expr
*exprterm(const struct mansearch
*, char *, int);
96 static int manpage_compare(const void *, const void *);
97 static void sql_append(char **sql
, size_t *sz
,
98 const char *newstr
, int count
);
99 static void sql_match(sqlite3_context
*context
,
100 int argc
, sqlite3_value
**argv
);
101 static void sql_regexp(sqlite3_context
*context
,
102 int argc
, sqlite3_value
**argv
);
103 static char *sql_statement(const struct expr
*);
107 mansearch_setup(int start
)
109 static void *pagecache
;
112 #define PC_PAGESIZE 1280
113 #define PC_NUMPAGES 256
116 if (NULL
!= pagecache
) {
117 warnx("pagecache already enabled");
118 return (int)MANDOCLEVEL_BADARG
;
121 pagecache
= mmap(NULL
, PC_PAGESIZE
* PC_NUMPAGES
,
122 PROT_READ
| PROT_WRITE
,
123 MAP_SHARED
| MAP_ANON
, -1, 0);
125 if (MAP_FAILED
== pagecache
) {
128 return (int)MANDOCLEVEL_SYSERR
;
131 c
= sqlite3_config(SQLITE_CONFIG_PAGECACHE
,
132 pagecache
, PC_PAGESIZE
, PC_NUMPAGES
);
135 return (int)MANDOCLEVEL_OK
;
137 warnx("pagecache: %s", sqlite3_errstr(c
));
139 } else if (NULL
== pagecache
) {
140 warnx("pagecache missing");
141 return (int)MANDOCLEVEL_BADARG
;
144 if (-1 == munmap(pagecache
, PC_PAGESIZE
* PC_NUMPAGES
)) {
147 return (int)MANDOCLEVEL_SYSERR
;
151 return (int)MANDOCLEVEL_OK
;
155 mansearch(const struct mansearch
*search
,
156 const struct manpaths
*paths
,
157 int argc
, char *argv
[],
158 struct manpage
**res
, size_t *sz
)
161 uint64_t outbit
, iterbit
;
164 struct manpage
*mpage
;
167 sqlite3_stmt
*s
, *s2
;
171 size_t i
, j
, cur
, maxres
;
172 int c
, chdir_status
, getcwd_status
, indexbit
;
174 if (argc
== 0 || (e
= exprcomp(search
, argc
, argv
)) == NULL
) {
182 if (NULL
!= search
->outkey
) {
184 for (indexbit
= 0, iterbit
= 1;
185 indexbit
< mansearch_keymax
;
186 indexbit
++, iterbit
<<= 1) {
187 if (0 == strcasecmp(search
->outkey
,
188 mansearch_keynames
[indexbit
])) {
197 * Remember the original working directory, if possible.
198 * This will be needed if the second or a later directory
199 * is given as a relative path.
200 * Do not error out if the current directory is not
201 * searchable: Maybe it won't be needed after all.
204 if (getcwd(buf
, PATH_MAX
) == NULL
) {
206 (void)strlcpy(buf
, strerror(errno
), sizeof(buf
));
210 sql
= sql_statement(e
);
213 * Loop over the directories (containing databases) for us to
215 * Don't let missing/bad databases/directories phase us.
216 * In each, try to open the resident database and, if it opens,
217 * scan it for our match expression.
221 for (i
= 0; i
< paths
->sz
; i
++) {
222 if (chdir_status
&& paths
->paths
[i
][0] != '/') {
223 if ( ! getcwd_status
) {
224 warnx("%s: getcwd: %s", paths
->paths
[i
], buf
);
226 } else if (chdir(buf
) == -1) {
231 if (chdir(paths
->paths
[i
]) == -1) {
232 perror(paths
->paths
[i
]);
237 c
= sqlite3_open_v2(MANDOC_DB
, &db
,
238 SQLITE_OPEN_READONLY
, NULL
);
240 if (SQLITE_OK
!= c
) {
241 warn("%s/%s", paths
->paths
[i
], MANDOC_DB
);
247 * Define the SQL functions for substring
248 * and regular expression matching.
251 c
= sqlite3_create_function(db
, "match", 2,
252 SQLITE_UTF8
| SQLITE_DETERMINISTIC
,
253 NULL
, sql_match
, NULL
, NULL
);
254 assert(SQLITE_OK
== c
);
255 c
= sqlite3_create_function(db
, "regexp", 2,
256 SQLITE_UTF8
| SQLITE_DETERMINISTIC
,
257 NULL
, sql_regexp
, NULL
, NULL
);
258 assert(SQLITE_OK
== c
);
261 c
= sqlite3_prepare_v2(db
, sql
, -1, &s
, NULL
);
263 warnx("%s", sqlite3_errmsg(db
));
265 for (ep
= e
; NULL
!= ep
; ep
= ep
->next
) {
266 if (NULL
== ep
->substr
) {
267 SQL_BIND_BLOB(db
, s
, j
, ep
->regexp
);
269 SQL_BIND_TEXT(db
, s
, j
, ep
->substr
);
270 if (0 == ((TYPE_Nd
| TYPE_Nm
) & ep
->bits
))
271 SQL_BIND_INT64(db
, s
, j
, ep
->bits
);
274 mandoc_ohash_init(&htab
, 4, offsetof(struct match
, pageid
));
277 * Hash each entry on its [unique] document identifier.
278 * This is a uint64_t.
279 * Instead of using a hash function, simply convert the
280 * uint64_t to a uint32_t, the hash value's type.
281 * This gives good performance and preserves the
282 * distribution of buckets in the table.
284 while (SQLITE_ROW
== (c
= sqlite3_step(s
))) {
285 pageid
= sqlite3_column_int64(s
, 2);
286 idx
= ohash_lookup_memory(&htab
,
287 (char *)&pageid
, sizeof(uint64_t),
290 if (NULL
!= ohash_find(&htab
, idx
))
293 mp
= mandoc_calloc(1, sizeof(struct match
));
295 mp
->form
= sqlite3_column_int(s
, 1);
296 mp
->bits
= sqlite3_column_int64(s
, 3);
297 if (TYPE_Nd
== outbit
)
298 mp
->desc
= mandoc_strdup((const char *)
299 sqlite3_column_text(s
, 0));
300 ohash_insert(&htab
, idx
, mp
);
303 if (SQLITE_DONE
!= c
)
304 warnx("%s", sqlite3_errmsg(db
));
308 c
= sqlite3_prepare_v2(db
,
309 "SELECT sec, arch, name, pageid FROM mlinks "
310 "WHERE pageid=? ORDER BY sec, arch, name",
313 warnx("%s", sqlite3_errmsg(db
));
315 c
= sqlite3_prepare_v2(db
,
316 "SELECT bits, key, pageid FROM keys "
317 "WHERE pageid=? AND bits & ?",
320 warnx("%s", sqlite3_errmsg(db
));
322 for (mp
= ohash_first(&htab
, &idx
);
324 mp
= ohash_next(&htab
, &idx
)) {
325 if (cur
+ 1 > maxres
) {
327 *res
= mandoc_reallocarray(*res
,
328 maxres
, sizeof(struct manpage
));
332 mpage
->bits
= mp
->bits
;
334 mpage
->form
= mp
->form
;
335 buildnames(search
, mpage
, db
, s
, mp
->pageid
,
336 paths
->paths
[i
], mp
->form
);
337 if (mpage
->names
!= NULL
) {
338 mpage
->output
= TYPE_Nd
& outbit
?
340 buildoutput(db
, s2
, mp
->pageid
, outbit
) :
348 sqlite3_finalize(s2
);
353 * In man(1) mode, prefer matches in earlier trees
354 * over matches in later trees.
357 if (cur
&& search
->firstmatch
)
360 qsort(*res
, cur
, sizeof(struct manpage
), manpage_compare
);
361 if (chdir_status
&& getcwd_status
&& chdir(buf
) == -1)
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 return (diff
= mp2
->bits
- mp1
->bits
) ? diff
:
391 (diff
= mp1
->sec
- mp2
->sec
) ? diff
:
392 strcasecmp(mp1
->names
, mp2
->names
);
396 buildnames(const struct mansearch
*search
, struct manpage
*mpage
,
397 sqlite3
*db
, sqlite3_stmt
*s
,
398 uint64_t pageid
, const char *path
, int form
)
401 char *firstname
, *newnames
, *prevsec
, *prevarch
;
402 const char *oldnames
, *sep1
, *name
, *sec
, *sep2
, *arch
, *fsec
;
408 firstname
= prevsec
= prevarch
= NULL
;
410 SQL_BIND_INT64(db
, s
, i
, pageid
);
411 while (SQLITE_ROW
== (c
= sqlite3_step(s
))) {
413 /* Decide whether we already have some names. */
415 if (NULL
== mpage
->names
) {
419 oldnames
= mpage
->names
;
423 /* Fetch the next name, rejecting sec/arch mismatches. */
425 sec
= (const char *)sqlite3_column_text(s
, 0);
426 if (search
->sec
!= NULL
&& strcasecmp(sec
, search
->sec
))
428 arch
= (const char *)sqlite3_column_text(s
, 1);
429 if (search
->arch
!= NULL
&& *arch
!= '\0' &&
430 strcasecmp(arch
, search
->arch
))
432 name
= (const char *)sqlite3_column_text(s
, 2);
434 /* Remember the first section found. */
436 if (9 < mpage
->sec
&& '1' <= *sec
&& '9' >= *sec
)
437 mpage
->sec
= (*sec
- '1') + 1;
439 /* If the section changed, append the old one. */
441 if (NULL
!= prevsec
&&
442 (strcmp(sec
, prevsec
) ||
443 strcmp(arch
, prevarch
))) {
444 sep2
= '\0' == *prevarch
? "" : "/";
445 mandoc_asprintf(&newnames
, "%s(%s%s%s)",
446 oldnames
, prevsec
, sep2
, prevarch
);
448 oldnames
= mpage
->names
= newnames
;
451 prevsec
= prevarch
= NULL
;
454 /* Save the new section, to append it later. */
456 if (NULL
== prevsec
) {
457 prevsec
= mandoc_strdup(sec
);
458 prevarch
= mandoc_strdup(arch
);
461 /* Append the new name. */
463 mandoc_asprintf(&newnames
, "%s%s%s",
464 oldnames
, sep1
, name
);
466 mpage
->names
= newnames
;
468 /* Also save the first file name encountered. */
470 if (mpage
->file
!= NULL
)
473 if (form
& FORM_SRC
) {
480 sep2
= *arch
== '\0' ? "" : "/";
481 mandoc_asprintf(&mpage
->file
, "%s/%s%s%s%s/%s.%s",
482 path
, sep1
, sec
, sep2
, arch
, name
, fsec
);
483 if (access(mpage
->file
, R_OK
) != -1)
486 /* Handle unusual file name extensions. */
488 if (firstname
== NULL
)
489 firstname
= mpage
->file
;
492 mandoc_asprintf(&mpage
->file
, "%s/%s%s%s%s/%s.*",
493 path
, sep1
, sec
, sep2
, arch
, name
);
494 globres
= glob(mpage
->file
, 0, NULL
, &globinfo
);
496 mpage
->file
= globres
? NULL
:
497 mandoc_strdup(*globinfo
.gl_pathv
);
500 if (c
!= SQLITE_DONE
)
501 warnx("%s", sqlite3_errmsg(db
));
504 /* If none of the files is usable, use the first name. */
506 if (mpage
->file
== NULL
)
507 mpage
->file
= firstname
;
508 else if (mpage
->file
!= firstname
)
511 /* Append one final section to the names. */
513 if (prevsec
!= NULL
) {
514 sep2
= *prevarch
== '\0' ? "" : "/";
515 mandoc_asprintf(&newnames
, "%s(%s%s%s)",
516 mpage
->names
, prevsec
, sep2
, prevarch
);
518 mpage
->names
= newnames
;
525 buildoutput(sqlite3
*db
, sqlite3_stmt
*s
, uint64_t pageid
, uint64_t outbit
)
527 char *output
, *newoutput
;
528 const char *oldoutput
, *sep1
, *data
;
534 SQL_BIND_INT64(db
, s
, i
, pageid
);
535 SQL_BIND_INT64(db
, s
, i
, outbit
);
536 while (SQLITE_ROW
== (c
= sqlite3_step(s
))) {
537 if (NULL
== output
) {
544 data
= (const char *)sqlite3_column_text(s
, 1);
545 mandoc_asprintf(&newoutput
, "%s%s%s",
546 oldoutput
, sep1
, data
);
550 if (SQLITE_DONE
!= c
)
551 warnx("%s", sqlite3_errmsg(db
));
557 * Implement substring match as an application-defined SQL function.
558 * Using the SQL LIKE or GLOB operators instead would be a bad idea
559 * because that would require escaping metacharacters in the string
560 * being searched for.
563 sql_match(sqlite3_context
*context
, int argc
, sqlite3_value
**argv
)
567 sqlite3_result_int(context
, NULL
!= strcasestr(
568 (const char *)sqlite3_value_text(argv
[1]),
569 (const char *)sqlite3_value_text(argv
[0])));
573 * Implement regular expression match
574 * as an application-defined SQL function.
577 sql_regexp(sqlite3_context
*context
, int argc
, sqlite3_value
**argv
)
581 sqlite3_result_int(context
, !regexec(
582 (regex_t
*)sqlite3_value_blob(argv
[0]),
583 (const char *)sqlite3_value_text(argv
[1]),
588 sql_append(char **sql
, size_t *sz
, const char *newstr
, int count
)
592 newsz
= 1 < count
? (size_t)count
: strlen(newstr
);
593 *sql
= mandoc_realloc(*sql
, *sz
+ newsz
+ 1);
595 memset(*sql
+ *sz
, *newstr
, (size_t)count
);
597 memcpy(*sql
+ *sz
, newstr
, newsz
);
603 * Prepare the search SQL statement.
606 sql_statement(const struct expr
*e
)
612 sql
= mandoc_strdup(e
->equal
?
613 "SELECT desc, form, pageid, bits "
614 "FROM mpages NATURAL JOIN names WHERE " :
615 "SELECT desc, form, pageid, 0 FROM mpages WHERE ");
618 for (needop
= 0; NULL
!= e
; e
= e
->next
) {
620 sql_append(&sql
, &sz
, " AND ", 1);
622 sql_append(&sql
, &sz
, " OR ", 1);
624 sql_append(&sql
, &sz
, "(", e
->open
);
625 sql_append(&sql
, &sz
,
632 ? "pageid IN (SELECT pageid FROM names "
633 "WHERE name REGEXP ?)"
636 : "pageid IN (SELECT pageid FROM names "
637 "WHERE name MATCH ?)")
639 ? "pageid IN (SELECT pageid FROM keys "
640 "WHERE key REGEXP ? AND bits & ?)"
641 : "pageid IN (SELECT pageid FROM keys "
642 "WHERE key MATCH ? AND bits & ?)"), 1);
644 sql_append(&sql
, &sz
, ")", e
->close
);
652 * Compile a set of string tokens into an expression.
653 * Tokens in "argv" are assumed to be individual expression atoms (e.g.,
654 * "(", "foo=bar", etc.).
657 exprcomp(const struct mansearch
*search
, int argc
, char *argv
[])
660 int i
, toopen
, logic
, igncase
, toclose
;
661 struct expr
*first
, *prev
, *cur
, *next
;
664 logic
= igncase
= toopen
= toclose
= 0;
666 for (i
= 0; i
< argc
; i
++) {
667 if (0 == strcmp("(", argv
[i
])) {
673 } else if (0 == strcmp(")", argv
[i
])) {
674 if (toopen
|| logic
|| igncase
|| NULL
== cur
)
680 } else if (0 == strcmp("-a", argv
[i
])) {
681 if (toopen
|| logic
|| igncase
|| NULL
== cur
)
685 } else if (0 == strcmp("-o", argv
[i
])) {
686 if (toopen
|| logic
|| igncase
|| NULL
== cur
)
690 } else if (0 == strcmp("-i", argv
[i
])) {
696 next
= exprterm(search
, argv
[i
], !igncase
);
706 * Searching for descriptions must be split out
707 * because they are stored in the mpages table,
708 * not in the keys table.
711 for (mask
= TYPE_Nm
; mask
<= TYPE_Nd
; mask
<<= 1) {
712 if (mask
& cur
->bits
&& ~mask
& cur
->bits
) {
713 next
= mandoc_calloc(1,
714 sizeof(struct expr
));
715 memcpy(next
, cur
, sizeof(struct expr
));
723 prev
->and = (1 == logic
);
724 prev
->open
+= toopen
;
728 toopen
= logic
= igncase
= 0;
730 if ( ! (toopen
|| logic
|| igncase
|| toclose
))
740 exprterm(const struct mansearch
*search
, char *buf
, int cs
)
751 e
= mandoc_calloc(1, sizeof(struct expr
));
753 if (search
->argmode
== ARG_NAME
) {
761 * Separate macro keys from search string.
762 * If needed, request regular expression handling
763 * by setting e->substr to NULL.
766 if (search
->argmode
== ARG_WORD
) {
769 mandoc_asprintf(&val
, "[[:<:]]%s[[:>:]]", buf
);
771 } else if ((val
= strpbrk(buf
, "=~")) == NULL
) {
772 e
->bits
= TYPE_Nm
| TYPE_Nd
;
776 e
->bits
= TYPE_Nm
| TYPE_Nd
;
780 if (NULL
!= strstr(buf
, "arch"))
784 /* Compile regular expressions. */
786 if (NULL
== e
->substr
) {
787 irc
= regcomp(&e
->regexp
, val
,
788 REG_EXTENDED
| REG_NOSUB
| (cs
? 0 : REG_ICASE
));
789 if (search
->argmode
== ARG_WORD
)
792 regerror(irc
, &e
->regexp
, errbuf
, sizeof(errbuf
));
793 warnx("regcomp: %s", errbuf
);
803 * Parse out all possible fields.
804 * If the field doesn't resolve, bail.
807 while (NULL
!= (key
= strsep(&buf
, ","))) {
810 for (i
= 0, iterbit
= 1;
811 i
< mansearch_keymax
;
812 i
++, iterbit
<<= 1) {
813 if (0 == strcasecmp(key
,
814 mansearch_keynames
[i
])) {
819 if (i
== mansearch_keymax
) {
820 if (strcasecmp(key
, "any")) {
832 exprfree(struct expr
*p
)