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