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