Home | History | Annotate | Line # | Download | only in makemandb
apropos-utils.c revision 1.26
      1 /*	$NetBSD: apropos-utils.c,v 1.26 2016/06/01 15:59:18 abhinav 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.26 2016/06/01 15:59:18 abhinav 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 (db_flag) {
    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  * generates sql query for matching the user entered query
    493  */
    494 static char *
    495 generate_search_query(query_args *args, const char *snippet_args[3])
    496 {
    497 	const char *default_snippet_args[3];
    498 	char *section_clause = NULL;
    499 	char *limit_clause = NULL;
    500 	char *machine_clause = NULL;
    501 	char *query;
    502 
    503 	if (args->machine)
    504 		easprintf(&machine_clause, "AND machine = \'%s\' ",
    505 		    args->machine);
    506 
    507 
    508 	/* We want to build a query of the form: "select x,y,z from mandb where
    509 	 * mandb match :query [AND (section LIKE '1' OR section LIKE '2' OR...)]
    510 	 * ORDER BY rank DESC..."
    511 	 * NOTES:
    512 	 *   1. The portion in square brackets is optional, it will be there
    513 	 *      only if the user has specified an option on the command line
    514 	 *      to search in one or more specific sections.
    515 	 */
    516 	char *sections_str = args->sec_nums;
    517 	char *temp;
    518 	if (sections_str) {
    519 		while (*sections_str) {
    520 			size_t len = strcspn(sections_str, " ");
    521 			char *sec = sections_str;
    522 			if (sections_str[len] == 0) {
    523 				sections_str += len;
    524 			} else {
    525 				sections_str[len] = 0;
    526 				sections_str += len + 1;
    527 			}
    528 			easprintf(&temp, "\'%s\',", sec);
    529 
    530 			if (section_clause) {
    531 				concat(&section_clause, temp);
    532 				free(temp);
    533 			} else {
    534 				section_clause = temp;
    535 			}
    536 		}
    537 		if (section_clause) {
    538 			/*
    539 			 * At least one section requested, add glue for query.
    540 			 * Before doing that, remove the comma at the end of
    541 			 * section_clause
    542 			 */
    543 			size_t section_clause_len = strlen(section_clause);
    544 			if (section_clause[section_clause_len - 1] == ',')
    545 				section_clause[section_clause_len - 1] = 0;
    546 			temp = section_clause;
    547 			easprintf(&section_clause, " AND section IN (%s)", temp);
    548 			free(temp);
    549 		}
    550 	}
    551 
    552 	if (args->nrec >= 0) {
    553 		/* Use the provided number of records and offset */
    554 		easprintf(&limit_clause, " LIMIT %d OFFSET %d",
    555 		    args->nrec, args->offset);
    556 	}
    557 
    558 	if (snippet_args == NULL) {
    559 		default_snippet_args[0] = "";
    560 		default_snippet_args[1] = "";
    561 		default_snippet_args[2] = "...";
    562 		snippet_args = default_snippet_args;
    563 	}
    564 
    565 	if (args->legacy) {
    566 	    char *wild;
    567 	    easprintf(&wild, "%%%s%%", args->search_str);
    568 	    query = sqlite3_mprintf("SELECT section, name, name_desc, machine"
    569 		" FROM mandb"
    570 		" WHERE name LIKE %Q OR name_desc LIKE %Q "
    571 		"%s"
    572 		"%s",
    573 		wild, wild,
    574 		section_clause ? section_clause : "",
    575 		limit_clause ? limit_clause : "");
    576 		free(wild);
    577 	} else {
    578 	    query = sqlite3_mprintf("SELECT section, name, name_desc, machine,"
    579 		" snippet(mandb, %Q, %Q, %Q, -1, 40 ),"
    580 		" rank_func(matchinfo(mandb, \"pclxn\")) AS rank"
    581 		" FROM mandb"
    582 		" WHERE mandb MATCH %Q %s "
    583 		"%s"
    584 		" ORDER BY rank DESC"
    585 		"%s",
    586 		snippet_args[0], snippet_args[1], snippet_args[2],
    587 		args->search_str, machine_clause ? machine_clause : "",
    588 		section_clause ? section_clause : "",
    589 		limit_clause ? limit_clause : "");
    590 	}
    591 
    592 	free(machine_clause);
    593 	free(section_clause);
    594 	free(limit_clause);
    595 	return query;
    596 }
    597 
    598 /*
    599  * Execute the full text search query and return the number of results
    600  * obtained.
    601  */
    602 static unsigned int
    603 execute_search_query(sqlite3 *db, char *query, query_args *args)
    604 {
    605 	sqlite3_stmt *stmt;
    606 	const char *section;
    607 	char *name;
    608 	char *slash_ptr;
    609 	const char *name_desc;
    610 	const char *machine;
    611 	const char *snippet = "";
    612 	const char *name_temp;
    613 	char *m = NULL;
    614 	int rc;
    615 	inverse_document_frequency idf = {0, 0};
    616 
    617 	if (!args->legacy) {
    618 		/* Register the rank function */
    619 		rc = sqlite3_create_function(db, "rank_func", 1, SQLITE_ANY,
    620 		    (void *) &idf, rank_func, NULL, NULL);
    621 		if (rc != SQLITE_OK) {
    622 			warnx("Unable to register the ranking function: %s",
    623 			    sqlite3_errmsg(db));
    624 			sqlite3_close(db);
    625 			sqlite3_shutdown();
    626 			exit(EXIT_FAILURE);
    627 		}
    628 	}
    629 
    630 	rc = sqlite3_prepare_v2(db, query, -1, &stmt, NULL);
    631 	if (rc == SQLITE_IOERR) {
    632 		warnx("Corrupt database. Please rerun makemandb");
    633 		return -1;
    634 	} else if (rc != SQLITE_OK) {
    635 		warnx("%s", sqlite3_errmsg(db));
    636 		return -1;
    637 	}
    638 
    639 	unsigned int nresults = 0;
    640 	while (sqlite3_step(stmt) == SQLITE_ROW) {
    641 		nresults++;
    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 		if (!args->legacy)
    647 			snippet = (const char *) sqlite3_column_text(stmt, 4);
    648 		if ((slash_ptr = strrchr(name_temp, '/')) != NULL)
    649 			name_temp = slash_ptr + 1;
    650 		if (machine && machine[0]) {
    651 			m = estrdup(machine);
    652 			easprintf(&name, "%s/%s", lower(m), name_temp);
    653 			free(m);
    654 		} else {
    655 			name = estrdup((const char *)
    656 			    sqlite3_column_text(stmt, 1));
    657 		}
    658 
    659 		(args->callback)(args->callback_data, section, name,
    660 		    name_desc, snippet, args->legacy? 0: strlen(snippet));
    661 		free(name);
    662 	}
    663 	sqlite3_finalize(stmt);
    664 	return nresults;
    665 }
    666 
    667 
    668 /*
    669  *  run_query_internal --
    670  *  Performs the searches for the keywords entered by the user.
    671  *  The 2nd param: snippet_args is an array of strings providing values for the
    672  *  last three parameters to the snippet function of sqlite. (Look at the docs).
    673  *  The 3rd param: args contains rest of the search parameters. Look at
    674  *  arpopos-utils.h for the description of individual fields.
    675  *
    676  */
    677 static int
    678 run_query_internal(sqlite3 *db, const char *snippet_args[3], query_args *args)
    679 {
    680 	char *query;
    681 	query = generate_search_query(args, snippet_args);
    682 	if (query == NULL) {
    683 		*args->errmsg = estrdup("malloc failed");
    684 		return -1;
    685 	}
    686 
    687 	execute_search_query(db, query, args);
    688 	sqlite3_free(query);
    689 	return *(args->errmsg) == NULL ? 0 : -1;
    690 }
    691 
    692 static char *
    693 get_escaped_html_string(const char *src, size_t *slen)
    694 {
    695 	static const char trouble[] = "<>\"&\002\003";
    696 	/*
    697 	 * First scan the src to find out the number of occurrences
    698 	 * of {'>', '<' '"', '&'}.  Then allocate a new buffer with
    699 	 * sufficient space to be able to store the quoted versions
    700 	 * of the special characters {&gt;, &lt;, &quot;, &amp;}.
    701 	 * Copy over the characters from the original src into
    702 	 * this buffer while replacing the special characters with
    703 	 * their quoted versions.
    704 	 */
    705 	char *dst, *ddst;
    706 	size_t count;
    707 	const char *ssrc;
    708 
    709 	for (count = 0, ssrc = src; *src; count++) {
    710 		size_t sz = strcspn(src, trouble);
    711 		src += sz + 1;
    712 	}
    713 
    714 
    715 #define append(a)				\
    716     do {					\
    717 	memcpy(dst, (a), sizeof(a) - 1);	\
    718 	dst += sizeof(a) - 1; 			\
    719     } while (/*CONSTCOND*/0)
    720 
    721 
    722 	ddst = dst = emalloc(*slen + count * 5 + 1);
    723 	for (src = ssrc; *src; src++) {
    724 		switch (*src) {
    725 		case '<':
    726 			append("&lt;");
    727 			break;
    728 		case '>':
    729 			append("&gt;");
    730 			break;
    731 		case '\"':
    732 			append("&quot;");
    733 			break;
    734 		case '&':
    735 			/*
    736 			 * Don't perform the quoting if this & is part of
    737 			 * an mdoc escape sequence, e.g. \&
    738 			 */
    739 			if (src != ssrc && src[-1] != '\\')
    740 				append("&amp;");
    741 			else
    742 				append("&");
    743 			break;
    744 		case '\002':
    745 			append("<b>");
    746 			break;
    747 		case '\003':
    748 			append("</b>");
    749 			break;
    750 		default:
    751 			*dst++ = *src;
    752 			break;
    753 		}
    754 	}
    755 	*dst = '\0';
    756 	*slen = dst - ddst;
    757 	return ddst;
    758 }
    759 
    760 
    761 /*
    762  * callback_html --
    763  *  Callback function for run_query_html. It builds the html output and then
    764  *  calls the actual user supplied callback function.
    765  */
    766 static int
    767 callback_html(void *data, const char *section, const char *name,
    768     const char *name_desc, const char *snippet, size_t snippet_length)
    769 {
    770 	struct orig_callback_data *orig_data = data;
    771 	int (*callback)(void *, const char *, const char *, const char *,
    772 	    const char *, size_t) = orig_data->callback;
    773 	size_t length = snippet_length;
    774 	size_t name_description_length = strlen(name_desc);
    775 	char *qsnippet = get_escaped_html_string(snippet, &length);
    776 	char *qname_description = get_escaped_html_string(name_desc,
    777 	    &name_description_length);
    778 
    779 	(*callback)(orig_data->data, section, name, qname_description,
    780 	    qsnippet, length);
    781 	free(qsnippet);
    782 	free(qname_description);
    783 	return 0;
    784 }
    785 
    786 /*
    787  * run_query_html --
    788  *  Utility function to output query result in HTML format.
    789  *  It internally calls run_query only, but it first passes the output to its
    790  *  own custom callback function, which preprocess the snippet for quoting
    791  *  inline HTML fragments.
    792  *  After that it delegates the call the actual user supplied callback function.
    793  */
    794 static int
    795 run_query_html(sqlite3 *db, query_args *args)
    796 {
    797 	struct orig_callback_data orig_data;
    798 	orig_data.callback = args->callback;
    799 	orig_data.data = args->callback_data;
    800 	const char *snippet_args[] = {"\002", "\003", "..."};
    801 	args->callback = &callback_html;
    802 	args->callback_data = (void *) &orig_data;
    803 	return run_query_internal(db, snippet_args, args);
    804 }
    805 
    806 /*
    807  * underline a string, pager style.
    808  */
    809 static char *
    810 ul_pager(int ul, const char *s)
    811 {
    812 	size_t len;
    813 	char *dst, *d;
    814 
    815 	if (!ul)
    816 		return estrdup(s);
    817 
    818 	// a -> _\ba
    819 	len = strlen(s) * 3 + 1;
    820 
    821 	d = dst = emalloc(len);
    822 	while (*s) {
    823 		*d++ = '_';
    824 		*d++ = '\b';
    825 		*d++ = *s++;
    826 	}
    827 	*d = '\0';
    828 	return dst;
    829 }
    830 
    831 /*
    832  * callback_pager --
    833  *  A callback similar to callback_html. It overstrikes the matching text in
    834  *  the snippet so that it appears emboldened when viewed using a pager like
    835  *  more or less.
    836  */
    837 static int
    838 callback_pager(void *data, const char *section, const char *name,
    839 	const char *name_desc, const char *snippet, size_t snippet_length)
    840 {
    841 	struct orig_callback_data *orig_data = data;
    842 	char *psnippet;
    843 	const char *temp = snippet;
    844 	int count = 0;
    845 	int i = 0, did;
    846 	size_t sz = 0;
    847 	size_t psnippet_length;
    848 
    849 	/* Count the number of bytes of matching text. For each of these
    850 	 * bytes we will use 2 extra bytes to overstrike it so that it
    851 	 * appears bold when viewed using a pager.
    852 	 */
    853 	while (*temp) {
    854 		sz = strcspn(temp, "\002\003");
    855 		temp += sz;
    856 		if (*temp == '\003') {
    857 			count += 2 * (sz);
    858 		}
    859 		temp++;
    860 	}
    861 
    862 	psnippet_length = snippet_length + count;
    863 	psnippet = emalloc(psnippet_length + 1);
    864 
    865 	/* Copy the bytes from snippet to psnippet:
    866 	 * 1. Copy the bytes before \002 as it is.
    867 	 * 2. The bytes after \002 need to be overstriked till we
    868 	 *    encounter \003.
    869 	 * 3. To overstrike a byte 'A' we need to write 'A\bA'
    870 	 */
    871 	did = 0;
    872 	while (*snippet) {
    873 		sz = strcspn(snippet, "\002");
    874 		memcpy(&psnippet[i], snippet, sz);
    875 		snippet += sz;
    876 		i += sz;
    877 
    878 		/* Don't change this. Advancing the pointer without reading the byte
    879 		 * is causing strange behavior.
    880 		 */
    881 		if (*snippet == '\002')
    882 			snippet++;
    883 		while (*snippet && *snippet != '\003') {
    884 			did = 1;
    885 			psnippet[i++] = *snippet;
    886 			psnippet[i++] = '\b';
    887 			psnippet[i++] = *snippet++;
    888 		}
    889 		if (*snippet)
    890 			snippet++;
    891 	}
    892 
    893 	psnippet[i] = 0;
    894 	char *ul_section = ul_pager(did, section);
    895 	char *ul_name = ul_pager(did, name);
    896 	char *ul_name_desc = ul_pager(did, name_desc);
    897 	(orig_data->callback)(orig_data->data, ul_section, ul_name,
    898 	    ul_name_desc, psnippet, psnippet_length);
    899 	free(ul_section);
    900 	free(ul_name);
    901 	free(ul_name_desc);
    902 	free(psnippet);
    903 	return 0;
    904 }
    905 
    906 struct term_args {
    907 	struct orig_callback_data *orig_data;
    908 	const char *smul;
    909 	const char *rmul;
    910 };
    911 
    912 /*
    913  * underline a string, pager style.
    914  */
    915 static char *
    916 ul_term(const char *s, const struct term_args *ta)
    917 {
    918 	char *dst;
    919 
    920 	easprintf(&dst, "%s%s%s", ta->smul, s, ta->rmul);
    921 	return dst;
    922 }
    923 
    924 /*
    925  * callback_term --
    926  *  A callback similar to callback_html. It overstrikes the matching text in
    927  *  the snippet so that it appears emboldened when viewed using a pager like
    928  *  more or less.
    929  */
    930 static int
    931 callback_term(void *data, const char *section, const char *name,
    932 	const char *name_desc, const char *snippet, size_t snippet_length)
    933 {
    934 	struct term_args *ta = data;
    935 	struct orig_callback_data *orig_data = ta->orig_data;
    936 
    937 	char *ul_section = ul_term(section, ta);
    938 	char *ul_name = ul_term(name, ta);
    939 	char *ul_name_desc = ul_term(name_desc, ta);
    940 	(orig_data->callback)(orig_data->data, ul_section, ul_name,
    941 	    ul_name_desc, snippet, snippet_length);
    942 	free(ul_section);
    943 	free(ul_name);
    944 	free(ul_name_desc);
    945 	return 0;
    946 }
    947 
    948 /*
    949  * run_query_pager --
    950  *  Utility function similar to run_query_html. This function tries to
    951  *  pre-process the result assuming it will be piped to a pager.
    952  *  For this purpose it first calls its own callback function callback_pager
    953  *  which then delegates the call to the user supplied callback.
    954  */
    955 static int
    956 run_query_pager(sqlite3 *db, query_args *args)
    957 {
    958 	struct orig_callback_data orig_data;
    959 	orig_data.callback = args->callback;
    960 	orig_data.data = args->callback_data;
    961 	const char *snippet_args[3] = { "\002", "\003", "..." };
    962 	args->callback = &callback_pager;
    963 	args->callback_data = (void *) &orig_data;
    964 	return run_query_internal(db, snippet_args, args);
    965 }
    966 
    967 struct nv {
    968 	char *s;
    969 	size_t l;
    970 };
    971 
    972 static int
    973 term_putc(int c, void *p)
    974 {
    975 	struct nv *nv = p;
    976 	nv->s[nv->l++] = c;
    977 	return 0;
    978 }
    979 
    980 static char *
    981 term_fix_seq(TERMINAL *ti, const char *seq)
    982 {
    983 	char *res = estrdup(seq);
    984 	struct nv nv;
    985 
    986 	if (ti == NULL)
    987 	    return res;
    988 
    989 	nv.s = res;
    990 	nv.l = 0;
    991 	ti_puts(ti, seq, 1, term_putc, &nv);
    992 	nv.s[nv.l] = '\0';
    993 
    994 	return res;
    995 }
    996 
    997 static void
    998 term_init(int fd, const char *sa[5])
    999 {
   1000 	TERMINAL *ti;
   1001 	int error;
   1002 	const char *bold, *sgr0, *smso, *rmso, *smul, *rmul;
   1003 
   1004 	if (ti_setupterm(&ti, NULL, fd, &error) == -1) {
   1005 		bold = sgr0 = NULL;
   1006 		smso = rmso = smul = rmul = "";
   1007 		ti = NULL;
   1008 	} else {
   1009 		bold = ti_getstr(ti, "bold");
   1010 		sgr0 = ti_getstr(ti, "sgr0");
   1011 		if (bold == NULL || sgr0 == NULL) {
   1012 			smso = ti_getstr(ti, "smso");
   1013 
   1014 			if (smso == NULL ||
   1015 			    (rmso = ti_getstr(ti, "rmso")) == NULL)
   1016 				smso = rmso = "";
   1017 			bold = sgr0 = NULL;
   1018 		} else
   1019 			smso = rmso = "";
   1020 
   1021 		smul = ti_getstr(ti, "smul");
   1022 		if (smul == NULL || (rmul = ti_getstr(ti, "rmul")) == NULL)
   1023 			smul = rmul = "";
   1024 	}
   1025 
   1026 	sa[0] = term_fix_seq(ti, bold ? bold : smso);
   1027 	sa[1] = term_fix_seq(ti, sgr0 ? sgr0 : rmso);
   1028 	sa[2] = estrdup("...");
   1029 	sa[3] = term_fix_seq(ti, smul);
   1030 	sa[4] = term_fix_seq(ti, rmul);
   1031 
   1032 	if (ti)
   1033 		del_curterm(ti);
   1034 }
   1035 
   1036 /*
   1037  * run_query_term --
   1038  *  Utility function similar to run_query_html. This function tries to
   1039  *  pre-process the result assuming it will be displayed on a terminal
   1040  *  For this purpose it first calls its own callback function callback_pager
   1041  *  which then delegates the call to the user supplied callback.
   1042  */
   1043 static int
   1044 run_query_term(sqlite3 *db, query_args *args)
   1045 {
   1046 	struct orig_callback_data orig_data;
   1047 	struct term_args ta;
   1048 	orig_data.callback = args->callback;
   1049 	orig_data.data = args->callback_data;
   1050 	const char *snippet_args[5];
   1051 
   1052 	term_init(STDOUT_FILENO, snippet_args);
   1053 	ta.smul = snippet_args[3];
   1054 	ta.rmul = snippet_args[4];
   1055 	ta.orig_data = (void *) &orig_data;
   1056 
   1057 	args->callback = &callback_term;
   1058 	args->callback_data = &ta;
   1059 	return run_query_internal(db, snippet_args, args);
   1060 }
   1061 
   1062 static int
   1063 run_query_none(sqlite3 *db, query_args *args)
   1064 {
   1065 	struct orig_callback_data orig_data;
   1066 	orig_data.callback = args->callback;
   1067 	orig_data.data = args->callback_data;
   1068 	const char *snippet_args[3] = { "", "", "..." };
   1069 	args->callback = &callback_pager;
   1070 	args->callback_data = (void *) &orig_data;
   1071 	return run_query_internal(db, snippet_args, args);
   1072 }
   1073 
   1074 int
   1075 run_query(sqlite3 *db, query_format fmt, query_args *args)
   1076 {
   1077 	switch (fmt) {
   1078 	case APROPOS_NONE:
   1079 		return run_query_none(db, args);
   1080 	case APROPOS_HTML:
   1081 		return run_query_html(db, args);
   1082 	case APROPOS_TERM:
   1083 		return run_query_term(db, args);
   1084 	case APROPOS_PAGER:
   1085 		return run_query_pager(db, args);
   1086 	default:
   1087 		warnx("Unknown query format %d", (int)fmt);
   1088 		return -1;
   1089 	}
   1090 }
   1091