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