97e1a84e5be8238e1f3a1395779a6330cd0e4eef
[oweals/opkg-lede.git] / libopkg / opkg_download.c
1 /* vi: set noexpandtab sw=4 sts=4: */
2 /* opkg_download.c - the opkg package management system
3
4    Carl D. Worth
5
6    Copyright (C) 2001 University of Southern California
7    Copyright (C) 2008 OpenMoko Inc
8
9    This program is free software; you can redistribute it and/or
10    modify it under the terms of the GNU General Public License as
11    published by the Free Software Foundation; either version 2, or (at
12    your option) any later version.
13
14    This program is distributed in the hope that it will be useful, but
15    WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17    General Public License for more details.
18 */
19
20 #include "config.h"
21
22 #include <sys/wait.h>
23 #include <stdio.h>
24 #include <unistd.h>
25 #include <libgen.h>
26
27 #include "opkg_download.h"
28 #include "opkg_message.h"
29
30 #include "sprintf_alloc.h"
31 #include "xsystem.h"
32 #include "file_util.h"
33 #include "opkg_defines.h"
34 #include "libbb/libbb.h"
35
36 #ifdef HAVE_CURL
37 #include <curl/curl.h>
38 #endif
39
40 #if defined(HAVE_SSLCURL) || defined(HAVE_OPENSSL)
41 #include <openssl/conf.h>
42 #include <openssl/evp.h>
43 #include <openssl/err.h>
44 #include <openssl/ssl.h>
45 #endif
46
47 #if defined(HAVE_GPGME)
48 #include <gpgme.h>
49 #elif defined(HAVE_OPENSSL)
50 #include <openssl/bio.h>
51 #include <openssl/objects.h>
52 #include <openssl/x509.h>
53 #include <openssl/pem.h>
54 #include <openssl/hmac.h>
55 #endif
56
57 #ifdef HAVE_PATHFINDER
58 #include "opkg_pathfinder.h"
59 #endif
60
61 #if defined(HAVE_OPENSSL) || defined(HAVE_SSLCURL)
62 static void openssl_init(void);
63 #endif
64
65 #ifdef HAVE_OPENSSL
66 static X509_STORE *setup_verify(char *CAfile, char *CApath);
67 #endif
68
69 #ifdef HAVE_CURL
70 /*
71  * Make curl an instance variable so we don't have to instanciate it
72  * each time
73  */
74 static CURL *curl = NULL;
75 static CURL *opkg_curl_init(curl_progress_func cb, void *data);
76 #endif
77
78 static int
79 str_starts_with(const char *str, const char *prefix)
80 {
81     return (strncmp(str, prefix, strlen(prefix)) == 0);
82 }
83
84 int
85 opkg_download(const char *src, const char *dest_file_name,
86         curl_progress_func cb, void *data, const short hide_error)
87 {
88     int err = 0;
89
90     char *src_basec = xstrdup(src);
91     char *src_base = basename(src_basec);
92     char *tmp_file_location;
93
94     opkg_msg(NOTICE,"Downloading %s.\n", src);
95
96     if (str_starts_with(src, "file:")) {
97         const char *file_src = src + 5;
98         opkg_msg(INFO, "Copying %s to %s...", file_src, dest_file_name);
99         err = file_copy(file_src, dest_file_name);
100         opkg_msg(INFO, "Done.\n");
101         free(src_basec);
102         return err;
103     }
104
105     sprintf_alloc(&tmp_file_location, "%s/%s", conf->tmp_dir, src_base);
106     free(src_basec);
107     err = unlink(tmp_file_location);
108     if (err && errno != ENOENT) {
109         opkg_perror(ERROR, "Failed to unlink %s", tmp_file_location);
110         free(tmp_file_location);
111         return -1;
112     }
113
114     if (conf->http_proxy) {
115         opkg_msg(DEBUG, "Setting environment variable: http_proxy = %s.\n",
116                 conf->http_proxy);
117         setenv("http_proxy", conf->http_proxy, 1);
118     }
119     if (conf->ftp_proxy) {
120         opkg_msg(DEBUG, "Setting environment variable: ftp_proxy = %s.\n",
121                 conf->ftp_proxy);
122         setenv("ftp_proxy", conf->ftp_proxy, 1);
123     }
124     if (conf->no_proxy) {
125         opkg_msg(DEBUG,"Setting environment variable: no_proxy = %s.\n",
126                 conf->no_proxy);
127         setenv("no_proxy", conf->no_proxy, 1);
128     }
129
130 #ifdef HAVE_CURL
131     CURLcode res;
132     FILE * file = fopen (tmp_file_location, "w");
133
134     curl = opkg_curl_init (cb, data);
135     if (curl)
136     {
137         curl_easy_setopt (curl, CURLOPT_URL, src);
138         curl_easy_setopt (curl, CURLOPT_WRITEDATA, file);
139
140         res = curl_easy_perform (curl);
141         fclose (file);
142         if (res)
143         {
144             long error_code;
145             curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &error_code);
146             opkg_msg(hide_error?DEBUG2:ERROR, "Failed to download %s: %s.\n",
147                     src, curl_easy_strerror(res));
148             free(tmp_file_location);
149             return -1;
150         }
151
152     }
153     else
154     {
155         free(tmp_file_location);
156         return -1;
157     }
158 #else
159     {
160       int res;
161       const char *argv[8];
162       int i = 0;
163
164       argv[i++] = "wget";
165       argv[i++] = "-q";
166       if (conf->http_proxy || conf->ftp_proxy) {
167         argv[i++] = "-Y";
168         argv[i++] = "on";
169       }
170       argv[i++] = "-O";
171       argv[i++] = tmp_file_location;
172       argv[i++] = src;
173       argv[i++] = NULL;
174       res = xsystem(argv);
175
176       if (res) {
177         opkg_msg(ERROR, "Failed to download %s, wget returned %d.\n", src, res);
178         free(tmp_file_location);
179         return -1;
180       }
181     }
182 #endif
183
184     err = file_move(tmp_file_location, dest_file_name);
185
186     free(tmp_file_location);
187
188     return err;
189 }
190
191 static int
192 opkg_download_cache(const char *src, const char *dest_file_name,
193         curl_progress_func cb, void *data)
194 {
195     char *cache_name = xstrdup(src);
196     char *cache_location, *p;
197     int err = 0;
198
199     if (!conf->cache || str_starts_with(src, "file:")) {
200         err = opkg_download(src, dest_file_name, cb, data, 0);
201         goto out1;
202     }
203
204     if(!file_is_dir(conf->cache)){
205             opkg_msg(ERROR, "%s is not a directory.\n",
206                             conf->cache);
207             err = 1;
208             goto out1;
209     }
210
211     for (p = cache_name; *p; p++)
212         if (*p == '/')
213             *p = ',';   /* looks nicer than | or # */
214
215     sprintf_alloc(&cache_location, "%s/%s", conf->cache, cache_name);
216     if (file_exists(cache_location))
217         opkg_msg(NOTICE, "Copying %s.\n", cache_location);
218     else {
219        /* cache file with funky name not found, try simple name */
220         free(cache_name);
221         char *filename = strrchr(dest_file_name,'/');
222         if (filename)
223            cache_name = xstrdup(filename+1); // strip leading '/'
224         else
225            cache_name = xstrdup(dest_file_name);
226         free(cache_location);
227         sprintf_alloc(&cache_location, "%s/%s", conf->cache, cache_name);
228         if (file_exists(cache_location))
229            opkg_msg(NOTICE, "Copying %s.\n", cache_location);
230         else  {
231             err = opkg_download(src, cache_location, cb, data, 0);
232             if (err) {
233                (void) unlink(cache_location);
234                goto out2;
235           }
236         }
237     }
238
239     err = file_copy(cache_location, dest_file_name);
240
241
242 out2:
243     free(cache_location);
244 out1:
245     free(cache_name);
246     return err;
247 }
248
249 int
250 opkg_download_pkg(pkg_t *pkg, const char *dir)
251 {
252     int err;
253     char *url;
254     char *stripped_filename;
255
256     if (pkg->src == NULL) {
257         opkg_msg(ERROR, "Package %s is not available from any configured src.\n",
258                 pkg->name);
259         return -1;
260     }
261     if (pkg->filename == NULL) {
262         opkg_msg(ERROR, "Package %s does not have a valid filename field.\n",
263                 pkg->name);
264         return -1;
265     }
266
267     sprintf_alloc(&url, "%s/%s", pkg->src->value, pkg->filename);
268
269     /* The pkg->filename might be something like
270        "../../foo.opk". While this is correct, and exactly what we
271        want to use to construct url above, here we actually need to
272        use just the filename part, without any directory. */
273
274     stripped_filename = strrchr(pkg->filename, '/');
275     if ( ! stripped_filename )
276         stripped_filename = pkg->filename;
277
278     sprintf_alloc(&pkg->local_filename, "%s/%s", dir, stripped_filename);
279
280     err = opkg_download_cache(url, pkg->local_filename, NULL, NULL);
281     free(url);
282
283     return err;
284 }
285
286 /*
287  * Downloads file from url, installs in package database, return package name.
288  */
289 int
290 opkg_prepare_url_for_install(const char *url, char **namep)
291 {
292      int err = 0;
293      pkg_t *pkg;
294
295      pkg = pkg_new();
296
297      if (str_starts_with(url, "http://")
298          || str_starts_with(url, "ftp://")) {
299           char *tmp_file;
300           char *file_basec = xstrdup(url);
301           char *file_base = basename(file_basec);
302
303           sprintf_alloc(&tmp_file, "%s/%s", conf->tmp_dir, file_base);
304           err = opkg_download(url, tmp_file, NULL, NULL, 0);
305           if (err)
306                return err;
307
308           err = pkg_init_from_file(pkg, tmp_file);
309           if (err)
310                return err;
311
312           free(tmp_file);
313           free(file_basec);
314
315      } else if (strcmp(&url[strlen(url) - 4], OPKG_PKG_EXTENSION) == 0
316                 || strcmp(&url[strlen(url) - 4], IPKG_PKG_EXTENSION) == 0
317                 || strcmp(&url[strlen(url) - 4], DPKG_PKG_EXTENSION) == 0) {
318
319           err = pkg_init_from_file(pkg, url);
320           if (err)
321                return err;
322           opkg_msg(DEBUG2, "Package %s provided by hand (%s).\n",
323                   pkg->name, pkg->local_filename);
324           pkg->provided_by_hand = 1;
325
326      } else {
327        pkg_deinit(pkg);
328        free(pkg);
329        return 0;
330      }
331
332      pkg->dest = conf->default_dest;
333      pkg->state_want = SW_INSTALL;
334      pkg->state_flag |= SF_PREFER;
335      hash_insert_pkg(pkg, 1);
336
337      if (namep) {
338           *namep = pkg->name;
339      }
340      return 0;
341 }
342
343 int
344 opkg_verify_file (char *text_file, char *sig_file)
345 {
346 #if defined HAVE_USIGN
347         int status = -1;
348         int pid;
349
350     if (conf->check_signature == 0 )
351         return 0;
352
353         pid = fork();
354         if (pid < 0)
355                 return -1;
356
357         if (!pid) {
358                 execl("/usr/sbin/opkg-key", "opkg-key", "verify", sig_file, text_file, NULL);
359                 exit(255);
360         }
361
362         waitpid(pid, &status, 0);
363         if (!WIFEXITED(status) || WEXITSTATUS(status))
364                 return -1;
365
366         return 0;
367 #elif defined HAVE_GPGME
368     if (conf->check_signature == 0 )
369         return 0;
370     int status = -1;
371     gpgme_ctx_t ctx;
372     gpgme_data_t sig, text, key;
373     gpgme_error_t err;
374     gpgme_verify_result_t result;
375     gpgme_signature_t s;
376     char *trusted_path = NULL;
377
378     gpgme_check_version (NULL);
379
380     err = gpgme_new (&ctx);
381
382     if (err)
383         return -1;
384
385     sprintf_alloc(&trusted_path, "%s/%s", conf->offline_root, "/etc/opkg/trusted.gpg");
386     err = gpgme_data_new_from_file (&key, trusted_path, 1);
387     free (trusted_path);
388     if (err)
389     {
390       return -1;
391     }
392     err = gpgme_op_import (ctx, key);
393     if (err)
394     {
395       gpgme_data_release (key);
396       return -1;
397     }
398     gpgme_data_release (key);
399
400     err = gpgme_data_new_from_file (&sig, sig_file, 1);
401     if (err)
402     {
403         gpgme_release (ctx);
404         return -1;
405     }
406
407     err = gpgme_data_new_from_file (&text, text_file, 1);
408     if (err)
409     {
410         gpgme_data_release (sig);
411         gpgme_release (ctx);
412         return -1;
413     }
414
415     err = gpgme_op_verify (ctx, sig, text, NULL);
416
417     result = gpgme_op_verify_result (ctx);
418     if (!result)
419         return -1;
420
421     /* see if any of the signitures matched */
422     s = result->signatures;
423     while (s)
424     {
425         status = gpg_err_code (s->status);
426         if (status == GPG_ERR_NO_ERROR)
427             break;
428         s = s->next;
429     }
430
431
432     gpgme_data_release (sig);
433     gpgme_data_release (text);
434     gpgme_release (ctx);
435
436     return status;
437 #elif defined HAVE_OPENSSL
438     X509_STORE *store = NULL;
439     PKCS7 *p7 = NULL;
440     BIO *in = NULL, *indata = NULL;
441
442     // Sig check failed by default !
443     int status = -1;
444
445     openssl_init();
446
447     // Set-up the key store
448     if(!(store = setup_verify(conf->signature_ca_file, conf->signature_ca_path))){
449         opkg_msg(ERROR, "Can't open CA certificates.\n");
450         goto verify_file_end;
451     }
452
453     // Open a BIO to read the sig file
454     if (!(in = BIO_new_file(sig_file, "rb"))){
455         opkg_msg(ERROR, "Can't open signature file %s.\n", sig_file);
456         goto verify_file_end;
457     }
458
459     // Read the PKCS7 block contained in the sig file
460     p7 = PEM_read_bio_PKCS7(in, NULL, NULL, NULL);
461     if(!p7){
462         opkg_msg(ERROR, "Can't read signature file %s (Corrupted ?).\n",
463                 sig_file);
464         goto verify_file_end;
465     }
466 #if defined(HAVE_PATHFINDER)
467     if(conf->check_x509_path){
468         if(!pkcs7_pathfinder_verify_signers(p7)){
469             opkg_msg(ERROR, "pkcs7_pathfinder_verify_signers: "
470                     "Path verification failed.\n");
471             goto verify_file_end;
472         }
473     }
474 #endif
475
476     // Open the Package file to authenticate
477     if (!(indata = BIO_new_file(text_file, "rb"))){
478         opkg_msg(ERROR, "Can't open file %s.\n", text_file);
479         goto verify_file_end;
480     }
481
482     // Let's verify the autenticity !
483     if (PKCS7_verify(p7, NULL, store, indata, NULL, PKCS7_BINARY) != 1){
484         // Get Off My Lawn!
485         opkg_msg(ERROR, "Verification failure.\n");
486     }else{
487         // Victory !
488         status = 0;
489     }
490
491 verify_file_end:
492     BIO_free(in);
493     BIO_free(indata);
494     PKCS7_free(p7);
495     X509_STORE_free(store);
496
497     return status;
498 #else
499     /* mute `unused variable' warnings. */
500     (void) sig_file;
501     (void) text_file;
502     (void) conf;
503     return 0;
504 #endif
505 }
506
507
508 #if defined(HAVE_OPENSSL) || defined(HAVE_SSLCURL)
509 static void openssl_init(void){
510     static int init = 0;
511
512     if(!init){
513         OPENSSL_config(NULL);
514         OpenSSL_add_all_algorithms();
515         ERR_load_crypto_strings();
516         init = 1;
517     }
518 }
519
520 #endif
521
522
523 #if defined HAVE_OPENSSL
524 static X509_STORE *
525 setup_verify(char *CAfile, char *CApath)
526 {
527     X509_STORE *store = NULL;
528     X509_LOOKUP *lookup = NULL;
529
530     if(!(store = X509_STORE_new())){
531         // Something bad is happening...
532         goto end;
533     }
534
535     // adds the X509 file lookup method
536     lookup = X509_STORE_add_lookup(store,X509_LOOKUP_file());
537     if (lookup == NULL){
538         goto end;
539     }
540
541     // Autenticating against one CA file
542     if (CAfile) {
543         if(!X509_LOOKUP_load_file(lookup,CAfile,X509_FILETYPE_PEM)) {
544             // Invalid CA => Bye bye
545             opkg_msg(ERROR, "Error loading file %s.\n", CAfile);
546             goto end;
547         }
548     } else {
549         X509_LOOKUP_load_file(lookup,NULL,X509_FILETYPE_DEFAULT);
550     }
551
552     // Now look into CApath directory if supplied
553     lookup = X509_STORE_add_lookup(store,X509_LOOKUP_hash_dir());
554     if (lookup == NULL){
555         goto end;
556     }
557
558     if (CApath) {
559         if(!X509_LOOKUP_add_dir(lookup,CApath,X509_FILETYPE_PEM)) {
560             opkg_msg(ERROR, "Error loading directory %s.\n", CApath);
561             goto end;
562         }
563     } else {
564         X509_LOOKUP_add_dir(lookup,NULL,X509_FILETYPE_DEFAULT);
565     }
566
567     // All right !
568     ERR_clear_error();
569     return store;
570
571 end:
572
573     X509_STORE_free(store);
574     return NULL;
575
576 }
577
578 #endif
579
580 #ifdef HAVE_CURL
581 void opkg_curl_cleanup(void){
582     if(curl != NULL){
583         curl_easy_cleanup (curl);
584         curl = NULL;
585     }
586 }
587
588 static CURL *
589 opkg_curl_init(curl_progress_func cb, void *data)
590 {
591
592     if(curl == NULL){
593         curl = curl_easy_init();
594
595 #ifdef HAVE_SSLCURL
596         openssl_init();
597
598         if (conf->ssl_engine) {
599
600             /* use crypto engine */
601             if (curl_easy_setopt(curl, CURLOPT_SSLENGINE, conf->ssl_engine) != CURLE_OK){
602                 opkg_msg(ERROR, "Can't set crypto engine '%s'.\n",
603                         conf->ssl_engine);
604
605                 opkg_curl_cleanup();
606                 return NULL;
607             }
608             /* set the crypto engine as default */
609             if (curl_easy_setopt(curl, CURLOPT_SSLENGINE_DEFAULT, 1L) != CURLE_OK){
610                 opkg_msg(ERROR, "Can't set crypto engine '%s' as default.\n",
611                         conf->ssl_engine);
612
613                 opkg_curl_cleanup();
614                 return NULL;
615             }
616         }
617
618         /* cert & key can only be in PEM case in the same file */
619         if(conf->ssl_key_passwd){
620             if (curl_easy_setopt(curl, CURLOPT_SSLKEYPASSWD, conf->ssl_key_passwd) != CURLE_OK)
621             {
622                 opkg_msg(DEBUG, "Failed to set key password.\n");
623             }
624         }
625
626         /* sets the client certificate and its type */
627         if(conf->ssl_cert_type){
628             if (curl_easy_setopt(curl, CURLOPT_SSLCERTTYPE, conf->ssl_cert_type) != CURLE_OK)
629             {
630                 opkg_msg(DEBUG, "Failed to set certificate format.\n");
631             }
632         }
633         /* SSL cert name isn't mandatory */
634         if(conf->ssl_cert){
635                 curl_easy_setopt(curl, CURLOPT_SSLCERT, conf->ssl_cert);
636         }
637
638         /* sets the client key and its type */
639         if(conf->ssl_key_type){
640             if (curl_easy_setopt(curl, CURLOPT_SSLKEYTYPE, conf->ssl_key_type) != CURLE_OK)
641             {
642                 opkg_msg(DEBUG, "Failed to set key format.\n");
643             }
644         }
645         if(conf->ssl_key){
646             if (curl_easy_setopt(curl, CURLOPT_SSLKEY, conf->ssl_key) != CURLE_OK)
647             {
648                 opkg_msg(DEBUG, "Failed to set key.\n");
649             }
650         }
651
652         /* Should we verify the peer certificate ? */
653         if(conf->ssl_dont_verify_peer){
654             /*
655              * CURLOPT_SSL_VERIFYPEER default is nonzero (curl => 7.10)
656              */
657             curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
658         }else{
659 #ifdef HAVE_PATHFINDER
660             if(conf->check_x509_path){
661                 if (curl_easy_setopt(curl, CURLOPT_SSL_CTX_FUNCTION, curl_ssl_ctx_function) != CURLE_OK){
662                     opkg_msg(DEBUG, "Failed to set ssl path verification callback.\n");
663                 }else{
664                     curl_easy_setopt(curl, CURLOPT_SSL_CTX_DATA, NULL);
665                 }
666             }
667 #endif
668         }
669
670         /* certification authority file and/or path */
671         if(conf->ssl_ca_file){
672             curl_easy_setopt(curl, CURLOPT_CAINFO, conf->ssl_ca_file);
673         }
674         if(conf->ssl_ca_path){
675             curl_easy_setopt(curl, CURLOPT_CAPATH, conf->ssl_ca_path);
676         }
677 #endif
678
679         curl_easy_setopt (curl, CURLOPT_FOLLOWLOCATION, 1);
680         curl_easy_setopt (curl, CURLOPT_FAILONERROR, 1);
681         if (conf->http_proxy || conf->ftp_proxy)
682         {
683             char *userpwd;
684             sprintf_alloc (&userpwd, "%s:%s", conf->proxy_user,
685                     conf->proxy_passwd);
686             curl_easy_setopt(curl, CURLOPT_PROXYUSERPWD, userpwd);
687             free (userpwd);
688         }
689     }
690
691     curl_easy_setopt (curl, CURLOPT_NOPROGRESS, (cb == NULL));
692     if (cb)
693     {
694         curl_easy_setopt (curl, CURLOPT_PROGRESSDATA, data);
695         curl_easy_setopt (curl, CURLOPT_PROGRESSFUNCTION, cb);
696     }
697
698     return curl;
699
700 }
701 #endif