d2ffde3f89423d975d38a730023d59db645c9217
[project/uclient.git] / uclient-fetch.c
1 /*
2  * uclient - ustream based protocol client library
3  *
4  * Copyright (C) 2014 Felix Fietkau <nbd@openwrt.org>
5  *
6  * Permission to use, copy, modify, and/or distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18
19 #define _GNU_SOURCE
20 #include <sys/stat.h>
21 #include <unistd.h>
22 #include <stdio.h>
23 #include <dlfcn.h>
24 #include <getopt.h>
25 #include <fcntl.h>
26 #include <glob.h>
27 #include <stdint.h>
28 #include <inttypes.h>
29 #include <signal.h>
30
31 #include <libubox/blobmsg.h>
32
33 #include "progress.h"
34 #include "uclient.h"
35 #include "uclient-utils.h"
36
37 #ifdef __APPLE__
38 #define LIB_EXT "dylib"
39 #else
40 #define LIB_EXT "so"
41 #endif
42
43 static const char *user_agent = "uclient-fetch";
44 static const char *post_data;
45 static struct ustream_ssl_ctx *ssl_ctx;
46 static const struct ustream_ssl_ops *ssl_ops;
47 static int quiet = false;
48 static bool verify = true;
49 static bool proxy = true;
50 static bool default_certs = false;
51 static bool no_output;
52 static const char *output_file;
53 static int output_fd = -1;
54 static int error_ret;
55 static off_t out_offset;
56 static off_t out_bytes;
57 static off_t out_len;
58 static char *auth_str;
59 static char **urls;
60 static int n_urls;
61 static int timeout;
62 static bool resume, cur_resume;
63
64 static struct progress pmt;
65 static struct uloop_timeout pmt_timer;
66
67 static int init_request(struct uclient *cl);
68 static void request_done(struct uclient *cl);
69
70 static void pmt_update(struct uloop_timeout *t)
71 {
72         progress_update(&pmt, out_offset, out_bytes, out_len);
73         uloop_timeout_set(t, 1000);
74 }
75
76 static const char *
77 get_proxy_url(char *url)
78 {
79         char prefix[16];
80         char *sep;
81
82         if (!proxy)
83                 return NULL;
84
85         sep = strchr(url, ':');
86         if (!sep)
87                 return NULL;
88
89         if (sep - url > 5)
90                 return NULL;
91
92         memcpy(prefix, url, sep - url);
93         strcpy(prefix + (sep - url), "_proxy");
94         return getenv(prefix);
95 }
96
97 static int open_output_file(const char *path, uint64_t resume_offset)
98 {
99         char *filename = NULL;
100         int flags;
101         int ret;
102
103         if (cur_resume)
104                 flags = O_RDWR;
105         else
106                 flags = O_WRONLY;
107
108         if (!cur_resume && !output_file)
109                 flags |= O_EXCL;
110
111         flags |= O_CREAT;
112
113         if (output_file) {
114                 if (!strcmp(output_file, "-")) {
115                         if (!quiet)
116                                 fprintf(stderr, "Writing to stdout\n");
117
118                         return STDOUT_FILENO;
119                 }
120         } else {
121                 filename = uclient_get_url_filename(path, "index.html");
122                 output_file = filename;
123         }
124
125         if (!quiet)
126                 fprintf(stderr, "Writing to '%s'\n", output_file);
127         ret = open(output_file, flags, 0644);
128         if (ret < 0)
129                 goto free;
130
131         if (resume_offset &&
132             lseek(ret, resume_offset, SEEK_SET) < 0) {
133                 if (!quiet)
134                         fprintf(stderr, "Failed to seek %"PRIu64" bytes in output file\n", resume_offset);
135                 close(ret);
136                 ret = -1;
137                 goto free;
138         }
139
140         out_offset = resume_offset;
141         out_bytes += resume_offset;
142         if (!quiet) {
143                 progress_init(&pmt, output_file);
144                 pmt_timer.cb = pmt_update;
145                 pmt_timer.cb(&pmt_timer);
146         }
147
148 free:
149         free(filename);
150         return ret;
151 }
152
153 static void header_done_cb(struct uclient *cl)
154 {
155         enum {
156                 H_RANGE,
157                 H_LEN,
158                 __H_MAX
159         };
160         static const struct blobmsg_policy policy[__H_MAX] = {
161                 [H_RANGE] = { .name = "content-range", .type = BLOBMSG_TYPE_STRING },
162                 [H_LEN] = { .name = "content-length", .type = BLOBMSG_TYPE_STRING },
163         };
164         struct blob_attr *tb[__H_MAX];
165         uint64_t resume_offset = 0, resume_end, resume_size;
166         static int retries;
167
168         if (retries < 10) {
169                 int ret = uclient_http_redirect(cl);
170                 if (ret < 0) {
171                         if (!quiet)
172                                 fprintf(stderr, "Failed to redirect to %s on %s\n", cl->url->location, cl->url->host);
173                         error_ret = 8;
174                         request_done(cl);
175                         return;
176                 }
177                 if (ret > 0) {
178                         if (!quiet)
179                                 fprintf(stderr, "Redirected to %s on %s\n", cl->url->location, cl->url->host);
180
181                         retries++;
182                         return;
183                 }
184         }
185
186         if (cl->status_code == 204 && cur_resume) {
187                 /* Resume attempt failed, try normal download */
188                 cur_resume = false;
189                 init_request(cl);
190                 return;
191         }
192
193         blobmsg_parse(policy, __H_MAX, tb, blob_data(cl->meta), blob_len(cl->meta));
194
195         switch (cl->status_code) {
196         case 416:
197                 if (!quiet)
198                         fprintf(stderr, "File download already fully retrieved; nothing to do.\n");
199                 request_done(cl);
200                 break;
201         case 206:
202                 if (!cur_resume) {
203                         if (!quiet)
204                                 fprintf(stderr, "Error: Partial content received, full content requested\n");
205                         error_ret = 8;
206                         request_done(cl);
207                         break;
208                 }
209
210                 if (!tb[H_RANGE]) {
211                         if (!quiet)
212                                 fprintf(stderr, "Content-Range header is missing\n");
213                         error_ret = 8;
214                         break;
215                 }
216
217                 if (sscanf(blobmsg_get_string(tb[H_RANGE]),
218                            "bytes %"PRIu64"-%"PRIu64"/%"PRIu64,
219                            &resume_offset, &resume_end, &resume_size) != 3) {
220                         if (!quiet)
221                                 fprintf(stderr, "Content-Range header is invalid\n");
222                         error_ret = 8;
223                         break;
224                 }
225         case 204:
226         case 200:
227                 if (no_output)
228                         break;
229
230                 if (tb[H_LEN])
231                         out_len = strtoul(blobmsg_get_string(tb[H_LEN]), NULL, 10);
232
233                 output_fd = open_output_file(cl->url->location, resume_offset);
234                 if (output_fd < 0) {
235                         if (!quiet)
236                                 perror("Cannot open output file");
237                         error_ret = 3;
238                         request_done(cl);
239                 }
240                 break;
241
242         default:
243                 if (!quiet)
244                         fprintf(stderr, "HTTP error %d\n", cl->status_code);
245                 request_done(cl);
246                 error_ret = 8;
247                 break;
248         }
249 }
250
251 static void read_data_cb(struct uclient *cl)
252 {
253         char buf[256];
254         int len;
255
256         if (!no_output && output_fd < 0)
257                 return;
258
259         while (1) {
260                 len = uclient_read(cl, buf, sizeof(buf));
261                 if (!len)
262                         return;
263
264                 out_bytes += len;
265                 if (!no_output)
266                         write(output_fd, buf, len);
267         }
268 }
269
270 static void msg_connecting(struct uclient *cl)
271 {
272         char addr[INET6_ADDRSTRLEN];
273         int port;
274
275         if (quiet)
276                 return;
277
278         uclient_get_addr(addr, &port, &cl->remote_addr);
279         fprintf(stderr, "Connecting to %s:%d\n", addr, port);
280 }
281
282 static void check_resume_offset(struct uclient *cl)
283 {
284         char range_str[64];
285         struct stat st;
286         char *file;
287         int ret;
288
289         file = uclient_get_url_filename(cl->url->location, "index.html");
290         if (!file)
291                 return;
292
293         ret = stat(file, &st);
294         free(file);
295         if (ret)
296                 return;
297
298         if (!st.st_size)
299                 return;
300
301         snprintf(range_str, sizeof(range_str), "bytes=%"PRIu64"-", (uint64_t) st.st_size);
302         uclient_http_set_header(cl, "Range", range_str);
303 }
304
305 static int init_request(struct uclient *cl)
306 {
307         int rc;
308
309         out_offset = 0;
310         out_bytes = 0;
311         out_len = 0;
312         uclient_http_set_ssl_ctx(cl, ssl_ops, ssl_ctx, verify);
313
314         if (timeout)
315                 cl->timeout_msecs = timeout * 1000;
316
317         rc = uclient_connect(cl);
318         if (rc)
319                 return rc;
320
321         msg_connecting(cl);
322
323         rc = uclient_http_set_request_type(cl, post_data ? "POST" : "GET");
324         if (rc)
325                 return rc;
326
327         uclient_http_reset_headers(cl);
328         uclient_http_set_header(cl, "User-Agent", user_agent);
329         if (cur_resume)
330                 check_resume_offset(cl);
331
332         if (post_data) {
333                 uclient_http_set_header(cl, "Content-Type", "application/x-www-form-urlencoded");
334                 uclient_write(cl, post_data, strlen(post_data));
335         }
336
337         rc = uclient_request(cl);
338         if (rc)
339                 return rc;
340
341         return 0;
342 }
343
344 static void request_done(struct uclient *cl)
345 {
346         const char *proxy_url;
347
348         if (n_urls) {
349                 proxy_url = get_proxy_url(*urls);
350                 if (proxy_url) {
351                         uclient_set_url(cl, proxy_url, NULL);
352                         uclient_set_proxy_url(cl, *urls, auth_str);
353                 } else {
354                         uclient_set_url(cl, *urls, auth_str);
355                 }
356                 n_urls--;
357                 cur_resume = resume;
358                 error_ret = init_request(cl);
359                 if (error_ret == 0)
360                         return;
361         }
362
363         if (output_fd >= 0 && !output_file) {
364                 close(output_fd);
365                 output_fd = -1;
366         }
367         uclient_disconnect(cl);
368         uloop_end();
369 }
370
371
372 static void eof_cb(struct uclient *cl)
373 {
374         if (!quiet) {
375                 pmt_update(&pmt_timer);
376                 uloop_timeout_cancel(&pmt_timer);
377                 fprintf(stderr, "\n");
378         }
379
380         if (!cl->data_eof) {
381                 if (!quiet)
382                         fprintf(stderr, "Connection reset prematurely\n");
383                 error_ret = 4;
384         } else if (!quiet) {
385                 fprintf(stderr, "Download completed (%"PRIu64" bytes)\n", (uint64_t) out_bytes);
386         }
387         request_done(cl);
388 }
389
390 static void handle_uclient_error(struct uclient *cl, int code)
391 {
392         const char *type = "Unknown error";
393         bool ignore = false;
394
395         switch(code) {
396         case UCLIENT_ERROR_CONNECT:
397                 type = "Connection failed";
398                 error_ret = 4;
399                 break;
400         case UCLIENT_ERROR_TIMEDOUT:
401                 type = "Connection timed out";
402                 error_ret = 4;
403                 break;
404         case UCLIENT_ERROR_SSL_INVALID_CERT:
405                 type = "Invalid SSL certificate";
406                 ignore = !verify;
407                 error_ret = 5;
408                 break;
409         case UCLIENT_ERROR_SSL_CN_MISMATCH:
410                 type = "Server hostname does not match SSL certificate";
411                 ignore = !verify;
412                 error_ret = 5;
413                 break;
414         default:
415                 error_ret = 1;
416                 break;
417         }
418
419         if (!quiet)
420                 fprintf(stderr, "Connection error: %s%s\n", type, ignore ? " (ignored)" : "");
421
422         if (ignore)
423                 error_ret = 0;
424         else
425                 request_done(cl);
426 }
427
428 static const struct uclient_cb cb = {
429         .header_done = header_done_cb,
430         .data_read = read_data_cb,
431         .data_eof = eof_cb,
432         .error = handle_uclient_error,
433 };
434
435 static int usage(const char *progname)
436 {
437         fprintf(stderr,
438                 "Usage: %s [options] <URL>\n"
439                 "Options:\n"
440                 "       -q:                             Turn off status messages\n"
441                 "       -O <file>:                      Redirect output to file (use \"-\" for stdout)\n"
442                 "       -P <dir>:                       Set directory for output files\n"
443                 "       --user=<user>                   HTTP authentication username\n"
444                 "       --password=<password>           HTTP authentication password\n"
445                 "       --user-agent|-U <str>           Set HTTP user agent\n"
446                 "       --post-data=STRING              use the POST method; send STRING as the data\n"
447                 "       --spider|-s                     Spider mode - only check file existence\n"
448                 "       --timeout=N|-T N                Set connect/request timeout to N seconds\n"
449                 "       --proxy=on|off|-Y on|off        Enable/disable env var configured proxy\n"
450                 "\n"
451                 "HTTPS options:\n"
452                 "       --ca-certificate=<cert>:        Load CA certificates from file <cert>\n"
453                 "       --no-check-certificate:         don't validate the server's certificate\n"
454                 "\n", progname);
455         return 1;
456 }
457
458 static void init_ca_cert(void)
459 {
460         glob_t gl;
461         int i;
462
463         glob("/etc/ssl/certs/*.crt", 0, NULL, &gl);
464         for (i = 0; i < gl.gl_pathc; i++)
465                 ssl_ops->context_add_ca_crt_file(ssl_ctx, gl.gl_pathv[i]);
466 }
467
468 static void init_ustream_ssl(void)
469 {
470         void *dlh;
471
472         dlh = dlopen("libustream-ssl." LIB_EXT, RTLD_LAZY | RTLD_LOCAL);
473         if (!dlh)
474                 return;
475
476         ssl_ops = dlsym(dlh, "ustream_ssl_ops");
477         if (!ssl_ops)
478                 return;
479
480         ssl_ctx = ssl_ops->context_new(false);
481 }
482
483 static int no_ssl(const char *progname)
484 {
485         fprintf(stderr, "%s: SSL support not available, please install ustream-ssl\n", progname);
486         return 1;
487 }
488
489 enum {
490         L_NO_CHECK_CERTIFICATE,
491         L_CA_CERTIFICATE,
492         L_USER,
493         L_PASSWORD,
494         L_USER_AGENT,
495         L_POST_DATA,
496         L_SPIDER,
497         L_TIMEOUT,
498         L_CONTINUE,
499         L_PROXY,
500         L_NO_PROXY,
501 };
502
503 static const struct option longopts[] = {
504         [L_NO_CHECK_CERTIFICATE] = { "no-check-certificate", no_argument },
505         [L_CA_CERTIFICATE] = { "ca-certificate", required_argument },
506         [L_USER] = { "user", required_argument },
507         [L_PASSWORD] = { "password", required_argument },
508         [L_USER_AGENT] = { "user-agent", required_argument },
509         [L_POST_DATA] = { "post-data", required_argument },
510         [L_SPIDER] = { "spider", no_argument },
511         [L_TIMEOUT] = { "timeout", required_argument },
512         [L_CONTINUE] = { "continue", no_argument },
513         [L_PROXY] = { "proxy", required_argument },
514         [L_NO_PROXY] = { "no-proxy", no_argument },
515         {}
516 };
517
518
519
520 int main(int argc, char **argv)
521 {
522         const char *progname = argv[0];
523         const char *proxy_url;
524         char *username = NULL;
525         char *password = NULL;
526         struct uclient *cl;
527         int longopt_idx = 0;
528         bool has_cert = false;
529         int i, ch;
530         int rc;
531
532         signal(SIGPIPE, SIG_IGN);
533         init_ustream_ssl();
534
535         while ((ch = getopt_long(argc, argv, "cO:P:qsT:U:Y:", longopts, &longopt_idx)) != -1) {
536                 switch(ch) {
537                 case 0:
538                         switch (longopt_idx) {
539                         case L_NO_CHECK_CERTIFICATE:
540                                 verify = false;
541                                 break;
542                         case L_CA_CERTIFICATE:
543                                 has_cert = true;
544                                 if (ssl_ctx)
545                                         ssl_ops->context_add_ca_crt_file(ssl_ctx, optarg);
546                                 break;
547                         case L_USER:
548                                 if (!strlen(optarg))
549                                         break;
550                                 username = strdup(optarg);
551                                 memset(optarg, '*', strlen(optarg));
552                                 break;
553                         case L_PASSWORD:
554                                 if (!strlen(optarg))
555                                         break;
556                                 password = strdup(optarg);
557                                 memset(optarg, '*', strlen(optarg));
558                                 break;
559                         case L_USER_AGENT:
560                                 user_agent = optarg;
561                                 break;
562                         case L_POST_DATA:
563                                 post_data = optarg;
564                                 break;
565                         case L_SPIDER:
566                                 no_output = true;
567                                 break;
568                         case L_TIMEOUT:
569                                 timeout = atoi(optarg);
570                                 break;
571                         case L_CONTINUE:
572                                 resume = true;
573                                 break;
574                         case L_PROXY:
575                                 if (strcmp(optarg, "on") != 0)
576                                         proxy = false;
577                                 break;
578                         case L_NO_PROXY:
579                                 proxy = false;
580                                 break;
581                         default:
582                                 return usage(progname);
583                         }
584                         break;
585                 case 'c':
586                         resume = true;
587                         break;
588                 case 'U':
589                         user_agent = optarg;
590                         break;
591                 case 'O':
592                         output_file = optarg;
593                         break;
594                 case 'P':
595                         if (chdir(optarg)) {
596                                 if (!quiet)
597                                         perror("Change output directory");
598                                 exit(1);
599                         }
600                         break;
601                 case 'q':
602                         quiet = true;
603                         break;
604                 case 's':
605                         no_output = true;
606                         break;
607                 case 'T':
608                         timeout = atoi(optarg);
609                         break;
610                 case 'Y':
611                         if (strcmp(optarg, "on") != 0)
612                                 proxy = false;
613                         break;
614                 default:
615                         return usage(progname);
616                 }
617         }
618
619         argv += optind;
620         argc -= optind;
621
622         if (verify && !has_cert)
623                 default_certs = true;
624
625         if (argc < 1)
626                 return usage(progname);
627
628         if (!ssl_ctx) {
629                 for (i = 0; i < argc; i++) {
630                         if (!strncmp(argv[i], "https", 5))
631                                 return no_ssl(progname);
632                 }
633         }
634
635         urls = argv + 1;
636         n_urls = argc - 1;
637
638         uloop_init();
639
640         if (username) {
641                 if (password)
642                         asprintf(&auth_str, "%s:%s", username, password);
643                 else
644                         auth_str = username;
645         }
646
647         if (!quiet)
648                 fprintf(stderr, "Downloading '%s'\n", argv[0]);
649
650         proxy_url = get_proxy_url(argv[0]);
651         if (proxy_url) {
652                 cl = uclient_new(proxy_url, auth_str, &cb);
653                 uclient_set_proxy_url(cl, argv[0], NULL);
654         } else {
655                 cl = uclient_new(argv[0], auth_str, &cb);
656         }
657         if (!cl) {
658                 fprintf(stderr, "Failed to allocate uclient context\n");
659                 return 1;
660         }
661
662         if (ssl_ctx && default_certs)
663                 init_ca_cert();
664
665         cur_resume = resume;
666         rc = init_request(cl);
667         if (!rc) {
668                 /* no error received, we can enter main loop */
669                 uloop_run();
670         } else {
671                 fprintf(stderr, "Failed to establish connection\n");
672                 error_ret = 4;
673         }
674
675         uloop_done();
676
677         uclient_free(cl);
678
679         if (output_fd >= 0 && output_fd != STDOUT_FILENO)
680                 close(output_fd);
681
682         if (ssl_ctx)
683                 ssl_ops->context_free(ssl_ctx);
684
685         return error_ret;
686 }