Home | History | Annotate | Line # | Download | only in makemandb
apropos-utils.c revision 1.2.2.1
      1 /*	$NetBSD: apropos-utils.c,v 1.2.2.1 2012/04/19 20:03:00 riz Exp $	*/
      2 /*-
      3  * Copyright (c) 2011 Abhinav Upadhyay <er.abhinav.upadhyay (at) 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.2.2.1 2012/04/19 20:03:00 riz 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 	const char *name_temp;
    453 	char *slash_ptr;
    454 	char *m = NULL;
    455 	int rc;
    456 	inverse_document_frequency idf = {0, 0};
    457 	sqlite3_stmt *stmt;
    458 
    459 	if (args->machine)
    460 		easprintf(&machine_clause, "AND machine = \'%s\' ", args->machine);
    461 
    462 	/* Register the rank function */
    463 	rc = sqlite3_create_function(db, "rank_func", 1, SQLITE_ANY, (void *)&idf,
    464 	                             rank_func, NULL, NULL);
    465 	if (rc != SQLITE_OK) {
    466 		warnx("Unable to register the ranking function: %s",
    467 		    sqlite3_errmsg(db));
    468 		sqlite3_close(db);
    469 		sqlite3_shutdown();
    470 		exit(EXIT_FAILURE);
    471 	}
    472 
    473 	/* We want to build a query of the form: "select x,y,z from mandb where
    474 	 * mandb match :query [AND (section LIKE '1' OR section LIKE '2' OR...)]
    475 	 * ORDER BY rank DESC..."
    476 	 * NOTES: 1. The portion in square brackets is optional, it will be there
    477 	 * only if the user has specified an option on the command line to search in
    478 	 * one or more specific sections.
    479 	 * 2. I am using LIKE operator because '=' or IN operators do not seem to be
    480 	 * working with the compression option enabled.
    481 	 */
    482 
    483 	if (args->sec_nums) {
    484 		char *temp;
    485 		int i;
    486 
    487 		for (i = 0; i < SECMAX; i++) {
    488 			if (args->sec_nums[i] == 0)
    489 				continue;
    490 			easprintf(&temp, " OR section = \'%d\'", i + 1);
    491 			if (section_clause) {
    492 				concat(&section_clause, temp);
    493 				free(temp);
    494 			} else {
    495 				section_clause = temp;
    496 			}
    497 		}
    498 		if (section_clause) {
    499 			/*
    500 			 * At least one section requested, add glue for query.
    501 			 */
    502 			temp = section_clause;
    503 			/* Skip " OR " before first term. */
    504 			easprintf(&section_clause, " AND (%s)", temp + 4);
    505 			free(temp);
    506 		}
    507 	}
    508 	if (args->nrec >= 0) {
    509 		/* Use the provided number of records and offset */
    510 		easprintf(&limit_clause, " LIMIT %d OFFSET %d",
    511 		    args->nrec, args->offset);
    512 	}
    513 
    514 	if (snippet_args == NULL) {
    515 		default_snippet_args[0] = "";
    516 		default_snippet_args[1] = "";
    517 		default_snippet_args[2] = "...";
    518 		snippet_args = default_snippet_args;
    519 	}
    520 	query = sqlite3_mprintf("SELECT section, name, name_desc, machine,"
    521 	    " snippet(mandb, %Q, %Q, %Q, -1, 40 ),"
    522 	    " rank_func(matchinfo(mandb, \"pclxn\")) AS rank"
    523 	    " FROM mandb"
    524 	    " WHERE mandb MATCH %Q %s "
    525 	    "%s"
    526 	    " ORDER BY rank DESC"
    527 	    "%s",
    528 	    snippet_args[0], snippet_args[1], snippet_args[2], args->search_str,
    529 	    machine_clause ? machine_clause : "",
    530 	    section_clause ? section_clause : "",
    531 	    limit_clause ? limit_clause : "");
    532 
    533 	free(machine_clause);
    534 	free(section_clause);
    535 	free(limit_clause);
    536 
    537 	if (query == NULL) {
    538 		*args->errmsg = estrdup("malloc failed");
    539 		return -1;
    540 	}
    541 	rc = sqlite3_prepare_v2(db, query, -1, &stmt, NULL);
    542 	if (rc == SQLITE_IOERR) {
    543 		warnx("Corrupt database. Please rerun makemandb");
    544 		sqlite3_free(query);
    545 		return -1;
    546 	} else if (rc != SQLITE_OK) {
    547 		warnx("%s", sqlite3_errmsg(db));
    548 		sqlite3_free(query);
    549 		return -1;
    550 	}
    551 
    552 	while (sqlite3_step(stmt) == SQLITE_ROW) {
    553 		section = (const char *) sqlite3_column_text(stmt, 0);
    554 		name_temp = (const char *) sqlite3_column_text(stmt, 1);
    555 		name_desc = (const char *) sqlite3_column_text(stmt, 2);
    556 		machine = (const char *) sqlite3_column_text(stmt, 3);
    557 		snippet = (const char *) sqlite3_column_text(stmt, 4);
    558 		if ((slash_ptr = strrchr(name_temp, '/')) != NULL)
    559 			name_temp = slash_ptr + 1;
    560 		if (machine && machine[0]) {
    561 			m = estrdup(machine);
    562 			easprintf(&name, "%s/%s", lower(m),
    563 				name_temp);
    564 			free(m);
    565 		} else {
    566 			name = estrdup((const char *) sqlite3_column_text(stmt, 1));
    567 		}
    568 
    569 		(args->callback)(args->callback_data, section, name, name_desc, snippet,
    570 			strlen(snippet));
    571 
    572 		free(name);
    573 	}
    574 
    575 	sqlite3_finalize(stmt);
    576 	sqlite3_free(query);
    577 	return *(args->errmsg) == NULL ? 0 : -1;
    578 }
    579 
    580 /*
    581  * callback_html --
    582  *  Callback function for run_query_html. It builds the html output and then
    583  *  calls the actual user supplied callback function.
    584  */
    585 static int
    586 callback_html(void *data, const char *section, const char *name,
    587 	const char *name_desc, const char *snippet, size_t snippet_length)
    588 {
    589 	const char *temp = snippet;
    590 	int i = 0;
    591 	size_t sz = 0;
    592 	int count = 0;
    593 	struct orig_callback_data *orig_data = (struct orig_callback_data *) data;
    594 	int (*callback) (void *, const char *, const char *, const char *,
    595 		const char *, size_t) = orig_data->callback;
    596 
    597 	/* First scan the snippet to find out the number of occurrences of {'>', '<'
    598 	 * '"', '&'}.
    599 	 * Then allocate a new buffer with sufficient space to be able to store the
    600 	 * quoted versions of the special characters {&gt;, &lt;, &quot;, &amp;}.
    601 	 * Copy over the characters from the original snippet to this buffer while
    602 	 * replacing the special characters with their quoted versions.
    603 	 */
    604 
    605 	while (*temp) {
    606 		sz = strcspn(temp, "<>\"&\002\003");
    607 		temp += sz + 1;
    608 		count++;
    609 	}
    610 	size_t qsnippet_length = snippet_length + count * 5;
    611 	char *qsnippet = emalloc(qsnippet_length + 1);
    612 	sz = 0;
    613 	while (*snippet) {
    614 		sz = strcspn(snippet, "<>\"&\002\003");
    615 		if (sz) {
    616 			memcpy(&qsnippet[i], snippet, sz);
    617 			snippet += sz;
    618 			i += sz;
    619 		}
    620 
    621 		switch (*snippet++) {
    622 		case '<':
    623 			memcpy(&qsnippet[i], "&lt;", 4);
    624 			i += 4;
    625 			break;
    626 		case '>':
    627 			memcpy(&qsnippet[i], "&gt;", 4);
    628 			i += 4;
    629 			break;
    630 		case '\"':
    631 			memcpy(&qsnippet[i], "&quot;", 6);
    632 			i += 6;
    633 			break;
    634 		case '&':
    635 			/* Don't perform the quoting if this & is part of an mdoc escape
    636 			 * sequence, e.g. \&
    637 			 */
    638 			if (i && *(snippet - 2) != '\\') {
    639 				memcpy(&qsnippet[i], "&amp;", 5);
    640 				i += 5;
    641 			} else {
    642 				qsnippet[i++] = '&';
    643 			}
    644 			break;
    645 		case '\002':
    646 			memcpy(&qsnippet[i], "<b>", 3);
    647 			i += 3;
    648 			break;
    649 		case '\003':
    650 			memcpy(&qsnippet[i], "</b>", 4);
    651 			i += 4;
    652 			break;
    653 		default:
    654 			break;
    655 		}
    656 	}
    657 	qsnippet[++i] = 0;
    658 	(*callback)(orig_data->data, section, name, name_desc,
    659 		(const char *)qsnippet,	qsnippet_length);
    660 	free(qsnippet);
    661 	return 0;
    662 }
    663 
    664 /*
    665  * run_query_html --
    666  *  Utility function to output query result in HTML format.
    667  *  It internally calls run_query only, but it first passes the output to it's
    668  *  own custom callback function, which preprocess the snippet for quoting
    669  *  inline HTML fragments.
    670  *  After that it delegates the call the actual user supplied callback function.
    671  */
    672 int
    673 run_query_html(sqlite3 *db, query_args *args)
    674 {
    675 	struct orig_callback_data orig_data;
    676 	orig_data.callback = args->callback;
    677 	orig_data.data = args->callback_data;
    678 	const char *snippet_args[] = {"\002", "\003", "..."};
    679 	args->callback = &callback_html;
    680 	args->callback_data = (void *) &orig_data;
    681 	return run_query(db, snippet_args, args);
    682 }
    683 
    684 /*
    685  * callback_pager --
    686  *  A callback similar to callback_html. It overstrikes the matching text in
    687  *  the snippet so that it appears emboldened when viewed using a pager like
    688  *  more or less.
    689  */
    690 static int
    691 callback_pager(void *data, const char *section, const char *name,
    692 	const char *name_desc, const char *snippet, size_t snippet_length)
    693 {
    694 	struct orig_callback_data *orig_data = (struct orig_callback_data *) data;
    695 	char *psnippet;
    696 	const char *temp = snippet;
    697 	int count = 0;
    698 	int i = 0;
    699 	size_t sz = 0;
    700 	size_t psnippet_length;
    701 
    702 	/* Count the number of bytes of matching text. For each of these bytes we
    703 	 * will use 2 extra bytes to overstrike it so that it appears bold when
    704 	 * viewed using a pager.
    705 	 */
    706 	while (*temp) {
    707 		sz = strcspn(temp, "\002\003");
    708 		temp += sz;
    709 		if (*temp == '\003') {
    710 			count += 2 * (sz);
    711 		}
    712 		temp++;
    713 	}
    714 
    715 	psnippet_length = snippet_length + count;
    716 	psnippet = emalloc(psnippet_length + 1);
    717 
    718 	/* Copy the bytes from snippet to psnippet:
    719 	 * 1. Copy the bytes before \002 as it is.
    720 	 * 2. The bytes after \002 need to be overstriked till we encounter \003.
    721 	 * 3. To overstrike a byte 'A' we need to write 'A\bA'
    722 	 */
    723 	while (*snippet) {
    724 		sz = strcspn(snippet, "\002");
    725 		memcpy(&psnippet[i], snippet, sz);
    726 		snippet += sz;
    727 		i += sz;
    728 
    729 		/* Don't change this. Advancing the pointer without reading the byte
    730 		 * is causing strange behavior.
    731 		 */
    732 		if (*snippet == '\002')
    733 			snippet++;
    734 		while (*snippet && *snippet != '\003') {
    735 			psnippet[i++] = *snippet;
    736 			psnippet[i++] = '\b';
    737 			psnippet[i++] = *snippet++;
    738 		}
    739 		if (*snippet)
    740 			snippet++;
    741 	}
    742 
    743 	psnippet[i] = 0;
    744 	(orig_data->callback)(orig_data->data, section, name, name_desc, psnippet,
    745 		psnippet_length);
    746 	free(psnippet);
    747 	return 0;
    748 }
    749 
    750 /*
    751  * run_query_pager --
    752  *  Utility function similar to run_query_html. This function tries to
    753  *  pre-process the result assuming it will be piped to a pager.
    754  *  For this purpose it first calls it's own callback function callback_pager
    755  *  which then delegates the call to the user supplied callback.
    756  */
    757 int run_query_pager(sqlite3 *db, query_args *args)
    758 {
    759 	struct orig_callback_data orig_data;
    760 	orig_data.callback = args->callback;
    761 	orig_data.data = args->callback_data;
    762 	const char *snippet_args[] = {"\002", "\003", "..."};
    763 	args->callback = &callback_pager;
    764 	args->callback_data = (void *) &orig_data;
    765 	return run_query(db, snippet_args, args);
    766 }
    767