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