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