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