xref: /netbsd-src/usr.sbin/makemandb/apropos-utils.c (revision 9ac63422b666fbe53a067de74d8af2aa4e45a08b)
1 /*	$NetBSD: apropos-utils.c,v 1.3 2012/04/07 10:44:58 apb Exp $	*/
2 /*-
3  * Copyright (c) 2011 Abhinav Upadhyay <er.abhinav.upadhyay@gmail.com>
4  * All rights reserved.
5  *
6  * This code was developed as part of Google's Summer of Code 2011 program.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in
16  *    the documentation and/or other materials provided with the
17  *    distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
22  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
23  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
24  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
25  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
27  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
28  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
29  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 #include <sys/cdefs.h>
34 __RCSID("$NetBSD: apropos-utils.c,v 1.3 2012/04/07 10:44:58 apb Exp $");
35 
36 #include <sys/stat.h>
37 
38 #include <assert.h>
39 #include <ctype.h>
40 #include <err.h>
41 #include <math.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <string.h>
45 #include <util.h>
46 #include <zlib.h>
47 
48 #include "apropos-utils.h"
49 #include "mandoc.h"
50 #include "sqlite3.h"
51 
52 typedef struct orig_callback_data {
53 	void *data;
54 	int (*callback) (void *, const char *, const char *, const char *,
55 		const char *, size_t);
56 } orig_callback_data;
57 
58 typedef struct inverse_document_frequency {
59 	double value;
60 	int status;
61 } inverse_document_frequency;
62 
63 /* weights for individual columns */
64 static const double col_weights[] = {
65 	2.0,	// NAME
66 	2.00,	// Name-description
67 	0.55,	// DESCRIPTION
68 	0.10,	// LIBRARY
69 	0.001,	//RETURN VALUES
70 	0.20,	//ENVIRONMENT
71 	0.01,	//FILES
72 	0.001,	//EXIT STATUS
73 	2.00,	//DIAGNOSTICS
74 	0.05,	//ERRORS
75 	0.00,	//md5_hash
76 	1.00	//machine
77 };
78 
79 /*
80  * lower --
81  *  Converts the string str to lower case
82  */
83 char *
84 lower(char *str)
85 {
86 	assert(str);
87 	int i = 0;
88 	char c;
89 	while (str[i] != '\0') {
90 		c = tolower((unsigned char) str[i]);
91 		str[i++] = c;
92 	}
93 	return str;
94 }
95 
96 /*
97 * concat--
98 *  Utility function. Concatenates together: dst, a space character and src.
99 * dst + " " + src
100 */
101 void
102 concat(char **dst, const char *src)
103 {
104 	concat2(dst, src, strlen(src));
105 }
106 
107 void
108 concat2(char **dst, const char *src, size_t srclen)
109 {
110 	size_t total_len, dst_len;
111 	assert(src != NULL);
112 
113 	/* If destination buffer dst is NULL, then simply strdup the source buffer */
114 	if (*dst == NULL) {
115 		*dst = estrdup(src);
116 		return;
117 	}
118 
119 	dst_len = strlen(*dst);
120 	/*
121 	 * NUL Byte and separator space
122 	 */
123 	total_len = dst_len + srclen + 2;
124 
125 	*dst = erealloc(*dst, total_len);
126 
127 	/* Append a space at the end of dst */
128 	(*dst)[dst_len++] = ' ';
129 
130 	/* Now, copy src at the end of dst */
131 	memcpy(*dst + dst_len, src, srclen + 1);
132 }
133 
134 void
135 close_db(sqlite3 *db)
136 {
137 	sqlite3_close(db);
138 	sqlite3_shutdown();
139 }
140 
141 /*
142  * create_db --
143  *  Creates the database schema.
144  */
145 static int
146 create_db(sqlite3 *db)
147 {
148 	const char *sqlstr = NULL;
149 	char *schemasql;
150 	char *errmsg = NULL;
151 
152 /*------------------------ Create the tables------------------------------*/
153 
154 #if NOTYET
155 	sqlite3_exec(db, "PRAGMA journal_mode = WAL", NULL, NULL, NULL);
156 #else
157 	sqlite3_exec(db, "PRAGMA journal_mode = DELETE", NULL, NULL, NULL);
158 #endif
159 
160 	schemasql = sqlite3_mprintf("PRAGMA user_version = %d",
161 	    APROPOS_SCHEMA_VERSION);
162 	sqlite3_exec(db, schemasql, NULL, NULL, &errmsg);
163 	if (errmsg != NULL)
164 		goto out;
165 	sqlite3_free(schemasql);
166 
167 	sqlstr = "CREATE VIRTUAL TABLE mandb USING fts4(section, name, "
168 			    "name_desc, desc, lib, return_vals, env, files, "
169 			    "exit_status, diagnostics, errors, md5_hash UNIQUE, machine, "
170 			    "compress=zip, uncompress=unzip, tokenize=porter); "	//mandb
171 			"CREATE TABLE IF NOT EXISTS mandb_meta(device, inode, mtime, "
172 			    "file UNIQUE, md5_hash UNIQUE, id  INTEGER PRIMARY KEY); "
173 				//mandb_meta
174 			"CREATE TABLE IF NOT EXISTS mandb_links(link, target, section, "
175 			    "machine); ";	//mandb_links
176 
177 	sqlite3_exec(db, sqlstr, NULL, NULL, &errmsg);
178 	if (errmsg != NULL)
179 		goto out;
180 
181 	sqlstr = "CREATE INDEX IF NOT EXISTS index_mandb_links ON mandb_links "
182 			"(link); "
183 			"CREATE INDEX IF NOT EXISTS index_mandb_meta_dev ON mandb_meta "
184 			"(device, inode)";
185 	sqlite3_exec(db, sqlstr, NULL, NULL, &errmsg);
186 	if (errmsg != NULL)
187 		goto out;
188 	return 0;
189 
190 out:
191 	warnx("%s", errmsg);
192 	free(errmsg);
193 	sqlite3_close(db);
194 	sqlite3_shutdown();
195 	return -1;
196 }
197 
198 /*
199  * zip --
200  *  User defined Sqlite function to compress the FTS table
201  */
202 static void
203 zip(sqlite3_context *pctx, int nval, sqlite3_value **apval)
204 {
205 	int nin;
206 	long int nout;
207 	const unsigned char * inbuf;
208 	unsigned char *outbuf;
209 
210 	assert(nval == 1);
211 	nin = sqlite3_value_bytes(apval[0]);
212 	inbuf = (const unsigned char *) sqlite3_value_blob(apval[0]);
213 	nout = nin + 13 + (nin + 999) / 1000;
214 	outbuf = emalloc(nout);
215 	compress(outbuf, (unsigned long *) &nout, inbuf, nin);
216 	sqlite3_result_blob(pctx, outbuf, nout, free);
217 }
218 
219 /*
220  * unzip --
221  *  User defined Sqlite function to uncompress the FTS table.
222  */
223 static void
224 unzip(sqlite3_context *pctx, int nval, sqlite3_value **apval)
225 {
226 	unsigned int rc;
227 	unsigned char *outbuf;
228 	z_stream stream;
229 
230 	assert(nval == 1);
231 	stream.next_in = __UNCONST(sqlite3_value_blob(apval[0]));
232 	stream.avail_in = sqlite3_value_bytes(apval[0]);
233 	stream.avail_out = stream.avail_in * 2 + 100;
234 	stream.next_out = outbuf = emalloc(stream.avail_out);
235 	stream.zalloc = NULL;
236 	stream.zfree = NULL;
237 
238 	if (inflateInit(&stream) != Z_OK) {
239 		free(outbuf);
240 		return;
241 	}
242 
243 	while ((rc = inflate(&stream, Z_SYNC_FLUSH)) != Z_STREAM_END) {
244 		if (rc != Z_OK ||
245 		    (stream.avail_out != 0 && stream.avail_in == 0)) {
246 			free(outbuf);
247 			return;
248 		}
249 		outbuf = erealloc(outbuf, stream.total_out * 2);
250 		stream.next_out = outbuf + stream.total_out;
251 		stream.avail_out = stream.total_out;
252 	}
253 	if (inflateEnd(&stream) != Z_OK) {
254 		free(outbuf);
255 		return;
256 	}
257 	outbuf = erealloc(outbuf, stream.total_out);
258 	sqlite3_result_text(pctx, (const char *) outbuf, stream.total_out, free);
259 }
260 
261 /* init_db --
262  *   Prepare the database. Register the compress/uncompress functions and the
263  *   stopword tokenizer.
264  *	 db_flag specifies the mode in which to open the database. 3 options are
265  *   available:
266  *   	1. DB_READONLY: Open in READONLY mode. An error if db does not exist.
267  *  	2. DB_READWRITE: Open in read-write mode. An error if db does not exist.
268  *  	3. DB_CREATE: Open in read-write mode. It will try to create the db if
269  *			it does not exist already.
270  *  RETURN VALUES:
271  *		The function will return NULL in case the db does not exist and DB_CREATE
272  *  	was not specified. And in case DB_CREATE was specified and yet NULL is
273  *  	returned, then there was some other error.
274  *  	In normal cases the function should return a handle to the db.
275  */
276 sqlite3 *
277 init_db(int db_flag)
278 {
279 	sqlite3 *db = NULL;
280 	sqlite3_stmt *stmt;
281 	struct stat sb;
282 	int rc;
283 	int create_db_flag = 0;
284 
285 	/* Check if the database exists or not */
286 	if (!(stat(DBPATH, &sb) == 0 && S_ISREG(sb.st_mode))) {
287 		/* Database does not exist, check if DB_CREATE was specified, and set
288 		 * flag to create the database schema
289 		 */
290 		if (db_flag != (MANDB_CREATE)) {
291 			warnx("Missing apropos database. "
292 			      "Please run makemandb to create it.");
293 			return NULL;
294 		}
295 		create_db_flag = 1;
296 	}
297 
298 	/* Now initialize the database connection */
299 	sqlite3_initialize();
300 	rc = sqlite3_open_v2(DBPATH, &db, db_flag, NULL);
301 
302 	if (rc != SQLITE_OK) {
303 		warnx("%s", sqlite3_errmsg(db));
304 		sqlite3_shutdown();
305 		return NULL;
306 	}
307 
308 	if (create_db_flag && create_db(db) < 0) {
309 		warnx("%s", "Unable to create database schema");
310 		goto error;
311 	}
312 
313 	rc = sqlite3_prepare_v2(db, "PRAGMA user_version", -1, &stmt, NULL);
314 	if (rc != SQLITE_OK) {
315 		warnx("Unable to query schema version: %s",
316 		    sqlite3_errmsg(db));
317 		goto error;
318 	}
319 	if (sqlite3_step(stmt) != SQLITE_ROW) {
320 		sqlite3_finalize(stmt);
321 		warnx("Unable to query schema version: %s",
322 		    sqlite3_errmsg(db));
323 		goto error;
324 	}
325 	if (sqlite3_column_int(stmt, 0) != APROPOS_SCHEMA_VERSION) {
326 		sqlite3_finalize(stmt);
327 		warnx("Incorrect schema version found. "
328 		      "Please run makemandb -f.");
329 		goto error;
330 	}
331 	sqlite3_finalize(stmt);
332 
333 	sqlite3_extended_result_codes(db, 1);
334 
335 	/* Register the zip and unzip functions for FTS compression */
336 	rc = sqlite3_create_function(db, "zip", 1, SQLITE_ANY, NULL, zip, NULL, NULL);
337 	if (rc != SQLITE_OK) {
338 		warnx("Unable to register function: compress: %s",
339 		    sqlite3_errmsg(db));
340 		goto error;
341 	}
342 
343 	rc = sqlite3_create_function(db, "unzip", 1, SQLITE_ANY, NULL,
344                                  unzip, NULL, NULL);
345 	if (rc != SQLITE_OK) {
346 		warnx("Unable to register function: uncompress: %s",
347 		    sqlite3_errmsg(db));
348 		goto error;
349 	}
350 	return db;
351 error:
352 	sqlite3_close(db);
353 	sqlite3_shutdown();
354 	return NULL;
355 }
356 
357 /*
358  * rank_func --
359  *  Sqlite user defined function for ranking the documents.
360  *  For each phrase of the query, it computes the tf and idf and adds them over.
361  *  It computes the final rank, by multiplying tf and idf together.
362  *  Weight of term t for document d = (term frequency of t in d *
363  *                                      inverse document frequency of t)
364  *
365  *  Term Frequency of term t in document d = Number of times t occurs in d /
366  *	                                        Number of times t appears in all
367  *											documents
368  *
369  *  Inverse document frequency of t = log(Total number of documents /
370  *										Number of documents in which t occurs)
371  */
372 static void
373 rank_func(sqlite3_context *pctx, int nval, sqlite3_value **apval)
374 {
375 	inverse_document_frequency *idf = sqlite3_user_data(pctx);
376 	double tf = 0.0;
377 	const unsigned int *matchinfo;
378 	int ncol;
379 	int nphrase;
380 	int iphrase;
381 	int ndoc;
382 	int doclen = 0;
383 	const double k = 3.75;
384 	/* Check that the number of arguments passed to this function is correct. */
385 	assert(nval == 1);
386 
387 	matchinfo = (const unsigned int *) sqlite3_value_blob(apval[0]);
388 	nphrase = matchinfo[0];
389 	ncol = matchinfo[1];
390 	ndoc = matchinfo[2 + 3 * ncol * nphrase + ncol];
391 	for (iphrase = 0; iphrase < nphrase; iphrase++) {
392 		int icol;
393 		const unsigned int *phraseinfo = &matchinfo[2 + ncol+ iphrase * ncol * 3];
394 		for(icol = 1; icol < ncol; icol++) {
395 
396 			/* nhitcount: number of times the current phrase occurs in the current
397 			 *            column in the current document.
398 			 * nglobalhitcount: number of times current phrase occurs in the current
399 			 *                  column in all documents.
400 			 * ndocshitcount:   number of documents in which the current phrase
401 			 *                  occurs in the current column at least once.
402 			 */
403   			int nhitcount = phraseinfo[3 * icol];
404 			int nglobalhitcount = phraseinfo[3 * icol + 1];
405 			int ndocshitcount = phraseinfo[3 * icol + 2];
406 			doclen = matchinfo[2 + icol ];
407 			double weight = col_weights[icol - 1];
408 			if (idf->status == 0 && ndocshitcount)
409 				idf->value += log(((double)ndoc / ndocshitcount))* weight;
410 
411 			/* Dividing the tf by document length to normalize the effect of
412 			 * longer documents.
413 			 */
414 			if (nglobalhitcount > 0 && nhitcount)
415 				tf += (((double)nhitcount  * weight) / (nglobalhitcount * doclen));
416 		}
417 	}
418 	idf->status = 1;
419 
420 	/* Final score = (tf * idf)/ ( k + tf)
421 	 *	Dividing by k+ tf further normalizes the weight leading to better
422 	 *  results.
423 	 *  The value of k is experimental
424 	 */
425 	double score = (tf * idf->value/ ( k + tf)) ;
426 	sqlite3_result_double(pctx, score);
427 	return;
428 }
429 
430 /*
431  *  run_query --
432  *  Performs the searches for the keywords entered by the user.
433  *  The 2nd param: snippet_args is an array of strings providing values for the
434  *  last three parameters to the snippet function of sqlite. (Look at the docs).
435  *  The 3rd param: args contains rest of the search parameters. Look at
436  *  arpopos-utils.h for the description of individual fields.
437  *
438  */
439 int
440 run_query(sqlite3 *db, const char *snippet_args[3], query_args *args)
441 {
442 	const char *default_snippet_args[3];
443 	char *section_clause = NULL;
444 	char *limit_clause = NULL;
445 	char *machine_clause = NULL;
446 	char *query;
447 	const char *section;
448 	char *name;
449 	const char *name_desc;
450 	const char *machine;
451 	const char *snippet;
452 	char *m = NULL;
453 	int rc;
454 	inverse_document_frequency idf = {0, 0};
455 	sqlite3_stmt *stmt;
456 
457 	if (args->machine)
458 		easprintf(&machine_clause, "AND machine = \'%s\' ", args->machine);
459 
460 	/* Register the rank function */
461 	rc = sqlite3_create_function(db, "rank_func", 1, SQLITE_ANY, (void *)&idf,
462 	                             rank_func, NULL, NULL);
463 	if (rc != SQLITE_OK) {
464 		warnx("Unable to register the ranking function: %s",
465 		    sqlite3_errmsg(db));
466 		sqlite3_close(db);
467 		sqlite3_shutdown();
468 		exit(EXIT_FAILURE);
469 	}
470 
471 	/* We want to build a query of the form: "select x,y,z from mandb where
472 	 * mandb match :query [AND (section LIKE '1' OR section LIKE '2' OR...)]
473 	 * ORDER BY rank DESC..."
474 	 * NOTES: 1. The portion in square brackets is optional, it will be there
475 	 * only if the user has specified an option on the command line to search in
476 	 * one or more specific sections.
477 	 * 2. I am using LIKE operator because '=' or IN operators do not seem to be
478 	 * working with the compression option enabled.
479 	 */
480 
481 	if (args->sec_nums) {
482 		char *temp;
483 		int i;
484 
485 		for (i = 0; i < SECMAX; i++) {
486 			if (args->sec_nums[i] == 0)
487 				continue;
488 			easprintf(&temp, " OR section = \'%d\'", i + 1);
489 			if (section_clause) {
490 				concat(&section_clause, temp);
491 				free(temp);
492 			} else {
493 				section_clause = temp;
494 			}
495 		}
496 		if (section_clause) {
497 			/*
498 			 * At least one section requested, add glue for query.
499 			 */
500 			temp = section_clause;
501 			/* Skip " OR " before first term. */
502 			easprintf(&section_clause, " AND (%s)", temp + 4);
503 			free(temp);
504 		}
505 	}
506 	if (args->nrec >= 0) {
507 		/* Use the provided number of records and offset */
508 		easprintf(&limit_clause, " LIMIT %d OFFSET %d",
509 		    args->nrec, args->offset);
510 	}
511 
512 	if (snippet_args == NULL) {
513 		default_snippet_args[0] = "";
514 		default_snippet_args[1] = "";
515 		default_snippet_args[2] = "...";
516 		snippet_args = default_snippet_args;
517 	}
518 	query = sqlite3_mprintf("SELECT section, name, name_desc, machine,"
519 	    " snippet(mandb, %Q, %Q, %Q, -1, 40 ),"
520 	    " rank_func(matchinfo(mandb, \"pclxn\")) AS rank"
521 	    " FROM mandb"
522 	    " WHERE mandb MATCH %Q %s "
523 	    "%s"
524 	    " ORDER BY rank DESC"
525 	    "%s",
526 	    snippet_args[0], snippet_args[1], snippet_args[2], args->search_str,
527 	    machine_clause ? machine_clause : "",
528 	    section_clause ? section_clause : "",
529 	    limit_clause ? limit_clause : "");
530 
531 	free(machine_clause);
532 	free(section_clause);
533 	free(limit_clause);
534 
535 	if (query == NULL) {
536 		*args->errmsg = estrdup("malloc failed");
537 		return -1;
538 	}
539 	rc = sqlite3_prepare_v2(db, query, -1, &stmt, NULL);
540 	if (rc == SQLITE_IOERR) {
541 		warnx("Corrupt database. Please rerun makemandb");
542 		sqlite3_free(query);
543 		return -1;
544 	} else if (rc != SQLITE_OK) {
545 		warnx("%s", sqlite3_errmsg(db));
546 		sqlite3_free(query);
547 		return -1;
548 	}
549 
550 	while (sqlite3_step(stmt) == SQLITE_ROW) {
551 		section = (const char *) sqlite3_column_text(stmt, 0);
552 		name_desc = (const char *) sqlite3_column_text(stmt, 2);
553 		machine = (const char *) sqlite3_column_text(stmt, 3);
554 		snippet = (const char *) sqlite3_column_text(stmt, 4);
555 		if (machine && machine[0]) {
556 			m = estrdup(machine);
557 			easprintf(&name, "%s/%s", lower(m),
558 				sqlite3_column_text(stmt, 1));
559 			free(m);
560 		} else {
561 			name = estrdup((const char *) sqlite3_column_text(stmt, 1));
562 		}
563 
564 		(args->callback)(args->callback_data, section, name, name_desc, snippet,
565 			strlen(snippet));
566 
567 		free(name);
568 	}
569 
570 	sqlite3_finalize(stmt);
571 	sqlite3_free(query);
572 	return *(args->errmsg) == NULL ? 0 : -1;
573 }
574 
575 /*
576  * callback_html --
577  *  Callback function for run_query_html. It builds the html output and then
578  *  calls the actual user supplied callback function.
579  */
580 static int
581 callback_html(void *data, const char *section, const char *name,
582 	const char *name_desc, const char *snippet, size_t snippet_length)
583 {
584 	const char *temp = snippet;
585 	int i = 0;
586 	size_t sz = 0;
587 	int count = 0;
588 	struct orig_callback_data *orig_data = (struct orig_callback_data *) data;
589 	int (*callback) (void *, const char *, const char *, const char *,
590 		const char *, size_t) = orig_data->callback;
591 
592 	/* First scan the snippet to find out the number of occurrences of {'>', '<'
593 	 * '"', '&'}.
594 	 * Then allocate a new buffer with sufficient space to be able to store the
595 	 * quoted versions of the special characters {&gt;, &lt;, &quot;, &amp;}.
596 	 * Copy over the characters from the original snippet to this buffer while
597 	 * replacing the special characters with their quoted versions.
598 	 */
599 
600 	while (*temp) {
601 		sz = strcspn(temp, "<>\"&\002\003");
602 		temp += sz + 1;
603 		count++;
604 	}
605 	size_t qsnippet_length = snippet_length + count * 5;
606 	char *qsnippet = emalloc(qsnippet_length + 1);
607 	sz = 0;
608 	while (*snippet) {
609 		sz = strcspn(snippet, "<>\"&\002\003");
610 		if (sz) {
611 			memcpy(&qsnippet[i], snippet, sz);
612 			snippet += sz;
613 			i += sz;
614 		}
615 
616 		switch (*snippet++) {
617 		case '<':
618 			memcpy(&qsnippet[i], "&lt;", 4);
619 			i += 4;
620 			break;
621 		case '>':
622 			memcpy(&qsnippet[i], "&gt;", 4);
623 			i += 4;
624 			break;
625 		case '\"':
626 			memcpy(&qsnippet[i], "&quot;", 6);
627 			i += 6;
628 			break;
629 		case '&':
630 			/* Don't perform the quoting if this & is part of an mdoc escape
631 			 * sequence, e.g. \&
632 			 */
633 			if (i && *(snippet - 2) != '\\') {
634 				memcpy(&qsnippet[i], "&amp;", 5);
635 				i += 5;
636 			} else {
637 				qsnippet[i++] = '&';
638 			}
639 			break;
640 		case '\002':
641 			memcpy(&qsnippet[i], "<b>", 3);
642 			i += 3;
643 			break;
644 		case '\003':
645 			memcpy(&qsnippet[i], "</b>", 4);
646 			i += 4;
647 			break;
648 		default:
649 			break;
650 		}
651 	}
652 	qsnippet[++i] = 0;
653 	(*callback)(orig_data->data, section, name, name_desc,
654 		(const char *)qsnippet,	qsnippet_length);
655 	free(qsnippet);
656 	return 0;
657 }
658 
659 /*
660  * run_query_html --
661  *  Utility function to output query result in HTML format.
662  *  It internally calls run_query only, but it first passes the output to it's
663  *  own custom callback function, which preprocess the snippet for quoting
664  *  inline HTML fragments.
665  *  After that it delegates the call the actual user supplied callback function.
666  */
667 int
668 run_query_html(sqlite3 *db, query_args *args)
669 {
670 	struct orig_callback_data orig_data;
671 	orig_data.callback = args->callback;
672 	orig_data.data = args->callback_data;
673 	const char *snippet_args[] = {"\002", "\003", "..."};
674 	args->callback = &callback_html;
675 	args->callback_data = (void *) &orig_data;
676 	return run_query(db, snippet_args, args);
677 }
678 
679 /*
680  * callback_pager --
681  *  A callback similar to callback_html. It overstrikes the matching text in
682  *  the snippet so that it appears emboldened when viewed using a pager like
683  *  more or less.
684  */
685 static int
686 callback_pager(void *data, const char *section, const char *name,
687 	const char *name_desc, const char *snippet, size_t snippet_length)
688 {
689 	struct orig_callback_data *orig_data = (struct orig_callback_data *) data;
690 	char *psnippet;
691 	const char *temp = snippet;
692 	int count = 0;
693 	int i = 0;
694 	size_t sz = 0;
695 	size_t psnippet_length;
696 
697 	/* Count the number of bytes of matching text. For each of these bytes we
698 	 * will use 2 extra bytes to overstrike it so that it appears bold when
699 	 * viewed using a pager.
700 	 */
701 	while (*temp) {
702 		sz = strcspn(temp, "\002\003");
703 		temp += sz;
704 		if (*temp == '\003') {
705 			count += 2 * (sz);
706 		}
707 		temp++;
708 	}
709 
710 	psnippet_length = snippet_length + count;
711 	psnippet = emalloc(psnippet_length + 1);
712 
713 	/* Copy the bytes from snippet to psnippet:
714 	 * 1. Copy the bytes before \002 as it is.
715 	 * 2. The bytes after \002 need to be overstriked till we encounter \003.
716 	 * 3. To overstrike a byte 'A' we need to write 'A\bA'
717 	 */
718 	while (*snippet) {
719 		sz = strcspn(snippet, "\002");
720 		memcpy(&psnippet[i], snippet, sz);
721 		snippet += sz;
722 		i += sz;
723 
724 		/* Don't change this. Advancing the pointer without reading the byte
725 		 * is causing strange behavior.
726 		 */
727 		if (*snippet == '\002')
728 			snippet++;
729 		while (*snippet && *snippet != '\003') {
730 			psnippet[i++] = *snippet;
731 			psnippet[i++] = '\b';
732 			psnippet[i++] = *snippet++;
733 		}
734 		if (*snippet)
735 			snippet++;
736 	}
737 
738 	psnippet[i] = 0;
739 	(orig_data->callback)(orig_data->data, section, name, name_desc, psnippet,
740 		psnippet_length);
741 	free(psnippet);
742 	return 0;
743 }
744 
745 /*
746  * run_query_pager --
747  *  Utility function similar to run_query_html. This function tries to
748  *  pre-process the result assuming it will be piped to a pager.
749  *  For this purpose it first calls it's own callback function callback_pager
750  *  which then delegates the call to the user supplied callback.
751  */
752 int run_query_pager(sqlite3 *db, query_args *args)
753 {
754 	struct orig_callback_data orig_data;
755 	orig_data.callback = args->callback;
756 	orig_data.data = args->callback_data;
757 	const char *snippet_args[] = {"\002", "\003", "..."};
758 	args->callback = &callback_pager;
759 	args->callback_data = (void *) &orig_data;
760 	return run_query(db, snippet_args, args);
761 }
762