Home | History | Annotate | Line # | Download | only in makemandb
apropos-utils.c revision 1.12
      1 /*	$NetBSD: apropos-utils.c,v 1.12 2013/03/29 20:07:31 christos 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.12 2013/03/29 20:07:31 christos Exp $");
     35 
     36 #include <sys/queue.h>
     37 #include <sys/stat.h>
     38 
     39 #include <assert.h>
     40 #include <ctype.h>
     41 #include <err.h>
     42 #include <math.h>
     43 #include <stdio.h>
     44 #include <stdlib.h>
     45 #include <string.h>
     46 #include <util.h>
     47 #include <zlib.h>
     48 #include <term.h>
     49 #undef tab	// XXX: manconf.h
     50 
     51 #include "apropos-utils.h"
     52 #include "manconf.h"
     53 #include "dist/mandoc.h"
     54 #include "sqlite3.h"
     55 
     56 typedef struct orig_callback_data {
     57 	void *data;
     58 	int (*callback) (void *, const char *, const char *, const char *,
     59 		const char *, size_t);
     60 } orig_callback_data;
     61 
     62 typedef struct inverse_document_frequency {
     63 	double value;
     64 	int status;
     65 } inverse_document_frequency;
     66 
     67 /* weights for individual columns */
     68 static const double col_weights[] = {
     69 	2.0,	// NAME
     70 	2.00,	// Name-description
     71 	0.55,	// DESCRIPTION
     72 	0.10,	// LIBRARY
     73 	0.001,	//RETURN VALUES
     74 	0.20,	//ENVIRONMENT
     75 	0.01,	//FILES
     76 	0.001,	//EXIT STATUS
     77 	2.00,	//DIAGNOSTICS
     78 	0.05,	//ERRORS
     79 	0.00,	//md5_hash
     80 	1.00	//machine
     81 };
     82 
     83 /*
     84  * lower --
     85  *  Converts the string str to lower case
     86  */
     87 char *
     88 lower(char *str)
     89 {
     90 	assert(str);
     91 	int i = 0;
     92 	char c;
     93 	while (str[i] != '\0') {
     94 		c = tolower((unsigned char) str[i]);
     95 		str[i++] = c;
     96 	}
     97 	return str;
     98 }
     99 
    100 /*
    101 * concat--
    102 *  Utility function. Concatenates together: dst, a space character and src.
    103 * dst + " " + src
    104 */
    105 void
    106 concat(char **dst, const char *src)
    107 {
    108 	concat2(dst, src, strlen(src));
    109 }
    110 
    111 void
    112 concat2(char **dst, const char *src, size_t srclen)
    113 {
    114 	size_t total_len, dst_len;
    115 	assert(src != NULL);
    116 
    117 	/* If destination buffer dst is NULL, then simply strdup the source buffer */
    118 	if (*dst == NULL) {
    119 		*dst = estrdup(src);
    120 		return;
    121 	}
    122 
    123 	dst_len = strlen(*dst);
    124 	/*
    125 	 * NUL Byte and separator space
    126 	 */
    127 	total_len = dst_len + srclen + 2;
    128 
    129 	*dst = erealloc(*dst, total_len);
    130 
    131 	/* Append a space at the end of dst */
    132 	(*dst)[dst_len++] = ' ';
    133 
    134 	/* Now, copy src at the end of dst */
    135 	memcpy(*dst + dst_len, src, srclen + 1);
    136 }
    137 
    138 void
    139 close_db(sqlite3 *db)
    140 {
    141 	sqlite3_close(db);
    142 	sqlite3_shutdown();
    143 }
    144 
    145 /*
    146  * create_db --
    147  *  Creates the database schema.
    148  */
    149 static int
    150 create_db(sqlite3 *db)
    151 {
    152 	const char *sqlstr = NULL;
    153 	char *schemasql;
    154 	char *errmsg = NULL;
    155 
    156 /*------------------------ Create the tables------------------------------*/
    157 
    158 #if NOTYET
    159 	sqlite3_exec(db, "PRAGMA journal_mode = WAL", NULL, NULL, NULL);
    160 #else
    161 	sqlite3_exec(db, "PRAGMA journal_mode = DELETE", NULL, NULL, NULL);
    162 #endif
    163 
    164 	schemasql = sqlite3_mprintf("PRAGMA user_version = %d",
    165 	    APROPOS_SCHEMA_VERSION);
    166 	sqlite3_exec(db, schemasql, NULL, NULL, &errmsg);
    167 	if (errmsg != NULL)
    168 		goto out;
    169 	sqlite3_free(schemasql);
    170 
    171 	sqlstr = "CREATE VIRTUAL TABLE mandb USING fts4(section, name, "
    172 			    "name_desc, desc, lib, return_vals, env, files, "
    173 			    "exit_status, diagnostics, errors, md5_hash UNIQUE, machine, "
    174 			    "compress=zip, uncompress=unzip, tokenize=porter); "	//mandb
    175 			"CREATE TABLE IF NOT EXISTS mandb_meta(device, inode, mtime, "
    176 			    "file UNIQUE, md5_hash UNIQUE, id  INTEGER PRIMARY KEY); "
    177 				//mandb_meta
    178 			"CREATE TABLE IF NOT EXISTS mandb_links(link, target, section, "
    179 			    "machine, md5_hash); ";	//mandb_links
    180 
    181 	sqlite3_exec(db, sqlstr, NULL, NULL, &errmsg);
    182 	if (errmsg != NULL)
    183 		goto out;
    184 
    185 	sqlstr = "CREATE INDEX IF NOT EXISTS index_mandb_links ON mandb_links "
    186 			"(link); "
    187 			"CREATE INDEX IF NOT EXISTS index_mandb_meta_dev ON mandb_meta "
    188 			"(device, inode); "
    189 			"CREATE INDEX IF NOT EXISTS index_mandb_links_md5 ON mandb_links "
    190 			"(md5_hash);";
    191 	sqlite3_exec(db, sqlstr, NULL, NULL, &errmsg);
    192 	if (errmsg != NULL)
    193 		goto out;
    194 	return 0;
    195 
    196 out:
    197 	warnx("%s", errmsg);
    198 	free(errmsg);
    199 	sqlite3_close(db);
    200 	sqlite3_shutdown();
    201 	return -1;
    202 }
    203 
    204 /*
    205  * zip --
    206  *  User defined Sqlite function to compress the FTS table
    207  */
    208 static void
    209 zip(sqlite3_context *pctx, int nval, sqlite3_value **apval)
    210 {
    211 	int nin;
    212 	long int nout;
    213 	const unsigned char * inbuf;
    214 	unsigned char *outbuf;
    215 
    216 	assert(nval == 1);
    217 	nin = sqlite3_value_bytes(apval[0]);
    218 	inbuf = (const unsigned char *) sqlite3_value_blob(apval[0]);
    219 	nout = nin + 13 + (nin + 999) / 1000;
    220 	outbuf = emalloc(nout);
    221 	compress(outbuf, (unsigned long *) &nout, inbuf, nin);
    222 	sqlite3_result_blob(pctx, outbuf, nout, free);
    223 }
    224 
    225 /*
    226  * unzip --
    227  *  User defined Sqlite function to uncompress the FTS table.
    228  */
    229 static void
    230 unzip(sqlite3_context *pctx, int nval, sqlite3_value **apval)
    231 {
    232 	unsigned int rc;
    233 	unsigned char *outbuf;
    234 	z_stream stream;
    235 
    236 	assert(nval == 1);
    237 	stream.next_in = __UNCONST(sqlite3_value_blob(apval[0]));
    238 	stream.avail_in = sqlite3_value_bytes(apval[0]);
    239 	stream.avail_out = stream.avail_in * 2 + 100;
    240 	stream.next_out = outbuf = emalloc(stream.avail_out);
    241 	stream.zalloc = NULL;
    242 	stream.zfree = NULL;
    243 
    244 	if (inflateInit(&stream) != Z_OK) {
    245 		free(outbuf);
    246 		return;
    247 	}
    248 
    249 	while ((rc = inflate(&stream, Z_SYNC_FLUSH)) != Z_STREAM_END) {
    250 		if (rc != Z_OK ||
    251 		    (stream.avail_out != 0 && stream.avail_in == 0)) {
    252 			free(outbuf);
    253 			return;
    254 		}
    255 		outbuf = erealloc(outbuf, stream.total_out * 2);
    256 		stream.next_out = outbuf + stream.total_out;
    257 		stream.avail_out = stream.total_out;
    258 	}
    259 	if (inflateEnd(&stream) != Z_OK) {
    260 		free(outbuf);
    261 		return;
    262 	}
    263 	outbuf = erealloc(outbuf, stream.total_out);
    264 	sqlite3_result_text(pctx, (const char *) outbuf, stream.total_out, free);
    265 }
    266 
    267 /*
    268  * get_dbpath --
    269  *   Read the path of the database from man.conf and return.
    270  */
    271 char *
    272 get_dbpath(const char *manconf)
    273 {
    274 	TAG *tp;
    275 	char *dbpath;
    276 
    277 	config(manconf);
    278 	tp = gettag("_mandb", 1);
    279 	if (!tp)
    280 		return NULL;
    281 
    282 	if (TAILQ_EMPTY(&tp->entrylist))
    283 		return NULL;
    284 
    285 	dbpath = TAILQ_LAST(&tp->entrylist, tqh)->s;
    286 	return dbpath;
    287 }
    288 
    289 /* init_db --
    290  *   Prepare the database. Register the compress/uncompress functions and the
    291  *   stopword tokenizer.
    292  *	 db_flag specifies the mode in which to open the database. 3 options are
    293  *   available:
    294  *   	1. DB_READONLY: Open in READONLY mode. An error if db does not exist.
    295  *  	2. DB_READWRITE: Open in read-write mode. An error if db does not exist.
    296  *  	3. DB_CREATE: Open in read-write mode. It will try to create the db if
    297  *			it does not exist already.
    298  *  RETURN VALUES:
    299  *		The function will return NULL in case the db does not exist and DB_CREATE
    300  *  	was not specified. And in case DB_CREATE was specified and yet NULL is
    301  *  	returned, then there was some other error.
    302  *  	In normal cases the function should return a handle to the db.
    303  */
    304 sqlite3 *
    305 init_db(int db_flag, const char *manconf)
    306 {
    307 	sqlite3 *db = NULL;
    308 	sqlite3_stmt *stmt;
    309 	struct stat sb;
    310 	int rc;
    311 	int create_db_flag = 0;
    312 
    313 	char *dbpath = get_dbpath(manconf);
    314 	if (dbpath == NULL)
    315 		errx(EXIT_FAILURE, "_mandb entry not found in man.conf");
    316 	/* Check if the database exists or not */
    317 	if (!(stat(dbpath, &sb) == 0 && S_ISREG(sb.st_mode))) {
    318 		/* Database does not exist, check if DB_CREATE was specified, and set
    319 		 * flag to create the database schema
    320 		 */
    321 		if (db_flag != (MANDB_CREATE)) {
    322 			warnx("Missing apropos database. "
    323 			      "Please run makemandb to create it.");
    324 			return NULL;
    325 		}
    326 		create_db_flag = 1;
    327 	}
    328 
    329 	/* Now initialize the database connection */
    330 	sqlite3_initialize();
    331 	rc = sqlite3_open_v2(dbpath, &db, db_flag, NULL);
    332 
    333 	if (rc != SQLITE_OK) {
    334 		warnx("%s", sqlite3_errmsg(db));
    335 		sqlite3_shutdown();
    336 		return NULL;
    337 	}
    338 
    339 	if (create_db_flag && create_db(db) < 0) {
    340 		warnx("%s", "Unable to create database schema");
    341 		goto error;
    342 	}
    343 
    344 	rc = sqlite3_prepare_v2(db, "PRAGMA user_version", -1, &stmt, NULL);
    345 	if (rc != SQLITE_OK) {
    346 		warnx("Unable to query schema version: %s",
    347 		    sqlite3_errmsg(db));
    348 		goto error;
    349 	}
    350 	if (sqlite3_step(stmt) != SQLITE_ROW) {
    351 		sqlite3_finalize(stmt);
    352 		warnx("Unable to query schema version: %s",
    353 		    sqlite3_errmsg(db));
    354 		goto error;
    355 	}
    356 	if (sqlite3_column_int(stmt, 0) != APROPOS_SCHEMA_VERSION) {
    357 		sqlite3_finalize(stmt);
    358 		warnx("Incorrect schema version found. "
    359 		      "Please run makemandb -f.");
    360 		goto error;
    361 	}
    362 	sqlite3_finalize(stmt);
    363 
    364 	sqlite3_extended_result_codes(db, 1);
    365 
    366 	/* Register the zip and unzip functions for FTS compression */
    367 	rc = sqlite3_create_function(db, "zip", 1, SQLITE_ANY, NULL, zip, NULL, NULL);
    368 	if (rc != SQLITE_OK) {
    369 		warnx("Unable to register function: compress: %s",
    370 		    sqlite3_errmsg(db));
    371 		goto error;
    372 	}
    373 
    374 	rc = sqlite3_create_function(db, "unzip", 1, SQLITE_ANY, NULL,
    375                                  unzip, NULL, NULL);
    376 	if (rc != SQLITE_OK) {
    377 		warnx("Unable to register function: uncompress: %s",
    378 		    sqlite3_errmsg(db));
    379 		goto error;
    380 	}
    381 	return db;
    382 
    383 error:
    384 	sqlite3_close(db);
    385 	sqlite3_shutdown();
    386 	return NULL;
    387 }
    388 
    389 /*
    390  * rank_func --
    391  *  Sqlite user defined function for ranking the documents.
    392  *  For each phrase of the query, it computes the tf and idf and adds them over.
    393  *  It computes the final rank, by multiplying tf and idf together.
    394  *  Weight of term t for document d = (term frequency of t in d *
    395  *                                      inverse document frequency of t)
    396  *
    397  *  Term Frequency of term t in document d = Number of times t occurs in d /
    398  *	                                        Number of times t appears in all
    399  *											documents
    400  *
    401  *  Inverse document frequency of t = log(Total number of documents /
    402  *										Number of documents in which t occurs)
    403  */
    404 static void
    405 rank_func(sqlite3_context *pctx, int nval, sqlite3_value **apval)
    406 {
    407 	inverse_document_frequency *idf = sqlite3_user_data(pctx);
    408 	double tf = 0.0;
    409 	const unsigned int *matchinfo;
    410 	int ncol;
    411 	int nphrase;
    412 	int iphrase;
    413 	int ndoc;
    414 	int doclen = 0;
    415 	const double k = 3.75;
    416 	/* Check that the number of arguments passed to this function is correct. */
    417 	assert(nval == 1);
    418 
    419 	matchinfo = (const unsigned int *) sqlite3_value_blob(apval[0]);
    420 	nphrase = matchinfo[0];
    421 	ncol = matchinfo[1];
    422 	ndoc = matchinfo[2 + 3 * ncol * nphrase + ncol];
    423 	for (iphrase = 0; iphrase < nphrase; iphrase++) {
    424 		int icol;
    425 		const unsigned int *phraseinfo = &matchinfo[2 + ncol+ iphrase * ncol * 3];
    426 		for(icol = 1; icol < ncol; icol++) {
    427 
    428 			/* nhitcount: number of times the current phrase occurs in the current
    429 			 *            column in the current document.
    430 			 * nglobalhitcount: number of times current phrase occurs in the current
    431 			 *                  column in all documents.
    432 			 * ndocshitcount:   number of documents in which the current phrase
    433 			 *                  occurs in the current column at least once.
    434 			 */
    435   			int nhitcount = phraseinfo[3 * icol];
    436 			int nglobalhitcount = phraseinfo[3 * icol + 1];
    437 			int ndocshitcount = phraseinfo[3 * icol + 2];
    438 			doclen = matchinfo[2 + icol ];
    439 			double weight = col_weights[icol - 1];
    440 			if (idf->status == 0 && ndocshitcount)
    441 				idf->value += log(((double)ndoc / ndocshitcount))* weight;
    442 
    443 			/* Dividing the tf by document length to normalize the effect of
    444 			 * longer documents.
    445 			 */
    446 			if (nglobalhitcount > 0 && nhitcount)
    447 				tf += (((double)nhitcount  * weight) / (nglobalhitcount * doclen));
    448 		}
    449 	}
    450 	idf->status = 1;
    451 
    452 	/* Final score = (tf * idf)/ ( k + tf)
    453 	 *	Dividing by k+ tf further normalizes the weight leading to better
    454 	 *  results.
    455 	 *  The value of k is experimental
    456 	 */
    457 	double score = (tf * idf->value/ ( k + tf)) ;
    458 	sqlite3_result_double(pctx, score);
    459 	return;
    460 }
    461 
    462 /*
    463  *  run_query --
    464  *  Performs the searches for the keywords entered by the user.
    465  *  The 2nd param: snippet_args is an array of strings providing values for the
    466  *  last three parameters to the snippet function of sqlite. (Look at the docs).
    467  *  The 3rd param: args contains rest of the search parameters. Look at
    468  *  arpopos-utils.h for the description of individual fields.
    469  *
    470  */
    471 int
    472 run_query(sqlite3 *db, const char *snippet_args[3], query_args *args)
    473 {
    474 	const char *default_snippet_args[3];
    475 	char *section_clause = NULL;
    476 	char *limit_clause = NULL;
    477 	char *machine_clause = NULL;
    478 	char *query;
    479 	const char *section;
    480 	char *name;
    481 	const char *name_desc;
    482 	const char *machine;
    483 	const char *snippet;
    484 	const char *name_temp;
    485 	char *slash_ptr;
    486 	char *m = NULL;
    487 	int rc;
    488 	inverse_document_frequency idf = {0, 0};
    489 	sqlite3_stmt *stmt;
    490 
    491 	if (args->machine)
    492 		easprintf(&machine_clause, "AND machine = \'%s\' ", args->machine);
    493 
    494 	/* Register the rank function */
    495 	rc = sqlite3_create_function(db, "rank_func", 1, SQLITE_ANY, (void *)&idf,
    496 	                             rank_func, NULL, NULL);
    497 	if (rc != SQLITE_OK) {
    498 		warnx("Unable to register the ranking function: %s",
    499 		    sqlite3_errmsg(db));
    500 		sqlite3_close(db);
    501 		sqlite3_shutdown();
    502 		exit(EXIT_FAILURE);
    503 	}
    504 
    505 	/* We want to build a query of the form: "select x,y,z from mandb where
    506 	 * mandb match :query [AND (section LIKE '1' OR section LIKE '2' OR...)]
    507 	 * ORDER BY rank DESC..."
    508 	 * NOTES: 1. The portion in square brackets is optional, it will be there
    509 	 * only if the user has specified an option on the command line to search in
    510 	 * one or more specific sections.
    511 	 * 2. I am using LIKE operator because '=' or IN operators do not seem to be
    512 	 * working with the compression option enabled.
    513 	 */
    514 
    515 	if (args->sec_nums) {
    516 		char *temp;
    517 		int i;
    518 
    519 		for (i = 0; i < SECMAX; i++) {
    520 			if (args->sec_nums[i] == 0)
    521 				continue;
    522 			easprintf(&temp, " OR section = \'%d\'", i + 1);
    523 			if (section_clause) {
    524 				concat(&section_clause, temp);
    525 				free(temp);
    526 			} else {
    527 				section_clause = temp;
    528 			}
    529 		}
    530 		if (section_clause) {
    531 			/*
    532 			 * At least one section requested, add glue for query.
    533 			 */
    534 			temp = section_clause;
    535 			/* Skip " OR " before first term. */
    536 			easprintf(&section_clause, " AND (%s)", temp + 4);
    537 			free(temp);
    538 		}
    539 	}
    540 	if (args->nrec >= 0) {
    541 		/* Use the provided number of records and offset */
    542 		easprintf(&limit_clause, " LIMIT %d OFFSET %d",
    543 		    args->nrec, args->offset);
    544 	}
    545 
    546 	if (snippet_args == NULL) {
    547 		default_snippet_args[0] = "";
    548 		default_snippet_args[1] = "";
    549 		default_snippet_args[2] = "...";
    550 		snippet_args = default_snippet_args;
    551 	}
    552 	if (args->legacy) {
    553 	    query = sqlite3_mprintf("SELECT section, name, name_desc, machine,"
    554 		" snippet(mandb, %Q, %Q, %Q, -1, 40 ),"
    555 		" rank_func(matchinfo(mandb, \"pclxn\")) AS rank"
    556 		" FROM mandb"
    557 		" WHERE name MATCH %Q "
    558 		"%s"
    559 		" UNION SELECT section, name, name_desc, machine,"
    560 		" snippet(mandb, %Q, %Q, %Q, -1, 40 ),"
    561 		" rank_func(matchinfo(mandb, \"pclxn\")) AS rank"
    562 		" FROM mandb"
    563 		" WHERE name_desc MATCH %Q "
    564 		"%s"
    565 		" ORDER BY rank DESC"
    566 		"%s",
    567 		snippet_args[0], snippet_args[1], snippet_args[2],
    568 		args->search_str,
    569 		section_clause ? section_clause : "",
    570 		snippet_args[0], snippet_args[1], snippet_args[2],
    571 		args->search_str,
    572 		section_clause ? section_clause : "",
    573 		limit_clause ? limit_clause : "");
    574 	} else {
    575 	    query = sqlite3_mprintf("SELECT section, name, name_desc, machine,"
    576 		" snippet(mandb, %Q, %Q, %Q, -1, 40 ),"
    577 		" rank_func(matchinfo(mandb, \"pclxn\")) AS rank"
    578 		" FROM mandb"
    579 		" WHERE mandb MATCH %Q %s "
    580 		"%s"
    581 		" ORDER BY rank DESC"
    582 		"%s",
    583 		snippet_args[0], snippet_args[1], snippet_args[2],
    584 		args->search_str, machine_clause ? machine_clause : "",
    585 		section_clause ? section_clause : "",
    586 		limit_clause ? limit_clause : "");
    587 	}
    588 
    589 	free(machine_clause);
    590 	free(section_clause);
    591 	free(limit_clause);
    592 
    593 	if (query == NULL) {
    594 		*args->errmsg = estrdup("malloc failed");
    595 		return -1;
    596 	}
    597 	rc = sqlite3_prepare_v2(db, query, -1, &stmt, NULL);
    598 	if (rc == SQLITE_IOERR) {
    599 		warnx("Corrupt database. Please rerun makemandb");
    600 		sqlite3_free(query);
    601 		return -1;
    602 	} else if (rc != SQLITE_OK) {
    603 		warnx("%s", sqlite3_errmsg(db));
    604 		sqlite3_free(query);
    605 		return -1;
    606 	}
    607 
    608 	while (sqlite3_step(stmt) == SQLITE_ROW) {
    609 		section = (const char *) sqlite3_column_text(stmt, 0);
    610 		name_temp = (const char *) sqlite3_column_text(stmt, 1);
    611 		name_desc = (const char *) sqlite3_column_text(stmt, 2);
    612 		machine = (const char *) sqlite3_column_text(stmt, 3);
    613 		snippet = (const char *) sqlite3_column_text(stmt, 4);
    614 		if ((slash_ptr = strrchr(name_temp, '/')) != NULL)
    615 			name_temp = slash_ptr + 1;
    616 		if (machine && machine[0]) {
    617 			m = estrdup(machine);
    618 			easprintf(&name, "%s/%s", lower(m),
    619 				name_temp);
    620 			free(m);
    621 		} else {
    622 			name = estrdup((const char *) sqlite3_column_text(stmt, 1));
    623 		}
    624 
    625 		(args->callback)(args->callback_data, section, name, name_desc, snippet,
    626 			strlen(snippet));
    627 
    628 		free(name);
    629 	}
    630 
    631 	sqlite3_finalize(stmt);
    632 	sqlite3_free(query);
    633 	return *(args->errmsg) == NULL ? 0 : -1;
    634 }
    635 
    636 /*
    637  * callback_html --
    638  *  Callback function for run_query_html. It builds the html output and then
    639  *  calls the actual user supplied callback function.
    640  */
    641 static int
    642 callback_html(void *data, const char *section, const char *name,
    643 	const char *name_desc, const char *snippet, size_t snippet_length)
    644 {
    645 	const char *temp = snippet;
    646 	int i = 0;
    647 	size_t sz = 0;
    648 	int count = 0;
    649 	struct orig_callback_data *orig_data = (struct orig_callback_data *) data;
    650 	int (*callback) (void *, const char *, const char *, const char *,
    651 		const char *, size_t) = orig_data->callback;
    652 
    653 	/* First scan the snippet to find out the number of occurrences of {'>', '<'
    654 	 * '"', '&'}.
    655 	 * Then allocate a new buffer with sufficient space to be able to store the
    656 	 * quoted versions of the special characters {&gt;, &lt;, &quot;, &amp;}.
    657 	 * Copy over the characters from the original snippet to this buffer while
    658 	 * replacing the special characters with their quoted versions.
    659 	 */
    660 
    661 	while (*temp) {
    662 		sz = strcspn(temp, "<>\"&\002\003");
    663 		temp += sz + 1;
    664 		count++;
    665 	}
    666 	size_t qsnippet_length = snippet_length + count * 5;
    667 	char *qsnippet = emalloc(qsnippet_length + 1);
    668 	sz = 0;
    669 	while (*snippet) {
    670 		sz = strcspn(snippet, "<>\"&\002\003");
    671 		if (sz) {
    672 			memcpy(&qsnippet[i], snippet, sz);
    673 			snippet += sz;
    674 			i += sz;
    675 		}
    676 
    677 		switch (*snippet++) {
    678 		case '<':
    679 			memcpy(&qsnippet[i], "&lt;", 4);
    680 			i += 4;
    681 			break;
    682 		case '>':
    683 			memcpy(&qsnippet[i], "&gt;", 4);
    684 			i += 4;
    685 			break;
    686 		case '\"':
    687 			memcpy(&qsnippet[i], "&quot;", 6);
    688 			i += 6;
    689 			break;
    690 		case '&':
    691 			/* Don't perform the quoting if this & is part of an mdoc escape
    692 			 * sequence, e.g. \&
    693 			 */
    694 			if (i && *(snippet - 2) != '\\') {
    695 				memcpy(&qsnippet[i], "&amp;", 5);
    696 				i += 5;
    697 			} else {
    698 				qsnippet[i++] = '&';
    699 			}
    700 			break;
    701 		case '\002':
    702 			memcpy(&qsnippet[i], "<b>", 3);
    703 			i += 3;
    704 			break;
    705 		case '\003':
    706 			memcpy(&qsnippet[i], "</b>", 4);
    707 			i += 4;
    708 			break;
    709 		default:
    710 			break;
    711 		}
    712 	}
    713 	qsnippet[++i] = 0;
    714 	(*callback)(orig_data->data, section, name, name_desc,
    715 		(const char *)qsnippet,	qsnippet_length);
    716 	free(qsnippet);
    717 	return 0;
    718 }
    719 
    720 /*
    721  * run_query_html --
    722  *  Utility function to output query result in HTML format.
    723  *  It internally calls run_query only, but it first passes the output to it's
    724  *  own custom callback function, which preprocess the snippet for quoting
    725  *  inline HTML fragments.
    726  *  After that it delegates the call the actual user supplied callback function.
    727  */
    728 int
    729 run_query_html(sqlite3 *db, query_args *args)
    730 {
    731 	struct orig_callback_data orig_data;
    732 	orig_data.callback = args->callback;
    733 	orig_data.data = args->callback_data;
    734 	const char *snippet_args[] = {"\002", "\003", "..."};
    735 	args->callback = &callback_html;
    736 	args->callback_data = (void *) &orig_data;
    737 	return run_query(db, snippet_args, args);
    738 }
    739 
    740 /*
    741  * underline a string, pager style.
    742  */
    743 static char *
    744 ul_pager(const char *s)
    745 {
    746 	size_t len;
    747 	char *dst, *d;
    748 
    749 	// a -> _\ba
    750 	len = strlen(s) * 3 + 1;
    751 
    752 	d = dst = emalloc(len);
    753 	while (*s) {
    754 		*d++ = '_';
    755 		*d++ = '\b';
    756 		*d++ = *s++;
    757 	}
    758 	*d = '\0';
    759 	return dst;
    760 }
    761 
    762 /*
    763  * callback_pager --
    764  *  A callback similar to callback_html. It overstrikes the matching text in
    765  *  the snippet so that it appears emboldened when viewed using a pager like
    766  *  more or less.
    767  */
    768 static int
    769 callback_pager(void *data, const char *section, const char *name,
    770 	const char *name_desc, const char *snippet, size_t snippet_length)
    771 {
    772 	struct orig_callback_data *orig_data = (struct orig_callback_data *) data;
    773 	char *psnippet;
    774 	const char *temp = snippet;
    775 	int count = 0;
    776 	int i = 0;
    777 	size_t sz = 0;
    778 	size_t psnippet_length;
    779 
    780 	/* Count the number of bytes of matching text. For each of these bytes we
    781 	 * will use 2 extra bytes to overstrike it so that it appears bold when
    782 	 * viewed using a pager.
    783 	 */
    784 	while (*temp) {
    785 		sz = strcspn(temp, "\002\003");
    786 		temp += sz;
    787 		if (*temp == '\003') {
    788 			count += 2 * (sz);
    789 		}
    790 		temp++;
    791 	}
    792 
    793 	psnippet_length = snippet_length + count;
    794 	psnippet = emalloc(psnippet_length + 1);
    795 
    796 	/* Copy the bytes from snippet to psnippet:
    797 	 * 1. Copy the bytes before \002 as it is.
    798 	 * 2. The bytes after \002 need to be overstriked till we encounter \003.
    799 	 * 3. To overstrike a byte 'A' we need to write 'A\bA'
    800 	 */
    801 	while (*snippet) {
    802 		sz = strcspn(snippet, "\002");
    803 		memcpy(&psnippet[i], snippet, sz);
    804 		snippet += sz;
    805 		i += sz;
    806 
    807 		/* Don't change this. Advancing the pointer without reading the byte
    808 		 * is causing strange behavior.
    809 		 */
    810 		if (*snippet == '\002')
    811 			snippet++;
    812 		while (*snippet && *snippet != '\003') {
    813 			psnippet[i++] = *snippet;
    814 			psnippet[i++] = '\b';
    815 			psnippet[i++] = *snippet++;
    816 		}
    817 		if (*snippet)
    818 			snippet++;
    819 	}
    820 
    821 	psnippet[i] = 0;
    822 	char *ul_section = ul_pager(section);
    823 	char *ul_name = ul_pager(name);
    824 	char *ul_name_desc = ul_pager(name_desc);
    825 	(orig_data->callback)(orig_data->data, ul_section, ul_name,
    826 	    ul_name_desc, psnippet, psnippet_length);
    827 	free(ul_section);
    828 	free(ul_name);
    829 	free(ul_name_desc);
    830 	free(psnippet);
    831 	return 0;
    832 }
    833 
    834 struct term_args {
    835 	struct orig_callback_data *orig_data;
    836 	const char *smul;
    837 	const char *rmul;
    838 };
    839 
    840 /*
    841  * underline a string, pager style.
    842  */
    843 static char *
    844 ul_term(const char *s, const struct term_args *ta)
    845 {
    846 	char *dst;
    847 
    848 	easprintf(&dst, "%s%s%s", ta->smul, s, ta->rmul);
    849 	return dst;
    850 }
    851 
    852 /*
    853  * callback_term --
    854  *  A callback similar to callback_html. It overstrikes the matching text in
    855  *  the snippet so that it appears emboldened when viewed using a pager like
    856  *  more or less.
    857  */
    858 static int
    859 callback_term(void *data, const char *section, const char *name,
    860 	const char *name_desc, const char *snippet, size_t snippet_length)
    861 {
    862 	struct term_args *ta = data;
    863 	struct orig_callback_data *orig_data = ta->orig_data;
    864 
    865 	char *ul_section = ul_term(section, ta);
    866 	char *ul_name = ul_term(name, ta);
    867 	char *ul_name_desc = ul_term(name_desc, ta);
    868 	(orig_data->callback)(orig_data->data, ul_section, ul_name,
    869 	    ul_name_desc, snippet, snippet_length);
    870 	free(ul_section);
    871 	free(ul_name);
    872 	free(ul_name_desc);
    873 	return 0;
    874 }
    875 
    876 /*
    877  * run_query_pager --
    878  *  Utility function similar to run_query_html. This function tries to
    879  *  pre-process the result assuming it will be piped to a pager.
    880  *  For this purpose it first calls it's own callback function callback_pager
    881  *  which then delegates the call to the user supplied callback.
    882  */
    883 int
    884 run_query_pager(sqlite3 *db, query_args *args)
    885 {
    886 	struct orig_callback_data orig_data;
    887 	orig_data.callback = args->callback;
    888 	orig_data.data = args->callback_data;
    889 	const char *snippet_args[3];
    890 
    891 	if (args->flags & APROPOS_NOFORMAT) {
    892 		snippet_args[0] = snippet_args[1] = "";
    893 	} else {
    894 		snippet_args[0] = "\002";
    895 		snippet_args[1] = "\003";
    896 	}
    897 	snippet_args[2] = "...";
    898 	args->callback = &callback_pager;
    899 	args->callback_data = (void *) &orig_data;
    900 	return run_query(db, snippet_args, args);
    901 }
    902 
    903 static void
    904 term_init(int fd, const char *sa[5])
    905 {
    906 	TERMINAL *ti;
    907 	int error;
    908 	const char *bold, *sgr0, *smso, *rmso, *smul, *rmul;
    909 
    910 	if (ti_setupterm(&ti, NULL, fd, &error) == -1) {
    911 		bold = sgr0 = NULL;
    912 		smso = rmso = smul = rmul = "";
    913 		ti = NULL;
    914 	} else {
    915 		bold = ti_getstr(ti, "bold");
    916 		sgr0 = ti_getstr(ti, "sgr0");
    917 		if (bold == NULL || sgr0 == NULL) {
    918 			smso = ti_getstr(ti, "smso");
    919 
    920 			if (smso == NULL ||
    921 			    (rmso = ti_getstr(ti, "rmso")) == NULL)
    922 				smso = rmso = "";
    923 			bold = sgr0 = NULL;
    924 		} else
    925 			smso = rmso = "";
    926 
    927 		smul = ti_getstr(ti, "smul");
    928 		if (smul == NULL || (rmul = ti_getstr(ti, "rmul")) == NULL)
    929 			smul = rmul = "";
    930 	}
    931 
    932 	sa[0] = estrdup(bold ? bold : smso);
    933 	sa[1] = estrdup(sgr0 ? sgr0 : rmso);
    934 	sa[2] = estrdup("...");
    935 	sa[3] = estrdup(smul);
    936 	sa[4] = estrdup(rmul);
    937 	if (ti)
    938 		del_curterm(ti);
    939 }
    940 
    941 /*
    942  * run_query_term --
    943  *  Utility function similar to run_query_html. This function tries to
    944  *  pre-process the result assuming it will be displayed on a terminal
    945  *  For this purpose it first calls it's own callback function callback_pager
    946  *  which then delegates the call to the user supplied callback.
    947  */
    948 int
    949 run_query_term(sqlite3 *db, query_args *args)
    950 {
    951 	struct orig_callback_data orig_data;
    952 	struct term_args ta;
    953 	orig_data.callback = args->callback;
    954 	orig_data.data = args->callback_data;
    955 	const char *snippet_args[5];
    956 	if (args->flags & APROPOS_NOFORMAT) {
    957 		snippet_args[0] = snippet_args[1] = snippet_args[3] =
    958 		    snippet_args[4] = "";
    959 		snippet_args[2] = "...";
    960 	} else
    961 		term_init(STDOUT_FILENO, snippet_args);
    962 	ta.smul = snippet_args[3];
    963 	ta.rmul = snippet_args[4];
    964 	ta.orig_data = (void *) &orig_data;
    965 
    966 	args->callback = &callback_term;
    967 	args->callback_data = &ta;
    968 	return run_query(db, snippet_args, args);
    969 }
    970