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