2 * uclient - ustream based protocol client library
4 * Copyright (C) 2014 Felix Fietkau <nbd@openwrt.org>
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.
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.
21 #include <sys/socket.h>
32 #include <libubox/blobmsg.h>
36 #include "uclient-utils.h"
39 #define LIB_EXT "dylib"
44 static const char *user_agent = "uclient-fetch";
45 static const char *post_data;
46 static const char *post_file;
47 static struct ustream_ssl_ctx *ssl_ctx;
48 static const struct ustream_ssl_ops *ssl_ops;
49 static int quiet = false;
50 static bool verify = true;
51 static bool proxy = true;
52 static bool default_certs = false;
53 static bool no_output;
54 static const char *opt_output_file;
55 static int output_fd = -1;
57 static off_t out_offset;
58 static off_t out_bytes;
60 static char *auth_str;
64 static bool resume, cur_resume;
66 static struct progress pmt;
67 static struct uloop_timeout pmt_timer;
69 static int init_request(struct uclient *cl);
70 static void request_done(struct uclient *cl);
72 static void pmt_update(struct uloop_timeout *t)
74 progress_update(&pmt, out_offset, out_bytes, out_len);
75 uloop_timeout_set(t, 1000);
79 get_proxy_url(char *url)
87 sep = strchr(url, ':');
94 memcpy(prefix, url, sep - url);
95 strcpy(prefix + (sep - url), "_proxy");
96 return getenv(prefix);
99 static int open_output_file(const char *path, uint64_t resume_offset)
101 const char *output_file = opt_output_file;
102 char *filename = NULL;
109 flags = O_WRONLY | O_TRUNC;
111 if (!cur_resume && !output_file)
117 if (!strcmp(output_file, "-")) {
119 fprintf(stderr, "Writing to stdout\n");
125 filename = uclient_get_url_filename(path, "index.html");
131 output_file = filename;
135 fprintf(stderr, "Writing to '%s'\n", output_file);
136 ret = open(output_file, flags, 0644);
141 lseek(ret, resume_offset, SEEK_SET) < 0) {
143 fprintf(stderr, "Failed to seek %"PRIu64" bytes in output file\n", resume_offset);
149 out_offset = resume_offset;
150 out_bytes += resume_offset;
153 progress_init(&pmt, output_file);
154 pmt_timer.cb = pmt_update;
155 pmt_timer.cb(&pmt_timer);
164 static void header_done_cb(struct uclient *cl)
171 static const struct blobmsg_policy policy[__H_MAX] = {
172 [H_RANGE] = { .name = "content-range", .type = BLOBMSG_TYPE_STRING },
173 [H_LEN] = { .name = "content-length", .type = BLOBMSG_TYPE_STRING },
175 struct blob_attr *tb[__H_MAX];
176 uint64_t resume_offset = 0, resume_end, resume_size;
180 int ret = uclient_http_redirect(cl);
183 fprintf(stderr, "Failed to redirect to %s on %s\n", cl->url->location, cl->url->host);
190 fprintf(stderr, "Redirected to %s on %s\n", cl->url->location, cl->url->host);
197 if (cl->status_code == 204 && cur_resume) {
198 /* Resume attempt failed, try normal download */
204 blobmsg_parse(policy, __H_MAX, tb, blob_data(cl->meta), blob_len(cl->meta));
206 switch (cl->status_code) {
209 fprintf(stderr, "File download already fully retrieved; nothing to do.\n");
215 fprintf(stderr, "Error: Partial content received, full content requested\n");
223 fprintf(stderr, "Content-Range header is missing\n");
228 if (sscanf(blobmsg_get_string(tb[H_RANGE]),
229 "bytes %"PRIu64"-%"PRIu64"/%"PRIu64,
230 &resume_offset, &resume_end, &resume_size) != 3) {
232 fprintf(stderr, "Content-Range header is invalid\n");
242 out_len = strtoul(blobmsg_get_string(tb[H_LEN]), NULL, 10);
244 output_fd = open_output_file(cl->url->location, resume_offset);
247 perror("Cannot open output file");
255 fprintf(stderr, "HTTP error %d\n", cl->status_code);
262 static void read_data_cb(struct uclient *cl)
268 if (!no_output && output_fd < 0)
272 len = uclient_read(cl, buf, sizeof(buf));
278 n = write(output_fd, buf, len);
285 static void msg_connecting(struct uclient *cl)
287 char addr[INET6_ADDRSTRLEN];
293 uclient_get_addr(addr, &port, &cl->remote_addr);
294 fprintf(stderr, "Connecting to %s:%d\n", addr, port);
297 static void check_resume_offset(struct uclient *cl)
304 file = uclient_get_url_filename(cl->url->location, "index.html");
308 ret = stat(file, &st);
316 snprintf(range_str, sizeof(range_str), "bytes=%"PRIu64"-", (uint64_t) st.st_size);
317 uclient_http_set_header(cl, "Range", range_str);
320 static int init_request(struct uclient *cl)
327 uclient_http_set_ssl_ctx(cl, ssl_ops, ssl_ctx, verify);
330 cl->timeout_msecs = timeout * 1000;
332 rc = uclient_connect(cl);
338 rc = uclient_http_set_request_type(cl, post_data || post_file ? "POST" : "GET");
342 uclient_http_reset_headers(cl);
343 uclient_http_set_header(cl, "User-Agent", user_agent);
345 check_resume_offset(cl);
348 uclient_http_set_header(cl, "Content-Type", "application/x-www-form-urlencoded");
349 uclient_write(cl, post_data, strlen(post_data));
354 uclient_http_set_header(cl, "Content-Type", "application/x-www-form-urlencoded");
356 input_file = fopen(post_file, "r");
364 rlen = fread(tbuf, 1, sizeof(tbuf), input_file);
365 uclient_write(cl, tbuf, rlen);
372 rc = uclient_request(cl);
379 static void request_done(struct uclient *cl)
381 const char *proxy_url;
384 proxy_url = get_proxy_url(*urls);
386 uclient_set_url(cl, proxy_url, NULL);
387 uclient_set_proxy_url(cl, *urls, auth_str);
389 uclient_set_url(cl, *urls, auth_str);
393 error_ret = init_request(cl);
398 if (output_fd >= 0 && !opt_output_file) {
402 uclient_disconnect(cl);
407 static void eof_cb(struct uclient *cl)
410 pmt_update(&pmt_timer);
411 uloop_timeout_cancel(&pmt_timer);
412 fprintf(stderr, "\n");
417 fprintf(stderr, "Connection reset prematurely\n");
420 fprintf(stderr, "Download completed (%"PRIu64" bytes)\n", (uint64_t) out_bytes);
425 static void handle_uclient_error(struct uclient *cl, int code)
427 const char *type = "Unknown error";
431 case UCLIENT_ERROR_CONNECT:
432 type = "Connection failed";
435 case UCLIENT_ERROR_TIMEDOUT:
436 type = "Connection timed out";
439 case UCLIENT_ERROR_SSL_INVALID_CERT:
440 type = "Invalid SSL certificate";
444 case UCLIENT_ERROR_SSL_CN_MISMATCH:
445 type = "Server hostname does not match SSL certificate";
455 fprintf(stderr, "Connection error: %s%s\n", type, ignore ? " (ignored)" : "");
463 static const struct uclient_cb cb = {
464 .header_done = header_done_cb,
465 .data_read = read_data_cb,
467 .error = handle_uclient_error,
470 static int usage(const char *progname)
473 "Usage: %s [options] <URL>\n"
475 " -4 Use IPv4 only\n"
476 " -6 Use IPv6 only\n"
477 " -q Turn off status messages\n"
478 " -O <file> Redirect output to file (use \"-\" for stdout)\n"
479 " -P <dir> Set directory for output files\n"
480 " --user=<user> HTTP authentication username\n"
481 " --password=<password> HTTP authentication password\n"
482 " --user-agent|-U <str> Set HTTP user agent\n"
483 " --post-data=STRING use the POST method; send STRING as the data\n"
484 " --post-file=FILE use the POST method; send FILE as the data\n"
485 " --spider|-s Spider mode - only check file existence\n"
486 " --timeout=N|-T N Set connect/request timeout to N seconds\n"
487 " --proxy=on|off|-Y on|off Enable/disable env var configured proxy\n"
490 " --ca-certificate=<cert> Load CA certificates from file <cert>\n"
491 " --no-check-certificate don't validate the server's certificate\n"
492 " --ciphers=<cipherlist> Set the cipher list string\n"
497 static void init_ca_cert(void)
502 glob("/etc/ssl/certs/*.crt", 0, NULL, &gl);
503 for (i = 0; i < gl.gl_pathc; i++)
504 ssl_ops->context_add_ca_crt_file(ssl_ctx, gl.gl_pathv[i]);
507 static void init_ustream_ssl(void)
511 dlh = dlopen("libustream-ssl." LIB_EXT, RTLD_LAZY | RTLD_LOCAL);
515 ssl_ops = dlsym(dlh, "ustream_ssl_ops");
519 ssl_ctx = ssl_ops->context_new(false);
522 static int no_ssl(const char *progname)
525 "%s: SSL support not available, please install one of the "
526 "libustream-.*[ssl|tls] packages as well as the ca-bundle and "
527 "ca-certificates packages.\n",
534 L_NO_CHECK_CERTIFICATE,
550 static const struct option longopts[] = {
551 [L_NO_CHECK_CERTIFICATE] = { "no-check-certificate", no_argument },
552 [L_CA_CERTIFICATE] = { "ca-certificate", required_argument },
553 [L_CIPHERS] = { "ciphers", required_argument },
554 [L_USER] = { "user", required_argument },
555 [L_PASSWORD] = { "password", required_argument },
556 [L_USER_AGENT] = { "user-agent", required_argument },
557 [L_POST_DATA] = { "post-data", required_argument },
558 [L_POST_FILE] = { "post-file", required_argument },
559 [L_SPIDER] = { "spider", no_argument },
560 [L_TIMEOUT] = { "timeout", required_argument },
561 [L_CONTINUE] = { "continue", no_argument },
562 [L_PROXY] = { "proxy", required_argument },
563 [L_NO_PROXY] = { "no-proxy", no_argument },
564 [L_QUIET] = { "quiet", no_argument },
570 int main(int argc, char **argv)
572 const char *progname = argv[0];
573 const char *proxy_url;
574 char *username = NULL;
575 char *password = NULL;
578 bool has_cert = false;
583 signal(SIGPIPE, SIG_IGN);
586 while ((ch = getopt_long(argc, argv, "46cO:P:qsT:U:Y:", longopts, &longopt_idx)) != -1) {
589 switch (longopt_idx) {
590 case L_NO_CHECK_CERTIFICATE:
593 case L_CA_CERTIFICATE:
596 ssl_ops->context_add_ca_crt_file(ssl_ctx, optarg);
600 if (ssl_ops->context_set_ciphers(ssl_ctx, optarg)) {
602 fprintf(stderr, "No recognized ciphers in cipher list\n");
610 username = strdup(optarg);
611 memset(optarg, '*', strlen(optarg));
616 password = strdup(optarg);
617 memset(optarg, '*', strlen(optarg));
632 timeout = atoi(optarg);
638 if (strcmp(optarg, "on") != 0)
648 return usage(progname);
664 opt_output_file = optarg;
669 perror("Change output directory");
680 timeout = atoi(optarg);
683 if (strcmp(optarg, "on") != 0)
687 return usage(progname);
694 if (verify && !has_cert)
695 default_certs = true;
698 return usage(progname);
701 for (i = 0; i < argc; i++) {
702 if (!strncmp(argv[i], "https", 5))
703 return no_ssl(progname);
714 rc = asprintf(&auth_str, "%s:%s", username, password);
722 fprintf(stderr, "Downloading '%s'\n", argv[0]);
724 proxy_url = get_proxy_url(argv[0]);
726 cl = uclient_new(proxy_url, auth_str, &cb);
728 uclient_set_proxy_url(cl, argv[0], NULL);
730 cl = uclient_new(argv[0], auth_str, &cb);
733 fprintf(stderr, "Failed to allocate uclient context\n");
737 uclient_http_set_address_family(cl, af);
739 if (ssl_ctx && default_certs)
743 rc = init_request(cl);
745 /* no error received, we can enter main loop */
748 fprintf(stderr, "Failed to send request: %s\n", strerror(rc));
756 if (output_fd >= 0 && output_fd != STDOUT_FILENO)
760 ssl_ops->context_free(ssl_ctx);