xref: /freebsd/usr.sbin/pkg/pkg.c (revision 6d732c66bca5da4d261577aad2c8ea84519b0bea)
1 /*-
2  * Copyright (c) 2012-2013 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$");
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 <yaml.h>
53 
54 #include <openssl/err.h>
55 #include <openssl/ssl.h>
56 
57 #include "dns_utils.h"
58 #include "config.h"
59 
60 struct sig_cert {
61 	char *name;
62 	unsigned char *sig;
63 	int siglen;
64 	unsigned char *cert;
65 	int certlen;
66 	bool trusted;
67 };
68 
69 typedef enum {
70        HASH_UNKNOWN,
71        HASH_SHA256,
72 } hash_t;
73 
74 struct fingerprint {
75        hash_t type;
76        char *name;
77        char hash[BUFSIZ];
78        STAILQ_ENTRY(fingerprint) next;
79 };
80 
81 STAILQ_HEAD(fingerprint_list, fingerprint);
82 
83 static int
84 extract_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("fail to extract pkg-static");
130 
131 cleanup:
132 	archive_read_free(a);
133 	return (ret);
134 
135 }
136 
137 static int
138 install_pkg_static(const char *path, const char *pkgpath, bool force)
139 {
140 	int pstat;
141 	pid_t pid;
142 
143 	switch ((pid = fork())) {
144 	case -1:
145 		return (-1);
146 	case 0:
147 		if (force)
148 			execl(path, "pkg-static", "add", "-f", pkgpath,
149 			    (char *)NULL);
150 		else
151 			execl(path, "pkg-static", "add", pkgpath,
152 			    (char *)NULL);
153 		_exit(1);
154 	default:
155 		break;
156 	}
157 
158 	while (waitpid(pid, &pstat, 0) == -1)
159 		if (errno != EINTR)
160 			return (-1);
161 
162 	if (WEXITSTATUS(pstat))
163 		return (WEXITSTATUS(pstat));
164 	else if (WIFSIGNALED(pstat))
165 		return (128 & (WTERMSIG(pstat)));
166 	return (pstat);
167 }
168 
169 static int
170 fetch_to_fd(const char *url, char *path)
171 {
172 	struct url *u;
173 	struct dns_srvinfo *mirrors, *current;
174 	struct url_stat st;
175 	FILE *remote;
176 	/* To store _https._tcp. + hostname + \0 */
177 	int fd;
178 	int retry, max_retry;
179 	off_t done, r;
180 	time_t now, last;
181 	char buf[10240];
182 	char zone[MAXHOSTNAMELEN + 13];
183 	static const char *mirror_type = NULL;
184 
185 	done = 0;
186 	last = 0;
187 	max_retry = 3;
188 	current = mirrors = NULL;
189 	remote = NULL;
190 
191 	if (mirror_type == NULL && config_string(MIRROR_TYPE, &mirror_type)
192 	    != 0) {
193 		warnx("No MIRROR_TYPE defined");
194 		return (-1);
195 	}
196 
197 	if ((fd = mkstemp(path)) == -1) {
198 		warn("mkstemp()");
199 		return (-1);
200 	}
201 
202 	retry = max_retry;
203 
204 	u = fetchParseURL(url);
205 	while (remote == NULL) {
206 		if (retry == max_retry) {
207 			if (strcmp(u->scheme, "file") != 0 &&
208 			    strcasecmp(mirror_type, "srv") == 0) {
209 				snprintf(zone, sizeof(zone),
210 				    "_%s._tcp.%s", u->scheme, u->host);
211 				mirrors = dns_getsrvinfo(zone);
212 				current = mirrors;
213 			}
214 		}
215 
216 		if (mirrors != NULL) {
217 			strlcpy(u->host, current->host, sizeof(u->host));
218 			u->port = current->port;
219 		}
220 
221 		remote = fetchXGet(u, &st, "");
222 		if (remote == NULL) {
223 			--retry;
224 			if (retry <= 0)
225 				goto fetchfail;
226 			if (mirrors == NULL) {
227 				sleep(1);
228 			} else {
229 				current = current->next;
230 				if (current == NULL)
231 					current = mirrors;
232 			}
233 		}
234 	}
235 
236 	while (done < st.size) {
237 		if ((r = fread(buf, 1, sizeof(buf), remote)) < 1)
238 			break;
239 
240 		if (write(fd, buf, r) != r) {
241 			warn("write()");
242 			goto fetchfail;
243 		}
244 
245 		done += r;
246 		now = time(NULL);
247 		if (now > last || done == st.size)
248 			last = now;
249 	}
250 
251 	if (ferror(remote))
252 		goto fetchfail;
253 
254 	goto cleanup;
255 
256 fetchfail:
257 	if (fd != -1) {
258 		close(fd);
259 		fd = -1;
260 		unlink(path);
261 	}
262 
263 cleanup:
264 	if (remote != NULL)
265 		fclose(remote);
266 
267 	return fd;
268 }
269 
270 static struct fingerprint *
271 parse_fingerprint(yaml_document_t *doc, yaml_node_t *node)
272 {
273 	yaml_node_pair_t *pair;
274 	yaml_char_t *function, *fp;
275 	struct fingerprint *f;
276 	hash_t fct = HASH_UNKNOWN;
277 
278 	function = fp = NULL;
279 
280 	pair = node->data.mapping.pairs.start;
281 	while (pair < node->data.mapping.pairs.top) {
282 		yaml_node_t *key = yaml_document_get_node(doc, pair->key);
283 		yaml_node_t *val = yaml_document_get_node(doc, pair->value);
284 
285 		if (key->data.scalar.length <= 0) {
286 			++pair;
287 			continue;
288 		}
289 
290 		if (val->type != YAML_SCALAR_NODE) {
291 			++pair;
292 			continue;
293 		}
294 
295 		if (strcasecmp(key->data.scalar.value, "function") == 0)
296 			function = val->data.scalar.value;
297 		else if (strcasecmp(key->data.scalar.value, "fingerprint")
298 		    == 0)
299 			fp = val->data.scalar.value;
300 
301 		++pair;
302 		continue;
303 	}
304 
305 	if (fp == NULL || function == NULL)
306 		return (NULL);
307 
308 	if (strcasecmp(function, "sha256") == 0)
309 		fct = HASH_SHA256;
310 
311 	if (fct == HASH_UNKNOWN) {
312 		fprintf(stderr, "Unsupported hashing function: %s\n", function);
313 		return (NULL);
314 	}
315 
316 	f = calloc(1, sizeof(struct fingerprint));
317 	f->type = fct;
318 	strlcpy(f->hash, fp, sizeof(f->hash));
319 
320 	return (f);
321 }
322 
323 static void
324 free_fingerprint_list(struct fingerprint_list* list)
325 {
326 	struct fingerprint *fingerprint, *tmp;
327 
328 	STAILQ_FOREACH_SAFE(fingerprint, list, next, tmp) {
329 		free(fingerprint->name);
330 		free(fingerprint);
331 	}
332 	free(list);
333 }
334 
335 static struct fingerprint *
336 load_fingerprint(const char *dir, const char *filename)
337 {
338 	yaml_parser_t parser;
339 	yaml_document_t doc;
340 	yaml_node_t *node;
341 	FILE *fp;
342 	struct fingerprint *f;
343 	char path[MAXPATHLEN];
344 
345 	f = NULL;
346 
347 	snprintf(path, MAXPATHLEN, "%s/%s", dir, filename);
348 
349 	if ((fp = fopen(path, "r")) == NULL)
350 		return (NULL);
351 
352 	yaml_parser_initialize(&parser);
353 	yaml_parser_set_input_file(&parser, fp);
354 	yaml_parser_load(&parser, &doc);
355 
356 	node = yaml_document_get_root_node(&doc);
357 	if (node == NULL || node->type != YAML_MAPPING_NODE)
358 		goto out;
359 
360 	f = parse_fingerprint(&doc, node);
361 	f->name = strdup(filename);
362 
363 out:
364 	yaml_document_delete(&doc);
365 	yaml_parser_delete(&parser);
366 	fclose(fp);
367 
368 	return (f);
369 }
370 
371 static struct fingerprint_list *
372 load_fingerprints(const char *path, int *count)
373 {
374 	DIR *d;
375 	struct dirent *ent;
376 	struct fingerprint *finger;
377 	struct fingerprint_list *fingerprints;
378 
379 	*count = 0;
380 
381 	fingerprints = calloc(1, sizeof(struct fingerprint_list));
382 	if (fingerprints == NULL)
383 		return (NULL);
384 	STAILQ_INIT(fingerprints);
385 
386 	if ((d = opendir(path)) == NULL)
387 		return (NULL);
388 
389 	while ((ent = readdir(d))) {
390 		if (strcmp(ent->d_name, ".") == 0 ||
391 		    strcmp(ent->d_name, "..") == 0)
392 			continue;
393 		finger = load_fingerprint(path, ent->d_name);
394 		if (finger != NULL) {
395 			STAILQ_INSERT_TAIL(fingerprints, finger, next);
396 			++(*count);
397 		}
398 	}
399 
400 	closedir(d);
401 
402 	return (fingerprints);
403 }
404 
405 static void
406 sha256_hash(unsigned char hash[SHA256_DIGEST_LENGTH],
407     char out[SHA256_DIGEST_LENGTH * 2 + 1])
408 {
409 	int i;
410 
411 	for (i = 0; i < SHA256_DIGEST_LENGTH; i++)
412 		sprintf(out + (i * 2), "%02x", hash[i]);
413 
414 	out[SHA256_DIGEST_LENGTH * 2] = '\0';
415 }
416 
417 static void
418 sha256_buf(char *buf, size_t len, char out[SHA256_DIGEST_LENGTH * 2 + 1])
419 {
420 	unsigned char hash[SHA256_DIGEST_LENGTH];
421 	SHA256_CTX sha256;
422 
423 	out[0] = '\0';
424 
425 	SHA256_Init(&sha256);
426 	SHA256_Update(&sha256, buf, len);
427 	SHA256_Final(hash, &sha256);
428 	sha256_hash(hash, out);
429 }
430 
431 static int
432 sha256_fd(int fd, char out[SHA256_DIGEST_LENGTH * 2 + 1])
433 {
434 	int my_fd;
435 	FILE *fp;
436 	char buffer[BUFSIZ];
437 	unsigned char hash[SHA256_DIGEST_LENGTH];
438 	size_t r;
439 	int ret;
440 	SHA256_CTX sha256;
441 
442 	my_fd = -1;
443 	fp = NULL;
444 	r = 0;
445 	ret = 1;
446 
447 	out[0] = '\0';
448 
449 	/* Duplicate the fd so that fclose(3) does not close it. */
450 	if ((my_fd = dup(fd)) == -1) {
451 		warnx("dup");
452 		goto cleanup;
453 	}
454 
455 	if ((fp = fdopen(my_fd, "rb")) == NULL) {
456 		warnx("fdopen");
457 		goto cleanup;
458 	}
459 
460 	SHA256_Init(&sha256);
461 
462 	while ((r = fread(buffer, 1, BUFSIZ, fp)) > 0)
463 		SHA256_Update(&sha256, buffer, r);
464 
465 	if (ferror(fp) != 0) {
466 		warnx("fread");
467 		goto cleanup;
468 	}
469 
470 	SHA256_Final(hash, &sha256);
471 	sha256_hash(hash, out);
472 	ret = 0;
473 
474 cleanup:
475 	if (fp != NULL)
476 		fclose(fp);
477 	else if (my_fd != -1)
478 		close(my_fd);
479 	(void)lseek(fd, 0, SEEK_SET);
480 
481 	return (ret);
482 }
483 
484 static EVP_PKEY *
485 load_public_key_buf(const unsigned char *cert, int certlen)
486 {
487 	EVP_PKEY *pkey;
488 	BIO *bp;
489 	char errbuf[1024];
490 
491 	bp = BIO_new_mem_buf(__DECONST(void *, cert), certlen);
492 
493 	if ((pkey = PEM_read_bio_PUBKEY(bp, NULL, NULL, NULL)) == NULL)
494 		warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
495 
496 	BIO_free(bp);
497 
498 	return (pkey);
499 }
500 
501 static bool
502 rsa_verify_cert(int fd, const unsigned char *key, int keylen,
503     unsigned char *sig, int siglen)
504 {
505 	EVP_MD_CTX *mdctx;
506 	EVP_PKEY *pkey;
507 	char sha256[(SHA256_DIGEST_LENGTH * 2) + 2];
508 	char errbuf[1024];
509 	bool ret;
510 
511 	pkey = NULL;
512 	mdctx = NULL;
513 	ret = false;
514 
515 	/* Compute SHA256 of the package. */
516 	if (lseek(fd, 0, 0) == -1) {
517 		warn("lseek");
518 		goto cleanup;
519 	}
520 	if ((sha256_fd(fd, sha256)) == -1) {
521 		warnx("Error creating SHA256 hash for package");
522 		goto cleanup;
523 	}
524 
525 	if ((pkey = load_public_key_buf(key, keylen)) == NULL) {
526 		warnx("Error reading public key");
527 		goto cleanup;
528 	}
529 
530 	/* Verify signature of the SHA256(pkg) is valid. */
531 	if ((mdctx = EVP_MD_CTX_create()) == NULL) {
532 		warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
533 		goto error;
534 	}
535 
536 	if (EVP_DigestVerifyInit(mdctx, NULL, EVP_sha256(), NULL, pkey) != 1) {
537 		warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
538 		goto error;
539 	}
540 	if (EVP_DigestVerifyUpdate(mdctx, sha256, strlen(sha256)) != 1) {
541 		warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
542 		goto error;
543 	}
544 
545 	if (EVP_DigestVerifyFinal(mdctx, sig, siglen) != 1) {
546 		warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
547 		goto error;
548 	}
549 
550 	ret = true;
551 	printf("done\n");
552 	goto cleanup;
553 
554 error:
555 	printf("failed\n");
556 
557 cleanup:
558 	if (pkey)
559 		EVP_PKEY_free(pkey);
560 	if (mdctx)
561 		EVP_MD_CTX_destroy(mdctx);
562 	ERR_free_strings();
563 
564 	return (ret);
565 }
566 
567 static struct sig_cert *
568 parse_cert(int fd) {
569 	int my_fd;
570 	struct sig_cert *sc;
571 	FILE *fp;
572 	struct sbuf *buf, *sig, *cert;
573 	char *line;
574 	size_t linecap;
575 	ssize_t linelen;
576 
577 	buf = NULL;
578 	my_fd = -1;
579 	sc = NULL;
580 	line = NULL;
581 	linecap = 0;
582 
583 	if (lseek(fd, 0, 0) == -1) {
584 		warn("lseek");
585 		return (NULL);
586 	}
587 
588 	/* Duplicate the fd so that fclose(3) does not close it. */
589 	if ((my_fd = dup(fd)) == -1) {
590 		warnx("dup");
591 		return (NULL);
592 	}
593 
594 	if ((fp = fdopen(my_fd, "rb")) == NULL) {
595 		warn("fdopen");
596 		close(my_fd);
597 		return (NULL);
598 	}
599 
600 	sig = sbuf_new_auto();
601 	cert = sbuf_new_auto();
602 
603 	while ((linelen = getline(&line, &linecap, fp)) > 0) {
604 		if (strcmp(line, "SIGNATURE\n") == 0) {
605 			buf = sig;
606 			continue;
607 		} else if (strcmp(line, "CERT\n") == 0) {
608 			buf = cert;
609 			continue;
610 		} else if (strcmp(line, "END\n") == 0) {
611 			break;
612 		}
613 		if (buf != NULL)
614 			sbuf_bcat(buf, line, linelen);
615 	}
616 
617 	fclose(fp);
618 
619 	/* Trim out unrelated trailing newline */
620 	sbuf_setpos(sig, sbuf_len(sig) - 1);
621 
622 	sbuf_finish(sig);
623 	sbuf_finish(cert);
624 
625 	sc = calloc(1, sizeof(struct sig_cert));
626 	sc->siglen = sbuf_len(sig);
627 	sc->sig = calloc(1, sc->siglen);
628 	memcpy(sc->sig, sbuf_data(sig), sc->siglen);
629 
630 	sc->certlen = sbuf_len(cert);
631 	sc->cert = strdup(sbuf_data(cert));
632 
633 	sbuf_delete(sig);
634 	sbuf_delete(cert);
635 
636 	return (sc);
637 }
638 
639 static bool
640 verify_signature(int fd_pkg, int fd_sig)
641 {
642 	struct fingerprint_list *trusted, *revoked;
643 	struct fingerprint *fingerprint;
644 	struct sig_cert *sc;
645 	bool ret;
646 	int trusted_count, revoked_count;
647 	const char *fingerprints;
648 	char path[MAXPATHLEN];
649 	char hash[SHA256_DIGEST_LENGTH * 2 + 1];
650 
651 	sc = NULL;
652 	trusted = revoked = NULL;
653 	ret = false;
654 
655 	/* Read and parse fingerprints. */
656 	if (config_string(FINGERPRINTS, &fingerprints) != 0) {
657 		warnx("No CONFIG_FINGERPRINTS defined");
658 		goto cleanup;
659 	}
660 
661 	snprintf(path, MAXPATHLEN, "%s/trusted", fingerprints);
662 	if ((trusted = load_fingerprints(path, &trusted_count)) == NULL) {
663 		warnx("Error loading trusted certificates");
664 		goto cleanup;
665 	}
666 
667 	if (trusted_count == 0 || trusted == NULL) {
668 		fprintf(stderr, "No trusted certificates found.\n");
669 		goto cleanup;
670 	}
671 
672 	snprintf(path, MAXPATHLEN, "%s/revoked", fingerprints);
673 	if ((revoked = load_fingerprints(path, &revoked_count)) == NULL) {
674 		warnx("Error loading revoked certificates");
675 		goto cleanup;
676 	}
677 
678 	/* Read certificate and signature in. */
679 	if ((sc = parse_cert(fd_sig)) == NULL) {
680 		warnx("Error parsing certificate");
681 		goto cleanup;
682 	}
683 	/* Explicitly mark as non-trusted until proven otherwise. */
684 	sc->trusted = false;
685 
686 	/* Parse signature and pubkey out of the certificate */
687 	sha256_buf(sc->cert, sc->certlen, hash);
688 
689 	/* Check if this hash is revoked */
690 	if (revoked != NULL) {
691 		STAILQ_FOREACH(fingerprint, revoked, next) {
692 			if (strcasecmp(fingerprint->hash, hash) == 0) {
693 				fprintf(stderr, "The package was signed with "
694 				    "revoked certificate %s\n",
695 				    fingerprint->name);
696 				goto cleanup;
697 			}
698 		}
699 	}
700 
701 	STAILQ_FOREACH(fingerprint, trusted, next) {
702 		if (strcasecmp(fingerprint->hash, hash) == 0) {
703 			sc->trusted = true;
704 			sc->name = strdup(fingerprint->name);
705 			break;
706 		}
707 	}
708 
709 	if (sc->trusted == false) {
710 		fprintf(stderr, "No trusted fingerprint found matching "
711 		    "package's certificate\n");
712 		goto cleanup;
713 	}
714 
715 	/* Verify the signature. */
716 	printf("Verifying signature with trusted certificate %s... ", sc->name);
717 	if (rsa_verify_cert(fd_pkg, sc->cert, sc->certlen, sc->sig,
718 	    sc->siglen) == false) {
719 		fprintf(stderr, "Signature is not valid\n");
720 		goto cleanup;
721 	}
722 
723 	ret = true;
724 
725 cleanup:
726 	if (trusted)
727 		free_fingerprint_list(trusted);
728 	if (revoked)
729 		free_fingerprint_list(revoked);
730 	if (sc) {
731 		free(sc->cert);
732 		free(sc->sig);
733 		free(sc->name);
734 		free(sc);
735 	}
736 
737 	return (ret);
738 }
739 
740 static int
741 bootstrap_pkg(bool force)
742 {
743 	int fd_pkg, fd_sig;
744 	int ret;
745 	char url[MAXPATHLEN];
746 	char tmppkg[MAXPATHLEN];
747 	char tmpsig[MAXPATHLEN];
748 	const char *packagesite;
749 	const char *signature_type;
750 	char pkgstatic[MAXPATHLEN];
751 
752 	fd_sig = -1;
753 	ret = -1;
754 
755 	if (config_string(PACKAGESITE, &packagesite) != 0) {
756 		warnx("No PACKAGESITE defined");
757 		return (-1);
758 	}
759 
760 	if (config_string(SIGNATURE_TYPE, &signature_type) != 0) {
761 		warnx("Error looking up SIGNATURE_TYPE");
762 		return (-1);
763 	}
764 
765 	printf("Bootstrapping pkg from %s, please wait...\n", packagesite);
766 
767 	/* Support pkg+http:// for PACKAGESITE which is the new format
768 	   in 1.2 to avoid confusion on why http://pkg.FreeBSD.org has
769 	   no A record. */
770 	if (strncmp(URL_SCHEME_PREFIX, packagesite,
771 	    strlen(URL_SCHEME_PREFIX)) == 0)
772 		packagesite += strlen(URL_SCHEME_PREFIX);
773 	snprintf(url, MAXPATHLEN, "%s/Latest/pkg.txz", packagesite);
774 
775 	snprintf(tmppkg, MAXPATHLEN, "%s/pkg.txz.XXXXXX",
776 	    getenv("TMPDIR") ? getenv("TMPDIR") : _PATH_TMP);
777 
778 	if ((fd_pkg = fetch_to_fd(url, tmppkg)) == -1)
779 		goto fetchfail;
780 
781 	if (signature_type != NULL &&
782 	    strcasecmp(signature_type, "FINGERPRINTS") == 0) {
783 		snprintf(tmpsig, MAXPATHLEN, "%s/pkg.txz.sig.XXXXXX",
784 		    getenv("TMPDIR") ? getenv("TMPDIR") : _PATH_TMP);
785 		snprintf(url, MAXPATHLEN, "%s/Latest/pkg.txz.sig",
786 		    packagesite);
787 
788 		if ((fd_sig = fetch_to_fd(url, tmpsig)) == -1) {
789 			fprintf(stderr, "Signature for pkg not available.\n");
790 			goto fetchfail;
791 		}
792 
793 		if (verify_signature(fd_pkg, fd_sig) == false)
794 			goto cleanup;
795 	}
796 
797 	if ((ret = extract_pkg_static(fd_pkg, pkgstatic, MAXPATHLEN)) == 0)
798 		ret = install_pkg_static(pkgstatic, tmppkg, force);
799 
800 	goto cleanup;
801 
802 fetchfail:
803 	warnx("Error fetching %s: %s", url, fetchLastErrString);
804 	fprintf(stderr, "A pre-built version of pkg could not be found for "
805 	    "your system.\n");
806 	fprintf(stderr, "Consider changing PACKAGESITE or installing it from "
807 	    "ports: 'ports-mgmt/pkg'.\n");
808 
809 cleanup:
810 	if (fd_sig != -1) {
811 		close(fd_sig);
812 		unlink(tmpsig);
813 	}
814 	close(fd_pkg);
815 	unlink(tmppkg);
816 
817 	return (ret);
818 }
819 
820 static const char confirmation_message[] =
821 "The package management tool is not yet installed on your system.\n"
822 "Do you want to fetch and install it now? [y/N]: ";
823 
824 static const char non_interactive_message[] =
825 "The package management tool is not yet installed on your system.\n"
826 "Please set ASSUME_ALWAYS_YES=yes environment variable to be able to bootstrap "
827 "in non-interactive (stdin not being a tty)\n";
828 
829 static int
830 pkg_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 
847 static int
848 bootstrap_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 		return (-1);
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 
882 cleanup:
883 	close(fd_pkg);
884 	if (fd_sig != -1)
885 		close(fd_sig);
886 
887 	return (ret);
888 }
889 
890 int
891 main(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 			if (!isatty(fileno(stdin))) {
948 				fprintf(stderr, non_interactive_message);
949 				exit(EXIT_FAILURE);
950 			}
951 
952 			printf("%s", confirmation_message);
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