pkg.c revision 278564
1/*-
2 * Copyright (c) 2012-2014 Baptiste Daroussin <bapt@FreeBSD.org>
3 * Copyright (c) 2013 Bryan Drewery <bdrewery@FreeBSD.org>
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 * 1. Redistributions of source code must retain the above copyright
10 *    notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 *    notice, this list of conditions and the following disclaimer in the
13 *    documentation and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25 * SUCH DAMAGE.
26 */
27
28#include <sys/cdefs.h>
29__FBSDID("$FreeBSD: stable/10/usr.sbin/pkg/pkg.c 278564 2015-02-11 08:20:07Z bapt $");
30
31#include <sys/param.h>
32#include <sys/queue.h>
33#include <sys/types.h>
34#include <sys/sbuf.h>
35#include <sys/wait.h>
36
37#define _WITH_GETLINE
38#include <archive.h>
39#include <archive_entry.h>
40#include <dirent.h>
41#include <err.h>
42#include <errno.h>
43#include <fcntl.h>
44#include <fetch.h>
45#include <paths.h>
46#include <stdbool.h>
47#include <stdlib.h>
48#include <stdio.h>
49#include <string.h>
50#include <time.h>
51#include <unistd.h>
52#include <ucl.h>
53
54#include <openssl/err.h>
55#include <openssl/ssl.h>
56
57#include "dns_utils.h"
58#include "config.h"
59
60struct sig_cert {
61	char *name;
62	unsigned char *sig;
63	int siglen;
64	unsigned char *cert;
65	int certlen;
66	bool trusted;
67};
68
69typedef enum {
70       HASH_UNKNOWN,
71       HASH_SHA256,
72} hash_t;
73
74struct fingerprint {
75       hash_t type;
76       char *name;
77       char hash[BUFSIZ];
78       STAILQ_ENTRY(fingerprint) next;
79};
80
81STAILQ_HEAD(fingerprint_list, fingerprint);
82
83static int
84extract_pkg_static(int fd, char *p, int sz)
85{
86	struct archive *a;
87	struct archive_entry *ae;
88	char *end;
89	int ret, r;
90
91	ret = -1;
92	a = archive_read_new();
93	if (a == NULL) {
94		warn("archive_read_new");
95		return (ret);
96	}
97	archive_read_support_filter_all(a);
98	archive_read_support_format_tar(a);
99
100	if (lseek(fd, 0, 0) == -1) {
101		warn("lseek");
102		goto cleanup;
103	}
104
105	if (archive_read_open_fd(a, fd, 4096) != ARCHIVE_OK) {
106		warnx("archive_read_open_fd: %s", archive_error_string(a));
107		goto cleanup;
108	}
109
110	ae = NULL;
111	while ((r = archive_read_next_header(a, &ae)) == ARCHIVE_OK) {
112		end = strrchr(archive_entry_pathname(ae), '/');
113		if (end == NULL)
114			continue;
115
116		if (strcmp(end, "/pkg-static") == 0) {
117			r = archive_read_extract(a, ae,
118			    ARCHIVE_EXTRACT_OWNER | ARCHIVE_EXTRACT_PERM |
119			    ARCHIVE_EXTRACT_TIME | ARCHIVE_EXTRACT_ACL |
120			    ARCHIVE_EXTRACT_FFLAGS | ARCHIVE_EXTRACT_XATTR);
121			strlcpy(p, archive_entry_pathname(ae), sz);
122			break;
123		}
124	}
125
126	if (r == ARCHIVE_OK)
127		ret = 0;
128	else
129		warnx("failed to extract pkg-static: %s",
130		    archive_error_string(a));
131
132cleanup:
133	archive_read_free(a);
134	return (ret);
135
136}
137
138static int
139install_pkg_static(const char *path, const char *pkgpath, bool force)
140{
141	int pstat;
142	pid_t pid;
143
144	switch ((pid = fork())) {
145	case -1:
146		return (-1);
147	case 0:
148		if (force)
149			execl(path, "pkg-static", "add", "-f", pkgpath,
150			    (char *)NULL);
151		else
152			execl(path, "pkg-static", "add", pkgpath,
153			    (char *)NULL);
154		_exit(1);
155	default:
156		break;
157	}
158
159	while (waitpid(pid, &pstat, 0) == -1)
160		if (errno != EINTR)
161			return (-1);
162
163	if (WEXITSTATUS(pstat))
164		return (WEXITSTATUS(pstat));
165	else if (WIFSIGNALED(pstat))
166		return (128 & (WTERMSIG(pstat)));
167	return (pstat);
168}
169
170static int
171fetch_to_fd(const char *url, char *path)
172{
173	struct url *u;
174	struct dns_srvinfo *mirrors, *current;
175	struct url_stat st;
176	FILE *remote;
177	/* To store _https._tcp. + hostname + \0 */
178	int fd;
179	int retry, max_retry;
180	off_t done, r;
181	time_t now, last;
182	char buf[10240];
183	char zone[MAXHOSTNAMELEN + 13];
184	static const char *mirror_type = NULL;
185
186	done = 0;
187	last = 0;
188	max_retry = 3;
189	current = mirrors = NULL;
190	remote = NULL;
191
192	if (mirror_type == NULL && config_string(MIRROR_TYPE, &mirror_type)
193	    != 0) {
194		warnx("No MIRROR_TYPE defined");
195		return (-1);
196	}
197
198	if ((fd = mkstemp(path)) == -1) {
199		warn("mkstemp()");
200		return (-1);
201	}
202
203	retry = max_retry;
204
205	if ((u = fetchParseURL(url)) == NULL) {
206		warn("fetchParseURL('%s')", url);
207		return (-1);
208	}
209
210	while (remote == NULL) {
211		if (retry == max_retry) {
212			if (strcmp(u->scheme, "file") != 0 &&
213			    strcasecmp(mirror_type, "srv") == 0) {
214				snprintf(zone, sizeof(zone),
215				    "_%s._tcp.%s", u->scheme, u->host);
216				mirrors = dns_getsrvinfo(zone);
217				current = mirrors;
218			}
219		}
220
221		if (mirrors != NULL) {
222			strlcpy(u->host, current->host, sizeof(u->host));
223			u->port = current->port;
224		}
225
226		remote = fetchXGet(u, &st, "");
227		if (remote == NULL) {
228			--retry;
229			if (retry <= 0)
230				goto fetchfail;
231			if (mirrors == NULL) {
232				sleep(1);
233			} else {
234				current = current->next;
235				if (current == NULL)
236					current = mirrors;
237			}
238		}
239	}
240
241	if (remote == NULL)
242		goto fetchfail;
243
244	while (done < st.size) {
245		if ((r = fread(buf, 1, sizeof(buf), remote)) < 1)
246			break;
247
248		if (write(fd, buf, r) != r) {
249			warn("write()");
250			goto fetchfail;
251		}
252
253		done += r;
254		now = time(NULL);
255		if (now > last || done == st.size)
256			last = now;
257	}
258
259	if (ferror(remote))
260		goto fetchfail;
261
262	goto cleanup;
263
264fetchfail:
265	if (fd != -1) {
266		close(fd);
267		fd = -1;
268		unlink(path);
269	}
270
271cleanup:
272	if (remote != NULL)
273		fclose(remote);
274
275	return fd;
276}
277
278static struct fingerprint *
279parse_fingerprint(ucl_object_t *obj)
280{
281	const ucl_object_t *cur;
282	ucl_object_iter_t it = NULL;
283	const char *function, *fp, *key;
284	struct fingerprint *f;
285	hash_t fct = HASH_UNKNOWN;
286
287	function = fp = NULL;
288
289	while ((cur = ucl_iterate_object(obj, &it, true))) {
290		key = ucl_object_key(cur);
291		if (cur->type != UCL_STRING)
292			continue;
293		if (strcasecmp(key, "function") == 0) {
294			function = ucl_object_tostring(cur);
295			continue;
296		}
297		if (strcasecmp(key, "fingerprint") == 0) {
298			fp = ucl_object_tostring(cur);
299			continue;
300		}
301	}
302
303	if (fp == NULL || function == NULL)
304		return (NULL);
305
306	if (strcasecmp(function, "sha256") == 0)
307		fct = HASH_SHA256;
308
309	if (fct == HASH_UNKNOWN) {
310		warnx("Unsupported hashing function: %s", function);
311		return (NULL);
312	}
313
314	f = calloc(1, sizeof(struct fingerprint));
315	f->type = fct;
316	strlcpy(f->hash, fp, sizeof(f->hash));
317
318	return (f);
319}
320
321static void
322free_fingerprint_list(struct fingerprint_list* list)
323{
324	struct fingerprint *fingerprint, *tmp;
325
326	STAILQ_FOREACH_SAFE(fingerprint, list, next, tmp) {
327		if (fingerprint->name)
328			free(fingerprint->name);
329		free(fingerprint);
330	}
331	free(list);
332}
333
334static struct fingerprint *
335load_fingerprint(const char *dir, const char *filename)
336{
337	ucl_object_t *obj = NULL;
338	struct ucl_parser *p = NULL;
339	struct fingerprint *f;
340	char path[MAXPATHLEN];
341
342	f = NULL;
343
344	snprintf(path, MAXPATHLEN, "%s/%s", dir, filename);
345
346	p = ucl_parser_new(0);
347	if (!ucl_parser_add_file(p, path)) {
348		warnx("%s: %s", path, ucl_parser_get_error(p));
349		ucl_parser_free(p);
350		return (NULL);
351	}
352
353	obj = ucl_parser_get_object(p);
354
355	if (obj->type == UCL_OBJECT)
356		f = parse_fingerprint(obj);
357
358	if (f != NULL)
359		f->name = strdup(filename);
360
361	ucl_object_unref(obj);
362	ucl_parser_free(p);
363
364	return (f);
365}
366
367static struct fingerprint_list *
368load_fingerprints(const char *path, int *count)
369{
370	DIR *d;
371	struct dirent *ent;
372	struct fingerprint *finger;
373	struct fingerprint_list *fingerprints;
374
375	*count = 0;
376
377	fingerprints = calloc(1, sizeof(struct fingerprint_list));
378	if (fingerprints == NULL)
379		return (NULL);
380	STAILQ_INIT(fingerprints);
381
382	if ((d = opendir(path)) == NULL) {
383		free(fingerprints);
384
385		return (NULL);
386	}
387
388	while ((ent = readdir(d))) {
389		if (strcmp(ent->d_name, ".") == 0 ||
390		    strcmp(ent->d_name, "..") == 0)
391			continue;
392		finger = load_fingerprint(path, ent->d_name);
393		if (finger != NULL) {
394			STAILQ_INSERT_TAIL(fingerprints, finger, next);
395			++(*count);
396		}
397	}
398
399	closedir(d);
400
401	return (fingerprints);
402}
403
404static void
405sha256_hash(unsigned char hash[SHA256_DIGEST_LENGTH],
406    char out[SHA256_DIGEST_LENGTH * 2 + 1])
407{
408	int i;
409
410	for (i = 0; i < SHA256_DIGEST_LENGTH; i++)
411		sprintf(out + (i * 2), "%02x", hash[i]);
412
413	out[SHA256_DIGEST_LENGTH * 2] = '\0';
414}
415
416static void
417sha256_buf(char *buf, size_t len, char out[SHA256_DIGEST_LENGTH * 2 + 1])
418{
419	unsigned char hash[SHA256_DIGEST_LENGTH];
420	SHA256_CTX sha256;
421
422	out[0] = '\0';
423
424	SHA256_Init(&sha256);
425	SHA256_Update(&sha256, buf, len);
426	SHA256_Final(hash, &sha256);
427	sha256_hash(hash, out);
428}
429
430static int
431sha256_fd(int fd, char out[SHA256_DIGEST_LENGTH * 2 + 1])
432{
433	int my_fd;
434	FILE *fp;
435	char buffer[BUFSIZ];
436	unsigned char hash[SHA256_DIGEST_LENGTH];
437	size_t r;
438	int ret;
439	SHA256_CTX sha256;
440
441	my_fd = -1;
442	fp = NULL;
443	r = 0;
444	ret = 1;
445
446	out[0] = '\0';
447
448	/* Duplicate the fd so that fclose(3) does not close it. */
449	if ((my_fd = dup(fd)) == -1) {
450		warnx("dup");
451		goto cleanup;
452	}
453
454	if ((fp = fdopen(my_fd, "rb")) == NULL) {
455		warnx("fdopen");
456		goto cleanup;
457	}
458
459	SHA256_Init(&sha256);
460
461	while ((r = fread(buffer, 1, BUFSIZ, fp)) > 0)
462		SHA256_Update(&sha256, buffer, r);
463
464	if (ferror(fp) != 0) {
465		warnx("fread");
466		goto cleanup;
467	}
468
469	SHA256_Final(hash, &sha256);
470	sha256_hash(hash, out);
471	ret = 0;
472
473cleanup:
474	if (fp != NULL)
475		fclose(fp);
476	else if (my_fd != -1)
477		close(my_fd);
478	(void)lseek(fd, 0, SEEK_SET);
479
480	return (ret);
481}
482
483static EVP_PKEY *
484load_public_key_buf(const unsigned char *cert, int certlen)
485{
486	EVP_PKEY *pkey;
487	BIO *bp;
488	char errbuf[1024];
489
490	bp = BIO_new_mem_buf(__DECONST(void *, cert), certlen);
491
492	if ((pkey = PEM_read_bio_PUBKEY(bp, NULL, NULL, NULL)) == NULL)
493		warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
494
495	BIO_free(bp);
496
497	return (pkey);
498}
499
500static bool
501rsa_verify_cert(int fd, const unsigned char *key, int keylen,
502    unsigned char *sig, int siglen)
503{
504	EVP_MD_CTX *mdctx;
505	EVP_PKEY *pkey;
506	char sha256[(SHA256_DIGEST_LENGTH * 2) + 2];
507	char errbuf[1024];
508	bool ret;
509
510	pkey = NULL;
511	mdctx = NULL;
512	ret = false;
513
514	/* Compute SHA256 of the package. */
515	if (lseek(fd, 0, 0) == -1) {
516		warn("lseek");
517		goto cleanup;
518	}
519	if ((sha256_fd(fd, sha256)) == -1) {
520		warnx("Error creating SHA256 hash for package");
521		goto cleanup;
522	}
523
524	if ((pkey = load_public_key_buf(key, keylen)) == NULL) {
525		warnx("Error reading public key");
526		goto cleanup;
527	}
528
529	/* Verify signature of the SHA256(pkg) is valid. */
530	if ((mdctx = EVP_MD_CTX_create()) == NULL) {
531		warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
532		goto error;
533	}
534
535	if (EVP_DigestVerifyInit(mdctx, NULL, EVP_sha256(), NULL, pkey) != 1) {
536		warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
537		goto error;
538	}
539	if (EVP_DigestVerifyUpdate(mdctx, sha256, strlen(sha256)) != 1) {
540		warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
541		goto error;
542	}
543
544	if (EVP_DigestVerifyFinal(mdctx, sig, siglen) != 1) {
545		warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
546		goto error;
547	}
548
549	ret = true;
550	printf("done\n");
551	goto cleanup;
552
553error:
554	printf("failed\n");
555
556cleanup:
557	if (pkey)
558		EVP_PKEY_free(pkey);
559	if (mdctx)
560		EVP_MD_CTX_destroy(mdctx);
561	ERR_free_strings();
562
563	return (ret);
564}
565
566static struct sig_cert *
567parse_cert(int fd) {
568	int my_fd;
569	struct sig_cert *sc;
570	FILE *fp;
571	struct sbuf *buf, *sig, *cert;
572	char *line;
573	size_t linecap;
574	ssize_t linelen;
575
576	buf = NULL;
577	my_fd = -1;
578	sc = NULL;
579	line = NULL;
580	linecap = 0;
581
582	if (lseek(fd, 0, 0) == -1) {
583		warn("lseek");
584		return (NULL);
585	}
586
587	/* Duplicate the fd so that fclose(3) does not close it. */
588	if ((my_fd = dup(fd)) == -1) {
589		warnx("dup");
590		return (NULL);
591	}
592
593	if ((fp = fdopen(my_fd, "rb")) == NULL) {
594		warn("fdopen");
595		close(my_fd);
596		return (NULL);
597	}
598
599	sig = sbuf_new_auto();
600	cert = sbuf_new_auto();
601
602	while ((linelen = getline(&line, &linecap, fp)) > 0) {
603		if (strcmp(line, "SIGNATURE\n") == 0) {
604			buf = sig;
605			continue;
606		} else if (strcmp(line, "CERT\n") == 0) {
607			buf = cert;
608			continue;
609		} else if (strcmp(line, "END\n") == 0) {
610			break;
611		}
612		if (buf != NULL)
613			sbuf_bcat(buf, line, linelen);
614	}
615
616	fclose(fp);
617
618	/* Trim out unrelated trailing newline */
619	sbuf_setpos(sig, sbuf_len(sig) - 1);
620
621	sbuf_finish(sig);
622	sbuf_finish(cert);
623
624	sc = calloc(1, sizeof(struct sig_cert));
625	sc->siglen = sbuf_len(sig);
626	sc->sig = calloc(1, sc->siglen);
627	memcpy(sc->sig, sbuf_data(sig), sc->siglen);
628
629	sc->certlen = sbuf_len(cert);
630	sc->cert = strdup(sbuf_data(cert));
631
632	sbuf_delete(sig);
633	sbuf_delete(cert);
634
635	return (sc);
636}
637
638static bool
639verify_signature(int fd_pkg, int fd_sig)
640{
641	struct fingerprint_list *trusted, *revoked;
642	struct fingerprint *fingerprint;
643	struct sig_cert *sc;
644	bool ret;
645	int trusted_count, revoked_count;
646	const char *fingerprints;
647	char path[MAXPATHLEN];
648	char hash[SHA256_DIGEST_LENGTH * 2 + 1];
649
650	sc = NULL;
651	trusted = revoked = NULL;
652	ret = false;
653
654	/* Read and parse fingerprints. */
655	if (config_string(FINGERPRINTS, &fingerprints) != 0) {
656		warnx("No CONFIG_FINGERPRINTS defined");
657		goto cleanup;
658	}
659
660	snprintf(path, MAXPATHLEN, "%s/trusted", fingerprints);
661	if ((trusted = load_fingerprints(path, &trusted_count)) == NULL) {
662		warnx("Error loading trusted certificates");
663		goto cleanup;
664	}
665
666	if (trusted_count == 0 || trusted == NULL) {
667		fprintf(stderr, "No trusted certificates found.\n");
668		goto cleanup;
669	}
670
671	snprintf(path, MAXPATHLEN, "%s/revoked", fingerprints);
672	if ((revoked = load_fingerprints(path, &revoked_count)) == NULL) {
673		warnx("Error loading revoked certificates");
674		goto cleanup;
675	}
676
677	/* Read certificate and signature in. */
678	if ((sc = parse_cert(fd_sig)) == NULL) {
679		warnx("Error parsing certificate");
680		goto cleanup;
681	}
682	/* Explicitly mark as non-trusted until proven otherwise. */
683	sc->trusted = false;
684
685	/* Parse signature and pubkey out of the certificate */
686	sha256_buf(sc->cert, sc->certlen, hash);
687
688	/* Check if this hash is revoked */
689	if (revoked != NULL) {
690		STAILQ_FOREACH(fingerprint, revoked, next) {
691			if (strcasecmp(fingerprint->hash, hash) == 0) {
692				fprintf(stderr, "The package was signed with "
693				    "revoked certificate %s\n",
694				    fingerprint->name);
695				goto cleanup;
696			}
697		}
698	}
699
700	STAILQ_FOREACH(fingerprint, trusted, next) {
701		if (strcasecmp(fingerprint->hash, hash) == 0) {
702			sc->trusted = true;
703			sc->name = strdup(fingerprint->name);
704			break;
705		}
706	}
707
708	if (sc->trusted == false) {
709		fprintf(stderr, "No trusted fingerprint found matching "
710		    "package's certificate\n");
711		goto cleanup;
712	}
713
714	/* Verify the signature. */
715	printf("Verifying signature with trusted certificate %s... ", sc->name);
716	if (rsa_verify_cert(fd_pkg, sc->cert, sc->certlen, sc->sig,
717	    sc->siglen) == false) {
718		fprintf(stderr, "Signature is not valid\n");
719		goto cleanup;
720	}
721
722	ret = true;
723
724cleanup:
725	if (trusted)
726		free_fingerprint_list(trusted);
727	if (revoked)
728		free_fingerprint_list(revoked);
729	if (sc) {
730		if (sc->cert)
731			free(sc->cert);
732		if (sc->sig)
733			free(sc->sig);
734		if (sc->name)
735			free(sc->name);
736		free(sc);
737	}
738
739	return (ret);
740}
741
742static int
743bootstrap_pkg(bool force)
744{
745	int fd_pkg, fd_sig;
746	int ret;
747	char url[MAXPATHLEN];
748	char tmppkg[MAXPATHLEN];
749	char tmpsig[MAXPATHLEN];
750	const char *packagesite;
751	const char *signature_type;
752	char pkgstatic[MAXPATHLEN];
753
754	fd_sig = -1;
755	ret = -1;
756
757	if (config_string(PACKAGESITE, &packagesite) != 0) {
758		warnx("No PACKAGESITE defined");
759		return (-1);
760	}
761
762	if (config_string(SIGNATURE_TYPE, &signature_type) != 0) {
763		warnx("Error looking up SIGNATURE_TYPE");
764		return (-1);
765	}
766
767	printf("Bootstrapping pkg from %s, please wait...\n", packagesite);
768
769	/* Support pkg+http:// for PACKAGESITE which is the new format
770	   in 1.2 to avoid confusion on why http://pkg.FreeBSD.org has
771	   no A record. */
772	if (strncmp(URL_SCHEME_PREFIX, packagesite,
773	    strlen(URL_SCHEME_PREFIX)) == 0)
774		packagesite += strlen(URL_SCHEME_PREFIX);
775	snprintf(url, MAXPATHLEN, "%s/Latest/pkg.txz", packagesite);
776
777	snprintf(tmppkg, MAXPATHLEN, "%s/pkg.txz.XXXXXX",
778	    getenv("TMPDIR") ? getenv("TMPDIR") : _PATH_TMP);
779
780	if ((fd_pkg = fetch_to_fd(url, tmppkg)) == -1)
781		goto fetchfail;
782
783	if (signature_type != NULL &&
784	    strcasecmp(signature_type, "FINGERPRINTS") == 0) {
785		snprintf(tmpsig, MAXPATHLEN, "%s/pkg.txz.sig.XXXXXX",
786		    getenv("TMPDIR") ? getenv("TMPDIR") : _PATH_TMP);
787		snprintf(url, MAXPATHLEN, "%s/Latest/pkg.txz.sig",
788		    packagesite);
789
790		if ((fd_sig = fetch_to_fd(url, tmpsig)) == -1) {
791			fprintf(stderr, "Signature for pkg not available.\n");
792			goto fetchfail;
793		}
794
795		if (verify_signature(fd_pkg, fd_sig) == false)
796			goto cleanup;
797	}
798
799	if ((ret = extract_pkg_static(fd_pkg, pkgstatic, MAXPATHLEN)) == 0)
800		ret = install_pkg_static(pkgstatic, tmppkg, force);
801
802	goto cleanup;
803
804fetchfail:
805	warnx("Error fetching %s: %s", url, fetchLastErrString);
806	fprintf(stderr, "A pre-built version of pkg could not be found for "
807	    "your system.\n");
808	fprintf(stderr, "Consider changing PACKAGESITE or installing it from "
809	    "ports: 'ports-mgmt/pkg'.\n");
810
811cleanup:
812	if (fd_sig != -1) {
813		close(fd_sig);
814		unlink(tmpsig);
815	}
816
817	if (fd_pkg != -1) {
818		close(fd_pkg);
819		unlink(tmppkg);
820	}
821
822	return (ret);
823}
824
825static const char confirmation_message[] =
826"The package management tool is not yet installed on your system.\n"
827"Do you want to fetch and install it now? [y/N]: ";
828
829static int
830pkg_query_yes_no(void)
831{
832	int ret, c;
833
834	c = getchar();
835
836	if (c == 'y' || c == 'Y')
837		ret = 1;
838	else
839		ret = 0;
840
841	while (c != '\n' && c != EOF)
842		c = getchar();
843
844	return (ret);
845}
846
847static int
848bootstrap_pkg_local(const char *pkgpath, bool force)
849{
850	char path[MAXPATHLEN];
851	char pkgstatic[MAXPATHLEN];
852	const char *signature_type;
853	int fd_pkg, fd_sig, ret;
854
855	fd_sig = -1;
856	ret = -1;
857
858	fd_pkg = open(pkgpath, O_RDONLY);
859	if (fd_pkg == -1)
860		err(EXIT_FAILURE, "Unable to open %s", pkgpath);
861
862	if (config_string(SIGNATURE_TYPE, &signature_type) != 0) {
863		warnx("Error looking up SIGNATURE_TYPE");
864		goto cleanup;
865	}
866	if (signature_type != NULL &&
867	    strcasecmp(signature_type, "FINGERPRINTS") == 0) {
868		snprintf(path, sizeof(path), "%s.sig", pkgpath);
869
870		if ((fd_sig = open(path, O_RDONLY)) == -1) {
871			fprintf(stderr, "Signature for pkg not available.\n");
872			goto cleanup;
873		}
874
875		if (verify_signature(fd_pkg, fd_sig) == false)
876			goto cleanup;
877	}
878
879	if ((ret = extract_pkg_static(fd_pkg, pkgstatic, MAXPATHLEN)) == 0)
880		ret = install_pkg_static(pkgstatic, pkgpath, force);
881
882cleanup:
883	close(fd_pkg);
884	if (fd_sig != -1)
885		close(fd_sig);
886
887	return (ret);
888}
889
890int
891main(__unused int argc, char *argv[])
892{
893	char pkgpath[MAXPATHLEN];
894	const char *pkgarg;
895	bool bootstrap_only, force, yes;
896
897	bootstrap_only = false;
898	force = false;
899	pkgarg = NULL;
900	yes = false;
901
902	snprintf(pkgpath, MAXPATHLEN, "%s/sbin/pkg",
903	    getenv("LOCALBASE") ? getenv("LOCALBASE") : _LOCALBASE);
904
905	if (argc > 1 && strcmp(argv[1], "bootstrap") == 0) {
906		bootstrap_only = true;
907		if (argc == 3 && strcmp(argv[2], "-f") == 0)
908			force = true;
909	}
910
911	if ((bootstrap_only && force) || access(pkgpath, X_OK) == -1) {
912		/*
913		 * To allow 'pkg -N' to be used as a reliable test for whether
914		 * a system is configured to use pkg, don't bootstrap pkg
915		 * when that argument is given as argv[1].
916		 */
917		if (argv[1] != NULL && strcmp(argv[1], "-N") == 0)
918			errx(EXIT_FAILURE, "pkg is not installed");
919
920		config_init();
921
922		if (argc > 1 && strcmp(argv[1], "add") == 0) {
923			if (argc > 2 && strcmp(argv[2], "-f") == 0) {
924				force = true;
925				pkgarg = argv[3];
926			} else
927				pkgarg = argv[2];
928			if (pkgarg == NULL) {
929				fprintf(stderr, "Path to pkg.txz required\n");
930				exit(EXIT_FAILURE);
931			}
932			if (access(pkgarg, R_OK) == -1) {
933				fprintf(stderr, "No such file: %s\n", pkgarg);
934				exit(EXIT_FAILURE);
935			}
936			if (bootstrap_pkg_local(pkgarg, force) != 0)
937				exit(EXIT_FAILURE);
938			exit(EXIT_SUCCESS);
939		}
940		/*
941		 * Do not ask for confirmation if either of stdin or stdout is
942		 * not tty. Check the environment to see if user has answer
943		 * tucked in there already.
944		 */
945		config_bool(ASSUME_ALWAYS_YES, &yes);
946		if (!yes) {
947			printf("%s", confirmation_message);
948			if (!isatty(fileno(stdin)))
949				exit(EXIT_FAILURE);
950
951			if (pkg_query_yes_no() == 0)
952				exit(EXIT_FAILURE);
953		}
954		if (bootstrap_pkg(force) != 0)
955			exit(EXIT_FAILURE);
956		config_finish();
957
958		if (bootstrap_only)
959			exit(EXIT_SUCCESS);
960	} else if (bootstrap_only) {
961		printf("pkg already bootstrapped at %s\n", pkgpath);
962		exit(EXIT_SUCCESS);
963	}
964
965	execv(pkgpath, argv);
966
967	/* NOT REACHED */
968	return (EXIT_FAILURE);
969}
970