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