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