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