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