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