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