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