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