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