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