pkg.c revision 257353
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: stable/10/usr.sbin/pkg/pkg.c 257353 2013-10-29 18:36:44Z bdrewery $");
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
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("fail to extract pkg-static");
130
131cleanup:
132	archive_read_free(a);
133	return (ret);
134
135}
136
137static int
138install_pkg_static(const char *path, const char *pkgpath)
139{
140	int pstat;
141	pid_t pid;
142
143	switch ((pid = fork())) {
144	case -1:
145		return (-1);
146	case 0:
147		execl(path, "pkg-static", "add", pkgpath, (char *)NULL);
148		_exit(1);
149	default:
150		break;
151	}
152
153	while (waitpid(pid, &pstat, 0) == -1)
154		if (errno != EINTR)
155			return (-1);
156
157	if (WEXITSTATUS(pstat))
158		return (WEXITSTATUS(pstat));
159	else if (WIFSIGNALED(pstat))
160		return (128 & (WTERMSIG(pstat)));
161	return (pstat);
162}
163
164static int
165fetch_to_fd(const char *url, char *path)
166{
167	struct url *u;
168	struct dns_srvinfo *mirrors, *current;
169	struct url_stat st;
170	FILE *remote;
171	/* To store _https._tcp. + hostname + \0 */
172	int fd;
173	int retry, max_retry;
174	off_t done, r;
175	time_t now, last;
176	char buf[10240];
177	char zone[MAXHOSTNAMELEN + 13];
178	static const char *mirror_type = NULL;
179
180	done = 0;
181	last = 0;
182	max_retry = 3;
183	current = mirrors = NULL;
184	remote = NULL;
185
186	if (mirror_type == NULL && config_string(MIRROR_TYPE, &mirror_type)
187	    != 0) {
188		warnx("No MIRROR_TYPE defined");
189		return (-1);
190	}
191
192	if ((fd = mkstemp(path)) == -1) {
193		warn("mkstemp()");
194		return (-1);
195	}
196
197	retry = max_retry;
198
199	u = fetchParseURL(url);
200	while (remote == NULL) {
201		if (retry == max_retry) {
202			if (strcmp(u->scheme, "file") != 0 &&
203			    strcasecmp(mirror_type, "srv") == 0) {
204				snprintf(zone, sizeof(zone),
205				    "_%s._tcp.%s", u->scheme, u->host);
206				mirrors = dns_getsrvinfo(zone);
207				current = mirrors;
208			}
209		}
210
211		if (mirrors != NULL) {
212			strlcpy(u->host, current->host, sizeof(u->host));
213			u->port = current->port;
214		}
215
216		remote = fetchXGet(u, &st, "");
217		if (remote == NULL) {
218			--retry;
219			if (retry <= 0)
220				goto fetchfail;
221			if (mirrors == NULL) {
222				sleep(1);
223			} else {
224				current = current->next;
225				if (current == NULL)
226					current = mirrors;
227			}
228		}
229	}
230
231	if (remote == NULL)
232		goto fetchfail;
233
234	while (done < st.size) {
235		if ((r = fread(buf, 1, sizeof(buf), remote)) < 1)
236			break;
237
238		if (write(fd, buf, r) != r) {
239			warn("write()");
240			goto fetchfail;
241		}
242
243		done += r;
244		now = time(NULL);
245		if (now > last || done == st.size)
246			last = now;
247	}
248
249	if (ferror(remote))
250		goto fetchfail;
251
252	goto cleanup;
253
254fetchfail:
255	if (fd != -1) {
256		close(fd);
257		fd = -1;
258		unlink(path);
259	}
260
261cleanup:
262	if (remote != NULL)
263		fclose(remote);
264
265	return fd;
266}
267
268static struct fingerprint *
269parse_fingerprint(yaml_document_t *doc, yaml_node_t *node)
270{
271	yaml_node_pair_t *pair;
272	yaml_char_t *function, *fp;
273	struct fingerprint *f;
274	hash_t fct = HASH_UNKNOWN;
275
276	function = fp = NULL;
277
278	pair = node->data.mapping.pairs.start;
279	while (pair < node->data.mapping.pairs.top) {
280		yaml_node_t *key = yaml_document_get_node(doc, pair->key);
281		yaml_node_t *val = yaml_document_get_node(doc, pair->value);
282
283		if (key->data.scalar.length <= 0) {
284			++pair;
285			continue;
286		}
287
288		if (val->type != YAML_SCALAR_NODE) {
289			++pair;
290			continue;
291		}
292
293		if (strcasecmp(key->data.scalar.value, "function") == 0)
294			function = val->data.scalar.value;
295		else if (strcasecmp(key->data.scalar.value, "fingerprint")
296		    == 0)
297			fp = val->data.scalar.value;
298
299		++pair;
300		continue;
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		fprintf(stderr, "Unsupported hashing function: %s\n", 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;
325
326	STAILQ_FOREACH(fingerprint, list, next) {
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	yaml_parser_t parser;
338	yaml_document_t doc;
339	yaml_node_t *node;
340	FILE *fp;
341	struct fingerprint *f;
342	char path[MAXPATHLEN];
343
344	f = NULL;
345
346	snprintf(path, MAXPATHLEN, "%s/%s", dir, filename);
347
348	if ((fp = fopen(path, "r")) == NULL)
349		return (NULL);
350
351	yaml_parser_initialize(&parser);
352	yaml_parser_set_input_file(&parser, fp);
353	yaml_parser_load(&parser, &doc);
354
355	node = yaml_document_get_root_node(&doc);
356	if (node == NULL || node->type != YAML_MAPPING_NODE)
357		goto out;
358
359	f = parse_fingerprint(&doc, node);
360	f->name = strdup(filename);
361
362out:
363	yaml_document_delete(&doc);
364	yaml_parser_delete(&parser);
365	fclose(fp);
366
367	return (f);
368}
369
370static struct fingerprint_list *
371load_fingerprints(const char *path, int *count)
372{
373	DIR *d;
374	struct dirent *ent;
375	struct fingerprint *finger;
376	struct fingerprint_list *fingerprints;
377
378	*count = 0;
379
380	fingerprints = calloc(1, sizeof(struct fingerprint_list));
381	if (fingerprints == NULL)
382		return (NULL);
383	STAILQ_INIT(fingerprints);
384
385	if ((d = opendir(path)) == NULL)
386		return (NULL);
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(void)
744{
745	FILE *config;
746	int fd_pkg, fd_sig;
747	int ret;
748	char *site;
749	char url[MAXPATHLEN];
750	char conf[MAXPATHLEN];
751	char tmppkg[MAXPATHLEN];
752	char tmpsig[MAXPATHLEN];
753	const char *packagesite;
754	const char *signature_type;
755	char pkgstatic[MAXPATHLEN];
756
757	fd_sig = -1;
758	ret = -1;
759	config = NULL;
760
761	if (config_string(PACKAGESITE, &packagesite) != 0) {
762		warnx("No PACKAGESITE defined");
763		return (-1);
764	}
765
766	if (config_string(SIGNATURE_TYPE, &signature_type) != 0) {
767		warnx("Error looking up SIGNATURE_TYPE");
768		return (-1);
769	}
770
771	printf("Bootstrapping pkg from %s, please wait...\n", packagesite);
772
773	/* Support pkg+http:// for PACKAGESITE which is the new format
774	   in 1.2 to avoid confusion on why http://pkg.FreeBSD.org has
775	   no A record. */
776	if (strncmp(URL_SCHEME_PREFIX, packagesite,
777	    strlen(URL_SCHEME_PREFIX)) == 0)
778		packagesite += strlen(URL_SCHEME_PREFIX);
779	snprintf(url, MAXPATHLEN, "%s/Latest/pkg.txz", packagesite);
780
781	snprintf(tmppkg, MAXPATHLEN, "%s/pkg.txz.XXXXXX",
782	    getenv("TMPDIR") ? getenv("TMPDIR") : _PATH_TMP);
783
784	if ((fd_pkg = fetch_to_fd(url, tmppkg)) == -1)
785		goto fetchfail;
786
787	if (signature_type != NULL &&
788	    strcasecmp(signature_type, "FINGERPRINTS") == 0) {
789		snprintf(tmpsig, MAXPATHLEN, "%s/pkg.txz.sig.XXXXXX",
790		    getenv("TMPDIR") ? getenv("TMPDIR") : _PATH_TMP);
791		snprintf(url, MAXPATHLEN, "%s/Latest/pkg.txz.sig",
792		    packagesite);
793
794		if ((fd_sig = fetch_to_fd(url, tmpsig)) == -1) {
795			fprintf(stderr, "Signature for pkg not available.\n");
796			goto fetchfail;
797		}
798
799		if (verify_signature(fd_pkg, fd_sig) == false)
800			goto cleanup;
801	}
802
803	if ((ret = extract_pkg_static(fd_pkg, pkgstatic, MAXPATHLEN)) == 0)
804		ret = install_pkg_static(pkgstatic, tmppkg);
805
806	snprintf(conf, MAXPATHLEN, "%s/etc/pkg.conf",
807	    getenv("LOCALBASE") ? getenv("LOCALBASE") : _LOCALBASE);
808
809	if (access(conf, R_OK) == -1) {
810		site = strrchr(url, '/');
811		if (site == NULL)
812			goto cleanup;
813		site[0] = '\0';
814		site = strrchr(url, '/');
815		if (site == NULL)
816			goto cleanup;
817		site[0] = '\0';
818
819		config = fopen(conf, "w+");
820		if (config == NULL)
821			goto cleanup;
822		fprintf(config, "packagesite: %s\n", url);
823		fclose(config);
824	}
825
826	goto cleanup;
827
828fetchfail:
829	warnx("Error fetching %s: %s", url, fetchLastErrString);
830	fprintf(stderr, "A pre-built version of pkg could not be found for "
831	    "your system.\n");
832	fprintf(stderr, "Consider changing PACKAGESITE or installing it from "
833	    "ports: 'ports-mgmt/pkg'.\n");
834
835cleanup:
836	if (fd_sig != -1) {
837		close(fd_sig);
838		unlink(tmpsig);
839	}
840	close(fd_pkg);
841	unlink(tmppkg);
842
843	return (ret);
844}
845
846static const char confirmation_message[] =
847"The package management tool is not yet installed on your system.\n"
848"Do you want to fetch and install it now? [y/N]: ";
849
850static int
851pkg_query_yes_no(void)
852{
853	int ret, c;
854
855	c = getchar();
856
857	if (c == 'y' || c == 'Y')
858		ret = 1;
859	else
860		ret = 0;
861
862	while (c != '\n' && c != EOF)
863		c = getchar();
864
865	return (ret);
866}
867
868static int
869bootstrap_pkg_local(const char *pkgpath)
870{
871	char path[MAXPATHLEN];
872	char pkgstatic[MAXPATHLEN];
873	const char *signature_type;
874	int fd_pkg, fd_sig, ret;
875
876	fd_sig = -1;
877	ret = -1;
878
879	fd_pkg = open(pkgpath, O_RDONLY);
880	if (fd_pkg == -1)
881		err(EXIT_FAILURE, "Unable to open %s", pkgpath);
882
883	if (config_string(SIGNATURE_TYPE, &signature_type) != 0) {
884		warnx("Error looking up SIGNATURE_TYPE");
885		return (-1);
886	}
887	if (signature_type != NULL &&
888	    strcasecmp(signature_type, "FINGERPRINTS") == 0) {
889		snprintf(path, sizeof(path), "%s.sig", pkgpath);
890
891		if ((fd_sig = open(path, O_RDONLY)) == -1) {
892			fprintf(stderr, "Signature for pkg not available.\n");
893			goto cleanup;
894		}
895
896		if (verify_signature(fd_pkg, fd_sig) == false)
897			goto cleanup;
898	}
899
900	if ((ret = extract_pkg_static(fd_pkg, pkgstatic, MAXPATHLEN)) == 0)
901		ret = install_pkg_static(pkgstatic, pkgpath);
902
903cleanup:
904	close(fd_pkg);
905	if (fd_sig != -1)
906		close(fd_sig);
907
908	return (ret);
909}
910
911int
912main(__unused int argc, char *argv[])
913{
914	char pkgpath[MAXPATHLEN];
915	bool yes = false;
916
917	snprintf(pkgpath, MAXPATHLEN, "%s/sbin/pkg",
918	    getenv("LOCALBASE") ? getenv("LOCALBASE") : _LOCALBASE);
919
920	if (access(pkgpath, X_OK) == -1) {
921		/*
922		 * To allow 'pkg -N' to be used as a reliable test for whether
923		 * a system is configured to use pkg, don't bootstrap pkg
924		 * when that argument is given as argv[1].
925		 */
926		if (argv[1] != NULL && strcmp(argv[1], "-N") == 0)
927			errx(EXIT_FAILURE, "pkg is not installed");
928
929		config_init();
930
931		if (argc > 2 && strcmp(argv[1], "add") == 0 &&
932		    access(argv[2], R_OK) == 0) {
933			if (bootstrap_pkg_local(argv[2]) != 0)
934				exit(EXIT_FAILURE);
935			exit(EXIT_SUCCESS);
936		}
937		/*
938		 * Do not ask for confirmation if either of stdin or stdout is
939		 * not tty. Check the environment to see if user has answer
940		 * tucked in there already.
941		 */
942		config_bool(ASSUME_ALWAYS_YES, &yes);
943		if (!yes) {
944			printf("%s", confirmation_message);
945			if (!isatty(fileno(stdin)))
946				exit(EXIT_FAILURE);
947
948			if (pkg_query_yes_no() == 0)
949				exit(EXIT_FAILURE);
950		}
951		if (bootstrap_pkg() != 0)
952			exit(EXIT_FAILURE);
953		config_finish();
954	}
955
956	execv(pkgpath, argv);
957
958	/* NOT REACHED */
959	return (EXIT_FAILURE);
960}
961