]> CyberLeo.Net >> Repos - FreeBSD/releng/10.0.git/blob - usr.sbin/pkg/pkg.c
- Copy stable/10 (r259064) to releng/10.0 as part of the
[FreeBSD/releng/10.0.git] / usr.sbin / pkg / pkg.c
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         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
259 fetchfail:
260         if (fd != -1) {
261                 close(fd);
262                 fd = -1;
263                 unlink(path);
264         }
265
266 cleanup:
267         if (remote != NULL)
268                 fclose(remote);
269
270         return fd;
271 }
272
273 static struct fingerprint *
274 parse_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
326 static void
327 free_fingerprint_list(struct fingerprint_list* list)
328 {
329         struct fingerprint *fingerprint, *tmp;
330
331         STAILQ_FOREACH_SAFE(fingerprint, list, next, tmp) {
332                 if (fingerprint->name)
333                         free(fingerprint->name);
334                 free(fingerprint);
335         }
336         free(list);
337 }
338
339 static struct fingerprint *
340 load_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
367 out:
368         yaml_document_delete(&doc);
369         yaml_parser_delete(&parser);
370         fclose(fp);
371
372         return (f);
373 }
374
375 static struct fingerprint_list *
376 load_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
409 static void
410 sha256_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
421 static void
422 sha256_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
435 static int
436 sha256_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
478 cleanup:
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
488 static EVP_PKEY *
489 load_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
505 static bool
506 rsa_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
558 error:
559         printf("failed\n");
560
561 cleanup:
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
571 static struct sig_cert *
572 parse_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
643 static bool
644 verify_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
729 cleanup:
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
747 static int
748 bootstrap_pkg(bool force)
749 {
750         int fd_pkg, fd_sig;
751         int ret;
752         char url[MAXPATHLEN];
753         char tmppkg[MAXPATHLEN];
754         char tmpsig[MAXPATHLEN];
755         const char *packagesite;
756         const char *signature_type;
757         char pkgstatic[MAXPATHLEN];
758
759         fd_sig = -1;
760         ret = -1;
761
762         if (config_string(PACKAGESITE, &packagesite) != 0) {
763                 warnx("No PACKAGESITE defined");
764                 return (-1);
765         }
766
767         if (config_string(SIGNATURE_TYPE, &signature_type) != 0) {
768                 warnx("Error looking up SIGNATURE_TYPE");
769                 return (-1);
770         }
771
772         printf("Bootstrapping pkg from %s, please wait...\n", packagesite);
773
774         /* Support pkg+http:// for PACKAGESITE which is the new format
775            in 1.2 to avoid confusion on why http://pkg.FreeBSD.org has
776            no A record. */
777         if (strncmp(URL_SCHEME_PREFIX, packagesite,
778             strlen(URL_SCHEME_PREFIX)) == 0)
779                 packagesite += strlen(URL_SCHEME_PREFIX);
780         snprintf(url, MAXPATHLEN, "%s/Latest/pkg.txz", packagesite);
781
782         snprintf(tmppkg, MAXPATHLEN, "%s/pkg.txz.XXXXXX",
783             getenv("TMPDIR") ? getenv("TMPDIR") : _PATH_TMP);
784
785         if ((fd_pkg = fetch_to_fd(url, tmppkg)) == -1)
786                 goto fetchfail;
787
788         if (signature_type != NULL &&
789             strcasecmp(signature_type, "FINGERPRINTS") == 0) {
790                 snprintf(tmpsig, MAXPATHLEN, "%s/pkg.txz.sig.XXXXXX",
791                     getenv("TMPDIR") ? getenv("TMPDIR") : _PATH_TMP);
792                 snprintf(url, MAXPATHLEN, "%s/Latest/pkg.txz.sig",
793                     packagesite);
794
795                 if ((fd_sig = fetch_to_fd(url, tmpsig)) == -1) {
796                         fprintf(stderr, "Signature for pkg not available.\n");
797                         goto fetchfail;
798                 }
799
800                 if (verify_signature(fd_pkg, fd_sig) == false)
801                         goto cleanup;
802         }
803
804         if ((ret = extract_pkg_static(fd_pkg, pkgstatic, MAXPATHLEN)) == 0)
805                 ret = install_pkg_static(pkgstatic, tmppkg, force);
806
807         goto cleanup;
808
809 fetchfail:
810         warnx("Error fetching %s: %s", url, fetchLastErrString);
811         fprintf(stderr, "A pre-built version of pkg could not be found for "
812             "your system.\n");
813         fprintf(stderr, "Consider changing PACKAGESITE or installing it from "
814             "ports: 'ports-mgmt/pkg'.\n");
815
816 cleanup:
817         if (fd_sig != -1) {
818                 close(fd_sig);
819                 unlink(tmpsig);
820         }
821         close(fd_pkg);
822         unlink(tmppkg);
823
824         return (ret);
825 }
826
827 static const char confirmation_message[] =
828 "The package management tool is not yet installed on your system.\n"
829 "Do you want to fetch and install it now? [y/N]: ";
830
831 static int
832 pkg_query_yes_no(void)
833 {
834         int ret, c;
835
836         c = getchar();
837
838         if (c == 'y' || c == 'Y')
839                 ret = 1;
840         else
841                 ret = 0;
842
843         while (c != '\n' && c != EOF)
844                 c = getchar();
845
846         return (ret);
847 }
848
849 static int
850 bootstrap_pkg_local(const char *pkgpath, bool force)
851 {
852         char path[MAXPATHLEN];
853         char pkgstatic[MAXPATHLEN];
854         const char *signature_type;
855         int fd_pkg, fd_sig, ret;
856
857         fd_sig = -1;
858         ret = -1;
859
860         fd_pkg = open(pkgpath, O_RDONLY);
861         if (fd_pkg == -1)
862                 err(EXIT_FAILURE, "Unable to open %s", pkgpath);
863
864         if (config_string(SIGNATURE_TYPE, &signature_type) != 0) {
865                 warnx("Error looking up SIGNATURE_TYPE");
866                 return (-1);
867         }
868         if (signature_type != NULL &&
869             strcasecmp(signature_type, "FINGERPRINTS") == 0) {
870                 snprintf(path, sizeof(path), "%s.sig", pkgpath);
871
872                 if ((fd_sig = open(path, O_RDONLY)) == -1) {
873                         fprintf(stderr, "Signature for pkg not available.\n");
874                         goto cleanup;
875                 }
876
877                 if (verify_signature(fd_pkg, fd_sig) == false)
878                         goto cleanup;
879         }
880
881         if ((ret = extract_pkg_static(fd_pkg, pkgstatic, MAXPATHLEN)) == 0)
882                 ret = install_pkg_static(pkgstatic, pkgpath, force);
883
884 cleanup:
885         close(fd_pkg);
886         if (fd_sig != -1)
887                 close(fd_sig);
888
889         return (ret);
890 }
891
892 int
893 main(__unused int argc, char *argv[])
894 {
895         char pkgpath[MAXPATHLEN];
896         const char *pkgarg;
897         bool bootstrap_only, force, yes;
898
899         bootstrap_only = false;
900         force = false;
901         pkgarg = NULL;
902         yes = false;
903
904         snprintf(pkgpath, MAXPATHLEN, "%s/sbin/pkg",
905             getenv("LOCALBASE") ? getenv("LOCALBASE") : _LOCALBASE);
906
907         if (argc > 1 && strcmp(argv[1], "bootstrap") == 0) {
908                 bootstrap_only = true;
909                 if (argc == 3 && strcmp(argv[2], "-f") == 0)
910                         force = true;
911         }
912
913         if ((bootstrap_only && force) || access(pkgpath, X_OK) == -1) {
914                 /* 
915                  * To allow 'pkg -N' to be used as a reliable test for whether
916                  * a system is configured to use pkg, don't bootstrap pkg
917                  * when that argument is given as argv[1].
918                  */
919                 if (argv[1] != NULL && strcmp(argv[1], "-N") == 0)
920                         errx(EXIT_FAILURE, "pkg is not installed");
921
922                 config_init();
923
924                 if (argc > 1 && strcmp(argv[1], "add") == 0) {
925                         if (argc > 2 && strcmp(argv[2], "-f") == 0) {
926                                 force = true;
927                                 pkgarg = argv[3];
928                         } else
929                                 pkgarg = argv[2];
930                         if (pkgarg == NULL) {
931                                 fprintf(stderr, "Path to pkg.txz required\n");
932                                 exit(EXIT_FAILURE);
933                         }
934                         if (access(pkgarg, R_OK) == -1) {
935                                 fprintf(stderr, "No such file: %s\n", pkgarg);
936                                 exit(EXIT_FAILURE);
937                         }
938                         if (bootstrap_pkg_local(pkgarg, force) != 0)
939                                 exit(EXIT_FAILURE);
940                         exit(EXIT_SUCCESS);
941                 }
942                 /*
943                  * Do not ask for confirmation if either of stdin or stdout is
944                  * not tty. Check the environment to see if user has answer
945                  * tucked in there already.
946                  */
947                 config_bool(ASSUME_ALWAYS_YES, &yes);
948                 if (!yes) {
949                         printf("%s", confirmation_message);
950                         if (!isatty(fileno(stdin)))
951                                 exit(EXIT_FAILURE);
952
953                         if (pkg_query_yes_no() == 0)
954                                 exit(EXIT_FAILURE);
955                 }
956                 if (bootstrap_pkg(force) != 0)
957                         exit(EXIT_FAILURE);
958                 config_finish();
959
960                 if (bootstrap_only)
961                         exit(EXIT_SUCCESS);
962         } else if (bootstrap_only) {
963                 printf("pkg already bootstrapped at %s\n", pkgpath);
964                 exit(EXIT_SUCCESS);
965         }
966
967         execv(pkgpath, argv);
968
969         /* NOT REACHED */
970         return (EXIT_FAILURE);
971 }