]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - usr.sbin/pkg/pkg.c
MFC: r257701 (by bdrewery)
[FreeBSD/stable/10.git] / usr.sbin / pkg / pkg.c
1 /*-
2  * Copyright (c) 2012-2014 Baptiste Daroussin <bapt@FreeBSD.org>
3  * Copyright (c) 2013 Bryan Drewery <bdrewery@FreeBSD.org>
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
30
31 #include <sys/param.h>
32 #include <sys/queue.h>
33 #include <sys/types.h>
34 #include <sys/sbuf.h>
35 #include <sys/wait.h>
36
37 #define _WITH_GETLINE
38 #include <archive.h>
39 #include <archive_entry.h>
40 #include <dirent.h>
41 #include <err.h>
42 #include <errno.h>
43 #include <fcntl.h>
44 #include <fetch.h>
45 #include <paths.h>
46 #include <stdbool.h>
47 #include <stdlib.h>
48 #include <stdio.h>
49 #include <string.h>
50 #include <time.h>
51 #include <unistd.h>
52 #include <ucl.h>
53
54 #include <openssl/err.h>
55 #include <openssl/ssl.h>
56
57 #include "dns_utils.h"
58 #include "config.h"
59
60 struct sig_cert {
61         char *name;
62         unsigned char *sig;
63         int siglen;
64         unsigned char *cert;
65         int certlen;
66         bool trusted;
67 };
68
69 typedef enum {
70        HASH_UNKNOWN,
71        HASH_SHA256,
72 } hash_t;
73
74 struct fingerprint {
75        hash_t type;
76        char *name;
77        char hash[BUFSIZ];
78        STAILQ_ENTRY(fingerprint) next;
79 };
80
81 STAILQ_HEAD(fingerprint_list, fingerprint);
82
83 static int
84 extract_pkg_static(int fd, char *p, int sz)
85 {
86         struct archive *a;
87         struct archive_entry *ae;
88         char *end;
89         int ret, r;
90
91         ret = -1;
92         a = archive_read_new();
93         if (a == NULL) {
94                 warn("archive_read_new");
95                 return (ret);
96         }
97         archive_read_support_filter_all(a);
98         archive_read_support_format_tar(a);
99
100         if (lseek(fd, 0, 0) == -1) {
101                 warn("lseek");
102                 goto cleanup;
103         }
104
105         if (archive_read_open_fd(a, fd, 4096) != ARCHIVE_OK) {
106                 warnx("archive_read_open_fd: %s", archive_error_string(a));
107                 goto cleanup;
108         }
109
110         ae = NULL;
111         while ((r = archive_read_next_header(a, &ae)) == ARCHIVE_OK) {
112                 end = strrchr(archive_entry_pathname(ae), '/');
113                 if (end == NULL)
114                         continue;
115
116                 if (strcmp(end, "/pkg-static") == 0) {
117                         r = archive_read_extract(a, ae,
118                             ARCHIVE_EXTRACT_OWNER | ARCHIVE_EXTRACT_PERM |
119                             ARCHIVE_EXTRACT_TIME | ARCHIVE_EXTRACT_ACL |
120                             ARCHIVE_EXTRACT_FFLAGS | ARCHIVE_EXTRACT_XATTR);
121                         strlcpy(p, archive_entry_pathname(ae), sz);
122                         break;
123                 }
124         }
125
126         if (r == ARCHIVE_OK)
127                 ret = 0;
128         else
129                 warnx("failed to extract pkg-static: %s",
130                     archive_error_string(a));
131
132 cleanup:
133         archive_read_free(a);
134         return (ret);
135
136 }
137
138 static int
139 install_pkg_static(const char *path, const char *pkgpath, bool force)
140 {
141         int pstat;
142         pid_t pid;
143
144         switch ((pid = fork())) {
145         case -1:
146                 return (-1);
147         case 0:
148                 if (force)
149                         execl(path, "pkg-static", "add", "-f", pkgpath,
150                             (char *)NULL);
151                 else
152                         execl(path, "pkg-static", "add", pkgpath,
153                             (char *)NULL);
154                 _exit(1);
155         default:
156                 break;
157         }
158
159         while (waitpid(pid, &pstat, 0) == -1)
160                 if (errno != EINTR)
161                         return (-1);
162
163         if (WEXITSTATUS(pstat))
164                 return (WEXITSTATUS(pstat));
165         else if (WIFSIGNALED(pstat))
166                 return (128 & (WTERMSIG(pstat)));
167         return (pstat);
168 }
169
170 static int
171 fetch_to_fd(const char *url, char *path)
172 {
173         struct url *u;
174         struct dns_srvinfo *mirrors, *current;
175         struct url_stat st;
176         FILE *remote;
177         /* To store _https._tcp. + hostname + \0 */
178         int fd;
179         int retry, max_retry;
180         off_t done, r;
181         time_t now, last;
182         char buf[10240];
183         char zone[MAXHOSTNAMELEN + 13];
184         static const char *mirror_type = NULL;
185
186         done = 0;
187         last = 0;
188         max_retry = 3;
189         current = mirrors = NULL;
190         remote = NULL;
191
192         if (mirror_type == NULL && config_string(MIRROR_TYPE, &mirror_type)
193             != 0) {
194                 warnx("No MIRROR_TYPE defined");
195                 return (-1);
196         }
197
198         if ((fd = mkstemp(path)) == -1) {
199                 warn("mkstemp()");
200                 return (-1);
201         }
202
203         retry = max_retry;
204
205         if ((u = fetchParseURL(url)) == NULL) {
206                 warn("fetchParseURL('%s')", url);
207                 return (-1);
208         }
209
210         while (remote == NULL) {
211                 if (retry == max_retry) {
212                         if (strcmp(u->scheme, "file") != 0 &&
213                             strcasecmp(mirror_type, "srv") == 0) {
214                                 snprintf(zone, sizeof(zone),
215                                     "_%s._tcp.%s", u->scheme, u->host);
216                                 mirrors = dns_getsrvinfo(zone);
217                                 current = mirrors;
218                         }
219                 }
220
221                 if (mirrors != NULL) {
222                         strlcpy(u->host, current->host, sizeof(u->host));
223                         u->port = current->port;
224                 }
225
226                 remote = fetchXGet(u, &st, "");
227                 if (remote == NULL) {
228                         --retry;
229                         if (retry <= 0)
230                                 goto fetchfail;
231                         if (mirrors == NULL) {
232                                 sleep(1);
233                         } else {
234                                 current = current->next;
235                                 if (current == NULL)
236                                         current = mirrors;
237                         }
238                 }
239         }
240
241         while (done < st.size) {
242                 if ((r = fread(buf, 1, sizeof(buf), remote)) < 1)
243                         break;
244
245                 if (write(fd, buf, r) != r) {
246                         warn("write()");
247                         goto fetchfail;
248                 }
249
250                 done += r;
251                 now = time(NULL);
252                 if (now > last || done == st.size)
253                         last = now;
254         }
255
256         if (ferror(remote))
257                 goto fetchfail;
258
259         goto cleanup;
260
261 fetchfail:
262         if (fd != -1) {
263                 close(fd);
264                 fd = -1;
265                 unlink(path);
266         }
267
268 cleanup:
269         if (remote != NULL)
270                 fclose(remote);
271
272         return fd;
273 }
274
275 static struct fingerprint *
276 parse_fingerprint(ucl_object_t *obj)
277 {
278         const ucl_object_t *cur;
279         ucl_object_iter_t it = NULL;
280         const char *function, *fp, *key;
281         struct fingerprint *f;
282         hash_t fct = HASH_UNKNOWN;
283
284         function = fp = NULL;
285
286         while ((cur = ucl_iterate_object(obj, &it, true))) {
287                 key = ucl_object_key(cur);
288                 if (cur->type != UCL_STRING)
289                         continue;
290                 if (strcasecmp(key, "function") == 0) {
291                         function = ucl_object_tostring(cur);
292                         continue;
293                 }
294                 if (strcasecmp(key, "fingerprint") == 0) {
295                         fp = ucl_object_tostring(cur);
296                         continue;
297                 }
298         }
299
300         if (fp == NULL || function == NULL)
301                 return (NULL);
302
303         if (strcasecmp(function, "sha256") == 0)
304                 fct = HASH_SHA256;
305
306         if (fct == HASH_UNKNOWN) {
307                 warnx("Unsupported hashing function: %s", function);
308                 return (NULL);
309         }
310
311         f = calloc(1, sizeof(struct fingerprint));
312         f->type = fct;
313         strlcpy(f->hash, fp, sizeof(f->hash));
314
315         return (f);
316 }
317
318 static void
319 free_fingerprint_list(struct fingerprint_list* list)
320 {
321         struct fingerprint *fingerprint, *tmp;
322
323         STAILQ_FOREACH_SAFE(fingerprint, list, next, tmp) {
324                 if (fingerprint->name)
325                         free(fingerprint->name);
326                 free(fingerprint);
327         }
328         free(list);
329 }
330
331 static struct fingerprint *
332 load_fingerprint(const char *dir, const char *filename)
333 {
334         ucl_object_t *obj = NULL;
335         struct ucl_parser *p = NULL;
336         struct fingerprint *f;
337         char path[MAXPATHLEN];
338
339         f = NULL;
340
341         snprintf(path, MAXPATHLEN, "%s/%s", dir, filename);
342
343         p = ucl_parser_new(0);
344         if (!ucl_parser_add_file(p, path)) {
345                 warnx("%s: %s", path, ucl_parser_get_error(p));
346                 ucl_parser_free(p);
347                 return (NULL);
348         }
349
350         obj = ucl_parser_get_object(p);
351
352         if (obj->type == UCL_OBJECT)
353                 f = parse_fingerprint(obj);
354
355         if (f != NULL)
356                 f->name = strdup(filename);
357
358         ucl_object_unref(obj);
359         ucl_parser_free(p);
360
361         return (f);
362 }
363
364 static struct fingerprint_list *
365 load_fingerprints(const char *path, int *count)
366 {
367         DIR *d;
368         struct dirent *ent;
369         struct fingerprint *finger;
370         struct fingerprint_list *fingerprints;
371
372         *count = 0;
373
374         fingerprints = calloc(1, sizeof(struct fingerprint_list));
375         if (fingerprints == NULL)
376                 return (NULL);
377         STAILQ_INIT(fingerprints);
378
379         if ((d = opendir(path)) == NULL) {
380                 free(fingerprints);
381
382                 return (NULL);
383         }
384
385         while ((ent = readdir(d))) {
386                 if (strcmp(ent->d_name, ".") == 0 ||
387                     strcmp(ent->d_name, "..") == 0)
388                         continue;
389                 finger = load_fingerprint(path, ent->d_name);
390                 if (finger != NULL) {
391                         STAILQ_INSERT_TAIL(fingerprints, finger, next);
392                         ++(*count);
393                 }
394         }
395
396         closedir(d);
397
398         return (fingerprints);
399 }
400
401 static void
402 sha256_hash(unsigned char hash[SHA256_DIGEST_LENGTH],
403     char out[SHA256_DIGEST_LENGTH * 2 + 1])
404 {
405         int i;
406
407         for (i = 0; i < SHA256_DIGEST_LENGTH; i++)
408                 sprintf(out + (i * 2), "%02x", hash[i]);
409
410         out[SHA256_DIGEST_LENGTH * 2] = '\0';
411 }
412
413 static void
414 sha256_buf(char *buf, size_t len, char out[SHA256_DIGEST_LENGTH * 2 + 1])
415 {
416         unsigned char hash[SHA256_DIGEST_LENGTH];
417         SHA256_CTX sha256;
418
419         out[0] = '\0';
420
421         SHA256_Init(&sha256);
422         SHA256_Update(&sha256, buf, len);
423         SHA256_Final(hash, &sha256);
424         sha256_hash(hash, out);
425 }
426
427 static int
428 sha256_fd(int fd, char out[SHA256_DIGEST_LENGTH * 2 + 1])
429 {
430         int my_fd;
431         FILE *fp;
432         char buffer[BUFSIZ];
433         unsigned char hash[SHA256_DIGEST_LENGTH];
434         size_t r;
435         int ret;
436         SHA256_CTX sha256;
437
438         my_fd = -1;
439         fp = NULL;
440         r = 0;
441         ret = 1;
442
443         out[0] = '\0';
444
445         /* Duplicate the fd so that fclose(3) does not close it. */
446         if ((my_fd = dup(fd)) == -1) {
447                 warnx("dup");
448                 goto cleanup;
449         }
450
451         if ((fp = fdopen(my_fd, "rb")) == NULL) {
452                 warnx("fdopen");
453                 goto cleanup;
454         }
455
456         SHA256_Init(&sha256);
457
458         while ((r = fread(buffer, 1, BUFSIZ, fp)) > 0)
459                 SHA256_Update(&sha256, buffer, r);
460
461         if (ferror(fp) != 0) {
462                 warnx("fread");
463                 goto cleanup;
464         }
465
466         SHA256_Final(hash, &sha256);
467         sha256_hash(hash, out);
468         ret = 0;
469
470 cleanup:
471         if (fp != NULL)
472                 fclose(fp);
473         else if (my_fd != -1)
474                 close(my_fd);
475         (void)lseek(fd, 0, SEEK_SET);
476
477         return (ret);
478 }
479
480 static EVP_PKEY *
481 load_public_key_buf(const unsigned char *cert, int certlen)
482 {
483         EVP_PKEY *pkey;
484         BIO *bp;
485         char errbuf[1024];
486
487         bp = BIO_new_mem_buf(__DECONST(void *, cert), certlen);
488
489         if ((pkey = PEM_read_bio_PUBKEY(bp, NULL, NULL, NULL)) == NULL)
490                 warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
491
492         BIO_free(bp);
493
494         return (pkey);
495 }
496
497 static bool
498 rsa_verify_cert(int fd, const unsigned char *key, int keylen,
499     unsigned char *sig, int siglen)
500 {
501         EVP_MD_CTX *mdctx;
502         EVP_PKEY *pkey;
503         char sha256[(SHA256_DIGEST_LENGTH * 2) + 2];
504         char errbuf[1024];
505         bool ret;
506
507         pkey = NULL;
508         mdctx = NULL;
509         ret = false;
510
511         /* Compute SHA256 of the package. */
512         if (lseek(fd, 0, 0) == -1) {
513                 warn("lseek");
514                 goto cleanup;
515         }
516         if ((sha256_fd(fd, sha256)) == -1) {
517                 warnx("Error creating SHA256 hash for package");
518                 goto cleanup;
519         }
520
521         if ((pkey = load_public_key_buf(key, keylen)) == NULL) {
522                 warnx("Error reading public key");
523                 goto cleanup;
524         }
525
526         /* Verify signature of the SHA256(pkg) is valid. */
527         if ((mdctx = EVP_MD_CTX_create()) == NULL) {
528                 warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
529                 goto error;
530         }
531
532         if (EVP_DigestVerifyInit(mdctx, NULL, EVP_sha256(), NULL, pkey) != 1) {
533                 warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
534                 goto error;
535         }
536         if (EVP_DigestVerifyUpdate(mdctx, sha256, strlen(sha256)) != 1) {
537                 warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
538                 goto error;
539         }
540
541         if (EVP_DigestVerifyFinal(mdctx, sig, siglen) != 1) {
542                 warnx("%s", ERR_error_string(ERR_get_error(), errbuf));
543                 goto error;
544         }
545
546         ret = true;
547         printf("done\n");
548         goto cleanup;
549
550 error:
551         printf("failed\n");
552
553 cleanup:
554         if (pkey)
555                 EVP_PKEY_free(pkey);
556         if (mdctx)
557                 EVP_MD_CTX_destroy(mdctx);
558         ERR_free_strings();
559
560         return (ret);
561 }
562
563 static struct sig_cert *
564 parse_cert(int fd) {
565         int my_fd;
566         struct sig_cert *sc;
567         FILE *fp;
568         struct sbuf *buf, *sig, *cert;
569         char *line;
570         size_t linecap;
571         ssize_t linelen;
572
573         buf = NULL;
574         my_fd = -1;
575         sc = NULL;
576         line = NULL;
577         linecap = 0;
578
579         if (lseek(fd, 0, 0) == -1) {
580                 warn("lseek");
581                 return (NULL);
582         }
583
584         /* Duplicate the fd so that fclose(3) does not close it. */
585         if ((my_fd = dup(fd)) == -1) {
586                 warnx("dup");
587                 return (NULL);
588         }
589
590         if ((fp = fdopen(my_fd, "rb")) == NULL) {
591                 warn("fdopen");
592                 close(my_fd);
593                 return (NULL);
594         }
595
596         sig = sbuf_new_auto();
597         cert = sbuf_new_auto();
598
599         while ((linelen = getline(&line, &linecap, fp)) > 0) {
600                 if (strcmp(line, "SIGNATURE\n") == 0) {
601                         buf = sig;
602                         continue;
603                 } else if (strcmp(line, "CERT\n") == 0) {
604                         buf = cert;
605                         continue;
606                 } else if (strcmp(line, "END\n") == 0) {
607                         break;
608                 }
609                 if (buf != NULL)
610                         sbuf_bcat(buf, line, linelen);
611         }
612
613         fclose(fp);
614
615         /* Trim out unrelated trailing newline */
616         sbuf_setpos(sig, sbuf_len(sig) - 1);
617
618         sbuf_finish(sig);
619         sbuf_finish(cert);
620
621         sc = calloc(1, sizeof(struct sig_cert));
622         sc->siglen = sbuf_len(sig);
623         sc->sig = calloc(1, sc->siglen);
624         memcpy(sc->sig, sbuf_data(sig), sc->siglen);
625
626         sc->certlen = sbuf_len(cert);
627         sc->cert = strdup(sbuf_data(cert));
628
629         sbuf_delete(sig);
630         sbuf_delete(cert);
631
632         return (sc);
633 }
634
635 static bool
636 verify_signature(int fd_pkg, int fd_sig)
637 {
638         struct fingerprint_list *trusted, *revoked;
639         struct fingerprint *fingerprint;
640         struct sig_cert *sc;
641         bool ret;
642         int trusted_count, revoked_count;
643         const char *fingerprints;
644         char path[MAXPATHLEN];
645         char hash[SHA256_DIGEST_LENGTH * 2 + 1];
646
647         sc = NULL;
648         trusted = revoked = NULL;
649         ret = false;
650
651         /* Read and parse fingerprints. */
652         if (config_string(FINGERPRINTS, &fingerprints) != 0) {
653                 warnx("No CONFIG_FINGERPRINTS defined");
654                 goto cleanup;
655         }
656
657         snprintf(path, MAXPATHLEN, "%s/trusted", fingerprints);
658         if ((trusted = load_fingerprints(path, &trusted_count)) == NULL) {
659                 warnx("Error loading trusted certificates");
660                 goto cleanup;
661         }
662
663         if (trusted_count == 0 || trusted == NULL) {
664                 fprintf(stderr, "No trusted certificates found.\n");
665                 goto cleanup;
666         }
667
668         snprintf(path, MAXPATHLEN, "%s/revoked", fingerprints);
669         if ((revoked = load_fingerprints(path, &revoked_count)) == NULL) {
670                 warnx("Error loading revoked certificates");
671                 goto cleanup;
672         }
673
674         /* Read certificate and signature in. */
675         if ((sc = parse_cert(fd_sig)) == NULL) {
676                 warnx("Error parsing certificate");
677                 goto cleanup;
678         }
679         /* Explicitly mark as non-trusted until proven otherwise. */
680         sc->trusted = false;
681
682         /* Parse signature and pubkey out of the certificate */
683         sha256_buf(sc->cert, sc->certlen, hash);
684
685         /* Check if this hash is revoked */
686         if (revoked != NULL) {
687                 STAILQ_FOREACH(fingerprint, revoked, next) {
688                         if (strcasecmp(fingerprint->hash, hash) == 0) {
689                                 fprintf(stderr, "The package was signed with "
690                                     "revoked certificate %s\n",
691                                     fingerprint->name);
692                                 goto cleanup;
693                         }
694                 }
695         }
696
697         STAILQ_FOREACH(fingerprint, trusted, next) {
698                 if (strcasecmp(fingerprint->hash, hash) == 0) {
699                         sc->trusted = true;
700                         sc->name = strdup(fingerprint->name);
701                         break;
702                 }
703         }
704
705         if (sc->trusted == false) {
706                 fprintf(stderr, "No trusted fingerprint found matching "
707                     "package's certificate\n");
708                 goto cleanup;
709         }
710
711         /* Verify the signature. */
712         printf("Verifying signature with trusted certificate %s... ", sc->name);
713         if (rsa_verify_cert(fd_pkg, sc->cert, sc->certlen, sc->sig,
714             sc->siglen) == false) {
715                 fprintf(stderr, "Signature is not valid\n");
716                 goto cleanup;
717         }
718
719         ret = true;
720
721 cleanup:
722         if (trusted)
723                 free_fingerprint_list(trusted);
724         if (revoked)
725                 free_fingerprint_list(revoked);
726         if (sc) {
727                 if (sc->cert)
728                         free(sc->cert);
729                 if (sc->sig)
730                         free(sc->sig);
731                 if (sc->name)
732                         free(sc->name);
733                 free(sc);
734         }
735
736         return (ret);
737 }
738
739 static int
740 bootstrap_pkg(bool force)
741 {
742         int fd_pkg, fd_sig;
743         int ret;
744         char url[MAXPATHLEN];
745         char tmppkg[MAXPATHLEN];
746         char tmpsig[MAXPATHLEN];
747         const char *packagesite;
748         const char *signature_type;
749         char pkgstatic[MAXPATHLEN];
750
751         fd_sig = -1;
752         ret = -1;
753
754         if (config_string(PACKAGESITE, &packagesite) != 0) {
755                 warnx("No PACKAGESITE defined");
756                 return (-1);
757         }
758
759         if (config_string(SIGNATURE_TYPE, &signature_type) != 0) {
760                 warnx("Error looking up SIGNATURE_TYPE");
761                 return (-1);
762         }
763
764         printf("Bootstrapping pkg from %s, please wait...\n", packagesite);
765
766         /* Support pkg+http:// for PACKAGESITE which is the new format
767            in 1.2 to avoid confusion on why http://pkg.FreeBSD.org has
768            no A record. */
769         if (strncmp(URL_SCHEME_PREFIX, packagesite,
770             strlen(URL_SCHEME_PREFIX)) == 0)
771                 packagesite += strlen(URL_SCHEME_PREFIX);
772         snprintf(url, MAXPATHLEN, "%s/Latest/pkg.txz", packagesite);
773
774         snprintf(tmppkg, MAXPATHLEN, "%s/pkg.txz.XXXXXX",
775             getenv("TMPDIR") ? getenv("TMPDIR") : _PATH_TMP);
776
777         if ((fd_pkg = fetch_to_fd(url, tmppkg)) == -1)
778                 goto fetchfail;
779
780         if (signature_type != NULL &&
781             strcasecmp(signature_type, "FINGERPRINTS") == 0) {
782                 snprintf(tmpsig, MAXPATHLEN, "%s/pkg.txz.sig.XXXXXX",
783                     getenv("TMPDIR") ? getenv("TMPDIR") : _PATH_TMP);
784                 snprintf(url, MAXPATHLEN, "%s/Latest/pkg.txz.sig",
785                     packagesite);
786
787                 if ((fd_sig = fetch_to_fd(url, tmpsig)) == -1) {
788                         fprintf(stderr, "Signature for pkg not available.\n");
789                         goto fetchfail;
790                 }
791
792                 if (verify_signature(fd_pkg, fd_sig) == false)
793                         goto cleanup;
794         }
795
796         if ((ret = extract_pkg_static(fd_pkg, pkgstatic, MAXPATHLEN)) == 0)
797                 ret = install_pkg_static(pkgstatic, tmppkg, force);
798
799         goto cleanup;
800
801 fetchfail:
802         warnx("Error fetching %s: %s", url, fetchLastErrString);
803         fprintf(stderr, "A pre-built version of pkg could not be found for "
804             "your system.\n");
805         fprintf(stderr, "Consider changing PACKAGESITE or installing it from "
806             "ports: 'ports-mgmt/pkg'.\n");
807
808 cleanup:
809         if (fd_sig != -1) {
810                 close(fd_sig);
811                 unlink(tmpsig);
812         }
813
814         if (fd_pkg != -1) {
815                 close(fd_pkg);
816                 unlink(tmppkg);
817         }
818
819         return (ret);
820 }
821
822 static const char confirmation_message[] =
823 "The package management tool is not yet installed on your system.\n"
824 "Do you want to fetch and install it now? [y/N]: ";
825
826 static int
827 pkg_query_yes_no(void)
828 {
829         int ret, c;
830
831         c = getchar();
832
833         if (c == 'y' || c == 'Y')
834                 ret = 1;
835         else
836                 ret = 0;
837
838         while (c != '\n' && c != EOF)
839                 c = getchar();
840
841         return (ret);
842 }
843
844 static int
845 bootstrap_pkg_local(const char *pkgpath, bool force)
846 {
847         char path[MAXPATHLEN];
848         char pkgstatic[MAXPATHLEN];
849         const char *signature_type;
850         int fd_pkg, fd_sig, ret;
851
852         fd_sig = -1;
853         ret = -1;
854
855         fd_pkg = open(pkgpath, O_RDONLY);
856         if (fd_pkg == -1)
857                 err(EXIT_FAILURE, "Unable to open %s", pkgpath);
858
859         if (config_string(SIGNATURE_TYPE, &signature_type) != 0) {
860                 warnx("Error looking up SIGNATURE_TYPE");
861                 goto cleanup;
862         }
863         if (signature_type != NULL &&
864             strcasecmp(signature_type, "FINGERPRINTS") == 0) {
865                 snprintf(path, sizeof(path), "%s.sig", pkgpath);
866
867                 if ((fd_sig = open(path, O_RDONLY)) == -1) {
868                         fprintf(stderr, "Signature for pkg not available.\n");
869                         goto cleanup;
870                 }
871
872                 if (verify_signature(fd_pkg, fd_sig) == false)
873                         goto cleanup;
874         }
875
876         if ((ret = extract_pkg_static(fd_pkg, pkgstatic, MAXPATHLEN)) == 0)
877                 ret = install_pkg_static(pkgstatic, pkgpath, force);
878
879 cleanup:
880         close(fd_pkg);
881         if (fd_sig != -1)
882                 close(fd_sig);
883
884         return (ret);
885 }
886
887 int
888 main(__unused int argc, char *argv[])
889 {
890         char pkgpath[MAXPATHLEN];
891         const char *pkgarg;
892         bool bootstrap_only, force, yes;
893
894         bootstrap_only = false;
895         force = false;
896         pkgarg = NULL;
897         yes = false;
898
899         snprintf(pkgpath, MAXPATHLEN, "%s/sbin/pkg",
900             getenv("LOCALBASE") ? getenv("LOCALBASE") : _LOCALBASE);
901
902         if (argc > 1 && strcmp(argv[1], "bootstrap") == 0) {
903                 bootstrap_only = true;
904                 if (argc == 3 && strcmp(argv[2], "-f") == 0)
905                         force = true;
906         }
907
908         if ((bootstrap_only && force) || access(pkgpath, X_OK) == -1) {
909                 /* 
910                  * To allow 'pkg -N' to be used as a reliable test for whether
911                  * a system is configured to use pkg, don't bootstrap pkg
912                  * when that argument is given as argv[1].
913                  */
914                 if (argv[1] != NULL && strcmp(argv[1], "-N") == 0)
915                         errx(EXIT_FAILURE, "pkg is not installed");
916
917                 config_init();
918
919                 if (argc > 1 && strcmp(argv[1], "add") == 0) {
920                         if (argc > 2 && strcmp(argv[2], "-f") == 0) {
921                                 force = true;
922                                 pkgarg = argv[3];
923                         } else
924                                 pkgarg = argv[2];
925                         if (pkgarg == NULL) {
926                                 fprintf(stderr, "Path to pkg.txz required\n");
927                                 exit(EXIT_FAILURE);
928                         }
929                         if (access(pkgarg, R_OK) == -1) {
930                                 fprintf(stderr, "No such file: %s\n", pkgarg);
931                                 exit(EXIT_FAILURE);
932                         }
933                         if (bootstrap_pkg_local(pkgarg, force) != 0)
934                                 exit(EXIT_FAILURE);
935                         exit(EXIT_SUCCESS);
936                 }
937                 /*
938                  * Do not ask for confirmation if either of stdin or stdout is
939                  * not tty. Check the environment to see if user has answer
940                  * tucked in there already.
941                  */
942                 config_bool(ASSUME_ALWAYS_YES, &yes);
943                 if (!yes) {
944                         printf("%s", confirmation_message);
945                         if (!isatty(fileno(stdin)))
946                                 exit(EXIT_FAILURE);
947
948                         if (pkg_query_yes_no() == 0)
949                                 exit(EXIT_FAILURE);
950                 }
951                 if (bootstrap_pkg(force) != 0)
952                         exit(EXIT_FAILURE);
953                 config_finish();
954
955                 if (bootstrap_only)
956                         exit(EXIT_SUCCESS);
957         } else if (bootstrap_only) {
958                 printf("pkg already bootstrapped at %s\n", pkgpath);
959                 exit(EXIT_SUCCESS);
960         }
961
962         execv(pkgpath, argv);
963
964         /* NOT REACHED */
965         return (EXIT_FAILURE);
966 }