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