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