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