pkg.c revision 287146
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: releng/10.1/usr.sbin/pkg/pkg.c 287146 2015-08-25 20:48:58Z delphij $");
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	u = fetchParseURL(url);
206	while (remote == NULL) {
207		if (retry == max_retry) {
208			if (strcmp(u->scheme, "file") != 0 &&
209			    strcasecmp(mirror_type, "srv") == 0) {
210				snprintf(zone, sizeof(zone),
211				    "_%s._tcp.%s", u->scheme, u->host);
212				mirrors = dns_getsrvinfo(zone);
213				current = mirrors;
214			}
215		}
216
217		if (mirrors != NULL) {
218			strlcpy(u->host, current->host, sizeof(u->host));
219			u->port = current->port;
220		}
221
222		remote = fetchXGet(u, &st, "");
223		if (remote == NULL) {
224			--retry;
225			if (retry <= 0)
226				goto fetchfail;
227			if (mirrors == NULL) {
228				sleep(1);
229			} else {
230				current = current->next;
231				if (current == NULL)
232					current = mirrors;
233			}
234		}
235	}
236
237	if (remote == NULL)
238		goto fetchfail;
239
240	while (done < st.size) {
241		if ((r = fread(buf, 1, sizeof(buf), remote)) < 1)
242			break;
243
244		if (write(fd, buf, r) != r) {
245			warn("write()");
246			goto fetchfail;
247		}
248
249		done += r;
250		now = time(NULL);
251		if (now > last || done == st.size)
252			last = now;
253	}
254
255	if (ferror(remote))
256		goto fetchfail;
257
258	goto cleanup;
259
260fetchfail:
261	if (fd != -1) {
262		close(fd);
263		fd = -1;
264		unlink(path);
265	}
266
267cleanup:
268	if (remote != NULL)
269		fclose(remote);
270
271	return fd;
272}
273
274static struct fingerprint *
275parse_fingerprint(ucl_object_t *obj)
276{
277	const ucl_object_t *cur;
278	ucl_object_iter_t it = NULL;
279	const char *function, *fp, *key;
280	struct fingerprint *f;
281	hash_t fct = HASH_UNKNOWN;
282
283	function = fp = NULL;
284
285	while ((cur = ucl_iterate_object(obj, &it, true))) {
286		key = ucl_object_key(cur);
287		if (cur->type != UCL_STRING)
288			continue;
289		if (strcasecmp(key, "function") == 0) {
290			function = ucl_object_tostring(cur);
291			continue;
292		}
293		if (strcasecmp(key, "fingerprint") == 0) {
294			fp = ucl_object_tostring(cur);
295			continue;
296		}
297	}
298
299	if (fp == NULL || function == NULL)
300		return (NULL);
301
302	if (strcasecmp(function, "sha256") == 0)
303		fct = HASH_SHA256;
304
305	if (fct == HASH_UNKNOWN) {
306		warnx("Unsupported hashing function: %s", function);
307		return (NULL);
308	}
309
310	f = calloc(1, sizeof(struct fingerprint));
311	f->type = fct;
312	strlcpy(f->hash, fp, sizeof(f->hash));
313
314	return (f);
315}
316
317static void
318free_fingerprint_list(struct fingerprint_list* list)
319{
320	struct fingerprint *fingerprint, *tmp;
321
322	STAILQ_FOREACH_SAFE(fingerprint, list, next, tmp) {
323		if (fingerprint->name)
324			free(fingerprint->name);
325		free(fingerprint);
326	}
327	free(list);
328}
329
330static struct fingerprint *
331load_fingerprint(const char *dir, const char *filename)
332{
333	ucl_object_t *obj = NULL;
334	struct ucl_parser *p = NULL;
335	struct fingerprint *f;
336	char path[MAXPATHLEN];
337
338	f = NULL;
339
340	snprintf(path, MAXPATHLEN, "%s/%s", dir, filename);
341
342	p = ucl_parser_new(0);
343	if (!ucl_parser_add_file(p, path)) {
344		warnx("%s: %s", path, ucl_parser_get_error(p));
345		ucl_parser_free(p);
346		return (NULL);
347	}
348
349	obj = ucl_parser_get_object(p);
350
351	if (obj->type == UCL_OBJECT)
352		f = parse_fingerprint(obj);
353
354	if (f != NULL)
355		f->name = strdup(filename);
356
357	ucl_object_unref(obj);
358	ucl_parser_free(p);
359
360	return (f);
361}
362
363static struct fingerprint_list *
364load_fingerprints(const char *path, int *count)
365{
366	DIR *d;
367	struct dirent *ent;
368	struct fingerprint *finger;
369	struct fingerprint_list *fingerprints;
370
371	*count = 0;
372
373	fingerprints = calloc(1, sizeof(struct fingerprint_list));
374	if (fingerprints == NULL)
375		return (NULL);
376	STAILQ_INIT(fingerprints);
377
378	if ((d = opendir(path)) == NULL)
379		return (NULL);
380
381	while ((ent = readdir(d))) {
382		if (strcmp(ent->d_name, ".") == 0 ||
383		    strcmp(ent->d_name, "..") == 0)
384			continue;
385		finger = load_fingerprint(path, ent->d_name);
386		if (finger != NULL) {
387			STAILQ_INSERT_TAIL(fingerprints, finger, next);
388			++(*count);
389		}
390	}
391
392	closedir(d);
393
394	return (fingerprints);
395}
396
397static void
398sha256_hash(unsigned char hash[SHA256_DIGEST_LENGTH],
399    char out[SHA256_DIGEST_LENGTH * 2 + 1])
400{
401	int i;
402
403	for (i = 0; i < SHA256_DIGEST_LENGTH; i++)
404		sprintf(out + (i * 2), "%02x", hash[i]);
405
406	out[SHA256_DIGEST_LENGTH * 2] = '\0';
407}
408
409static void
410sha256_buf(char *buf, size_t len, char out[SHA256_DIGEST_LENGTH * 2 + 1])
411{
412	unsigned char hash[SHA256_DIGEST_LENGTH];
413	SHA256_CTX sha256;
414
415	out[0] = '\0';
416
417	SHA256_Init(&sha256);
418	SHA256_Update(&sha256, buf, len);
419	SHA256_Final(hash, &sha256);
420	sha256_hash(hash, out);
421}
422
423static int
424sha256_fd(int fd, char out[SHA256_DIGEST_LENGTH * 2 + 1])
425{
426	int my_fd;
427	FILE *fp;
428	char buffer[BUFSIZ];
429	unsigned char hash[SHA256_DIGEST_LENGTH];
430	size_t r;
431	int ret;
432	SHA256_CTX sha256;
433
434	my_fd = -1;
435	fp = NULL;
436	r = 0;
437	ret = 1;
438
439	out[0] = '\0';
440
441	/* Duplicate the fd so that fclose(3) does not close it. */
442	if ((my_fd = dup(fd)) == -1) {
443		warnx("dup");
444		goto cleanup;
445	}
446
447	if ((fp = fdopen(my_fd, "rb")) == NULL) {
448		warnx("fdopen");
449		goto cleanup;
450	}
451
452	SHA256_Init(&sha256);
453
454	while ((r = fread(buffer, 1, BUFSIZ, fp)) > 0)
455		SHA256_Update(&sha256, buffer, r);
456
457	if (ferror(fp) != 0) {
458		warnx("fread");
459		goto cleanup;
460	}
461
462	SHA256_Final(hash, &sha256);
463	sha256_hash(hash, out);
464	ret = 0;
465
466cleanup:
467	if (fp != NULL)
468		fclose(fp);
469	else if (my_fd != -1)
470		close(my_fd);
471	(void)lseek(fd, 0, SEEK_SET);
472
473	return (ret);
474}
475
476static EVP_PKEY *
477load_public_key_buf(const unsigned char *cert, int certlen)
478{
479	EVP_PKEY *pkey;
480	BIO *bp;
481	char errbuf[1024];
482
483	bp = BIO_new_mem_buf(__DECONST(void *, cert), certlen);
484
485	if ((pkey = PEM_read_bio_PUBKEY(bp, NULL, NULL, NULL)) == NULL)
486		warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
487
488	BIO_free(bp);
489
490	return (pkey);
491}
492
493static bool
494rsa_verify_cert(int fd, const unsigned char *key, int keylen,
495    unsigned char *sig, int siglen)
496{
497	EVP_MD_CTX *mdctx;
498	EVP_PKEY *pkey;
499	char sha256[(SHA256_DIGEST_LENGTH * 2) + 2];
500	char errbuf[1024];
501	bool ret;
502
503	pkey = NULL;
504	mdctx = NULL;
505	ret = false;
506
507	/* Compute SHA256 of the package. */
508	if (lseek(fd, 0, 0) == -1) {
509		warn("lseek");
510		goto cleanup;
511	}
512	if ((sha256_fd(fd, sha256)) == -1) {
513		warnx("Error creating SHA256 hash for package");
514		goto cleanup;
515	}
516
517	if ((pkey = load_public_key_buf(key, keylen)) == NULL) {
518		warnx("Error reading public key");
519		goto cleanup;
520	}
521
522	/* Verify signature of the SHA256(pkg) is valid. */
523	if ((mdctx = EVP_MD_CTX_create()) == NULL) {
524		warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
525		goto error;
526	}
527
528	if (EVP_DigestVerifyInit(mdctx, NULL, EVP_sha256(), NULL, pkey) != 1) {
529		warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
530		goto error;
531	}
532	if (EVP_DigestVerifyUpdate(mdctx, sha256, strlen(sha256)) != 1) {
533		warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
534		goto error;
535	}
536
537	if (EVP_DigestVerifyFinal(mdctx, sig, siglen) != 1) {
538		warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
539		goto error;
540	}
541
542	ret = true;
543	printf("done\n");
544	goto cleanup;
545
546error:
547	printf("failed\n");
548
549cleanup:
550	if (pkey)
551		EVP_PKEY_free(pkey);
552	if (mdctx)
553		EVP_MD_CTX_destroy(mdctx);
554	ERR_free_strings();
555
556	return (ret);
557}
558
559static struct sig_cert *
560parse_cert(int fd) {
561	int my_fd;
562	struct sig_cert *sc;
563	FILE *fp;
564	struct sbuf *buf, *sig, *cert;
565	char *line;
566	size_t linecap;
567	ssize_t linelen;
568
569	buf = NULL;
570	my_fd = -1;
571	sc = NULL;
572	line = NULL;
573	linecap = 0;
574
575	if (lseek(fd, 0, 0) == -1) {
576		warn("lseek");
577		return (NULL);
578	}
579
580	/* Duplicate the fd so that fclose(3) does not close it. */
581	if ((my_fd = dup(fd)) == -1) {
582		warnx("dup");
583		return (NULL);
584	}
585
586	if ((fp = fdopen(my_fd, "rb")) == NULL) {
587		warn("fdopen");
588		close(my_fd);
589		return (NULL);
590	}
591
592	sig = sbuf_new_auto();
593	cert = sbuf_new_auto();
594
595	while ((linelen = getline(&line, &linecap, fp)) > 0) {
596		if (strcmp(line, "SIGNATURE\n") == 0) {
597			buf = sig;
598			continue;
599		} else if (strcmp(line, "CERT\n") == 0) {
600			buf = cert;
601			continue;
602		} else if (strcmp(line, "END\n") == 0) {
603			break;
604		}
605		if (buf != NULL)
606			sbuf_bcat(buf, line, linelen);
607	}
608
609	fclose(fp);
610
611	/* Trim out unrelated trailing newline */
612	sbuf_setpos(sig, sbuf_len(sig) - 1);
613
614	sbuf_finish(sig);
615	sbuf_finish(cert);
616
617	sc = calloc(1, sizeof(struct sig_cert));
618	sc->siglen = sbuf_len(sig);
619	sc->sig = calloc(1, sc->siglen);
620	memcpy(sc->sig, sbuf_data(sig), sc->siglen);
621
622	sc->certlen = sbuf_len(cert);
623	sc->cert = strdup(sbuf_data(cert));
624
625	sbuf_delete(sig);
626	sbuf_delete(cert);
627
628	return (sc);
629}
630
631static bool
632verify_signature(int fd_pkg, int fd_sig)
633{
634	struct fingerprint_list *trusted, *revoked;
635	struct fingerprint *fingerprint;
636	struct sig_cert *sc;
637	bool ret;
638	int trusted_count, revoked_count;
639	const char *fingerprints;
640	char path[MAXPATHLEN];
641	char hash[SHA256_DIGEST_LENGTH * 2 + 1];
642
643	sc = NULL;
644	trusted = revoked = NULL;
645	ret = false;
646
647	/* Read and parse fingerprints. */
648	if (config_string(FINGERPRINTS, &fingerprints) != 0) {
649		warnx("No CONFIG_FINGERPRINTS defined");
650		goto cleanup;
651	}
652
653	snprintf(path, MAXPATHLEN, "%s/trusted", fingerprints);
654	if ((trusted = load_fingerprints(path, &trusted_count)) == NULL) {
655		warnx("Error loading trusted certificates");
656		goto cleanup;
657	}
658
659	if (trusted_count == 0 || trusted == NULL) {
660		fprintf(stderr, "No trusted certificates found.\n");
661		goto cleanup;
662	}
663
664	snprintf(path, MAXPATHLEN, "%s/revoked", fingerprints);
665	if ((revoked = load_fingerprints(path, &revoked_count)) == NULL) {
666		warnx("Error loading revoked certificates");
667		goto cleanup;
668	}
669
670	/* Read certificate and signature in. */
671	if ((sc = parse_cert(fd_sig)) == NULL) {
672		warnx("Error parsing certificate");
673		goto cleanup;
674	}
675	/* Explicitly mark as non-trusted until proven otherwise. */
676	sc->trusted = false;
677
678	/* Parse signature and pubkey out of the certificate */
679	sha256_buf(sc->cert, sc->certlen, hash);
680
681	/* Check if this hash is revoked */
682	if (revoked != NULL) {
683		STAILQ_FOREACH(fingerprint, revoked, next) {
684			if (strcasecmp(fingerprint->hash, hash) == 0) {
685				fprintf(stderr, "The package was signed with "
686				    "revoked certificate %s\n",
687				    fingerprint->name);
688				goto cleanup;
689			}
690		}
691	}
692
693	STAILQ_FOREACH(fingerprint, trusted, next) {
694		if (strcasecmp(fingerprint->hash, hash) == 0) {
695			sc->trusted = true;
696			sc->name = strdup(fingerprint->name);
697			break;
698		}
699	}
700
701	if (sc->trusted == false) {
702		fprintf(stderr, "No trusted fingerprint found matching "
703		    "package's certificate\n");
704		goto cleanup;
705	}
706
707	/* Verify the signature. */
708	printf("Verifying signature with trusted certificate %s... ", sc->name);
709	if (rsa_verify_cert(fd_pkg, sc->cert, sc->certlen, sc->sig,
710	    sc->siglen) == false) {
711		fprintf(stderr, "Signature is not valid\n");
712		goto cleanup;
713	}
714
715	ret = true;
716
717cleanup:
718	if (trusted)
719		free_fingerprint_list(trusted);
720	if (revoked)
721		free_fingerprint_list(revoked);
722	if (sc) {
723		if (sc->cert)
724			free(sc->cert);
725		if (sc->sig)
726			free(sc->sig);
727		if (sc->name)
728			free(sc->name);
729		free(sc);
730	}
731
732	return (ret);
733}
734
735static int
736bootstrap_pkg(bool force)
737{
738	int fd_pkg, fd_sig;
739	int ret;
740	char url[MAXPATHLEN];
741	char tmppkg[MAXPATHLEN];
742	char tmpsig[MAXPATHLEN];
743	const char *packagesite;
744	const char *signature_type;
745	char pkgstatic[MAXPATHLEN];
746
747	fd_sig = -1;
748	ret = -1;
749
750	if (config_string(PACKAGESITE, &packagesite) != 0) {
751		warnx("No PACKAGESITE defined");
752		return (-1);
753	}
754
755	if (config_string(SIGNATURE_TYPE, &signature_type) != 0) {
756		warnx("Error looking up SIGNATURE_TYPE");
757		return (-1);
758	}
759
760	printf("Bootstrapping pkg from %s, please wait...\n", packagesite);
761
762	/* Support pkg+http:// for PACKAGESITE which is the new format
763	   in 1.2 to avoid confusion on why http://pkg.FreeBSD.org has
764	   no A record. */
765	if (strncmp(URL_SCHEME_PREFIX, packagesite,
766	    strlen(URL_SCHEME_PREFIX)) == 0)
767		packagesite += strlen(URL_SCHEME_PREFIX);
768	snprintf(url, MAXPATHLEN, "%s/Latest/pkg.txz", packagesite);
769
770	snprintf(tmppkg, MAXPATHLEN, "%s/pkg.txz.XXXXXX",
771	    getenv("TMPDIR") ? getenv("TMPDIR") : _PATH_TMP);
772
773	if ((fd_pkg = fetch_to_fd(url, tmppkg)) == -1)
774		goto fetchfail;
775
776	if (signature_type != NULL &&
777	    strcasecmp(signature_type, "NONE") != 0) {
778		if (strcasecmp(signature_type, "FINGERPRINTS") != 0) {
779			warnx("Signature type %s is not supported for "
780			    "bootstrapping.", signature_type);
781			goto cleanup;
782		}
783
784		snprintf(tmpsig, MAXPATHLEN, "%s/pkg.txz.sig.XXXXXX",
785		    getenv("TMPDIR") ? getenv("TMPDIR") : _PATH_TMP);
786		snprintf(url, MAXPATHLEN, "%s/Latest/pkg.txz.sig",
787		    packagesite);
788
789		if ((fd_sig = fetch_to_fd(url, tmpsig)) == -1) {
790			fprintf(stderr, "Signature for pkg not available.\n");
791			goto fetchfail;
792		}
793
794		if (verify_signature(fd_pkg, fd_sig) == false)
795			goto cleanup;
796	}
797
798	if ((ret = extract_pkg_static(fd_pkg, pkgstatic, MAXPATHLEN)) == 0)
799		ret = install_pkg_static(pkgstatic, tmppkg, force);
800
801	goto cleanup;
802
803fetchfail:
804	warnx("Error fetching %s: %s", url, fetchLastErrString);
805	fprintf(stderr, "A pre-built version of pkg could not be found for "
806	    "your system.\n");
807	fprintf(stderr, "Consider changing PACKAGESITE or installing it from "
808	    "ports: 'ports-mgmt/pkg'.\n");
809
810cleanup:
811	if (fd_sig != -1) {
812		close(fd_sig);
813		unlink(tmpsig);
814	}
815	close(fd_pkg);
816	unlink(tmppkg);
817
818	return (ret);
819}
820
821static const char confirmation_message[] =
822"The package management tool is not yet installed on your system.\n"
823"Do you want to fetch and install it now? [y/N]: ";
824
825static int
826pkg_query_yes_no(void)
827{
828	int ret, c;
829
830	c = getchar();
831
832	if (c == 'y' || c == 'Y')
833		ret = 1;
834	else
835		ret = 0;
836
837	while (c != '\n' && c != EOF)
838		c = getchar();
839
840	return (ret);
841}
842
843static int
844bootstrap_pkg_local(const char *pkgpath, bool force)
845{
846	char path[MAXPATHLEN];
847	char pkgstatic[MAXPATHLEN];
848	const char *signature_type;
849	int fd_pkg, fd_sig, ret;
850
851	fd_sig = -1;
852	ret = -1;
853
854	fd_pkg = open(pkgpath, O_RDONLY);
855	if (fd_pkg == -1)
856		err(EXIT_FAILURE, "Unable to open %s", pkgpath);
857
858	if (config_string(SIGNATURE_TYPE, &signature_type) != 0) {
859		warnx("Error looking up SIGNATURE_TYPE");
860		return (-1);
861	}
862	if (signature_type != NULL &&
863	    strcasecmp(signature_type, "NONE") != 0) {
864		if (strcasecmp(signature_type, "FINGERPRINTS") != 0) {
865			warnx("Signature type %s is not supported for "
866			    "bootstrapping.", signature_type);
867			goto cleanup;
868		}
869
870		snprintf(path, sizeof(path), "%s.sig", pkgpath);
871
872		if ((fd_sig = open(path, O_RDONLY)) == -1) {
873			fprintf(stderr, "Signature for pkg not available.\n");
874			goto cleanup;
875		}
876
877		if (verify_signature(fd_pkg, fd_sig) == false)
878			goto cleanup;
879	}
880
881	if ((ret = extract_pkg_static(fd_pkg, pkgstatic, MAXPATHLEN)) == 0)
882		ret = install_pkg_static(pkgstatic, pkgpath, force);
883
884cleanup:
885	close(fd_pkg);
886	if (fd_sig != -1)
887		close(fd_sig);
888
889	return (ret);
890}
891
892int
893main(__unused int argc, char *argv[])
894{
895	char pkgpath[MAXPATHLEN];
896	const char *pkgarg;
897	bool bootstrap_only, force, yes;
898
899	bootstrap_only = false;
900	force = false;
901	pkgarg = NULL;
902	yes = false;
903
904	snprintf(pkgpath, MAXPATHLEN, "%s/sbin/pkg",
905	    getenv("LOCALBASE") ? getenv("LOCALBASE") : _LOCALBASE);
906
907	if (argc > 1 && strcmp(argv[1], "bootstrap") == 0) {
908		bootstrap_only = true;
909		if (argc == 3 && strcmp(argv[2], "-f") == 0)
910			force = true;
911	}
912
913	if ((bootstrap_only && force) || access(pkgpath, X_OK) == -1) {
914		/*
915		 * To allow 'pkg -N' to be used as a reliable test for whether
916		 * a system is configured to use pkg, don't bootstrap pkg
917		 * when that argument is given as argv[1].
918		 */
919		if (argv[1] != NULL && strcmp(argv[1], "-N") == 0)
920			errx(EXIT_FAILURE, "pkg is not installed");
921
922		config_init();
923
924		if (argc > 1 && strcmp(argv[1], "add") == 0) {
925			if (argc > 2 && strcmp(argv[2], "-f") == 0) {
926				force = true;
927				pkgarg = argv[3];
928			} else
929				pkgarg = argv[2];
930			if (pkgarg == NULL) {
931				fprintf(stderr, "Path to pkg.txz required\n");
932				exit(EXIT_FAILURE);
933			}
934			if (access(pkgarg, R_OK) == -1) {
935				fprintf(stderr, "No such file: %s\n", pkgarg);
936				exit(EXIT_FAILURE);
937			}
938			if (bootstrap_pkg_local(pkgarg, force) != 0)
939				exit(EXIT_FAILURE);
940			exit(EXIT_SUCCESS);
941		}
942		/*
943		 * Do not ask for confirmation if either of stdin or stdout is
944		 * not tty. Check the environment to see if user has answer
945		 * tucked in there already.
946		 */
947		config_bool(ASSUME_ALWAYS_YES, &yes);
948		if (!yes) {
949			printf("%s", confirmation_message);
950			if (!isatty(fileno(stdin)))
951				exit(EXIT_FAILURE);
952
953			if (pkg_query_yes_no() == 0)
954				exit(EXIT_FAILURE);
955		}
956		if (bootstrap_pkg(force) != 0)
957			exit(EXIT_FAILURE);
958		config_finish();
959
960		if (bootstrap_only)
961			exit(EXIT_SUCCESS);
962	} else if (bootstrap_only) {
963		printf("pkg already bootstrapped at %s\n", pkgpath);
964		exit(EXIT_SUCCESS);
965	}
966
967	execv(pkgpath, argv);
968
969	/* NOT REACHED */
970	return (EXIT_FAILURE);
971}
972