Home | History | Annotate | Line # | Download | only in makemandb
makemandb.c revision 1.34
      1 /*	$NetBSD: makemandb.c,v 1.34 2016/04/13 01:32:00 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.34 2016/04/13 01:32:00 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_close(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_close(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_close(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 (mflags.verbosity == 2)
    847 				printf("Parsing: %s\n", file);
    848 			rec->md5_hash = md5sum;
    849 			rec->file_path = estrdup(file);
    850 			// file_path is freed by insert_into_db itself.
    851 			chdir(parent);
    852 			begin_parse(file, mp, rec, buf, buflen);
    853 			if (insert_into_db(db, rec) < 0) {
    854 				if (mflags.verbosity)
    855 					warnx("Error in indexing %s", file);
    856 				err_count++;
    857 			} else {
    858 				new_count++;
    859 			}
    860 		}
    861 	}
    862 
    863 	if (mflags.verbosity == 2) {
    864 		printf("Total Number of new or updated pages encountered = %d\n"
    865 			"Total number of (hard or symbolic) links found = %d\n"
    866 			"Total number of pages that were successfully"
    867 			" indexed/updated = %d\n"
    868 			"Total number of pages that could not be indexed"
    869 			" due to errors = %d\n",
    870 			total_count - link_count, link_count, new_count, err_count);
    871 	}
    872 
    873 	if (mflags.recreate)
    874 		return;
    875 
    876 	if (mflags.verbosity == 2)
    877 		printf("Deleting stale index entries\n");
    878 
    879 	sqlstr = "DELETE FROM mandb_meta WHERE file NOT IN"
    880 		 " (SELECT file FROM metadb.file_cache);"
    881 		 "DELETE FROM mandb_links WHERE md5_hash NOT IN"
    882 		 " (SELECT md5_hash from mandb_meta);"
    883 		 "DROP TABLE metadb.file_cache;"
    884 		 "DELETE FROM mandb WHERE rowid NOT IN"
    885 		 " (SELECT id FROM mandb_meta);";
    886 
    887 	sqlite3_exec(db, sqlstr, NULL, NULL, &errmsg);
    888 	if (errmsg != NULL) {
    889 		warnx("Removing old entries failed: %s", errmsg);
    890 		warnx("Please rebuild database from scratch with -f.");
    891 		free(errmsg);
    892 		return;
    893 	}
    894 }
    895 
    896 /*
    897  * begin_parse --
    898  *  parses the man page using libmandoc
    899  */
    900 static void
    901 begin_parse(const char *file, struct mparse *mp, mandb_rec *rec,
    902     const void *buf, size_t len)
    903 {
    904 	struct mdoc *mdoc;
    905 	struct man *man;
    906 	mparse_reset(mp);
    907 
    908 	rec->xr_found = 0;
    909 
    910 	if (mparse_readmem(mp, buf, len, file) >= MANDOCLEVEL_BADARG) {
    911 		/* Printing this warning at verbosity level 2
    912 		 * because some packages from pkgsrc might trigger several
    913 		 * of such warnings.
    914 		 */
    915 		if (mflags.verbosity == 2)
    916 			warnx("%s: Parse failure", file);
    917 		return;
    918 	}
    919 
    920 	mparse_result(mp, &mdoc, &man, NULL);
    921 	if (mdoc == NULL && man == NULL) {
    922 		if (mflags.verbosity == 2)
    923 			warnx("Not a man(7) or mdoc(7) page");
    924 		return;
    925 	}
    926 
    927 	set_machine(mdoc, rec);
    928 	set_section(mdoc, man, rec);
    929 	if (mdoc) {
    930 		rec->page_type = MDOC;
    931 		pmdoc_node(mdoc_node(mdoc), rec);
    932 	} else {
    933 		rec->page_type = MAN;
    934 		pman_node(man_node(man), rec);
    935 	}
    936 }
    937 
    938 /*
    939  * set_section --
    940  *  Extracts the section number and normalizes it to only the numeric part
    941  *  (Which should be the first character of the string).
    942  */
    943 static void
    944 set_section(const struct mdoc *md, const struct man *m, mandb_rec *rec)
    945 {
    946 	if (md) {
    947 		const struct mdoc_meta *md_meta = mdoc_meta(md);
    948 		if (md_meta->msec == NULL) {
    949 			rec->section[0] = '?';
    950 		} else
    951 			rec->section[0] = md_meta->msec[0];
    952 	} else if (m) {
    953 		const struct man_meta *m_meta = man_meta(m);
    954 		if (m_meta->msec == NULL)
    955 			rec->section[0] = '?';
    956 		else
    957 			rec->section[0] = m_meta->msec[0];
    958 	} else
    959 		return;
    960 
    961 	if (rec->section[0] == '?' && mflags.verbosity == 2)
    962 		warnx("%s: Missing section number", rec->file_path);
    963 }
    964 
    965 /*
    966  * get_machine --
    967  *  Extracts the machine architecture information if available.
    968  */
    969 static void
    970 set_machine(const struct mdoc *md, mandb_rec *rec)
    971 {
    972 	if (md == NULL)
    973 		return;
    974 	const struct mdoc_meta *md_meta = mdoc_meta(md);
    975 	if (md_meta->arch)
    976 		rec->machine = estrdup(md_meta->arch);
    977 }
    978 
    979 static void
    980 pmdoc_node(const struct mdoc_node *n, mandb_rec *rec)
    981 {
    982 
    983 	if (n == NULL)
    984 		return;
    985 
    986 	switch (n->type) {
    987 	case (MDOC_BODY):
    988 		/* FALLTHROUGH */
    989 	case (MDOC_TAIL):
    990 		/* FALLTHROUGH */
    991 	case (MDOC_ELEM):
    992 		if (mdocs[n->tok] == NULL)
    993 			break;
    994 		(*mdocs[n->tok])(n, rec);
    995 		break;
    996 	default:
    997 		break;
    998 	}
    999 
   1000 	pmdoc_node(n->child, rec);
   1001 	pmdoc_node(n->next, rec);
   1002 }
   1003 
   1004 /*
   1005  * pmdoc_Nm --
   1006  *  Extracts the Name of the manual page from the .Nm macro
   1007  */
   1008 static void
   1009 pmdoc_Nm(const struct mdoc_node *n, mandb_rec *rec)
   1010 {
   1011 	if (n->sec != SEC_NAME)
   1012 		return;
   1013 
   1014 	for (n = n->child; n; n = n->next) {
   1015 		if (n->type == MDOC_TEXT) {
   1016 			char *escaped_name = parse_escape(n->string);
   1017 			concat(&rec->name, escaped_name);
   1018 			free(escaped_name);
   1019 		}
   1020 	}
   1021 }
   1022 
   1023 /*
   1024  * pmdoc_Nd --
   1025  *  Extracts the one line description of the man page from the .Nd macro
   1026  */
   1027 static void
   1028 pmdoc_Nd(const struct mdoc_node *n, mandb_rec *rec)
   1029 {
   1030 	char *buf = NULL;
   1031 	char *name;
   1032 	char *nd_text;
   1033 
   1034 	if (n == NULL || (n->type != MDOC_TEXT && n->tok == MDOC_MAX))
   1035 		return;
   1036 
   1037 	if (n->type == MDOC_TEXT) {
   1038 		if (rec->xr_found && n->next) {
   1039 			/*
   1040 			 * An Xr macro was seen previously, so parse this
   1041 			 * and the next node, as "Name(Section)".
   1042 			 */
   1043 			name = n->string;
   1044 			n = n->next;
   1045 			assert(n->type == MDOC_TEXT);
   1046 			easprintf(&buf, "%s(%s)", name, n->string);
   1047 			concat(&rec->name_desc, buf);
   1048 			free(buf);
   1049 		} else {
   1050 			nd_text = parse_escape(n->string);
   1051 			concat(&rec->name_desc, nd_text);
   1052 			free(nd_text);
   1053 		}
   1054 		rec->xr_found = 0;
   1055 	} else if (mdocs[n->tok] == pmdoc_Xr) {
   1056 		/* Remember that we have encountered an Xr macro */
   1057 		rec->xr_found = 1;
   1058 	}
   1059 
   1060 	if (n->child)
   1061 		pmdoc_Nd(n->child, rec);
   1062 
   1063 	if(n->next)
   1064 		pmdoc_Nd(n->next, rec);
   1065 }
   1066 
   1067 /*
   1068  * pmdoc_macro_handler--
   1069  *  This function is a single point of handling all the special macros that we
   1070  *  want to handle especially. For example the .Xr macro for properly parsing
   1071  *  the referenced page name along with the section number, or the .Pp macro
   1072  *  for adding a new line whenever we encounter it.
   1073  */
   1074 static void
   1075 pmdoc_macro_handler(const struct mdoc_node *n, mandb_rec *rec, enum mdoct doct)
   1076 {
   1077 	const struct mdoc_node *sn;
   1078 	assert(n);
   1079 
   1080 	switch (doct) {
   1081 	/*  Parse the man page references.
   1082 	 * Basically the .Xr macros are used like:
   1083 	 *  .Xr ls 1
   1084  	 *  and formatted like this:
   1085 	 *  ls(1)
   1086 	 *  Prepare a buffer to format the data like the above example and call
   1087 	 *  pmdoc_parse_section to append it.
   1088 	 */
   1089 	case MDOC_Xr:
   1090 		n = n->child;
   1091 		while (n->type != MDOC_TEXT && n->next)
   1092 			n = n->next;
   1093 
   1094 		if (n && n->type != MDOC_TEXT)
   1095 			return;
   1096 		sn = n;
   1097 		if (n->next)
   1098 			n = n->next;
   1099 
   1100 		while (n->type != MDOC_TEXT && n->next)
   1101 			n = n->next;
   1102 
   1103 		if (n && n->type == MDOC_TEXT) {
   1104 			char *buf;
   1105 			easprintf(&buf, "%s(%s)", sn->string, n->string);
   1106 			mdoc_parse_section(n->sec, buf, rec);
   1107 			free(buf);
   1108 		}
   1109 
   1110 		break;
   1111 
   1112 	/* Parse the .Pp macro to add a new line */
   1113 	case MDOC_Pp:
   1114 		if (n->type == MDOC_TEXT)
   1115 			mdoc_parse_section(n->sec, "\n", rec);
   1116 		break;
   1117 	default:
   1118 		break;
   1119 	}
   1120 
   1121 }
   1122 
   1123 /*
   1124  * pmdoc_Xr, pmdoc_Pp--
   1125  *  Empty stubs.
   1126  *  The parser calls these functions each time it encounters
   1127  *  a .Xr or .Pp macro. We are parsing all the data from
   1128  *  the pmdoc_Sh function, so don't do anything here.
   1129  *  (See if else blocks in pmdoc_Sh.)
   1130  */
   1131 static void
   1132 pmdoc_Xr(const struct mdoc_node *n, mandb_rec *rec)
   1133 {
   1134 }
   1135 
   1136 static void
   1137 pmdoc_Pp(const struct mdoc_node *n, mandb_rec *rec)
   1138 {
   1139 }
   1140 
   1141 /*
   1142  * pmdoc_Sh --
   1143  *  Called when a .Sh macro is encountered and loops through its body, calling
   1144  *  mdoc_parse_section to append the data to the section specific buffer.
   1145  *  Two special macros which may occur inside the body of Sh are .Nm and .Xr and
   1146  *  they need special handling, thus the separate if branches for them.
   1147  */
   1148 static void
   1149 pmdoc_Sh(const struct mdoc_node *n, mandb_rec *rec)
   1150 {
   1151 	if (n == NULL || (n->type != MDOC_TEXT && n->tok == MDOC_MAX))
   1152 		return;
   1153 	int xr_found = 0;
   1154 
   1155 	if (n->type == MDOC_TEXT) {
   1156 		mdoc_parse_section(n->sec, n->string, rec);
   1157 	} else if (mdocs[n->tok] == pmdoc_Nm && rec->name != NULL) {
   1158 		/*
   1159 		 * When encountering a .Nm macro, substitute it
   1160 		 * with its previously cached value of the argument.
   1161 		 */
   1162 		mdoc_parse_section(n->sec, rec->name, rec);
   1163 	} else if (mdocs[n->tok] == pmdoc_Xr) {
   1164 		/*
   1165 		 * When encountering other inline macros,
   1166 		 * call pmdoc_macro_handler.
   1167 		 */
   1168 		pmdoc_macro_handler(n, rec, MDOC_Xr);
   1169 		xr_found = 1;
   1170 	} else if (mdocs[n->tok] == pmdoc_Pp) {
   1171 		pmdoc_macro_handler(n, rec, MDOC_Pp);
   1172 	}
   1173 
   1174 	/*
   1175 	 * If an Xr macro was encountered then the child node has
   1176 	 * already been explored by pmdoc_macro_handler.
   1177 	 */
   1178 	if (xr_found == 0)
   1179 		pmdoc_Sh(n->child, rec);
   1180 	pmdoc_Sh(n->next, rec);
   1181 }
   1182 
   1183 /*
   1184  * mdoc_parse_section--
   1185  *  Utility function for parsing sections of the mdoc type pages.
   1186  *  Takes two params:
   1187  *   1. sec is an enum which indicates the section in which we are present
   1188  *   2. string is the string which we need to append to the secbuff for this
   1189  *      particular section.
   1190  *  The function appends string to the global section buffer and returns.
   1191  */
   1192 static void
   1193 mdoc_parse_section(enum mdoc_sec sec, const char *string, mandb_rec *rec)
   1194 {
   1195 	/*
   1196 	 * If the user specified the 'l' flag, then parse and store only the
   1197 	 * NAME section. Ignore the rest.
   1198 	 */
   1199 	if (mflags.limit)
   1200 		return;
   1201 
   1202 	switch (sec) {
   1203 	case SEC_LIBRARY:
   1204 		append(&rec->lib, string);
   1205 		break;
   1206 	case SEC_RETURN_VALUES:
   1207 		append(&rec->return_vals, string);
   1208 		break;
   1209 	case SEC_ENVIRONMENT:
   1210 		append(&rec->env, string);
   1211 		break;
   1212 	case SEC_FILES:
   1213 		append(&rec->files, string);
   1214 		break;
   1215 	case SEC_EXIT_STATUS:
   1216 		append(&rec->exit_status, string);
   1217 		break;
   1218 	case SEC_DIAGNOSTICS:
   1219 		append(&rec->diagnostics, string);
   1220 		break;
   1221 	case SEC_ERRORS:
   1222 		append(&rec->errors, string);
   1223 		break;
   1224 	case SEC_NAME:
   1225 	case SEC_SYNOPSIS:
   1226 	case SEC_EXAMPLES:
   1227 	case SEC_STANDARDS:
   1228 	case SEC_HISTORY:
   1229 	case SEC_AUTHORS:
   1230 	case SEC_BUGS:
   1231 		break;
   1232 	default:
   1233 		append(&rec->desc, string);
   1234 		break;
   1235 	}
   1236 }
   1237 
   1238 static void
   1239 pman_node(const struct man_node *n, mandb_rec *rec)
   1240 {
   1241 	if (n == NULL)
   1242 		return;
   1243 
   1244 	switch (n->type) {
   1245 	case (MAN_BODY):
   1246 		/* FALLTHROUGH */
   1247 	case (MAN_BLOCK):
   1248 		/* FALLTHROUGH */
   1249 	case (MAN_ELEM):
   1250 		if (mans[n->tok] != NULL)
   1251 			(*mans[n->tok])(n, rec);
   1252 		break;
   1253 	default:
   1254 		break;
   1255 	}
   1256 
   1257 	pman_node(n->child, rec);
   1258 	pman_node(n->next, rec);
   1259 }
   1260 
   1261 /*
   1262  * pman_parse_name --
   1263  *  Parses the NAME section and puts the complete content in the name_desc
   1264  *  variable.
   1265  */
   1266 static void
   1267 pman_parse_name(const struct man_node *n, mandb_rec *rec)
   1268 {
   1269 	if (n == NULL)
   1270 		return;
   1271 
   1272 	if (n->type == MAN_TEXT) {
   1273 		char *tmp = parse_escape(n->string);
   1274 		concat(&rec->name_desc, tmp);
   1275 		free(tmp);
   1276 	}
   1277 
   1278 	if (n->child)
   1279 		pman_parse_name(n->child, rec);
   1280 
   1281 	if(n->next)
   1282 		pman_parse_name(n->next, rec);
   1283 }
   1284 
   1285 /*
   1286  * A stub function to be able to parse the macros like .B embedded inside
   1287  * a section.
   1288  */
   1289 static void
   1290 pman_block(const struct man_node *n, mandb_rec *rec)
   1291 {
   1292 }
   1293 
   1294 /*
   1295  * pman_sh --
   1296  * This function does one of the two things:
   1297  *  1. If the present section is NAME, then it will:
   1298  *    (a) Extract the name of the page (in case of multiple comma separated
   1299  *        names, it will pick up the first one).
   1300  *    (b) Build a space spearated list of all the symlinks/hardlinks to
   1301  *        this page and store in the buffer 'links'. These are extracted from
   1302  *        the comma separated list of names in the NAME section as well.
   1303  *    (c) Move on to the one line description section, which is after the list
   1304  *        of names in the NAME section.
   1305  *  2. Otherwise, it will check the section name and call the man_parse_section
   1306  *     function, passing the enum corresponding that section.
   1307  */
   1308 static void
   1309 pman_sh(const struct man_node *n, mandb_rec *rec)
   1310 {
   1311 	static const struct {
   1312 		enum man_sec section;
   1313 		const char *header;
   1314 	} mapping[] = {
   1315 	    { MANSEC_DESCRIPTION, "DESCRIPTION" },
   1316 	    { MANSEC_SYNOPSIS, "SYNOPSIS" },
   1317 	    { MANSEC_LIBRARY, "LIBRARY" },
   1318 	    { MANSEC_ERRORS, "ERRORS" },
   1319 	    { MANSEC_FILES, "FILES" },
   1320 	    { MANSEC_RETURN_VALUES, "RETURN VALUE" },
   1321 	    { MANSEC_RETURN_VALUES, "RETURN VALUES" },
   1322 	    { MANSEC_EXIT_STATUS, "EXIT STATUS" },
   1323 	    { MANSEC_EXAMPLES, "EXAMPLES" },
   1324 	    { MANSEC_EXAMPLES, "EXAMPLE" },
   1325 	    { MANSEC_STANDARDS, "STANDARDS" },
   1326 	    { MANSEC_HISTORY, "HISTORY" },
   1327 	    { MANSEC_BUGS, "BUGS" },
   1328 	    { MANSEC_AUTHORS, "AUTHORS" },
   1329 	    { MANSEC_COPYRIGHT, "COPYRIGHT" },
   1330 	};
   1331 	const struct man_node *head;
   1332 	char *name_desc;
   1333 	size_t sz;
   1334 	size_t i;
   1335 
   1336 	if ((head = n->parent->head) == NULL || (head = head->child) == NULL ||
   1337 	    head->type != MAN_TEXT)
   1338 		return;
   1339 
   1340 	/*
   1341 	 * Check if this section should be extracted and
   1342 	 * where it should be stored. Handled the trival cases first.
   1343 	 */
   1344 	for (i = 0; i < sizeof(mapping) / sizeof(mapping[0]); ++i) {
   1345 		if (strcmp(head->string, mapping[i].header) == 0) {
   1346 			man_parse_section(mapping[i].section, n, rec);
   1347 			return;
   1348 		}
   1349 	}
   1350 
   1351 	if (strcmp(head->string, "NAME") == 0) {
   1352 		/*
   1353 		 * We are in the NAME section.
   1354 		 * pman_parse_name will put the complete content in name_desc.
   1355 		 */
   1356 		pman_parse_name(n, rec);
   1357 
   1358 		name_desc = rec->name_desc;
   1359 		if (name_desc == NULL)
   1360 			return;
   1361 
   1362 		/* Remove any leading spaces. */
   1363 		while (name_desc[0] == ' ')
   1364 			name_desc++;
   1365 
   1366 		/* If the line begins with a "\&", avoid those */
   1367 		if (name_desc[0] == '\\' && name_desc[1] == '&')
   1368 			name_desc += 2;
   1369 
   1370 		/* Now name_desc should be left with a comma-space
   1371 		 * separated list of names and the one line description
   1372 		 * of the page:
   1373 		 *     "a, b, c \- sample description"
   1374 		 * Take out the first name, before the first comma
   1375 		 * (or space) and store it in rec->name.
   1376 		 * If the page has aliases then they should be
   1377 		 * in the form of a comma separated list.
   1378 		 * Keep looping while there is a comma in name_desc,
   1379 		 * extract the alias name and store in rec->links.
   1380 		 * When there are no more commas left, break out.
   1381 		 */
   1382 		int has_alias = 0;	// Any more aliases left?
   1383 		while (*name_desc) {
   1384 			/* Remove any leading spaces or hyphens. */
   1385 			if (name_desc[0] == ' ' || name_desc[0] =='-') {
   1386 				name_desc++;
   1387 				continue;
   1388 			}
   1389 			sz = strcspn(name_desc, ", ");
   1390 
   1391 			/* Extract the first term and store it in rec->name. */
   1392 			if (rec->name == NULL) {
   1393 				if (name_desc[sz] == ',')
   1394 					has_alias = 1;
   1395 				name_desc[sz] = 0;
   1396 				rec->name = emalloc(sz + 1);
   1397 				memcpy(rec->name, name_desc, sz + 1);
   1398 				name_desc += sz + 1;
   1399 				continue;
   1400 			}
   1401 
   1402 			/*
   1403 			 * Once rec->name is set, rest of the names
   1404 			 * are to be treated as links or aliases.
   1405 			 */
   1406 			if (rec->name && has_alias) {
   1407 				if (name_desc[sz] != ',') {
   1408 					/* No more commas left -->
   1409 					 * no more aliases to take out
   1410 					 */
   1411 					has_alias = 0;
   1412 				}
   1413 				name_desc[sz] = 0;
   1414 				concat2(&rec->links, name_desc, sz);
   1415 				name_desc += sz + 1;
   1416 				continue;
   1417 			}
   1418 			break;
   1419 		}
   1420 
   1421 		/* Parse any escape sequences that might be there */
   1422 		char *temp = parse_escape(name_desc);
   1423 		free(rec->name_desc);
   1424 		rec->name_desc = temp;
   1425 		temp = parse_escape(rec->name);
   1426 		free(rec->name);
   1427 		rec->name = temp;
   1428 		return;
   1429 	}
   1430 
   1431 	/* The RETURN VALUE section might be specified in multiple ways */
   1432 	if (strcmp(head->string, "RETURN") == 0 &&
   1433 	    head->next != NULL && head->next->type == MAN_TEXT &&
   1434 	    (strcmp(head->next->string, "VALUE") == 0 ||
   1435 	    strcmp(head->next->string, "VALUES") == 0)) {
   1436 		man_parse_section(MANSEC_RETURN_VALUES, n, rec);
   1437 		return;
   1438 	}
   1439 
   1440 	/*
   1441 	 * EXIT STATUS section can also be specified all on one line or on two
   1442 	 * separate lines.
   1443 	 */
   1444 	if (strcmp(head->string, "EXIT") == 0 &&
   1445 	    head->next != NULL && head->next->type == MAN_TEXT &&
   1446 	    strcmp(head->next->string, "STATUS") == 0) {
   1447 		man_parse_section(MANSEC_EXIT_STATUS, n, rec);
   1448 		return;
   1449 	}
   1450 
   1451 	/* Store the rest of the content in desc. */
   1452 	man_parse_section(MANSEC_NONE, n, rec);
   1453 }
   1454 
   1455 /*
   1456  * pman_parse_node --
   1457  *  Generic function to iterate through a node. Usually called from
   1458  *  man_parse_section to parse a particular section of the man page.
   1459  */
   1460 static void
   1461 pman_parse_node(const struct man_node *n, secbuff *s)
   1462 {
   1463 	if (n == NULL)
   1464 		return;
   1465 
   1466 	if (n->type == MAN_TEXT)
   1467 		append(s, n->string);
   1468 
   1469 	pman_parse_node(n->child, s);
   1470 	pman_parse_node(n->next, s);
   1471 }
   1472 
   1473 /*
   1474  * man_parse_section --
   1475  *  Takes two parameters:
   1476  *   sec: Tells which section we are present in
   1477  *   n: Is the present node of the AST.
   1478  * Depending on the section, we call pman_parse_node to parse that section and
   1479  * concatenate the content from that section into the buffer for that section.
   1480  */
   1481 static void
   1482 man_parse_section(enum man_sec sec, const struct man_node *n, mandb_rec *rec)
   1483 {
   1484 	/*
   1485 	 * If the user sepecified the 'l' flag then just parse
   1486 	 * the NAME section, ignore the rest.
   1487 	 */
   1488 	if (mflags.limit)
   1489 		return;
   1490 
   1491 	switch (sec) {
   1492 	case MANSEC_LIBRARY:
   1493 		pman_parse_node(n, &rec->lib);
   1494 		break;
   1495 	case MANSEC_RETURN_VALUES:
   1496 		pman_parse_node(n, &rec->return_vals);
   1497 		break;
   1498 	case MANSEC_ENVIRONMENT:
   1499 		pman_parse_node(n, &rec->env);
   1500 		break;
   1501 	case MANSEC_FILES:
   1502 		pman_parse_node(n, &rec->files);
   1503 		break;
   1504 	case MANSEC_EXIT_STATUS:
   1505 		pman_parse_node(n, &rec->exit_status);
   1506 		break;
   1507 	case MANSEC_DIAGNOSTICS:
   1508 		pman_parse_node(n, &rec->diagnostics);
   1509 		break;
   1510 	case MANSEC_ERRORS:
   1511 		pman_parse_node(n, &rec->errors);
   1512 		break;
   1513 	case MANSEC_NAME:
   1514 	case MANSEC_SYNOPSIS:
   1515 	case MANSEC_EXAMPLES:
   1516 	case MANSEC_STANDARDS:
   1517 	case MANSEC_HISTORY:
   1518 	case MANSEC_BUGS:
   1519 	case MANSEC_AUTHORS:
   1520 	case MANSEC_COPYRIGHT:
   1521 		break;
   1522 	default:
   1523 		pman_parse_node(n, &rec->desc);
   1524 		break;
   1525 	}
   1526 
   1527 }
   1528 
   1529 /*
   1530  * insert_into_db --
   1531  *  Inserts the parsed data of the man page in the Sqlite databse.
   1532  *  If any of the values is NULL, then we cleanup and return -1 indicating
   1533  *  an error.
   1534  *  Otherwise, store the data in the database and return 0.
   1535  */
   1536 static int
   1537 insert_into_db(sqlite3 *db, mandb_rec *rec)
   1538 {
   1539 	int rc = 0;
   1540 	int idx = -1;
   1541 	const char *sqlstr = NULL;
   1542 	sqlite3_stmt *stmt = NULL;
   1543 	char *ln = NULL;
   1544 	char *errmsg = NULL;
   1545 	long int mandb_rowid;
   1546 
   1547 	/*
   1548 	 * At the very minimum we want to make sure that we store
   1549 	 * the following data:
   1550 	 *   Name, one line description, and the MD5 hash
   1551 	 */
   1552 	if (rec->name == NULL || rec->name_desc == NULL ||
   1553 	    rec->md5_hash == NULL) {
   1554 		cleanup(rec);
   1555 		return -1;
   1556 	}
   1557 
   1558 	/* Write null byte at the end of all the sec_buffs */
   1559 	rec->desc.data[rec->desc.offset] = 0;
   1560 	rec->lib.data[rec->lib.offset] = 0;
   1561 	rec->env.data[rec->env.offset] = 0;
   1562 	rec->return_vals.data[rec->return_vals.offset] = 0;
   1563 	rec->exit_status.data[rec->exit_status.offset] = 0;
   1564 	rec->files.data[rec->files.offset] = 0;
   1565 	rec->diagnostics.data[rec->diagnostics.offset] = 0;
   1566 	rec->errors.data[rec->errors.offset] = 0;
   1567 
   1568 	/*
   1569 	 * In case of a mdoc page: (sorry, no better place to put this code)
   1570 	 * parse the comma separated list of names of man pages,
   1571 	 * the first name will be stored in the mandb table, rest will be
   1572 	 * treated as links and put in the mandb_links table.
   1573 	 */
   1574 	if (rec->page_type == MDOC) {
   1575 		char *tmp;
   1576 		rec->links = estrdup(rec->name);
   1577 		free(rec->name);
   1578 		int sz = strcspn(rec->links, " \0");
   1579 		rec->name = emalloc(sz + 1);
   1580 		memcpy(rec->name, rec->links, sz);
   1581 		if(rec->name[sz - 1] == ',')
   1582 			rec->name[sz - 1] = 0;
   1583 		else
   1584 			rec->name[sz] = 0;
   1585 		while (rec->links[sz] == ' ')
   1586 			++sz;
   1587 		tmp = estrdup(rec->links + sz);
   1588 		free(rec->links);
   1589 		rec->links = tmp;
   1590 	}
   1591 
   1592 /*------------------------ Populate the mandb table---------------------------*/
   1593 	sqlstr = "INSERT INTO mandb VALUES (:section, :name, :name_desc, :desc,"
   1594 		 " :lib, :return_vals, :env, :files, :exit_status,"
   1595 		 " :diagnostics, :errors, :md5_hash, :machine)";
   1596 
   1597 	rc = sqlite3_prepare_v2(db, sqlstr, -1, &stmt, NULL);
   1598 	if (rc != SQLITE_OK)
   1599 		goto Out;
   1600 
   1601 	idx = sqlite3_bind_parameter_index(stmt, ":name");
   1602 	rc = sqlite3_bind_text(stmt, idx, rec->name, -1, NULL);
   1603 	if (rc != SQLITE_OK) {
   1604 		sqlite3_finalize(stmt);
   1605 		goto Out;
   1606 	}
   1607 
   1608 	idx = sqlite3_bind_parameter_index(stmt, ":section");
   1609 	rc = sqlite3_bind_text(stmt, idx, rec->section, -1, NULL);
   1610 	if (rc != SQLITE_OK) {
   1611 		sqlite3_finalize(stmt);
   1612 		goto Out;
   1613 	}
   1614 
   1615 	idx = sqlite3_bind_parameter_index(stmt, ":name_desc");
   1616 	rc = sqlite3_bind_text(stmt, idx, rec->name_desc, -1, NULL);
   1617 	if (rc != SQLITE_OK) {
   1618 		sqlite3_finalize(stmt);
   1619 		goto Out;
   1620 	}
   1621 
   1622 	idx = sqlite3_bind_parameter_index(stmt, ":desc");
   1623 	rc = sqlite3_bind_text(stmt, idx, rec->desc.data,
   1624 	                       rec->desc.offset + 1, NULL);
   1625 	if (rc != SQLITE_OK) {
   1626 		sqlite3_finalize(stmt);
   1627 		goto Out;
   1628 	}
   1629 
   1630 	idx = sqlite3_bind_parameter_index(stmt, ":lib");
   1631 	rc = sqlite3_bind_text(stmt, idx, rec->lib.data, rec->lib.offset + 1, NULL);
   1632 	if (rc != SQLITE_OK) {
   1633 		sqlite3_finalize(stmt);
   1634 		goto Out;
   1635 	}
   1636 
   1637 	idx = sqlite3_bind_parameter_index(stmt, ":return_vals");
   1638 	rc = sqlite3_bind_text(stmt, idx, rec->return_vals.data,
   1639 	                      rec->return_vals.offset + 1, NULL);
   1640 	if (rc != SQLITE_OK) {
   1641 		sqlite3_finalize(stmt);
   1642 		goto Out;
   1643 	}
   1644 
   1645 	idx = sqlite3_bind_parameter_index(stmt, ":env");
   1646 	rc = sqlite3_bind_text(stmt, idx, rec->env.data, rec->env.offset + 1, NULL);
   1647 	if (rc != SQLITE_OK) {
   1648 		sqlite3_finalize(stmt);
   1649 		goto Out;
   1650 	}
   1651 
   1652 	idx = sqlite3_bind_parameter_index(stmt, ":files");
   1653 	rc = sqlite3_bind_text(stmt, idx, rec->files.data,
   1654 	                       rec->files.offset + 1, NULL);
   1655 	if (rc != SQLITE_OK) {
   1656 		sqlite3_finalize(stmt);
   1657 		goto Out;
   1658 	}
   1659 
   1660 	idx = sqlite3_bind_parameter_index(stmt, ":exit_status");
   1661 	rc = sqlite3_bind_text(stmt, idx, rec->exit_status.data,
   1662 	                       rec->exit_status.offset + 1, NULL);
   1663 	if (rc != SQLITE_OK) {
   1664 		sqlite3_finalize(stmt);
   1665 		goto Out;
   1666 	}
   1667 
   1668 	idx = sqlite3_bind_parameter_index(stmt, ":diagnostics");
   1669 	rc = sqlite3_bind_text(stmt, idx, rec->diagnostics.data,
   1670 	                       rec->diagnostics.offset + 1, NULL);
   1671 	if (rc != SQLITE_OK) {
   1672 		sqlite3_finalize(stmt);
   1673 		goto Out;
   1674 	}
   1675 
   1676 	idx = sqlite3_bind_parameter_index(stmt, ":errors");
   1677 	rc = sqlite3_bind_text(stmt, idx, rec->errors.data,
   1678 	                       rec->errors.offset + 1, NULL);
   1679 	if (rc != SQLITE_OK) {
   1680 		sqlite3_finalize(stmt);
   1681 		goto Out;
   1682 	}
   1683 
   1684 	idx = sqlite3_bind_parameter_index(stmt, ":md5_hash");
   1685 	rc = sqlite3_bind_text(stmt, idx, rec->md5_hash, -1, NULL);
   1686 	if (rc != SQLITE_OK) {
   1687 		sqlite3_finalize(stmt);
   1688 		goto Out;
   1689 	}
   1690 
   1691 	idx = sqlite3_bind_parameter_index(stmt, ":machine");
   1692 	if (rec->machine)
   1693 		rc = sqlite3_bind_text(stmt, idx, rec->machine, -1, NULL);
   1694 	else
   1695 		rc = sqlite3_bind_null(stmt, idx);
   1696 	if (rc != SQLITE_OK) {
   1697 		sqlite3_finalize(stmt);
   1698 		goto Out;
   1699 	}
   1700 
   1701 	rc = sqlite3_step(stmt);
   1702 	if (rc != SQLITE_DONE) {
   1703 		sqlite3_finalize(stmt);
   1704 		goto Out;
   1705 	}
   1706 
   1707 	sqlite3_finalize(stmt);
   1708 
   1709 	/* Get the row id of the last inserted row */
   1710 	mandb_rowid = sqlite3_last_insert_rowid(db);
   1711 
   1712 /*------------------------Populate the mandb_meta table-----------------------*/
   1713 	sqlstr = "INSERT INTO mandb_meta VALUES (:device, :inode, :mtime,"
   1714 		 " :file, :md5_hash, :id)";
   1715 	rc = sqlite3_prepare_v2(db, sqlstr, -1, &stmt, NULL);
   1716 	if (rc != SQLITE_OK)
   1717 		goto Out;
   1718 
   1719 	idx = sqlite3_bind_parameter_index(stmt, ":device");
   1720 	rc = sqlite3_bind_int64(stmt, idx, rec->device);
   1721 	if (rc != SQLITE_OK) {
   1722 		sqlite3_finalize(stmt);
   1723 		goto Out;
   1724 	}
   1725 
   1726 	idx = sqlite3_bind_parameter_index(stmt, ":inode");
   1727 	rc = sqlite3_bind_int64(stmt, idx, rec->inode);
   1728 	if (rc != SQLITE_OK) {
   1729 		sqlite3_finalize(stmt);
   1730 		goto Out;
   1731 	}
   1732 
   1733 	idx = sqlite3_bind_parameter_index(stmt, ":mtime");
   1734 	rc = sqlite3_bind_int64(stmt, idx, rec->mtime);
   1735 	if (rc != SQLITE_OK) {
   1736 		sqlite3_finalize(stmt);
   1737 		goto Out;
   1738 	}
   1739 
   1740 	idx = sqlite3_bind_parameter_index(stmt, ":file");
   1741 	rc = sqlite3_bind_text(stmt, idx, rec->file_path, -1, NULL);
   1742 	if (rc != SQLITE_OK) {
   1743 		sqlite3_finalize(stmt);
   1744 		goto Out;
   1745 	}
   1746 
   1747 	idx = sqlite3_bind_parameter_index(stmt, ":md5_hash");
   1748 	rc = sqlite3_bind_text(stmt, idx, rec->md5_hash, -1, NULL);
   1749 	if (rc != SQLITE_OK) {
   1750 		sqlite3_finalize(stmt);
   1751 		goto Out;
   1752 	}
   1753 
   1754 	idx = sqlite3_bind_parameter_index(stmt, ":id");
   1755 	rc = sqlite3_bind_int64(stmt, idx, mandb_rowid);
   1756 	if (rc != SQLITE_OK) {
   1757 		sqlite3_finalize(stmt);
   1758 		goto Out;
   1759 	}
   1760 
   1761 	rc = sqlite3_step(stmt);
   1762 	sqlite3_finalize(stmt);
   1763 	if (rc == SQLITE_CONSTRAINT_UNIQUE) {
   1764 		/* The *most* probable reason for reaching here is that
   1765 		 * the UNIQUE contraint on the file column of the mandb_meta
   1766 		 * table was violated.
   1767 		 * This can happen when a file was updated/modified.
   1768 		 * To fix this we need to do two things:
   1769 		 * 1. Delete the row for the older version of this file
   1770 		 *    from mandb table.
   1771 		 * 2. Run an UPDATE query to update the row for this file
   1772 		 *    in the mandb_meta table.
   1773 		 */
   1774 		warnx("Trying to update index for %s", rec->file_path);
   1775 		char *sql = sqlite3_mprintf("DELETE FROM mandb "
   1776 					    "WHERE rowid = (SELECT id"
   1777 					    "  FROM mandb_meta"
   1778 					    "  WHERE file = %Q)",
   1779 					    rec->file_path);
   1780 		sqlite3_exec(db, sql, NULL, NULL, &errmsg);
   1781 		sqlite3_free(sql);
   1782 		if (errmsg != NULL) {
   1783 			if (mflags.verbosity)
   1784 				warnx("%s", errmsg);
   1785 			free(errmsg);
   1786 		}
   1787 		sqlstr = "UPDATE mandb_meta SET device = :device,"
   1788 			 " inode = :inode, mtime = :mtime, id = :id,"
   1789 			 " md5_hash = :md5 WHERE file = :file";
   1790 		rc = sqlite3_prepare_v2(db, sqlstr, -1, &stmt, NULL);
   1791 		if (rc != SQLITE_OK) {
   1792 			if (mflags.verbosity)
   1793 				warnx("Update failed with error: %s",
   1794 			    sqlite3_errmsg(db));
   1795 			close_db(db);
   1796 			cleanup(rec);
   1797 			errx(EXIT_FAILURE,
   1798 			    "Consider running makemandb with -f option");
   1799 		}
   1800 
   1801 		idx = sqlite3_bind_parameter_index(stmt, ":device");
   1802 		sqlite3_bind_int64(stmt, idx, rec->device);
   1803 		idx = sqlite3_bind_parameter_index(stmt, ":inode");
   1804 		sqlite3_bind_int64(stmt, idx, rec->inode);
   1805 		idx = sqlite3_bind_parameter_index(stmt, ":mtime");
   1806 		sqlite3_bind_int64(stmt, idx, rec->mtime);
   1807 		idx = sqlite3_bind_parameter_index(stmt, ":id");
   1808 		sqlite3_bind_int64(stmt, idx, mandb_rowid);
   1809 		idx = sqlite3_bind_parameter_index(stmt, ":md5");
   1810 		sqlite3_bind_text(stmt, idx, rec->md5_hash, -1, NULL);
   1811 		idx = sqlite3_bind_parameter_index(stmt, ":file");
   1812 		sqlite3_bind_text(stmt, idx, rec->file_path, -1, NULL);
   1813 		rc = sqlite3_step(stmt);
   1814 		sqlite3_finalize(stmt);
   1815 
   1816 		if (rc != SQLITE_DONE) {
   1817 			if (mflags.verbosity)
   1818 				warnx("%s", sqlite3_errmsg(db));
   1819 			close_db(db);
   1820 			cleanup(rec);
   1821 			errx(EXIT_FAILURE,
   1822 			    "Consider running makemandb with -f option");
   1823 		}
   1824 	} else if (rc != SQLITE_DONE) {
   1825 		/* Otherwise make this error fatal */
   1826 		warnx("Failed at %s\n%s", rec->file_path, sqlite3_errmsg(db));
   1827 		cleanup(rec);
   1828 		close_db(db);
   1829 		exit(EXIT_FAILURE);
   1830 	}
   1831 
   1832 /*------------------------ Populate the mandb_links table---------------------*/
   1833 	char *str = NULL;
   1834 	char *links;
   1835 	if (rec->links && strlen(rec->links)) {
   1836 		links = rec->links;
   1837 		for(ln = strtok(links, " "); ln; ln = strtok(NULL, " ")) {
   1838 			if (ln[0] == ',')
   1839 				ln++;
   1840 			if(ln[strlen(ln) - 1] == ',')
   1841 				ln[strlen(ln) - 1] = 0;
   1842 
   1843 			str = sqlite3_mprintf("INSERT INTO mandb_links"
   1844 					      " VALUES (%Q, %Q, %Q, %Q, %Q)",
   1845 					      ln, rec->name, rec->section,
   1846 					      rec->machine, rec->md5_hash);
   1847 			sqlite3_exec(db, str, NULL, NULL, &errmsg);
   1848 			sqlite3_free(str);
   1849 			if (errmsg != NULL) {
   1850 				warnx("%s", errmsg);
   1851 				cleanup(rec);
   1852 				free(errmsg);
   1853 				return -1;
   1854 			}
   1855 		}
   1856 	}
   1857 
   1858 	cleanup(rec);
   1859 	return 0;
   1860 
   1861   Out:
   1862 	if (mflags.verbosity)
   1863 		warnx("%s", sqlite3_errmsg(db));
   1864 	cleanup(rec);
   1865 	return -1;
   1866 }
   1867 
   1868 /*
   1869  * check_md5--
   1870  *  Generates the md5 hash of the file and checks if it already doesn't exist
   1871  *  in the table (passed as the 3rd parameter).
   1872  *  This function is being used to avoid hardlinks.
   1873  *  On successful completion it will also set the value of the fourth parameter
   1874  *  to the md5 hash of the file (computed previously). It is the responsibility
   1875  *  of the caller to free this buffer.
   1876  *  Return values:
   1877  *  -1: If an error occurs somewhere and sets the md5 return buffer to NULL.
   1878  *  0: If the md5 hash does not exist in the table.
   1879  *  1: If the hash exists in the database.
   1880  */
   1881 static int
   1882 check_md5(const char *file, sqlite3 *db, const char *table, char **md5sum,
   1883     void *buf, size_t buflen)
   1884 {
   1885 	int rc = 0;
   1886 	int idx = -1;
   1887 	char *sqlstr = NULL;
   1888 	sqlite3_stmt *stmt = NULL;
   1889 
   1890 	assert(file != NULL);
   1891 	*md5sum = MD5Data(buf, buflen, NULL);
   1892 	if (*md5sum == NULL) {
   1893 		if (mflags.verbosity)
   1894 			warn("md5 failed: %s", file);
   1895 		return -1;
   1896 	}
   1897 
   1898 	easprintf(&sqlstr, "SELECT * FROM %s WHERE md5_hash = :md5_hash",
   1899 	    table);
   1900 	rc = sqlite3_prepare_v2(db, sqlstr, -1, &stmt, NULL);
   1901 	if (rc != SQLITE_OK) {
   1902 		free(sqlstr);
   1903 		free(*md5sum);
   1904 		*md5sum = NULL;
   1905 		return -1;
   1906 	}
   1907 
   1908 	idx = sqlite3_bind_parameter_index(stmt, ":md5_hash");
   1909 	rc = sqlite3_bind_text(stmt, idx, *md5sum, -1, NULL);
   1910 	if (rc != SQLITE_OK) {
   1911 		if (mflags.verbosity)
   1912 			warnx("%s", sqlite3_errmsg(db));
   1913 		sqlite3_finalize(stmt);
   1914 		free(sqlstr);
   1915 		free(*md5sum);
   1916 		*md5sum = NULL;
   1917 		return -1;
   1918 	}
   1919 
   1920 	if (sqlite3_step(stmt) == SQLITE_ROW) {
   1921 		sqlite3_finalize(stmt);
   1922 		free(sqlstr);
   1923 		return 0;
   1924 	}
   1925 
   1926 	sqlite3_finalize(stmt);
   1927 	free(sqlstr);
   1928 	return 1;
   1929 }
   1930 
   1931 /* Optimize the index for faster search */
   1932 static void
   1933 optimize(sqlite3 *db)
   1934 {
   1935 	const char *sqlstr;
   1936 	char *errmsg = NULL;
   1937 
   1938 	if (mflags.verbosity == 2)
   1939 		printf("Optimizing the database index\n");
   1940 	sqlstr = "INSERT INTO mandb(mandb) VALUES (\'optimize\');"
   1941 		 "VACUUM";
   1942 	sqlite3_exec(db, sqlstr, NULL, NULL, &errmsg);
   1943 	if (errmsg != NULL) {
   1944 		if (mflags.verbosity)
   1945 			warnx("%s", errmsg);
   1946 		free(errmsg);
   1947 		return;
   1948 	}
   1949 }
   1950 
   1951 /*
   1952  * cleanup --
   1953  *  cleans up the global buffers
   1954  */
   1955 static void
   1956 cleanup(mandb_rec *rec)
   1957 {
   1958 	rec->desc.offset = 0;
   1959 	rec->lib.offset = 0;
   1960 	rec->return_vals.offset = 0;
   1961 	rec->env.offset = 0;
   1962 	rec->exit_status.offset = 0;
   1963 	rec->diagnostics.offset = 0;
   1964 	rec->errors.offset = 0;
   1965 	rec->files.offset = 0;
   1966 
   1967 	free(rec->machine);
   1968 	rec->machine = NULL;
   1969 
   1970 	free(rec->links);
   1971 	rec->links = NULL;
   1972 
   1973 	free(rec->file_path);
   1974 	rec->file_path = NULL;
   1975 
   1976 	free(rec->name);
   1977 	rec->name = NULL;
   1978 
   1979 	free(rec->name_desc);
   1980 	rec->name_desc = NULL;
   1981 
   1982 	free(rec->md5_hash);
   1983 	rec->md5_hash = NULL;
   1984 }
   1985 
   1986 /*
   1987  * init_secbuffs--
   1988  *  Sets the value of buflen for all the sec_buff field of rec. And then
   1989  *  allocate memory to each sec_buff member of rec.
   1990  */
   1991 static void
   1992 init_secbuffs(mandb_rec *rec)
   1993 {
   1994 	/*
   1995 	 * Some sec_buff might need more memory, for example desc,
   1996 	 * which stores the data of the DESCRIPTION section,
   1997 	 * while some might need very small amount of memory.
   1998 	 * Therefore explicitly setting the value of buflen field for
   1999 	 * each sec_buff.
   2000 	 */
   2001 	rec->desc.buflen = 10 * BUFLEN;
   2002 	rec->desc.data = emalloc(rec->desc.buflen);
   2003 	rec->desc.offset = 0;
   2004 
   2005 	rec->lib.buflen = BUFLEN / 2;
   2006 	rec->lib.data = emalloc(rec->lib.buflen);
   2007 	rec->lib.offset = 0;
   2008 
   2009 	rec->return_vals.buflen = BUFLEN;
   2010 	rec->return_vals.data = emalloc(rec->return_vals.buflen);
   2011 	rec->return_vals.offset = 0;
   2012 
   2013 	rec->exit_status.buflen = BUFLEN;
   2014 	rec->exit_status.data = emalloc(rec->exit_status.buflen);
   2015 	rec->exit_status.offset = 0;
   2016 
   2017 	rec->env.buflen = BUFLEN;
   2018 	rec->env.data = emalloc(rec->env.buflen);
   2019 	rec->env.offset = 0;
   2020 
   2021 	rec->files.buflen = BUFLEN;
   2022 	rec->files.data = emalloc(rec->files.buflen);
   2023 	rec->files.offset = 0;
   2024 
   2025 	rec->diagnostics.buflen = BUFLEN;
   2026 	rec->diagnostics.data = emalloc(rec->diagnostics.buflen);
   2027 	rec->diagnostics.offset = 0;
   2028 
   2029 	rec->errors.buflen = BUFLEN;
   2030 	rec->errors.data = emalloc(rec->errors.buflen);
   2031 	rec->errors.offset = 0;
   2032 }
   2033 
   2034 /*
   2035  * free_secbuffs--
   2036  *  This function should be called at the end, when all the pages have been
   2037  *  parsed.
   2038  *  It frees the memory allocated to sec_buffs by init_secbuffs in the starting.
   2039  */
   2040 static void
   2041 free_secbuffs(mandb_rec *rec)
   2042 {
   2043 	free(rec->desc.data);
   2044 	free(rec->lib.data);
   2045 	free(rec->return_vals.data);
   2046 	free(rec->exit_status.data);
   2047 	free(rec->env.data);
   2048 	free(rec->files.data);
   2049 	free(rec->diagnostics.data);
   2050 	free(rec->errors.data);
   2051 }
   2052 
   2053 static void
   2054 replace_hyph(char *str)
   2055 {
   2056 	char *iter = str;
   2057 	while ((iter = strchr(iter, ASCII_HYPH)) != NULL)
   2058 		*iter = '-';
   2059 
   2060 	iter = str;
   2061 	while ((iter = strchr(iter, ASCII_NBRSP)) != NULL)
   2062 		*iter = '-';
   2063 }
   2064 
   2065 static char *
   2066 parse_escape(const char *str)
   2067 {
   2068 	const char *backslash, *last_backslash;
   2069 	char *result, *iter;
   2070 	size_t len;
   2071 
   2072 	assert(str);
   2073 
   2074 	last_backslash = str;
   2075 	backslash = strchr(str, '\\');
   2076 	if (backslash == NULL) {
   2077 		result = estrdup(str);
   2078 		replace_hyph(result);
   2079 		return result;
   2080 	}
   2081 
   2082 	result = emalloc(strlen(str) + 1);
   2083 	iter = result;
   2084 
   2085 	do {
   2086 		len = backslash - last_backslash;
   2087 		memcpy(iter, last_backslash, len);
   2088 		iter += len;
   2089 		if (backslash[1] == '-' || backslash[1] == ' ') {
   2090 			*iter++ = backslash[1];
   2091 			last_backslash = backslash + 2;
   2092 			backslash = strchr(backslash + 2, '\\');
   2093 		} else {
   2094 			++backslash;
   2095 			mandoc_escape(&backslash, NULL, NULL);
   2096 			last_backslash = backslash;
   2097 			if (backslash == NULL)
   2098 				break;
   2099 			backslash = strchr(last_backslash, '\\');
   2100 		}
   2101 	} while (backslash != NULL);
   2102 	if (last_backslash != NULL)
   2103 		strcpy(iter, last_backslash);
   2104 
   2105 	replace_hyph(result);
   2106 	return result;
   2107 }
   2108 
   2109 /*
   2110  * append--
   2111  *  Concatenates a space and src at the end of sbuff->data (much like concat in
   2112  *  apropos-utils.c).
   2113  *  Rather than reallocating space for writing data, it uses the value of the
   2114  *  offset field of sec_buff to write new data at the free space left in the
   2115  *  buffer.
   2116  *  In case the size of the data to be appended exceeds the number of bytes left
   2117  *  in the buffer, it reallocates buflen number of bytes and then continues.
   2118  *  Value of offset field should be adjusted as new data is written.
   2119  *
   2120  *  NOTE: This function does not write the null byte at the end of the buffers,
   2121  *  write a null byte at the position pointed to by offset before inserting data
   2122  *  in the db.
   2123  */
   2124 static void
   2125 append(secbuff *sbuff, const char *src)
   2126 {
   2127 	short flag = 0;
   2128 	size_t srclen, newlen;
   2129 	char *temp;
   2130 
   2131 	assert(src != NULL);
   2132 	temp = parse_escape(src);
   2133 	srclen = strlen(temp);
   2134 
   2135 	if (sbuff->data == NULL) {
   2136 		sbuff->data = emalloc(sbuff->buflen);
   2137 		sbuff->offset = 0;
   2138 	}
   2139 
   2140 	newlen = sbuff->offset + srclen + 2;
   2141 	if (newlen >= sbuff->buflen) {
   2142 		while (sbuff->buflen < newlen)
   2143 			sbuff->buflen += sbuff->buflen;
   2144 		sbuff->data = erealloc(sbuff->data, sbuff->buflen);
   2145 		flag = 1;
   2146 	}
   2147 
   2148 	/* Append a space at the end of the buffer. */
   2149 	if (sbuff->offset || flag)
   2150 		sbuff->data[sbuff->offset++] = ' ';
   2151 	/* Now, copy src at the end of the buffer. */
   2152 	memcpy(sbuff->data + sbuff->offset, temp, srclen);
   2153 	sbuff->offset += srclen;
   2154 	free(temp);
   2155 }
   2156 
   2157 static void
   2158 usage(void)
   2159 {
   2160 	fprintf(stderr, "Usage: %s [-floQqv] [-C path]\n", getprogname());
   2161 	exit(1);
   2162 }
   2163