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