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