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