Home | History | Annotate | Line # | Download | only in makemandb
makemandb.c revision 1.40
      1 /*	$NetBSD: makemandb.c,v 1.40 2016/07/15 19:41:33 christos Exp $	*/
      2 /*
      3  * Copyright (c) 2011 Abhinav Upadhyay <er.abhinav.upadhyay (at) gmail.com>
      4  * Copyright (c) 2011 Kristaps Dzonsons <kristaps (at) bsd.lv>
      5  *
      6  * Permission to use, copy, modify, and distribute this software for any
      7  * purpose with or without fee is hereby granted, provided that the above
      8  * copyright notice and this permission notice appear in all copies.
      9  *
     10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
     11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
     12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
     13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
     14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
     15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
     16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
     17  */
     18 
     19 #include <sys/cdefs.h>
     20 __RCSID("$NetBSD: makemandb.c,v 1.40 2016/07/15 19:41:33 christos Exp $");
     21 
     22 #include <sys/stat.h>
     23 #include <sys/types.h>
     24 
     25 #include <assert.h>
     26 #include <dirent.h>
     27 #include <err.h>
     28 #include <archive.h>
     29 #include <libgen.h>
     30 #include <md5.h>
     31 #include <stdio.h>
     32 #include <stdlib.h>
     33 #include <string.h>
     34 #include <unistd.h>
     35 #include <util.h>
     36 
     37 #include "apropos-utils.h"
     38 #include "dist/man.h"
     39 #include "dist/mandoc.h"
     40 #include "dist/mdoc.h"
     41 #include "dist/roff.h"
     42 
     43 #define BUFLEN 1024
     44 #define MDOC 0	//If the page is of mdoc(7) type
     45 #define MAN 1	//If the page  is of man(7) type
     46 
     47 /*
     48  * A data structure for holding section specific data.
     49  */
     50 typedef struct secbuff {
     51 	char *data;
     52 	size_t buflen;	//Total length of buffer allocated initially
     53 	size_t offset;	// Current offset in the buffer.
     54 } secbuff;
     55 
     56 typedef struct makemandb_flags {
     57 	int optimize;
     58 	int limit;	// limit the indexing to only NAME section
     59 	int recreate;	// Database was created from scratch
     60 	int verbosity;	// 0: quiet, 1: default, 2: verbose
     61 } makemandb_flags;
     62 
     63 typedef struct roff_mandb_rec {
     64 	/* Fields for mandb table */
     65 	char *name;	// for storing the name of the man page
     66 	char *name_desc; // for storing the one line description (.Nd)
     67 	secbuff desc; // for storing the DESCRIPTION section
     68 	secbuff lib; // for the LIBRARY section
     69 	secbuff return_vals; // RETURN VALUES
     70 	secbuff env; // ENVIRONMENT
     71 	secbuff files; // FILES
     72 	secbuff exit_status; // EXIT STATUS
     73 	secbuff diagnostics; // DIAGNOSTICS
     74 	secbuff errors; // ERRORS
     75 	char *section;
     76 
     77 	int xr_found; // To track whether a .Xr was seen when parsing a section
     78 
     79 	/* Fields for mandb_meta table */
     80 	char *md5_hash;
     81 	dev_t device;
     82 	ino_t inode;
     83 	time_t mtime;
     84 
     85 	/* Fields for mandb_links table */
     86 	char *machine;
     87 	char *links; //all the links to a page in a space separated form
     88 	char *file_path;
     89 
     90 	/* Non-db fields */
     91 	int page_type; //Indicates the type of page: mdoc or man
     92 } mandb_rec;
     93 
     94 typedef	void (*proff_nf)(const struct roff_node *n, mandb_rec *);
     95 
     96 static void append(secbuff *sbuff, const char *src);
     97 static void init_secbuffs(mandb_rec *);
     98 static void free_secbuffs(mandb_rec *);
     99 static int check_md5(const char *, sqlite3 *, const char *, char **, void *, size_t);
    100 static void cleanup(mandb_rec *);
    101 static void set_section(const struct roff_man *, mandb_rec *);
    102 static void set_machine(const struct roff_man *, mandb_rec *);
    103 static int insert_into_db(sqlite3 *, mandb_rec *);
    104 static	void begin_parse(const char *, struct mparse *, mandb_rec *,
    105 			 const void *, size_t len);
    106 static void proff_node(const struct roff_node *, mandb_rec *, const proff_nf *);
    107 static void pmdoc_Nm(const struct roff_node *, mandb_rec *);
    108 static void pmdoc_Nd(const struct roff_node *, mandb_rec *);
    109 static void pmdoc_Sh(const struct roff_node *, mandb_rec *);
    110 static void pmdoc_Xr(const struct roff_node *, mandb_rec *);
    111 static void pmdoc_Pp(const struct roff_node *, mandb_rec *);
    112 static void pmdoc_macro_handler(const struct roff_node *, mandb_rec *, int);
    113 static void pman_parse_node(const struct roff_node *, secbuff *);
    114 static void pman_parse_name(const struct roff_node *, mandb_rec *);
    115 static void pman_sh(const struct roff_node *, mandb_rec *);
    116 static void pman_block(const struct roff_node *, mandb_rec *);
    117 static void traversedir(const char *, const char *, sqlite3 *, struct mparse *);
    118 static void mdoc_parse_section(enum roff_sec, const char *, mandb_rec *);
    119 static void man_parse_section(enum man_sec, const struct roff_node *, mandb_rec *);
    120 static void build_file_cache(sqlite3 *, const char *, const char *,
    121 			     struct stat *);
    122 static void update_db(sqlite3 *, struct mparse *, mandb_rec *);
    123 __dead static void usage(void);
    124 static void optimize(sqlite3 *);
    125 static char *parse_escape(const char *);
    126 static void replace_hyph(char *);
    127 static makemandb_flags mflags = { .verbosity = 1 };
    128 
    129 static	const proff_nf mdocs[MDOC_MAX + 1] = {
    130 	NULL, /* Ap */
    131 	NULL, /* Dd */
    132 	NULL, /* Dt */
    133 	NULL, /* Os */
    134 
    135 	pmdoc_Sh, /* Sh */
    136 	NULL, /* Ss */
    137 	pmdoc_Pp, /* Pp */
    138 	NULL, /* D1 */
    139 
    140 	NULL, /* Dl */
    141 	NULL, /* Bd */
    142 	NULL, /* Ed */
    143 	NULL, /* Bl */
    144 
    145 	NULL, /* El */
    146 	NULL, /* It */
    147 	NULL, /* Ad */
    148 	NULL, /* An */
    149 
    150 	NULL, /* Ar */
    151 	NULL, /* Cd */
    152 	NULL, /* Cm */
    153 	NULL, /* Dv */
    154 
    155 	NULL, /* Er */
    156 	NULL, /* Ev */
    157 	NULL, /* Ex */
    158 	NULL, /* Fa */
    159 
    160 	NULL, /* Fd */
    161 	NULL, /* Fl */
    162 	NULL, /* Fn */
    163 	NULL, /* Ft */
    164 
    165 	NULL, /* Ic */
    166 	NULL, /* In */
    167 	NULL, /* Li */
    168 	pmdoc_Nd, /* Nd */
    169 
    170 	pmdoc_Nm, /* Nm */
    171 	NULL, /* Op */
    172 	NULL, /* Ot */
    173 	NULL, /* Pa */
    174 
    175 	NULL, /* Rv */
    176 	NULL, /* St */
    177 	NULL, /* Va */
    178 	NULL, /* Vt */
    179 
    180 	pmdoc_Xr, /* Xr */
    181 	NULL, /* %A */
    182 	NULL, /* %B */
    183 	NULL, /* %D */
    184 
    185 	NULL, /* %I */
    186 	NULL, /* %J */
    187 	NULL, /* %N */
    188 	NULL, /* %O */
    189 
    190 	NULL, /* %P */
    191 	NULL, /* %R */
    192 	NULL, /* %T */
    193 	NULL, /* %V */
    194 
    195 	NULL, /* Ac */
    196 	NULL, /* Ao */
    197 	NULL, /* Aq */
    198 	NULL, /* At */
    199 
    200 	NULL, /* Bc */
    201 	NULL, /* Bf */
    202 	NULL, /* Bo */
    203 	NULL, /* Bq */
    204 
    205 	NULL, /* Bsx */
    206 	NULL, /* Bx */
    207 	NULL, /* Db */
    208 	NULL, /* Dc */
    209 
    210 	NULL, /* Do */
    211 	NULL, /* Dq */
    212 	NULL, /* Ec */
    213 	NULL, /* Ef */
    214 
    215 	NULL, /* Em */
    216 	NULL, /* Eo */
    217 	NULL, /* Fx */
    218 	NULL, /* Ms */
    219 
    220 	NULL, /* No */
    221 	NULL, /* Ns */
    222 	NULL, /* Nx */
    223 	NULL, /* Ox */
    224 
    225 	NULL, /* Pc */
    226 	NULL, /* Pf */
    227 	NULL, /* Po */
    228 	NULL, /* Pq */
    229 
    230 	NULL, /* Qc */
    231 	NULL, /* Ql */
    232 	NULL, /* Qo */
    233 	NULL, /* Qq */
    234 
    235 	NULL, /* Re */
    236 	NULL, /* Rs */
    237 	NULL, /* Sc */
    238 	NULL, /* So */
    239 
    240 	NULL, /* Sq */
    241 	NULL, /* Sm */
    242 	NULL, /* Sx */
    243 	NULL, /* Sy */
    244 
    245 	NULL, /* Tn */
    246 	NULL, /* Ux */
    247 	NULL, /* Xc */
    248 	NULL, /* Xo */
    249 
    250 	NULL, /* Fo */
    251 	NULL, /* Fc */
    252 	NULL, /* Oo */
    253 	NULL, /* Oc */
    254 
    255 	NULL, /* Bk */
    256 	NULL, /* Ek */
    257 	NULL, /* Bt */
    258 	NULL, /* Hf */
    259 
    260 	NULL, /* Fr */
    261 	NULL, /* Ud */
    262 	NULL, /* Lb */
    263 	NULL, /* Lp */
    264 
    265 	NULL, /* Lk */
    266 	NULL, /* Mt */
    267 	NULL, /* Brq */
    268 	NULL, /* Bro */
    269 
    270 	NULL, /* Brc */
    271 	NULL, /* %C */
    272 	NULL, /* Es */
    273 	NULL, /* En */
    274 
    275 	NULL, /* Dx */
    276 	NULL, /* %Q */
    277 	NULL, /* br */
    278 	NULL, /* sp */
    279 
    280 	NULL, /* %U */
    281 	NULL, /* Ta */
    282 	NULL, /* ll */
    283 	NULL, /* text */
    284 };
    285 
    286 static	const proff_nf mans[MAN_MAX] = {
    287 	NULL,	//br
    288 	NULL,	//TH
    289 	pman_sh, //SH
    290 	NULL,	//SS
    291 	NULL,	//TP
    292 	NULL,	//LP
    293 	NULL,	//PP
    294 	NULL,	//P
    295 	NULL,	//IP
    296 	NULL,	//HP
    297 	NULL,	//SM
    298 	NULL,	//SB
    299 	NULL,	//BI
    300 	NULL,	//IB
    301 	NULL,	//BR
    302 	NULL,	//RB
    303 	NULL,	//R
    304 	pman_block,	//B
    305 	NULL,	//I
    306 	NULL,	//IR
    307 	NULL,	//RI
    308 	NULL,	//sp
    309 	NULL,	//nf
    310 	NULL,	//fi
    311 	NULL,	//RE
    312 	NULL,	//RS
    313 	NULL,	//DT
    314 	NULL,	//UC
    315 	NULL,	//PD
    316 	NULL,	//AT
    317 	NULL,	//in
    318 	NULL,	//ft
    319 	NULL,	//OP
    320 	NULL,	//EX
    321 	NULL,	//EE
    322 	NULL,	//UR
    323 	NULL,	//UE
    324 	NULL,	//ll
    325 };
    326 
    327 
    328 int
    329 main(int argc, char *argv[])
    330 {
    331 	FILE *file;
    332 	const char *sqlstr, *manconf = NULL;
    333 	char *line, *command, *parent;
    334 	char *errmsg;
    335 	int ch;
    336 	struct mparse *mp;
    337 	sqlite3 *db;
    338 	ssize_t len;
    339 	size_t linesize;
    340 	struct roff_mandb_rec rec;
    341 
    342 	while ((ch = getopt(argc, argv, "C:floQqv")) != -1) {
    343 		switch (ch) {
    344 		case 'C':
    345 			manconf = optarg;
    346 			break;
    347 		case 'f':
    348 			mflags.recreate = 1;
    349 			break;
    350 		case 'l':
    351 			mflags.limit = 1;
    352 			break;
    353 		case 'o':
    354 			mflags.optimize = 1;
    355 			break;
    356 		case 'Q':
    357 			mflags.verbosity = 0;
    358 			break;
    359 		case 'q':
    360 			mflags.verbosity = 1;
    361 			break;
    362 		case 'v':
    363 			mflags.verbosity = 2;
    364 			break;
    365 		default:
    366 			usage();
    367 		}
    368 	}
    369 
    370 	memset(&rec, 0, sizeof(rec));
    371 
    372 	init_secbuffs(&rec);
    373 	mchars_alloc();
    374 	mp = mparse_alloc(0, MANDOCLEVEL_BADARG, NULL, NULL);
    375 
    376 	if (manconf) {
    377 		char *arg;
    378 		size_t command_len = shquote(manconf, NULL, 0) + 1;
    379 		arg = emalloc(command_len);
    380 		shquote(manconf, arg, command_len);
    381 		easprintf(&command, "man -p -C %s", arg);
    382 		free(arg);
    383 	} else {
    384 		command = estrdup("man -p");
    385 		manconf = MANCONF;
    386 	}
    387 
    388 	if (mflags.recreate) {
    389 		char *dbp = get_dbpath(manconf);
    390 		/* No error here, it will fail in init_db in the same call */
    391 		if (dbp != NULL)
    392 			remove(dbp);
    393 	}
    394 
    395 	if ((db = init_db(MANDB_CREATE, manconf)) == NULL)
    396 		exit(EXIT_FAILURE);
    397 
    398 	sqlite3_exec(db, "PRAGMA synchronous = 0", NULL, NULL, 	&errmsg);
    399 	if (errmsg != NULL) {
    400 		warnx("%s", errmsg);
    401 		free(errmsg);
    402 		close_db(db);
    403 		exit(EXIT_FAILURE);
    404 	}
    405 
    406 	sqlite3_exec(db, "ATTACH DATABASE \':memory:\' AS metadb", NULL, NULL,
    407 	    &errmsg);
    408 	if (errmsg != NULL) {
    409 		warnx("%s", errmsg);
    410 		free(errmsg);
    411 		close_db(db);
    412 		exit(EXIT_FAILURE);
    413 	}
    414 
    415 
    416 	/* Call man -p to get the list of man page dirs */
    417 	if ((file = popen(command, "r")) == NULL) {
    418 		close_db(db);
    419 		err(EXIT_FAILURE, "fopen failed");
    420 	}
    421 	free(command);
    422 
    423 	/* Begin the transaction for indexing the pages	*/
    424 	sqlite3_exec(db, "BEGIN", NULL, NULL, &errmsg);
    425 	if (errmsg != NULL) {
    426 		warnx("%s", errmsg);
    427 		free(errmsg);
    428 		close_db(db);
    429 		exit(EXIT_FAILURE);
    430 	}
    431 
    432 	sqlstr = "CREATE TABLE metadb.file_cache(device, inode, mtime, parent,"
    433 		 " file PRIMARY KEY);"
    434 		 "CREATE UNIQUE INDEX metadb.index_file_cache_dev"
    435 		 " ON file_cache (device, inode)";
    436 
    437 	sqlite3_exec(db, sqlstr, NULL, NULL, &errmsg);
    438 	if (errmsg != NULL) {
    439 		warnx("%s", errmsg);
    440 		free(errmsg);
    441 		close_db(db);
    442 		exit(EXIT_FAILURE);
    443 	}
    444 
    445 	if (mflags.verbosity)
    446 		printf("Building temporary file cache\n");
    447 	line = NULL;
    448 	linesize = 0;
    449 	while ((len = getline(&line, &linesize, file)) != -1) {
    450 		/* Replace the new line character at the end of string with '\0' */
    451 		line[len - 1] = '\0';
    452 		parent = estrdup(line);
    453 		char *pdir = estrdup(dirname(parent));
    454 		free(parent);
    455 		/* Traverse the man page directories and parse the pages */
    456 		traversedir(pdir, line, db, mp);
    457 		free(pdir);
    458 	}
    459 	free(line);
    460 
    461 	if (pclose(file) == -1) {
    462 		close_db(db);
    463 		cleanup(&rec);
    464 		free_secbuffs(&rec);
    465 		err(EXIT_FAILURE, "pclose error");
    466 	}
    467 
    468 	if (mflags.verbosity)
    469 		printf("Performing index update\n");
    470 	update_db(db, mp, &rec);
    471 	mparse_free(mp);
    472 	mchars_free();
    473 	free_secbuffs(&rec);
    474 
    475 	/* Commit the transaction */
    476 	sqlite3_exec(db, "COMMIT", NULL, NULL, &errmsg);
    477 	if (errmsg != NULL) {
    478 		warnx("%s", errmsg);
    479 		free(errmsg);
    480 		close_db(db);
    481 		exit(EXIT_FAILURE);
    482 	}
    483 
    484 	if (mflags.optimize)
    485 		optimize(db);
    486 
    487 	close_db(db);
    488 	return 0;
    489 }
    490 
    491 /*
    492  * traversedir --
    493  *  Traverses the given directory recursively and passes all the man page files
    494  *  in the way to build_file_cache()
    495  */
    496 static void
    497 traversedir(const char *parent, const char *file, sqlite3 *db,
    498             struct mparse *mp)
    499 {
    500 	struct stat sb;
    501 	struct dirent *dirp;
    502 	DIR *dp;
    503 	char *buf;
    504 
    505 	if (stat(file, &sb) < 0) {
    506 		if (mflags.verbosity)
    507 			warn("stat failed: %s", file);
    508 		return;
    509 	}
    510 
    511 	/* If it is a directory, traverse it recursively */
    512 	if (S_ISDIR(sb.st_mode)) {
    513 		if ((dp = opendir(file)) == NULL) {
    514 			if (mflags.verbosity)
    515 				warn("opendir error: %s", file);
    516 			return;
    517 		}
    518 
    519 		while ((dirp = readdir(dp)) != NULL) {
    520 			/* Avoid . and .. entries in a directory */
    521 			if (strncmp(dirp->d_name, ".", 1)) {
    522 				easprintf(&buf, "%s/%s", file, dirp->d_name);
    523 				traversedir(parent, buf, db, mp);
    524 				free(buf);
    525 			}
    526 		}
    527 		closedir(dp);
    528 	}
    529 
    530 	if (!S_ISREG(sb.st_mode) && !S_ISLNK(sb.st_mode))
    531 		return;
    532 
    533 	if (sb.st_size == 0) {
    534 		if (mflags.verbosity)
    535 			warnx("Empty file: %s", file);
    536 		return;
    537 	}
    538 	build_file_cache(db, parent, file, &sb);
    539 }
    540 
    541 /* build_file_cache --
    542  *   This function generates an md5 hash of the file passed as its 2nd parameter
    543  *   and stores it in a temporary table file_cache along with the full file path.
    544  *   This is done to support incremental updation of the database.
    545  *   The temporary table file_cache is dropped thereafter in the function
    546  *   update_db(), once the database has been updated.
    547  */
    548 static void
    549 build_file_cache(sqlite3 *db, const char *parent, const char *file,
    550 		 struct stat *sb)
    551 {
    552 	const char *sqlstr;
    553 	sqlite3_stmt *stmt = NULL;
    554 	int rc, idx;
    555 	assert(file != NULL);
    556 	dev_t device_cache = sb->st_dev;
    557 	ino_t inode_cache = sb->st_ino;
    558 	time_t mtime_cache = sb->st_mtime;
    559 
    560 	sqlstr = "INSERT INTO metadb.file_cache VALUES (:device, :inode,"
    561 		 " :mtime, :parent, :file)";
    562 	rc = sqlite3_prepare_v2(db, sqlstr, -1, &stmt, NULL);
    563 	if (rc != SQLITE_OK) {
    564 		if (mflags.verbosity)
    565 			warnx("%s", sqlite3_errmsg(db));
    566 		return;
    567 	}
    568 
    569 	idx = sqlite3_bind_parameter_index(stmt, ":device");
    570 	rc = sqlite3_bind_int64(stmt, idx, device_cache);
    571 	if (rc != SQLITE_OK) {
    572 		if (mflags.verbosity)
    573 			warnx("%s", sqlite3_errmsg(db));
    574 		sqlite3_finalize(stmt);
    575 		return;
    576 	}
    577 
    578 	idx = sqlite3_bind_parameter_index(stmt, ":inode");
    579 	rc = sqlite3_bind_int64(stmt, idx, inode_cache);
    580 	if (rc != SQLITE_OK) {
    581 		if (mflags.verbosity)
    582 			warnx("%s", sqlite3_errmsg(db));
    583 		sqlite3_finalize(stmt);
    584 		return;
    585 	}
    586 
    587 	idx = sqlite3_bind_parameter_index(stmt, ":mtime");
    588 	rc = sqlite3_bind_int64(stmt, idx, mtime_cache);
    589 	if (rc != SQLITE_OK) {
    590 		if (mflags.verbosity)
    591 			warnx("%s", sqlite3_errmsg(db));
    592 		sqlite3_finalize(stmt);
    593 		return;
    594 	}
    595 
    596 	idx = sqlite3_bind_parameter_index(stmt, ":parent");
    597 	rc = sqlite3_bind_text(stmt, idx, parent, -1, NULL);
    598 	if (rc != SQLITE_OK) {
    599 		if (mflags.verbosity)
    600 			warnx("%s", sqlite3_errmsg(db));
    601 		sqlite3_finalize(stmt);
    602 		return;
    603 	}
    604 
    605 	idx = sqlite3_bind_parameter_index(stmt, ":file");
    606 	rc = sqlite3_bind_text(stmt, idx, file, -1, NULL);
    607 	if (rc != SQLITE_OK) {
    608 		if (mflags.verbosity)
    609 			warnx("%s", sqlite3_errmsg(db));
    610 		sqlite3_finalize(stmt);
    611 		return;
    612 	}
    613 
    614 	sqlite3_step(stmt);
    615 	sqlite3_finalize(stmt);
    616 }
    617 
    618 static void
    619 update_existing_entry(sqlite3 *db, const char *file, const char *hash,
    620     mandb_rec *rec, int *new_count, int *link_count, int *err_count)
    621 {
    622 	int update_count, rc, idx;
    623 	const char *inner_sqlstr;
    624 	sqlite3_stmt *inner_stmt;
    625 
    626 	update_count = sqlite3_total_changes(db);
    627 	inner_sqlstr = "UPDATE mandb_meta SET device = :device,"
    628 		       " inode = :inode, mtime = :mtime WHERE"
    629 		       " md5_hash = :md5 AND file = :file AND"
    630 		       " (device <> :device2 OR inode <> "
    631 		       "  :inode2 OR mtime <> :mtime2)";
    632 	rc = sqlite3_prepare_v2(db, inner_sqlstr, -1, &inner_stmt, NULL);
    633 	if (rc != SQLITE_OK) {
    634 		if (mflags.verbosity)
    635 			warnx("%s", sqlite3_errmsg(db));
    636 		return;
    637 	}
    638 	idx = sqlite3_bind_parameter_index(inner_stmt, ":device");
    639 	sqlite3_bind_int64(inner_stmt, idx, rec->device);
    640 	idx = sqlite3_bind_parameter_index(inner_stmt, ":inode");
    641 	sqlite3_bind_int64(inner_stmt, idx, rec->inode);
    642 	idx = sqlite3_bind_parameter_index(inner_stmt, ":mtime");
    643 	sqlite3_bind_int64(inner_stmt, idx, rec->mtime);
    644 	idx = sqlite3_bind_parameter_index(inner_stmt, ":md5");
    645 	sqlite3_bind_text(inner_stmt, idx, hash, -1, NULL);
    646 	idx = sqlite3_bind_parameter_index(inner_stmt, ":file");
    647 	sqlite3_bind_text(inner_stmt, idx, file, -1, NULL);
    648 	idx = sqlite3_bind_parameter_index(inner_stmt, ":device2");
    649 	sqlite3_bind_int64(inner_stmt, idx, rec->device);
    650 	idx = sqlite3_bind_parameter_index(inner_stmt, ":inode2");
    651 	sqlite3_bind_int64(inner_stmt, idx, rec->inode);
    652 	idx = sqlite3_bind_parameter_index(inner_stmt, ":mtime2");
    653 	sqlite3_bind_int64(inner_stmt, idx, rec->mtime);
    654 
    655 	rc = sqlite3_step(inner_stmt);
    656 	if (rc == SQLITE_DONE) {
    657 		/* Check if an update has been performed. */
    658 		if (update_count != sqlite3_total_changes(db)) {
    659 			if (mflags.verbosity == 2)
    660 				printf("Updated %s\n", file);
    661 			(*new_count)++;
    662 		} else {
    663 			/* Otherwise it was a hardlink. */
    664 			(*link_count)++;
    665 		}
    666 	} else {
    667 		if (mflags.verbosity == 2)
    668 			warnx("Could not update the meta data for %s", file);
    669 		(*err_count)++;
    670 	}
    671 	sqlite3_finalize(inner_stmt);
    672 }
    673 
    674 /* read_and_decompress --
    675  *	Reads the given file into memory. If it is compressed, decompress
    676  *	it before returning to the caller.
    677  */
    678 static int
    679 read_and_decompress(const char *file, void **bufp, size_t *len)
    680 {
    681 	size_t off;
    682 	ssize_t r;
    683 	struct archive *a;
    684 	struct archive_entry *ae;
    685 	char *buf;
    686 
    687 	if ((a = archive_read_new()) == NULL)
    688 		errx(EXIT_FAILURE, "memory allocation failed");
    689 
    690 	*bufp = NULL;
    691 	if (archive_read_support_compression_all(a) != ARCHIVE_OK ||
    692 	    archive_read_support_format_raw(a) != ARCHIVE_OK ||
    693 	    archive_read_open_filename(a, file, 65536) != ARCHIVE_OK ||
    694 	    archive_read_next_header(a, &ae) != ARCHIVE_OK)
    695 		goto archive_error;
    696 	*len = 65536;
    697 	buf = emalloc(*len);
    698 	off = 0;
    699 	for (;;) {
    700 		r = archive_read_data(a, buf + off, *len - off);
    701 		if (r == ARCHIVE_OK) {
    702 			archive_read_finish(a);
    703 			*bufp = buf;
    704 			*len = off;
    705 			return 0;
    706 		}
    707 		if (r <= 0) {
    708 			free(buf);
    709 			break;
    710 		}
    711 		off += r;
    712 		if (off == *len) {
    713 			*len *= 2;
    714 			if (*len < off) {
    715 				if (mflags.verbosity)
    716 					warnx("File too large: %s", file);
    717 				free(buf);
    718 				archive_read_finish(a);
    719 				return -1;
    720 			}
    721 			buf = erealloc(buf, *len);
    722 		}
    723 	}
    724 
    725 archive_error:
    726 	warnx("Error while reading `%s': %s", file, archive_error_string(a));
    727 	archive_read_finish(a);
    728 	return -1;
    729 }
    730 
    731 /* update_db --
    732  *	Does an incremental updation of the database by checking the file_cache.
    733  *	It parses and adds the pages which are present in file_cache,
    734  *	but not in the database.
    735  *	It also removes the pages which are present in the databse,
    736  *	but not in the file_cache.
    737  */
    738 static void
    739 update_db(sqlite3 *db, struct mparse *mp, mandb_rec *rec)
    740 {
    741 	const char *sqlstr;
    742 	sqlite3_stmt *stmt = NULL;
    743 	char *file;
    744 	char *parent;
    745 	char *errmsg = NULL;
    746 	char *md5sum;
    747 	void *buf;
    748 	size_t buflen;
    749 	struct sql_row {
    750 		struct sql_row *next;
    751 		dev_t device;
    752 		ino_t inode;
    753 		time_t mtime;
    754 		char *parent;
    755 		char *file;
    756 	} *rows, *row;
    757 	int new_count = 0;	/* Counter for newly indexed/updated pages */
    758 	int total_count = 0;	/* Counter for total number of pages */
    759 	int err_count = 0;	/* Counter for number of failed pages */
    760 	int link_count = 0;	/* Counter for number of hard/sym links */
    761 	int md5_status;
    762 	int rc;
    763 
    764 	sqlstr = "SELECT device, inode, mtime, parent, file"
    765 	         " FROM metadb.file_cache fc"
    766 	         " WHERE NOT EXISTS(SELECT 1 FROM mandb_meta WHERE"
    767 	         "  device = fc.device AND inode = fc.inode AND "
    768 	         "  mtime = fc.mtime AND file = fc.file)";
    769 
    770 	rc = sqlite3_prepare_v2(db, sqlstr, -1, &stmt, NULL);
    771 	if (rc != SQLITE_OK) {
    772 		if (mflags.verbosity)
    773 			warnx("%s", sqlite3_errmsg(db));
    774 		close_db(db);
    775 		errx(EXIT_FAILURE, "Could not query file cache");
    776 	}
    777 
    778 	buf = NULL;
    779 	rows = NULL;
    780 	while (sqlite3_step(stmt) == SQLITE_ROW) {
    781 		row = emalloc(sizeof(struct sql_row));
    782 		row->device = sqlite3_column_int64(stmt, 0);
    783 		row->inode = sqlite3_column_int64(stmt, 1);
    784 		row->mtime = sqlite3_column_int64(stmt, 2);
    785 		row->parent = estrdup((const char *) sqlite3_column_text(stmt, 3));
    786 		row->file = estrdup((const char *) sqlite3_column_text(stmt, 4));
    787 		row->next = rows;
    788 		rows = row;
    789 		total_count++;
    790 	}
    791 	sqlite3_finalize(stmt);
    792 
    793 	for ( ; rows != NULL; free(parent), free(file), free(buf)) {
    794 		row = rows;
    795 		rows = rows->next;
    796 
    797 		rec->device = row->device;
    798 		rec->inode = row->inode;
    799 		rec->mtime = row->mtime;
    800 		parent = row->parent;
    801 		file = row->file;
    802 		free(row);
    803 
    804 		if (read_and_decompress(file, &buf, &buflen)) {
    805 			err_count++;
    806 			continue;
    807 		}
    808 		md5_status = check_md5(file, db, "mandb_meta", &md5sum, buf,
    809 		    buflen);
    810 		assert(md5sum != NULL);
    811 		if (md5_status == -1) {
    812 			if (mflags.verbosity)
    813 				warnx("An error occurred in checking md5 value"
    814 			      " for file %s", file);
    815 			err_count++;
    816 			continue;
    817 		}
    818 
    819 		if (md5_status == 0) {
    820 			/*
    821 			 * The MD5 hash is already present in the database,
    822 			 * so simply update the metadata, ignoring symlinks.
    823 			 */
    824 			struct stat sb;
    825 			stat(file, &sb);
    826 			if (S_ISLNK(sb.st_mode)) {
    827 				free(md5sum);
    828 				link_count++;
    829 				continue;
    830 			}
    831 			update_existing_entry(db, file, md5sum, rec,
    832 			    &new_count, &link_count, &err_count);
    833 			free(md5sum);
    834 			continue;
    835 		}
    836 
    837 		if (md5_status == 1) {
    838 			/*
    839 			 * The MD5 hash was not present in the database.
    840 			 * This means is either a new file or an updated file.
    841 			 * We should go ahead with parsing.
    842 			 */
    843 			if (chdir(parent) == -1) {
    844 				if (mflags.verbosity)
    845 					warn("chdir failed for `%s', could "
    846 					    "not index `%s'", parent, file);
    847 				err_count++;
    848 				free(md5sum);
    849 				continue;
    850 			}
    851 
    852 			if (mflags.verbosity == 2)
    853 				printf("Parsing: %s\n", file);
    854 			rec->md5_hash = md5sum;
    855 			rec->file_path = estrdup(file);
    856 			// file_path is freed by insert_into_db itself.
    857 			begin_parse(file, mp, rec, buf, buflen);
    858 			if (insert_into_db(db, rec) < 0) {
    859 				if (mflags.verbosity)
    860 					warnx("Error in indexing `%s'", file);
    861 				err_count++;
    862 			} else {
    863 				new_count++;
    864 			}
    865 		}
    866 	}
    867 
    868 	if (mflags.verbosity == 2) {
    869 		printf("Total Number of new or updated pages encountered = %d\n"
    870 		    "Total number of (hard or symbolic) links found = %d\n"
    871 		    "Total number of pages that were successfully"
    872 		    " indexed/updated = %d\n"
    873 		    "Total number of pages that could not be indexed"
    874 		    " due to errors = %d\n",
    875 		    total_count - link_count, link_count, new_count, err_count);
    876 	}
    877 
    878 	if (mflags.recreate)
    879 		return;
    880 
    881 	if (mflags.verbosity == 2)
    882 		printf("Deleting stale index entries\n");
    883 
    884 	sqlstr = "DELETE FROM mandb_meta WHERE file NOT IN"
    885 		 " (SELECT file FROM metadb.file_cache);"
    886 		 "DELETE FROM mandb_links WHERE md5_hash NOT IN"
    887 		 " (SELECT md5_hash from mandb_meta);"
    888 		 "DROP TABLE metadb.file_cache;"
    889 		 "DELETE FROM mandb WHERE rowid NOT IN"
    890 		 " (SELECT id FROM mandb_meta);";
    891 
    892 	sqlite3_exec(db, sqlstr, NULL, NULL, &errmsg);
    893 	if (errmsg != NULL) {
    894 		warnx("Removing old entries failed: %s", errmsg);
    895 		warnx("Please rebuild database from scratch with -f.");
    896 		free(errmsg);
    897 		return;
    898 	}
    899 }
    900 
    901 /*
    902  * begin_parse --
    903  *  parses the man page using libmandoc
    904  */
    905 static void
    906 begin_parse(const char *file, struct mparse *mp, mandb_rec *rec,
    907     const void *buf, size_t len)
    908 {
    909 	struct roff_man *roff;
    910 	mparse_reset(mp);
    911 
    912 	rec->xr_found = 0;
    913 
    914 	if (mparse_readmem(mp, buf, len, file) >= MANDOCLEVEL_BADARG) {
    915 		/* Printing this warning at verbosity level 2
    916 		 * because some packages from pkgsrc might trigger several
    917 		 * of such warnings.
    918 		 */
    919 		if (mflags.verbosity == 2)
    920 			warnx("%s: Parse failure", file);
    921 		return;
    922 	}
    923 
    924 	mparse_result(mp, &roff, NULL);
    925 	if (roff == NULL) {
    926 		if (mflags.verbosity == 2)
    927 			warnx("Not a roff(7) page");
    928 		return;
    929 	}
    930 
    931 	set_machine(roff, rec);
    932 	set_section(roff, rec);
    933 	if (roff->macroset == MACROSET_MDOC) {
    934 		rec->page_type = MDOC;
    935 		proff_node(roff->first->child, rec, mdocs);
    936 	} else if (roff->macroset == MACROSET_MAN) {
    937 		rec->page_type = MAN;
    938 		proff_node(roff->first->child, rec, mans);
    939 	} else
    940 		warnx("Unknown macroset %d", roff->macroset);
    941 }
    942 
    943 /*
    944  * set_section --
    945  *  Extracts the section number and normalizes it to only the numeric part
    946  *  (Which should be the first character of the string).
    947  */
    948 static void
    949 set_section(const struct roff_man *rm, mandb_rec *rec)
    950 {
    951 	if (!rm)
    952 		return;
    953 	const struct roff_meta *rm_meta = &rm->meta;
    954 	const char *s = rm_meta->msec == NULL ? "?" : rm_meta->msec;
    955 	easprintf(&rec->section, "%s", s);
    956 	if (rec->section[0] == '?' && mflags.verbosity == 2)
    957 		warnx("%s: Missing section number", rec->file_path);
    958 }
    959 
    960 /*
    961  * get_machine --
    962  *  Extracts the machine architecture information if available.
    963  */
    964 static void
    965 set_machine(const struct roff_man *rm, mandb_rec *rec)
    966 {
    967 	if (rm == NULL)
    968 		return;
    969 	const struct roff_meta *rm_meta = &rm->meta;
    970 	const char *a = rm_meta->arch == NULL ? "?" : rm_meta->arch;
    971 	rec->machine = estrdup(a);
    972 }
    973 
    974 /*
    975  * pmdoc_Nm --
    976  *  Extracts the Name of the manual page from the .Nm macro
    977  */
    978 static void
    979 pmdoc_Nm(const struct roff_node *n, mandb_rec *rec)
    980 {
    981 	if (n->sec != SEC_NAME)
    982 		return;
    983 
    984 	for (n = n->child; n; n = n->next) {
    985 		if (n->type == ROFFT_TEXT) {
    986 			char *escaped_name = parse_escape(n->string);
    987 			concat(&rec->name, escaped_name);
    988 			free(escaped_name);
    989 		}
    990 	}
    991 }
    992 
    993 /*
    994  * pmdoc_Nd --
    995  *  Extracts the one line description of the man page from the .Nd macro
    996  */
    997 static void
    998 pmdoc_Nd(const struct roff_node *n, mandb_rec *rec)
    999 {
   1000 	char *buf = NULL;
   1001 	char *name;
   1002 	char *nd_text;
   1003 
   1004 	if (n == NULL || (n->type != ROFFT_TEXT && n->tok == MDOC_MAX))
   1005 		return;
   1006 
   1007 	if (n->type == ROFFT_TEXT) {
   1008 		if (rec->xr_found && n->next) {
   1009 			/*
   1010 			 * An Xr macro was seen previously, so parse this
   1011 			 * and the next node, as "Name(Section)".
   1012 			 */
   1013 			name = n->string;
   1014 			n = n->next;
   1015 			assert(n->type == ROFFT_TEXT);
   1016 			easprintf(&buf, "%s(%s)", name, n->string);
   1017 			concat(&rec->name_desc, buf);
   1018 			free(buf);
   1019 		} else {
   1020 			nd_text = parse_escape(n->string);
   1021 			concat(&rec->name_desc, nd_text);
   1022 			free(nd_text);
   1023 		}
   1024 		rec->xr_found = 0;
   1025 	} else if (mdocs[n->tok] == pmdoc_Xr) {
   1026 		/* Remember that we have encountered an Xr macro */
   1027 		rec->xr_found = 1;
   1028 	}
   1029 
   1030 	if (n->child)
   1031 		pmdoc_Nd(n->child, rec);
   1032 
   1033 	if(n->next)
   1034 		pmdoc_Nd(n->next, rec);
   1035 }
   1036 
   1037 /*
   1038  * pmdoc_macro_handler--
   1039  *  This function is a single point of handling all the special macros that we
   1040  *  want to handle especially. For example the .Xr macro for properly parsing
   1041  *  the referenced page name along with the section number, or the .Pp macro
   1042  *  for adding a new line whenever we encounter it.
   1043  */
   1044 static void
   1045 pmdoc_macro_handler(const struct roff_node *n, mandb_rec *rec, int doct)
   1046 {
   1047 	const struct roff_node *sn;
   1048 	assert(n);
   1049 
   1050 	switch (doct) {
   1051 	/*  Parse the man page references.
   1052 	 * Basically the .Xr macros are used like:
   1053 	 *  .Xr ls 1
   1054  	 *  and formatted like this:
   1055 	 *  ls(1)
   1056 	 *  Prepare a buffer to format the data like the above example and call
   1057 	 *  pmdoc_parse_section to append it.
   1058 	 */
   1059 	case MDOC_Xr:
   1060 		n = n->child;
   1061 		while (n->type != ROFFT_TEXT && n->next)
   1062 			n = n->next;
   1063 
   1064 		if (n && n->type != ROFFT_TEXT)
   1065 			return;
   1066 		sn = n;
   1067 		if (n->next)
   1068 			n = n->next;
   1069 
   1070 		while (n->type != ROFFT_TEXT && n->next)
   1071 			n = n->next;
   1072 
   1073 		if (n && n->type == ROFFT_TEXT) {
   1074 			char *buf;
   1075 			easprintf(&buf, "%s(%s)", sn->string, n->string);
   1076 			mdoc_parse_section(n->sec, buf, rec);
   1077 			free(buf);
   1078 		}
   1079 
   1080 		break;
   1081 
   1082 	/* Parse the .Pp macro to add a new line */
   1083 	case MDOC_Pp:
   1084 		if (n->type == ROFFT_TEXT)
   1085 			mdoc_parse_section(n->sec, "\n", rec);
   1086 		break;
   1087 	default:
   1088 		break;
   1089 	}
   1090 
   1091 }
   1092 
   1093 /*
   1094  * pmdoc_Xr, pmdoc_Pp--
   1095  *  Empty stubs.
   1096  *  The parser calls these functions each time it encounters
   1097  *  a .Xr or .Pp macro. We are parsing all the data from
   1098  *  the pmdoc_Sh function, so don't do anything here.
   1099  *  (See if else blocks in pmdoc_Sh.)
   1100  */
   1101 static void
   1102 pmdoc_Xr(const struct roff_node *n, mandb_rec *rec)
   1103 {
   1104 }
   1105 
   1106 static void
   1107 pmdoc_Pp(const struct roff_node *n, mandb_rec *rec)
   1108 {
   1109 }
   1110 
   1111 /*
   1112  * pmdoc_Sh --
   1113  *  Called when a .Sh macro is encountered and loops through its body, calling
   1114  *  mdoc_parse_section to append the data to the section specific buffer.
   1115  *  Two special macros which may occur inside the body of Sh are .Nm and .Xr and
   1116  *  they need special handling, thus the separate if branches for them.
   1117  */
   1118 static void
   1119 pmdoc_Sh(const struct roff_node *n, mandb_rec *rec)
   1120 {
   1121 	if (n == NULL || (n->type != ROFFT_TEXT && n->tok == MDOC_MAX))
   1122 		return;
   1123 	int xr_found = 0;
   1124 
   1125 	if (n->type == ROFFT_TEXT) {
   1126 		mdoc_parse_section(n->sec, n->string, rec);
   1127 	} else if (mdocs[n->tok] == pmdoc_Nm && rec->name != NULL) {
   1128 		/*
   1129 		 * When encountering a .Nm macro, substitute it
   1130 		 * with its previously cached value of the argument.
   1131 		 */
   1132 		mdoc_parse_section(n->sec, rec->name, rec);
   1133 	} else if (mdocs[n->tok] == pmdoc_Xr) {
   1134 		/*
   1135 		 * When encountering other inline macros,
   1136 		 * call pmdoc_macro_handler.
   1137 		 */
   1138 		pmdoc_macro_handler(n, rec, MDOC_Xr);
   1139 		xr_found = 1;
   1140 	} else if (mdocs[n->tok] == pmdoc_Pp) {
   1141 		pmdoc_macro_handler(n, rec, MDOC_Pp);
   1142 	}
   1143 
   1144 	/*
   1145 	 * If an Xr macro was encountered then the child node has
   1146 	 * already been explored by pmdoc_macro_handler.
   1147 	 */
   1148 	if (xr_found == 0)
   1149 		pmdoc_Sh(n->child, rec);
   1150 	pmdoc_Sh(n->next, rec);
   1151 }
   1152 
   1153 /*
   1154  * mdoc_parse_section--
   1155  *  Utility function for parsing sections of the mdoc type pages.
   1156  *  Takes two params:
   1157  *   1. sec is an enum which indicates the section in which we are present
   1158  *   2. string is the string which we need to append to the secbuff for this
   1159  *      particular section.
   1160  *  The function appends string to the global section buffer and returns.
   1161  */
   1162 static void
   1163 mdoc_parse_section(enum roff_sec sec, const char *string, mandb_rec *rec)
   1164 {
   1165 	/*
   1166 	 * If the user specified the 'l' flag, then parse and store only the
   1167 	 * NAME section. Ignore the rest.
   1168 	 */
   1169 	if (mflags.limit)
   1170 		return;
   1171 
   1172 	switch (sec) {
   1173 	case SEC_LIBRARY:
   1174 		append(&rec->lib, string);
   1175 		break;
   1176 	case SEC_RETURN_VALUES:
   1177 		append(&rec->return_vals, string);
   1178 		break;
   1179 	case SEC_ENVIRONMENT:
   1180 		append(&rec->env, string);
   1181 		break;
   1182 	case SEC_FILES:
   1183 		append(&rec->files, string);
   1184 		break;
   1185 	case SEC_EXIT_STATUS:
   1186 		append(&rec->exit_status, string);
   1187 		break;
   1188 	case SEC_DIAGNOSTICS:
   1189 		append(&rec->diagnostics, string);
   1190 		break;
   1191 	case SEC_ERRORS:
   1192 		append(&rec->errors, string);
   1193 		break;
   1194 	case SEC_NAME:
   1195 	case SEC_SYNOPSIS:
   1196 	case SEC_EXAMPLES:
   1197 	case SEC_STANDARDS:
   1198 	case SEC_HISTORY:
   1199 	case SEC_AUTHORS:
   1200 	case SEC_BUGS:
   1201 		break;
   1202 	default:
   1203 		append(&rec->desc, string);
   1204 		break;
   1205 	}
   1206 }
   1207 
   1208 static void
   1209 proff_node(const struct roff_node *n, mandb_rec *rec, const proff_nf *func)
   1210 {
   1211 	if (n == NULL)
   1212 		return;
   1213 
   1214 	switch (n->type) {
   1215 	case (ROFFT_BODY):
   1216 		/* FALLTHROUGH */
   1217 	case (ROFFT_BLOCK):
   1218 		/* FALLTHROUGH */
   1219 	case (ROFFT_ELEM):
   1220 		if (func[n->tok] != NULL)
   1221 			(*func[n->tok])(n, rec);
   1222 		break;
   1223 	default:
   1224 		break;
   1225 	}
   1226 
   1227 	proff_node(n->child, rec, func);
   1228 	proff_node(n->next, rec, func);
   1229 }
   1230 
   1231 /*
   1232  * pman_parse_name --
   1233  *  Parses the NAME section and puts the complete content in the name_desc
   1234  *  variable.
   1235  */
   1236 static void
   1237 pman_parse_name(const struct roff_node *n, mandb_rec *rec)
   1238 {
   1239 	if (n == NULL)
   1240 		return;
   1241 
   1242 	if (n->type == ROFFT_TEXT) {
   1243 		char *tmp = parse_escape(n->string);
   1244 		concat(&rec->name_desc, tmp);
   1245 		free(tmp);
   1246 	}
   1247 
   1248 	if (n->child)
   1249 		pman_parse_name(n->child, rec);
   1250 
   1251 	if(n->next)
   1252 		pman_parse_name(n->next, rec);
   1253 }
   1254 
   1255 /*
   1256  * A stub function to be able to parse the macros like .B embedded inside
   1257  * a section.
   1258  */
   1259 static void
   1260 pman_block(const struct roff_node *n, mandb_rec *rec)
   1261 {
   1262 }
   1263 
   1264 /*
   1265  * pman_sh --
   1266  * This function does one of the two things:
   1267  *  1. If the present section is NAME, then it will:
   1268  *    (a) Extract the name of the page (in case of multiple comma separated
   1269  *        names, it will pick up the first one).
   1270  *    (b) Build a space spearated list of all the symlinks/hardlinks to
   1271  *        this page and store in the buffer 'links'. These are extracted from
   1272  *        the comma separated list of names in the NAME section as well.
   1273  *    (c) Move on to the one line description section, which is after the list
   1274  *        of names in the NAME section.
   1275  *  2. Otherwise, it will check the section name and call the man_parse_section
   1276  *     function, passing the enum corresponding to that section.
   1277  */
   1278 static void
   1279 pman_sh(const struct roff_node *n, mandb_rec *rec)
   1280 {
   1281 	static const struct {
   1282 		enum man_sec section;
   1283 		const char *header;
   1284 	} mapping[] = {
   1285 	    { MANSEC_DESCRIPTION, "DESCRIPTION" },
   1286 	    { MANSEC_SYNOPSIS, "SYNOPSIS" },
   1287 	    { MANSEC_LIBRARY, "LIBRARY" },
   1288 	    { MANSEC_ERRORS, "ERRORS" },
   1289 	    { MANSEC_FILES, "FILES" },
   1290 	    { MANSEC_RETURN_VALUES, "RETURN VALUE" },
   1291 	    { MANSEC_RETURN_VALUES, "RETURN VALUES" },
   1292 	    { MANSEC_EXIT_STATUS, "EXIT STATUS" },
   1293 	    { MANSEC_EXAMPLES, "EXAMPLES" },
   1294 	    { MANSEC_EXAMPLES, "EXAMPLE" },
   1295 	    { MANSEC_STANDARDS, "STANDARDS" },
   1296 	    { MANSEC_HISTORY, "HISTORY" },
   1297 	    { MANSEC_BUGS, "BUGS" },
   1298 	    { MANSEC_AUTHORS, "AUTHORS" },
   1299 	    { MANSEC_COPYRIGHT, "COPYRIGHT" },
   1300 	};
   1301 	const struct roff_node *head;
   1302 	char *name_desc;
   1303 	size_t sz;
   1304 	size_t i;
   1305 
   1306 	if ((head = n->parent->head) == NULL || (head = head->child) == NULL ||
   1307 	    head->type != ROFFT_TEXT)
   1308 		return;
   1309 
   1310 	/*
   1311 	 * Check if this section should be extracted and
   1312 	 * where it should be stored. Handled the trival cases first.
   1313 	 */
   1314 	for (i = 0; i < sizeof(mapping) / sizeof(mapping[0]); ++i) {
   1315 		if (strcmp(head->string, mapping[i].header) == 0) {
   1316 			man_parse_section(mapping[i].section, n, rec);
   1317 			return;
   1318 		}
   1319 	}
   1320 
   1321 	if (strcmp(head->string, "NAME") == 0) {
   1322 		/*
   1323 		 * We are in the NAME section.
   1324 		 * pman_parse_name will put the complete content in name_desc.
   1325 		 */
   1326 		pman_parse_name(n, rec);
   1327 
   1328 		name_desc = rec->name_desc;
   1329 		if (name_desc == NULL)
   1330 			return;
   1331 
   1332 		/* Remove any leading spaces. */
   1333 		while (name_desc[0] == ' ')
   1334 			name_desc++;
   1335 
   1336 		/* If the line begins with a "\&", avoid those */
   1337 		if (name_desc[0] == '\\' && name_desc[1] == '&')
   1338 			name_desc += 2;
   1339 
   1340 		/* Now name_desc should be left with a comma-space
   1341 		 * separated list of names and the one line description
   1342 		 * of the page:
   1343 		 *     "a, b, c \- sample description"
   1344 		 * Take out the first name, before the first comma
   1345 		 * (or space) and store it in rec->name.
   1346 		 * If the page has aliases then they should be
   1347 		 * in the form of a comma separated list.
   1348 		 * Keep looping while there is a comma in name_desc,
   1349 		 * extract the alias name and store in rec->links.
   1350 		 * When there are no more commas left, break out.
   1351 		 */
   1352 		int has_alias = 0;	// Any more aliases left?
   1353 		while (*name_desc) {
   1354 			/* Remove any leading spaces or hyphens. */
   1355 			if (name_desc[0] == ' ' || name_desc[0] == '-') {
   1356 				name_desc++;
   1357 				continue;
   1358 			}
   1359 			sz = strcspn(name_desc, ", ");
   1360 
   1361 			/* Extract the first term and store it in rec->name. */
   1362 			if (rec->name == NULL) {
   1363 				if (name_desc[sz] == ',')
   1364 					has_alias = 1;
   1365 				rec->name = estrndup(name_desc, sz);
   1366 				/* XXX This would only happen with a poorly
   1367 				 * written man page, maybe warn? */
   1368 				if (name_desc[sz] == '\0')
   1369 					break;
   1370 				name_desc += sz + 1;
   1371 				continue;
   1372 			}
   1373 
   1374 			/*
   1375 			 * Once rec->name is set, rest of the names
   1376 			 * are to be treated as links or aliases.
   1377 			 */
   1378 			if (rec->name && has_alias) {
   1379 				if (name_desc[sz] != ',') {
   1380 					/* No more commas left --> no more
   1381 					 * aliases to take out */
   1382 					has_alias = 0;
   1383 				}
   1384 				concat2(&rec->links, name_desc, sz);
   1385 				/* XXX This would only happen with a poorly
   1386 				 * written man page, maybe warn? */
   1387 				if (name_desc[sz] == '\0')
   1388 					break;
   1389 				name_desc += sz + 1;
   1390 				continue;
   1391 			}
   1392 			break;
   1393 		}
   1394 
   1395 		/* Parse any escape sequences that might be there */
   1396 		char *temp = parse_escape(name_desc);
   1397 		free(rec->name_desc);
   1398 		rec->name_desc = temp;
   1399 		temp = parse_escape(rec->name);
   1400 		free(rec->name);
   1401 		rec->name = temp;
   1402 		return;
   1403 	}
   1404 
   1405 	/* The RETURN VALUE section might be specified in multiple ways */
   1406 	if (strcmp(head->string, "RETURN") == 0 &&
   1407 	    head->next != NULL && head->next->type == ROFFT_TEXT &&
   1408 	    (strcmp(head->next->string, "VALUE") == 0 ||
   1409 	    strcmp(head->next->string, "VALUES") == 0)) {
   1410 		man_parse_section(MANSEC_RETURN_VALUES, n, rec);
   1411 		return;
   1412 	}
   1413 
   1414 	/*
   1415 	 * EXIT STATUS section can also be specified all on one line or on two
   1416 	 * separate lines.
   1417 	 */
   1418 	if (strcmp(head->string, "EXIT") == 0 &&
   1419 	    head->next != NULL && head->next->type == ROFFT_TEXT &&
   1420 	    strcmp(head->next->string, "STATUS") == 0) {
   1421 		man_parse_section(MANSEC_EXIT_STATUS, n, rec);
   1422 		return;
   1423 	}
   1424 
   1425 	/* Store the rest of the content in desc. */
   1426 	man_parse_section(MANSEC_NONE, n, rec);
   1427 }
   1428 
   1429 /*
   1430  * pman_parse_node --
   1431  *  Generic function to iterate through a node. Usually called from
   1432  *  man_parse_section to parse a particular section of the man page.
   1433  */
   1434 static void
   1435 pman_parse_node(const struct roff_node *n, secbuff *s)
   1436 {
   1437 	if (n == NULL)
   1438 		return;
   1439 
   1440 	if (n->type == ROFFT_TEXT)
   1441 		append(s, n->string);
   1442 
   1443 	pman_parse_node(n->child, s);
   1444 	pman_parse_node(n->next, s);
   1445 }
   1446 
   1447 /*
   1448  * man_parse_section --
   1449  *  Takes two parameters:
   1450  *   sec: Tells which section we are present in
   1451  *   n: Is the present node of the AST.
   1452  * Depending on the section, we call pman_parse_node to parse that section and
   1453  * concatenate the content from that section into the buffer for that section.
   1454  */
   1455 static void
   1456 man_parse_section(enum man_sec sec, const struct roff_node *n, mandb_rec *rec)
   1457 {
   1458 	/*
   1459 	 * If the user sepecified the 'l' flag then just parse
   1460 	 * the NAME section, ignore the rest.
   1461 	 */
   1462 	if (mflags.limit)
   1463 		return;
   1464 
   1465 	switch (sec) {
   1466 	case MANSEC_LIBRARY:
   1467 		pman_parse_node(n, &rec->lib);
   1468 		break;
   1469 	case MANSEC_RETURN_VALUES:
   1470 		pman_parse_node(n, &rec->return_vals);
   1471 		break;
   1472 	case MANSEC_ENVIRONMENT:
   1473 		pman_parse_node(n, &rec->env);
   1474 		break;
   1475 	case MANSEC_FILES:
   1476 		pman_parse_node(n, &rec->files);
   1477 		break;
   1478 	case MANSEC_EXIT_STATUS:
   1479 		pman_parse_node(n, &rec->exit_status);
   1480 		break;
   1481 	case MANSEC_DIAGNOSTICS:
   1482 		pman_parse_node(n, &rec->diagnostics);
   1483 		break;
   1484 	case MANSEC_ERRORS:
   1485 		pman_parse_node(n, &rec->errors);
   1486 		break;
   1487 	case MANSEC_NAME:
   1488 	case MANSEC_SYNOPSIS:
   1489 	case MANSEC_EXAMPLES:
   1490 	case MANSEC_STANDARDS:
   1491 	case MANSEC_HISTORY:
   1492 	case MANSEC_BUGS:
   1493 	case MANSEC_AUTHORS:
   1494 	case MANSEC_COPYRIGHT:
   1495 		break;
   1496 	default:
   1497 		pman_parse_node(n, &rec->desc);
   1498 		break;
   1499 	}
   1500 
   1501 }
   1502 
   1503 /*
   1504  * insert_into_db --
   1505  *  Inserts the parsed data of the man page in the Sqlite databse.
   1506  *  If any of the values is NULL, then we cleanup and return -1 indicating
   1507  *  an error.
   1508  *  Otherwise, store the data in the database and return 0.
   1509  */
   1510 static int
   1511 insert_into_db(sqlite3 *db, mandb_rec *rec)
   1512 {
   1513 	int rc = 0;
   1514 	int idx = -1;
   1515 	const char *sqlstr = NULL;
   1516 	sqlite3_stmt *stmt = NULL;
   1517 	char *ln = NULL;
   1518 	char *errmsg = NULL;
   1519 	long int mandb_rowid;
   1520 
   1521 	/*
   1522 	 * At the very minimum we want to make sure that we store
   1523 	 * the following data:
   1524 	 *   Name, one line description, and the MD5 hash
   1525 	 */
   1526 	if (rec->name == NULL || rec->name_desc == NULL ||
   1527 	    rec->md5_hash == NULL) {
   1528 		cleanup(rec);
   1529 		return -1;
   1530 	}
   1531 
   1532 	/* Write null byte at the end of all the sec_buffs */
   1533 	rec->desc.data[rec->desc.offset] = 0;
   1534 	rec->lib.data[rec->lib.offset] = 0;
   1535 	rec->env.data[rec->env.offset] = 0;
   1536 	rec->return_vals.data[rec->return_vals.offset] = 0;
   1537 	rec->exit_status.data[rec->exit_status.offset] = 0;
   1538 	rec->files.data[rec->files.offset] = 0;
   1539 	rec->diagnostics.data[rec->diagnostics.offset] = 0;
   1540 	rec->errors.data[rec->errors.offset] = 0;
   1541 
   1542 	/*
   1543 	 * In case of a mdoc page: (sorry, no better place to put this code)
   1544 	 * parse the comma separated list of names of man pages,
   1545 	 * the first name will be stored in the mandb table, rest will be
   1546 	 * treated as links and put in the mandb_links table.
   1547 	 */
   1548 	if (rec->page_type == MDOC) {
   1549 		char *tmp;
   1550 		rec->links = estrdup(rec->name);
   1551 		free(rec->name);
   1552 		size_t sz = strcspn(rec->links, " \0");
   1553 		rec->name = emalloc(sz + 1);
   1554 		memcpy(rec->name, rec->links, sz);
   1555 		if(rec->name[sz - 1] == ',')
   1556 			rec->name[sz - 1] = 0;
   1557 		else
   1558 			rec->name[sz] = 0;
   1559 		while (rec->links[sz] == ' ')
   1560 			++sz;
   1561 		tmp = estrdup(rec->links + sz);
   1562 		free(rec->links);
   1563 		rec->links = tmp;
   1564 	}
   1565 
   1566 /*------------------------ Populate the mandb table---------------------------*/
   1567 	sqlstr = "INSERT INTO mandb VALUES (:section, :name, :name_desc, :desc,"
   1568 		 " :lib, :return_vals, :env, :files, :exit_status,"
   1569 		 " :diagnostics, :errors, :md5_hash, :machine)";
   1570 
   1571 	rc = sqlite3_prepare_v2(db, sqlstr, -1, &stmt, NULL);
   1572 	if (rc != SQLITE_OK)
   1573 		goto Out;
   1574 
   1575 	idx = sqlite3_bind_parameter_index(stmt, ":name");
   1576 	rc = sqlite3_bind_text(stmt, idx, rec->name, -1, NULL);
   1577 	if (rc != SQLITE_OK) {
   1578 		sqlite3_finalize(stmt);
   1579 		goto Out;
   1580 	}
   1581 
   1582 	idx = sqlite3_bind_parameter_index(stmt, ":section");
   1583 	rc = sqlite3_bind_text(stmt, idx, rec->section, -1, NULL);
   1584 	if (rc != SQLITE_OK) {
   1585 		sqlite3_finalize(stmt);
   1586 		goto Out;
   1587 	}
   1588 
   1589 	idx = sqlite3_bind_parameter_index(stmt, ":name_desc");
   1590 	rc = sqlite3_bind_text(stmt, idx, rec->name_desc, -1, NULL);
   1591 	if (rc != SQLITE_OK) {
   1592 		sqlite3_finalize(stmt);
   1593 		goto Out;
   1594 	}
   1595 
   1596 	idx = sqlite3_bind_parameter_index(stmt, ":desc");
   1597 	rc = sqlite3_bind_text(stmt, idx, rec->desc.data,
   1598 	                       rec->desc.offset + 1, NULL);
   1599 	if (rc != SQLITE_OK) {
   1600 		sqlite3_finalize(stmt);
   1601 		goto Out;
   1602 	}
   1603 
   1604 	idx = sqlite3_bind_parameter_index(stmt, ":lib");
   1605 	rc = sqlite3_bind_text(stmt, idx, rec->lib.data,
   1606 	    rec->lib.offset + 1, NULL);
   1607 	if (rc != SQLITE_OK) {
   1608 		sqlite3_finalize(stmt);
   1609 		goto Out;
   1610 	}
   1611 
   1612 	idx = sqlite3_bind_parameter_index(stmt, ":return_vals");
   1613 	rc = sqlite3_bind_text(stmt, idx, rec->return_vals.data,
   1614 	                      rec->return_vals.offset + 1, NULL);
   1615 	if (rc != SQLITE_OK) {
   1616 		sqlite3_finalize(stmt);
   1617 		goto Out;
   1618 	}
   1619 
   1620 	idx = sqlite3_bind_parameter_index(stmt, ":env");
   1621 	rc = sqlite3_bind_text(stmt, idx, rec->env.data,
   1622 	    rec->env.offset + 1, NULL);
   1623 	if (rc != SQLITE_OK) {
   1624 		sqlite3_finalize(stmt);
   1625 		goto Out;
   1626 	}
   1627 
   1628 	idx = sqlite3_bind_parameter_index(stmt, ":files");
   1629 	rc = sqlite3_bind_text(stmt, idx, rec->files.data,
   1630 	                       rec->files.offset + 1, NULL);
   1631 	if (rc != SQLITE_OK) {
   1632 		sqlite3_finalize(stmt);
   1633 		goto Out;
   1634 	}
   1635 
   1636 	idx = sqlite3_bind_parameter_index(stmt, ":exit_status");
   1637 	rc = sqlite3_bind_text(stmt, idx, rec->exit_status.data,
   1638 	                       rec->exit_status.offset + 1, NULL);
   1639 	if (rc != SQLITE_OK) {
   1640 		sqlite3_finalize(stmt);
   1641 		goto Out;
   1642 	}
   1643 
   1644 	idx = sqlite3_bind_parameter_index(stmt, ":diagnostics");
   1645 	rc = sqlite3_bind_text(stmt, idx, rec->diagnostics.data,
   1646 	                       rec->diagnostics.offset + 1, NULL);
   1647 	if (rc != SQLITE_OK) {
   1648 		sqlite3_finalize(stmt);
   1649 		goto Out;
   1650 	}
   1651 
   1652 	idx = sqlite3_bind_parameter_index(stmt, ":errors");
   1653 	rc = sqlite3_bind_text(stmt, idx, rec->errors.data,
   1654 	                       rec->errors.offset + 1, NULL);
   1655 	if (rc != SQLITE_OK) {
   1656 		sqlite3_finalize(stmt);
   1657 		goto Out;
   1658 	}
   1659 
   1660 	idx = sqlite3_bind_parameter_index(stmt, ":md5_hash");
   1661 	rc = sqlite3_bind_text(stmt, idx, rec->md5_hash, -1, NULL);
   1662 	if (rc != SQLITE_OK) {
   1663 		sqlite3_finalize(stmt);
   1664 		goto Out;
   1665 	}
   1666 
   1667 	idx = sqlite3_bind_parameter_index(stmt, ":machine");
   1668 	if (rec->machine)
   1669 		rc = sqlite3_bind_text(stmt, idx, rec->machine, -1, NULL);
   1670 	else
   1671 		rc = sqlite3_bind_null(stmt, idx);
   1672 	if (rc != SQLITE_OK) {
   1673 		sqlite3_finalize(stmt);
   1674 		goto Out;
   1675 	}
   1676 
   1677 	rc = sqlite3_step(stmt);
   1678 	if (rc != SQLITE_DONE) {
   1679 		sqlite3_finalize(stmt);
   1680 		goto Out;
   1681 	}
   1682 
   1683 	sqlite3_finalize(stmt);
   1684 
   1685 	/* Get the row id of the last inserted row */
   1686 	mandb_rowid = sqlite3_last_insert_rowid(db);
   1687 
   1688 /*------------------------Populate the mandb_meta table-----------------------*/
   1689 	sqlstr = "INSERT INTO mandb_meta VALUES (:device, :inode, :mtime,"
   1690 		 " :file, :md5_hash, :id)";
   1691 	rc = sqlite3_prepare_v2(db, sqlstr, -1, &stmt, NULL);
   1692 	if (rc != SQLITE_OK)
   1693 		goto Out;
   1694 
   1695 	idx = sqlite3_bind_parameter_index(stmt, ":device");
   1696 	rc = sqlite3_bind_int64(stmt, idx, rec->device);
   1697 	if (rc != SQLITE_OK) {
   1698 		sqlite3_finalize(stmt);
   1699 		goto Out;
   1700 	}
   1701 
   1702 	idx = sqlite3_bind_parameter_index(stmt, ":inode");
   1703 	rc = sqlite3_bind_int64(stmt, idx, rec->inode);
   1704 	if (rc != SQLITE_OK) {
   1705 		sqlite3_finalize(stmt);
   1706 		goto Out;
   1707 	}
   1708 
   1709 	idx = sqlite3_bind_parameter_index(stmt, ":mtime");
   1710 	rc = sqlite3_bind_int64(stmt, idx, rec->mtime);
   1711 	if (rc != SQLITE_OK) {
   1712 		sqlite3_finalize(stmt);
   1713 		goto Out;
   1714 	}
   1715 
   1716 	idx = sqlite3_bind_parameter_index(stmt, ":file");
   1717 	rc = sqlite3_bind_text(stmt, idx, rec->file_path, -1, NULL);
   1718 	if (rc != SQLITE_OK) {
   1719 		sqlite3_finalize(stmt);
   1720 		goto Out;
   1721 	}
   1722 
   1723 	idx = sqlite3_bind_parameter_index(stmt, ":md5_hash");
   1724 	rc = sqlite3_bind_text(stmt, idx, rec->md5_hash, -1, NULL);
   1725 	if (rc != SQLITE_OK) {
   1726 		sqlite3_finalize(stmt);
   1727 		goto Out;
   1728 	}
   1729 
   1730 	idx = sqlite3_bind_parameter_index(stmt, ":id");
   1731 	rc = sqlite3_bind_int64(stmt, idx, mandb_rowid);
   1732 	if (rc != SQLITE_OK) {
   1733 		sqlite3_finalize(stmt);
   1734 		goto Out;
   1735 	}
   1736 
   1737 	rc = sqlite3_step(stmt);
   1738 	sqlite3_finalize(stmt);
   1739 	if (rc == SQLITE_CONSTRAINT_UNIQUE) {
   1740 		/* The *most* probable reason for reaching here is that
   1741 		 * the UNIQUE contraint on the file column of the mandb_meta
   1742 		 * table was violated.
   1743 		 * This can happen when a file was updated/modified.
   1744 		 * To fix this we need to do two things:
   1745 		 * 1. Delete the row for the older version of this file
   1746 		 *    from mandb table.
   1747 		 * 2. Run an UPDATE query to update the row for this file
   1748 		 *    in the mandb_meta table.
   1749 		 */
   1750 		warnx("Trying to update index for %s", rec->file_path);
   1751 		char *sql = sqlite3_mprintf("DELETE FROM mandb "
   1752 					    "WHERE rowid = (SELECT id"
   1753 					    "  FROM mandb_meta"
   1754 					    "  WHERE file = %Q)",
   1755 					    rec->file_path);
   1756 		sqlite3_exec(db, sql, NULL, NULL, &errmsg);
   1757 		sqlite3_free(sql);
   1758 		if (errmsg != NULL) {
   1759 			if (mflags.verbosity)
   1760 				warnx("%s", errmsg);
   1761 			free(errmsg);
   1762 		}
   1763 		sqlstr = "UPDATE mandb_meta SET device = :device,"
   1764 			 " inode = :inode, mtime = :mtime, id = :id,"
   1765 			 " md5_hash = :md5 WHERE file = :file";
   1766 		rc = sqlite3_prepare_v2(db, sqlstr, -1, &stmt, NULL);
   1767 		if (rc != SQLITE_OK) {
   1768 			if (mflags.verbosity)
   1769 				warnx("Update failed with error: %s",
   1770 			    sqlite3_errmsg(db));
   1771 			close_db(db);
   1772 			cleanup(rec);
   1773 			errx(EXIT_FAILURE,
   1774 			    "Consider running makemandb with -f option");
   1775 		}
   1776 
   1777 		idx = sqlite3_bind_parameter_index(stmt, ":device");
   1778 		sqlite3_bind_int64(stmt, idx, rec->device);
   1779 		idx = sqlite3_bind_parameter_index(stmt, ":inode");
   1780 		sqlite3_bind_int64(stmt, idx, rec->inode);
   1781 		idx = sqlite3_bind_parameter_index(stmt, ":mtime");
   1782 		sqlite3_bind_int64(stmt, idx, rec->mtime);
   1783 		idx = sqlite3_bind_parameter_index(stmt, ":id");
   1784 		sqlite3_bind_int64(stmt, idx, mandb_rowid);
   1785 		idx = sqlite3_bind_parameter_index(stmt, ":md5");
   1786 		sqlite3_bind_text(stmt, idx, rec->md5_hash, -1, NULL);
   1787 		idx = sqlite3_bind_parameter_index(stmt, ":file");
   1788 		sqlite3_bind_text(stmt, idx, rec->file_path, -1, NULL);
   1789 		rc = sqlite3_step(stmt);
   1790 		sqlite3_finalize(stmt);
   1791 
   1792 		if (rc != SQLITE_DONE) {
   1793 			if (mflags.verbosity)
   1794 				warnx("%s", sqlite3_errmsg(db));
   1795 			close_db(db);
   1796 			cleanup(rec);
   1797 			errx(EXIT_FAILURE,
   1798 			    "Consider running makemandb with -f option");
   1799 		}
   1800 	} else if (rc != SQLITE_DONE) {
   1801 		/* Otherwise make this error fatal */
   1802 		warnx("Failed at %s\n%s", rec->file_path, sqlite3_errmsg(db));
   1803 		cleanup(rec);
   1804 		close_db(db);
   1805 		exit(EXIT_FAILURE);
   1806 	}
   1807 
   1808 /*------------------------ Populate the mandb_links table---------------------*/
   1809 	char *str = NULL;
   1810 	char *links;
   1811 	if (rec->links && strlen(rec->links)) {
   1812 		links = rec->links;
   1813 		for(ln = strtok(links, " "); ln; ln = strtok(NULL, " ")) {
   1814 			if (ln[0] == ',')
   1815 				ln++;
   1816 			if(ln[strlen(ln) - 1] == ',')
   1817 				ln[strlen(ln) - 1] = 0;
   1818 
   1819 			str = sqlite3_mprintf("INSERT INTO mandb_links"
   1820 					      " VALUES (%Q, %Q, %Q, %Q, %Q)",
   1821 					      ln, rec->name, rec->section,
   1822 					      rec->machine, rec->md5_hash);
   1823 			sqlite3_exec(db, str, NULL, NULL, &errmsg);
   1824 			sqlite3_free(str);
   1825 			if (errmsg != NULL) {
   1826 				warnx("%s", errmsg);
   1827 				cleanup(rec);
   1828 				free(errmsg);
   1829 				return -1;
   1830 			}
   1831 		}
   1832 	}
   1833 
   1834 	cleanup(rec);
   1835 	return 0;
   1836 
   1837   Out:
   1838 	if (mflags.verbosity)
   1839 		warnx("%s", sqlite3_errmsg(db));
   1840 	cleanup(rec);
   1841 	return -1;
   1842 }
   1843 
   1844 /*
   1845  * check_md5--
   1846  *  Generates the md5 hash of the file and checks if it already doesn't exist
   1847  *  in the table (passed as the 3rd parameter).
   1848  *  This function is being used to avoid hardlinks.
   1849  *  On successful completion it will also set the value of the fourth parameter
   1850  *  to the md5 hash of the file (computed previously). It is the responsibility
   1851  *  of the caller to free this buffer.
   1852  *  Return values:
   1853  *  -1: If an error occurs somewhere and sets the md5 return buffer to NULL.
   1854  *  0: If the md5 hash does not exist in the table.
   1855  *  1: If the hash exists in the database.
   1856  */
   1857 static int
   1858 check_md5(const char *file, sqlite3 *db, const char *table, char **md5sum,
   1859     void *buf, size_t buflen)
   1860 {
   1861 	int rc = 0;
   1862 	int idx = -1;
   1863 	char *sqlstr = NULL;
   1864 	sqlite3_stmt *stmt = NULL;
   1865 
   1866 	assert(file != NULL);
   1867 	*md5sum = MD5Data(buf, buflen, NULL);
   1868 	if (*md5sum == NULL) {
   1869 		if (mflags.verbosity)
   1870 			warn("md5 failed: %s", file);
   1871 		return -1;
   1872 	}
   1873 
   1874 	easprintf(&sqlstr, "SELECT * FROM %s WHERE md5_hash = :md5_hash",
   1875 	    table);
   1876 	rc = sqlite3_prepare_v2(db, sqlstr, -1, &stmt, NULL);
   1877 	if (rc != SQLITE_OK) {
   1878 		free(sqlstr);
   1879 		free(*md5sum);
   1880 		*md5sum = NULL;
   1881 		return -1;
   1882 	}
   1883 
   1884 	idx = sqlite3_bind_parameter_index(stmt, ":md5_hash");
   1885 	rc = sqlite3_bind_text(stmt, idx, *md5sum, -1, NULL);
   1886 	if (rc != SQLITE_OK) {
   1887 		if (mflags.verbosity)
   1888 			warnx("%s", sqlite3_errmsg(db));
   1889 		sqlite3_finalize(stmt);
   1890 		free(sqlstr);
   1891 		free(*md5sum);
   1892 		*md5sum = NULL;
   1893 		return -1;
   1894 	}
   1895 
   1896 	if (sqlite3_step(stmt) == SQLITE_ROW) {
   1897 		sqlite3_finalize(stmt);
   1898 		free(sqlstr);
   1899 		return 0;
   1900 	}
   1901 
   1902 	sqlite3_finalize(stmt);
   1903 	free(sqlstr);
   1904 	return 1;
   1905 }
   1906 
   1907 /* Optimize the index for faster search */
   1908 static void
   1909 optimize(sqlite3 *db)
   1910 {
   1911 	const char *sqlstr;
   1912 	char *errmsg = NULL;
   1913 
   1914 	if (mflags.verbosity == 2)
   1915 		printf("Optimizing the database index\n");
   1916 	sqlstr = "INSERT INTO mandb(mandb) VALUES (\'optimize\');"
   1917 		 "VACUUM";
   1918 	sqlite3_exec(db, sqlstr, NULL, NULL, &errmsg);
   1919 	if (errmsg != NULL) {
   1920 		if (mflags.verbosity)
   1921 			warnx("%s", errmsg);
   1922 		free(errmsg);
   1923 		return;
   1924 	}
   1925 }
   1926 
   1927 /*
   1928  * cleanup --
   1929  *  cleans up the global buffers
   1930  */
   1931 static void
   1932 cleanup(mandb_rec *rec)
   1933 {
   1934 	rec->desc.offset = 0;
   1935 	rec->lib.offset = 0;
   1936 	rec->return_vals.offset = 0;
   1937 	rec->env.offset = 0;
   1938 	rec->exit_status.offset = 0;
   1939 	rec->diagnostics.offset = 0;
   1940 	rec->errors.offset = 0;
   1941 	rec->files.offset = 0;
   1942 
   1943 	free(rec->machine);
   1944 	rec->machine = NULL;
   1945 
   1946 	free(rec->links);
   1947 	rec->links = NULL;
   1948 
   1949 	free(rec->file_path);
   1950 	rec->file_path = NULL;
   1951 
   1952 	free(rec->name);
   1953 	rec->name = NULL;
   1954 
   1955 	free(rec->name_desc);
   1956 	rec->name_desc = NULL;
   1957 
   1958 	free(rec->md5_hash);
   1959 	rec->md5_hash = NULL;
   1960 
   1961 	free(rec->section);
   1962 	rec->section = NULL;
   1963 }
   1964 
   1965 /*
   1966  * init_secbuffs--
   1967  *  Sets the value of buflen for all the sec_buff field of rec. And then
   1968  *  allocate memory to each sec_buff member of rec.
   1969  */
   1970 static void
   1971 init_secbuffs(mandb_rec *rec)
   1972 {
   1973 	/*
   1974 	 * Some sec_buff might need more memory, for example desc,
   1975 	 * which stores the data of the DESCRIPTION section,
   1976 	 * while some might need very small amount of memory.
   1977 	 * Therefore explicitly setting the value of buflen field for
   1978 	 * each sec_buff.
   1979 	 */
   1980 	rec->desc.buflen = 10 * BUFLEN;
   1981 	rec->desc.data = emalloc(rec->desc.buflen);
   1982 	rec->desc.offset = 0;
   1983 
   1984 	rec->lib.buflen = BUFLEN / 2;
   1985 	rec->lib.data = emalloc(rec->lib.buflen);
   1986 	rec->lib.offset = 0;
   1987 
   1988 	rec->return_vals.buflen = BUFLEN;
   1989 	rec->return_vals.data = emalloc(rec->return_vals.buflen);
   1990 	rec->return_vals.offset = 0;
   1991 
   1992 	rec->exit_status.buflen = BUFLEN;
   1993 	rec->exit_status.data = emalloc(rec->exit_status.buflen);
   1994 	rec->exit_status.offset = 0;
   1995 
   1996 	rec->env.buflen = BUFLEN;
   1997 	rec->env.data = emalloc(rec->env.buflen);
   1998 	rec->env.offset = 0;
   1999 
   2000 	rec->files.buflen = BUFLEN;
   2001 	rec->files.data = emalloc(rec->files.buflen);
   2002 	rec->files.offset = 0;
   2003 
   2004 	rec->diagnostics.buflen = BUFLEN;
   2005 	rec->diagnostics.data = emalloc(rec->diagnostics.buflen);
   2006 	rec->diagnostics.offset = 0;
   2007 
   2008 	rec->errors.buflen = BUFLEN;
   2009 	rec->errors.data = emalloc(rec->errors.buflen);
   2010 	rec->errors.offset = 0;
   2011 }
   2012 
   2013 /*
   2014  * free_secbuffs--
   2015  *  This function should be called at the end, when all the pages have been
   2016  *  parsed.
   2017  *  It frees the memory allocated to sec_buffs by init_secbuffs in the starting.
   2018  */
   2019 static void
   2020 free_secbuffs(mandb_rec *rec)
   2021 {
   2022 	free(rec->desc.data);
   2023 	free(rec->lib.data);
   2024 	free(rec->return_vals.data);
   2025 	free(rec->exit_status.data);
   2026 	free(rec->env.data);
   2027 	free(rec->files.data);
   2028 	free(rec->diagnostics.data);
   2029 	free(rec->errors.data);
   2030 }
   2031 
   2032 static void
   2033 replace_hyph(char *str)
   2034 {
   2035 	char *iter = str;
   2036 	while ((iter = strchr(iter, ASCII_HYPH)) != NULL)
   2037 		*iter = '-';
   2038 
   2039 	iter = str;
   2040 	while ((iter = strchr(iter, ASCII_NBRSP)) != NULL)
   2041 		*iter = '-';
   2042 }
   2043 
   2044 static char *
   2045 parse_escape(const char *str)
   2046 {
   2047 	const char *backslash, *last_backslash;
   2048 	char *result, *iter;
   2049 	size_t len;
   2050 
   2051 	assert(str);
   2052 
   2053 	last_backslash = str;
   2054 	backslash = strchr(str, '\\');
   2055 	if (backslash == NULL) {
   2056 		result = estrdup(str);
   2057 		replace_hyph(result);
   2058 		return result;
   2059 	}
   2060 
   2061 	result = emalloc(strlen(str) + 1);
   2062 	iter = result;
   2063 
   2064 	do {
   2065 		len = backslash - last_backslash;
   2066 		memcpy(iter, last_backslash, len);
   2067 		iter += len;
   2068 		if (backslash[1] == '-' || backslash[1] == ' ') {
   2069 			*iter++ = backslash[1];
   2070 			last_backslash = backslash + 2;
   2071 			backslash = strchr(last_backslash, '\\');
   2072 		} else {
   2073 			++backslash;
   2074 			mandoc_escape(&backslash, NULL, NULL);
   2075 			last_backslash = backslash;
   2076 			if (backslash == NULL)
   2077 				break;
   2078 			backslash = strchr(last_backslash, '\\');
   2079 		}
   2080 	} while (backslash != NULL);
   2081 	if (last_backslash != NULL)
   2082 		strcpy(iter, last_backslash);
   2083 
   2084 	replace_hyph(result);
   2085 	return result;
   2086 }
   2087 
   2088 /*
   2089  * append--
   2090  *  Concatenates a space and src at the end of sbuff->data (much like concat in
   2091  *  apropos-utils.c).
   2092  *  Rather than reallocating space for writing data, it uses the value of the
   2093  *  offset field of sec_buff to write new data at the free space left in the
   2094  *  buffer.
   2095  *  In case the size of the data to be appended exceeds the number of bytes left
   2096  *  in the buffer, it reallocates buflen number of bytes and then continues.
   2097  *  Value of offset field should be adjusted as new data is written.
   2098  *
   2099  *  NOTE: This function does not write the null byte at the end of the buffers,
   2100  *  write a null byte at the position pointed to by offset before inserting data
   2101  *  in the db.
   2102  */
   2103 static void
   2104 append(secbuff *sbuff, const char *src)
   2105 {
   2106 	short flag = 0;
   2107 	size_t srclen, newlen;
   2108 	char *temp;
   2109 
   2110 	assert(src != NULL);
   2111 	temp = parse_escape(src);
   2112 	srclen = strlen(temp);
   2113 
   2114 	if (sbuff->data == NULL) {
   2115 		sbuff->data = emalloc(sbuff->buflen);
   2116 		sbuff->offset = 0;
   2117 	}
   2118 
   2119 	newlen = sbuff->offset + srclen + 2;
   2120 	if (newlen >= sbuff->buflen) {
   2121 		while (sbuff->buflen < newlen)
   2122 			sbuff->buflen += sbuff->buflen;
   2123 		sbuff->data = erealloc(sbuff->data, sbuff->buflen);
   2124 		flag = 1;
   2125 	}
   2126 
   2127 	/* Append a space at the end of the buffer. */
   2128 	if (sbuff->offset || flag)
   2129 		sbuff->data[sbuff->offset++] = ' ';
   2130 	/* Now, copy src at the end of the buffer. */
   2131 	memcpy(sbuff->data + sbuff->offset, temp, srclen);
   2132 	sbuff->offset += srclen;
   2133 	free(temp);
   2134 }
   2135 
   2136 static void
   2137 usage(void)
   2138 {
   2139 	fprintf(stderr, "Usage: %s [-floQqv] [-C path]\n", getprogname());
   2140 	exit(1);
   2141 }
   2142