treewrite: use Lindent to reformat to kernel coding style
[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 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,
115                          "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,
121                          "Setting environment variable: ftp_proxy = %s.\n",
122                          conf->ftp_proxy);
123                 setenv("ftp_proxy", conf->ftp_proxy, 1);
124         }
125         if (conf->no_proxy) {
126                 opkg_msg(DEBUG,
127                          "Setting environment variable: no_proxy = %s.\n",
128                          conf->no_proxy);
129                 setenv("no_proxy", conf->no_proxy, 1);
130         }
131 #ifdef HAVE_CURL
132         CURLcode res;
133         FILE *file = fopen(tmp_file_location, "w");
134
135         curl = opkg_curl_init(cb, data);
136         if (curl) {
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                         long error_code;
144                         curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE,
145                                           &error_code);
146                         opkg_msg(hide_error ? DEBUG2 : ERROR,
147                                  "Failed to download %s: %s.\n", src,
148                                  curl_easy_strerror(res));
149                         free(tmp_file_location);
150                         return -1;
151                 }
152
153         } else {
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,
177                                  "Failed to download %s, wget returned %d.\n",
178                                  src, res);
179                         if (res == 4)
180                                 opkg_msg(ERROR,
181                                          "Check your network settings and connectivity.\n\n");
182                         free(tmp_file_location);
183                         return -1;
184                 }
185         }
186 #endif
187
188         err = file_move(tmp_file_location, dest_file_name);
189
190         free(tmp_file_location);
191
192         return err;
193 }
194
195 static int
196 opkg_download_cache(const char *src, const char *dest_file_name,
197                     curl_progress_func cb, void *data)
198 {
199         char *cache_name = xstrdup(src);
200         char *cache_location, *p;
201         int err = 0;
202
203         if (!conf->cache || str_starts_with(src, "file:")) {
204                 err = opkg_download(src, dest_file_name, cb, data, 0);
205                 goto out1;
206         }
207
208         if (!file_is_dir(conf->cache)) {
209                 opkg_msg(ERROR, "%s is not a directory.\n", conf->cache);
210                 err = 1;
211                 goto out1;
212         }
213
214         for (p = cache_name; *p; p++)
215                 if (*p == '/')
216                         *p = ',';       /* looks nicer than | or # */
217
218         sprintf_alloc(&cache_location, "%s/%s", conf->cache, cache_name);
219         if (file_exists(cache_location))
220                 opkg_msg(NOTICE, "Copying %s.\n", cache_location);
221         else {
222                 /* cache file with funky name not found, try simple name */
223                 free(cache_name);
224                 char *filename = strrchr(dest_file_name, '/');
225                 if (filename)
226                         cache_name = xstrdup(filename + 1);     // strip leading '/'
227                 else
228                         cache_name = xstrdup(dest_file_name);
229                 free(cache_location);
230                 sprintf_alloc(&cache_location, "%s/%s", conf->cache,
231                               cache_name);
232                 if (file_exists(cache_location))
233                         opkg_msg(NOTICE, "Copying %s.\n", cache_location);
234                 else {
235                         err = opkg_download(src, cache_location, cb, data, 0);
236                         if (err) {
237                                 (void)unlink(cache_location);
238                                 goto out2;
239                         }
240                 }
241         }
242
243         err = file_copy(cache_location, dest_file_name);
244
245 out2:
246         free(cache_location);
247 out1:
248         free(cache_name);
249         return err;
250 }
251
252 int opkg_download_pkg(pkg_t * pkg, const char *dir)
253 {
254         int err;
255         char *url;
256         char *stripped_filename;
257
258         if (pkg->src == NULL) {
259                 opkg_msg(ERROR,
260                          "Package %s is not available from any configured src.\n",
261                          pkg->name);
262                 return -1;
263         }
264         if (pkg->filename == NULL) {
265                 opkg_msg(ERROR,
266                          "Package %s does not have a valid filename field.\n",
267                          pkg->name);
268                 return -1;
269         }
270
271         sprintf_alloc(&url, "%s/%s", pkg->src->value, pkg->filename);
272
273         /* The pkg->filename might be something like
274            "../../foo.opk". While this is correct, and exactly what we
275            want to use to construct url above, here we actually need to
276            use just the filename part, without any directory. */
277
278         stripped_filename = strrchr(pkg->filename, '/');
279         if (!stripped_filename)
280                 stripped_filename = pkg->filename;
281
282         sprintf_alloc(&pkg->local_filename, "%s/%s", dir, stripped_filename);
283
284         err = opkg_download_cache(url, pkg->local_filename, NULL, NULL);
285         free(url);
286
287         return err;
288 }
289
290 /*
291  * Downloads file from url, installs in package database, return package name.
292  */
293 int opkg_prepare_url_for_install(const char *url, char **namep)
294 {
295         int err = 0;
296         pkg_t *pkg;
297
298         pkg = pkg_new();
299
300         if (str_starts_with(url, "http://")
301             || str_starts_with(url, "ftp://")) {
302                 char *tmp_file;
303                 char *file_basec = xstrdup(url);
304                 char *file_base = basename(file_basec);
305
306                 sprintf_alloc(&tmp_file, "%s/%s", conf->tmp_dir, file_base);
307                 err = opkg_download(url, tmp_file, NULL, NULL, 0);
308                 if (err)
309                         return err;
310
311                 err = pkg_init_from_file(pkg, tmp_file);
312                 if (err)
313                         return err;
314
315                 free(tmp_file);
316                 free(file_basec);
317
318         } else if (strcmp(&url[strlen(url) - 4], OPKG_PKG_EXTENSION) == 0
319                    || strcmp(&url[strlen(url) - 4], IPKG_PKG_EXTENSION) == 0
320                    || strcmp(&url[strlen(url) - 4], DPKG_PKG_EXTENSION) == 0) {
321
322                 err = pkg_init_from_file(pkg, url);
323                 if (err)
324                         return err;
325                 opkg_msg(DEBUG2, "Package %s provided by hand (%s).\n",
326                          pkg->name, pkg->local_filename);
327                 pkg->provided_by_hand = 1;
328
329         } else {
330                 pkg_deinit(pkg);
331                 free(pkg);
332                 return 0;
333         }
334
335         pkg->dest = conf->default_dest;
336         pkg->state_want = SW_INSTALL;
337         pkg->state_flag |= SF_PREFER;
338         hash_insert_pkg(pkg, 1);
339
340         if (namep) {
341                 *namep = xstrdup(pkg->name);
342         }
343         return 0;
344 }
345
346 int opkg_verify_file(char *text_file, char *sig_file)
347 {
348 #if defined HAVE_USIGN
349         int status = -1;
350         int pid;
351
352         if (conf->check_signature == 0)
353                 return 0;
354
355         pid = fork();
356         if (pid < 0)
357                 return -1;
358
359         if (!pid) {
360                 execl("/usr/sbin/opkg-key", "opkg-key", "verify", sig_file,
361                       text_file, NULL);
362                 exit(255);
363         }
364
365         waitpid(pid, &status, 0);
366         if (!WIFEXITED(status) || WEXITSTATUS(status))
367                 return -1;
368
369         return 0;
370 #elif defined HAVE_GPGME
371         if (conf->check_signature == 0)
372                 return 0;
373         int status = -1;
374         gpgme_ctx_t ctx;
375         gpgme_data_t sig, text, key;
376         gpgme_error_t err;
377         gpgme_verify_result_t result;
378         gpgme_signature_t s;
379         char *trusted_path = NULL;
380
381         gpgme_check_version(NULL);
382
383         err = gpgme_new(&ctx);
384
385         if (err)
386                 return -1;
387
388         sprintf_alloc(&trusted_path, "%s/%s", conf->offline_root,
389                       "/etc/opkg/trusted.gpg");
390         err = gpgme_data_new_from_file(&key, trusted_path, 1);
391         free(trusted_path);
392         if (err) {
393                 return -1;
394         }
395         err = gpgme_op_import(ctx, key);
396         if (err) {
397                 gpgme_data_release(key);
398                 return -1;
399         }
400         gpgme_data_release(key);
401
402         err = gpgme_data_new_from_file(&sig, sig_file, 1);
403         if (err) {
404                 gpgme_release(ctx);
405                 return -1;
406         }
407
408         err = gpgme_data_new_from_file(&text, text_file, 1);
409         if (err) {
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                 status = gpg_err_code(s->status);
425                 if (status == GPG_ERR_NO_ERROR)
426                         break;
427                 s = s->next;
428         }
429
430         gpgme_data_release(sig);
431         gpgme_data_release(text);
432         gpgme_release(ctx);
433
434         return status;
435 #elif defined HAVE_OPENSSL
436         X509_STORE *store = NULL;
437         PKCS7 *p7 = NULL;
438         BIO *in = NULL, *indata = NULL;
439
440         // Sig check failed by default !
441         int status = -1;
442
443         openssl_init();
444
445         // Set-up the key store
446         if (!
447             (store =
448              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         // Open a BIO to read the sig file
453         if (!(in = BIO_new_file(sig_file, "rb"))) {
454                 opkg_msg(ERROR, "Can't open signature file %s.\n", sig_file);
455                 goto verify_file_end;
456         }
457         // Read the PKCS7 block contained in the sig file
458         p7 = PEM_read_bio_PKCS7(in, NULL, NULL, NULL);
459         if (!p7) {
460                 opkg_msg(ERROR, "Can't read signature file %s (Corrupted ?).\n",
461                          sig_file);
462                 goto verify_file_end;
463         }
464 #if defined(HAVE_PATHFINDER)
465         if (conf->check_x509_path) {
466                 if (!pkcs7_pathfinder_verify_signers(p7)) {
467                         opkg_msg(ERROR, "pkcs7_pathfinder_verify_signers: "
468                                  "Path verification failed.\n");
469                         goto verify_file_end;
470                 }
471         }
472 #endif
473
474         // Open the Package file to authenticate
475         if (!(indata = BIO_new_file(text_file, "rb"))) {
476                 opkg_msg(ERROR, "Can't open file %s.\n", text_file);
477                 goto verify_file_end;
478         }
479         // Let's verify the autenticity !
480         if (PKCS7_verify(p7, NULL, store, indata, NULL, PKCS7_BINARY) != 1) {
481                 // Get Off My Lawn!
482                 opkg_msg(ERROR, "Verification failure.\n");
483         } else {
484                 // Victory !
485                 status = 0;
486         }
487
488 verify_file_end:
489         BIO_free(in);
490         BIO_free(indata);
491         PKCS7_free(p7);
492         X509_STORE_free(store);
493
494         return status;
495 #else
496         /* mute `unused variable' warnings. */
497         (void)sig_file;
498         (void)text_file;
499         (void)conf;
500         return 0;
501 #endif
502 }
503
504 #if defined(HAVE_OPENSSL) || defined(HAVE_SSLCURL)
505 static void openssl_init(void)
506 {
507         static int init = 0;
508
509         if (!init) {
510                 OPENSSL_config(NULL);
511                 OpenSSL_add_all_algorithms();
512                 ERR_load_crypto_strings();
513                 init = 1;
514         }
515 }
516
517 #endif
518
519 #if defined HAVE_OPENSSL
520 static X509_STORE *setup_verify(char *CAfile, char *CApath)
521 {
522         X509_STORE *store = NULL;
523         X509_LOOKUP *lookup = NULL;
524
525         if (!(store = X509_STORE_new())) {
526                 // Something bad is happening...
527                 goto end;
528         }
529         // adds the X509 file lookup method
530         lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
531         if (lookup == NULL) {
532                 goto end;
533         }
534         // Autenticating against one CA file
535         if (CAfile) {
536                 if (!X509_LOOKUP_load_file(lookup, CAfile, X509_FILETYPE_PEM)) {
537                         // Invalid CA => Bye bye
538                         opkg_msg(ERROR, "Error loading file %s.\n", CAfile);
539                         goto end;
540                 }
541         } else {
542                 X509_LOOKUP_load_file(lookup, NULL, X509_FILETYPE_DEFAULT);
543         }
544
545         // Now look into CApath directory if supplied
546         lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
547         if (lookup == NULL) {
548                 goto end;
549         }
550
551         if (CApath) {
552                 if (!X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM)) {
553                         opkg_msg(ERROR, "Error loading directory %s.\n",
554                                  CApath);
555                         goto end;
556                 }
557         } else {
558                 X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);
559         }
560
561         // All right !
562         ERR_clear_error();
563         return store;
564
565 end:
566
567         X509_STORE_free(store);
568         return NULL;
569
570 }
571
572 #endif
573
574 #ifdef HAVE_CURL
575 void opkg_curl_cleanup(void)
576 {
577         if (curl != NULL) {
578                 curl_easy_cleanup(curl);
579                 curl = NULL;
580         }
581 }
582
583 static CURL *opkg_curl_init(curl_progress_func cb, void *data)
584 {
585
586         if (curl == NULL) {
587                 curl = curl_easy_init();
588
589 #ifdef HAVE_SSLCURL
590                 openssl_init();
591
592                 if (conf->ssl_engine) {
593
594                         /* use crypto engine */
595                         if (curl_easy_setopt
596                             (curl, CURLOPT_SSLENGINE,
597                              conf->ssl_engine) != CURLE_OK) {
598                                 opkg_msg(ERROR,
599                                          "Can't set crypto engine '%s'.\n",
600                                          conf->ssl_engine);
601
602                                 opkg_curl_cleanup();
603                                 return NULL;
604                         }
605                         /* set the crypto engine as default */
606                         if (curl_easy_setopt
607                             (curl, CURLOPT_SSLENGINE_DEFAULT, 1L) != CURLE_OK) {
608                                 opkg_msg(ERROR,
609                                          "Can't set crypto engine '%s' as default.\n",
610                                          conf->ssl_engine);
611
612                                 opkg_curl_cleanup();
613                                 return NULL;
614                         }
615                 }
616
617                 /* cert & key can only be in PEM case in the same file */
618                 if (conf->ssl_key_passwd) {
619                         if (curl_easy_setopt
620                             (curl, CURLOPT_SSLKEYPASSWD,
621                              conf->ssl_key_passwd) != CURLE_OK) {
622                                 opkg_msg(DEBUG,
623                                          "Failed to set key password.\n");
624                         }
625                 }
626
627                 /* sets the client certificate and its type */
628                 if (conf->ssl_cert_type) {
629                         if (curl_easy_setopt
630                             (curl, CURLOPT_SSLCERTTYPE,
631                              conf->ssl_cert_type) != CURLE_OK) {
632                                 opkg_msg(DEBUG,
633                                          "Failed to set certificate format.\n");
634                         }
635                 }
636                 /* SSL cert name isn't mandatory */
637                 if (conf->ssl_cert) {
638                         curl_easy_setopt(curl, CURLOPT_SSLCERT, conf->ssl_cert);
639                 }
640
641                 /* sets the client key and its type */
642                 if (conf->ssl_key_type) {
643                         if (curl_easy_setopt
644                             (curl, CURLOPT_SSLKEYTYPE,
645                              conf->ssl_key_type) != CURLE_OK) {
646                                 opkg_msg(DEBUG, "Failed to set key format.\n");
647                         }
648                 }
649                 if (conf->ssl_key) {
650                         if (curl_easy_setopt
651                             (curl, CURLOPT_SSLKEY, conf->ssl_key) != CURLE_OK) {
652                                 opkg_msg(DEBUG, "Failed to set key.\n");
653                         }
654                 }
655
656                 /* Should we verify the peer certificate ? */
657                 if (conf->ssl_dont_verify_peer) {
658                         /*
659                          * CURLOPT_SSL_VERIFYPEER default is nonzero (curl => 7.10)
660                          */
661                         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
662                 } else {
663 #ifdef HAVE_PATHFINDER
664                         if (conf->check_x509_path) {
665                                 if (curl_easy_setopt
666                                     (curl, CURLOPT_SSL_CTX_FUNCTION,
667                                      curl_ssl_ctx_function) != CURLE_OK) {
668                                         opkg_msg(DEBUG,
669                                                  "Failed to set ssl path verification callback.\n");
670                                 } else {
671                                         curl_easy_setopt(curl,
672                                                          CURLOPT_SSL_CTX_DATA,
673                                                          NULL);
674                                 }
675                         }
676 #endif
677                 }
678
679                 /* certification authority file and/or path */
680                 if (conf->ssl_ca_file) {
681                         curl_easy_setopt(curl, CURLOPT_CAINFO,
682                                          conf->ssl_ca_file);
683                 }
684                 if (conf->ssl_ca_path) {
685                         curl_easy_setopt(curl, CURLOPT_CAPATH,
686                                          conf->ssl_ca_path);
687                 }
688 #endif
689
690                 curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
691                 curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
692                 if (conf->http_proxy || conf->ftp_proxy) {
693                         char *userpwd;
694                         sprintf_alloc(&userpwd, "%s:%s", conf->proxy_user,
695                                       conf->proxy_passwd);
696                         curl_easy_setopt(curl, CURLOPT_PROXYUSERPWD, userpwd);
697                         free(userpwd);
698                 }
699         }
700
701         curl_easy_setopt(curl, CURLOPT_NOPROGRESS, (cb == NULL));
702         if (cb) {
703                 curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, data);
704                 curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, cb);
705         }
706
707         return curl;
708
709 }
710 #endif