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 struct ustream_ssl_ctx *ssl_ctx;
47 static const struct ustream_ssl_ops *ssl_ops;
48 static int quiet = false;
49 static bool verify = true;
50 static bool proxy = true;
51 static bool default_certs = false;
52 static bool no_output;
53 static const char *opt_output_file;
54 static int output_fd = -1;
56 static off_t out_offset;
57 static off_t out_bytes;
59 static char *auth_str;
63 static bool resume, cur_resume;
65 static struct progress pmt;
66 static struct uloop_timeout pmt_timer;
68 static int init_request(struct uclient *cl);
69 static void request_done(struct uclient *cl);
71 static void pmt_update(struct uloop_timeout *t)
73 progress_update(&pmt, out_offset, out_bytes, out_len);
74 uloop_timeout_set(t, 1000);
78 get_proxy_url(char *url)
86 sep = strchr(url, ':');
93 memcpy(prefix, url, sep - url);
94 strcpy(prefix + (sep - url), "_proxy");
95 return getenv(prefix);
98 static int open_output_file(const char *path, uint64_t resume_offset)
100 const char *output_file = opt_output_file;
101 char *filename = NULL;
108 flags = O_WRONLY | O_TRUNC;
110 if (!cur_resume && !output_file)
116 if (!strcmp(output_file, "-")) {
118 fprintf(stderr, "Writing to stdout\n");
124 filename = uclient_get_url_filename(path, "index.html");
130 output_file = filename;
134 fprintf(stderr, "Writing to '%s'\n", output_file);
135 ret = open(output_file, flags, 0644);
140 lseek(ret, resume_offset, SEEK_SET) < 0) {
142 fprintf(stderr, "Failed to seek %"PRIu64" bytes in output file\n", resume_offset);
148 out_offset = resume_offset;
149 out_bytes += resume_offset;
152 progress_init(&pmt, output_file);
153 pmt_timer.cb = pmt_update;
154 pmt_timer.cb(&pmt_timer);
163 static void header_done_cb(struct uclient *cl)
170 static const struct blobmsg_policy policy[__H_MAX] = {
171 [H_RANGE] = { .name = "content-range", .type = BLOBMSG_TYPE_STRING },
172 [H_LEN] = { .name = "content-length", .type = BLOBMSG_TYPE_STRING },
174 struct blob_attr *tb[__H_MAX];
175 uint64_t resume_offset = 0, resume_end, resume_size;
179 int ret = uclient_http_redirect(cl);
182 fprintf(stderr, "Failed to redirect to %s on %s\n", cl->url->location, cl->url->host);
189 fprintf(stderr, "Redirected to %s on %s\n", cl->url->location, cl->url->host);
196 if (cl->status_code == 204 && cur_resume) {
197 /* Resume attempt failed, try normal download */
203 blobmsg_parse(policy, __H_MAX, tb, blob_data(cl->meta), blob_len(cl->meta));
205 switch (cl->status_code) {
208 fprintf(stderr, "File download already fully retrieved; nothing to do.\n");
214 fprintf(stderr, "Error: Partial content received, full content requested\n");
222 fprintf(stderr, "Content-Range header is missing\n");
227 if (sscanf(blobmsg_get_string(tb[H_RANGE]),
228 "bytes %"PRIu64"-%"PRIu64"/%"PRIu64,
229 &resume_offset, &resume_end, &resume_size) != 3) {
231 fprintf(stderr, "Content-Range header is invalid\n");
241 out_len = strtoul(blobmsg_get_string(tb[H_LEN]), NULL, 10);
243 output_fd = open_output_file(cl->url->location, resume_offset);
246 perror("Cannot open output file");
254 fprintf(stderr, "HTTP error %d\n", cl->status_code);
261 static void read_data_cb(struct uclient *cl)
267 if (!no_output && output_fd < 0)
271 len = uclient_read(cl, buf, sizeof(buf));
277 n = write(output_fd, buf, len);
284 static void msg_connecting(struct uclient *cl)
286 char addr[INET6_ADDRSTRLEN];
292 uclient_get_addr(addr, &port, &cl->remote_addr);
293 fprintf(stderr, "Connecting to %s:%d\n", addr, port);
296 static void check_resume_offset(struct uclient *cl)
303 file = uclient_get_url_filename(cl->url->location, "index.html");
307 ret = stat(file, &st);
315 snprintf(range_str, sizeof(range_str), "bytes=%"PRIu64"-", (uint64_t) st.st_size);
316 uclient_http_set_header(cl, "Range", range_str);
319 static int init_request(struct uclient *cl)
326 uclient_http_set_ssl_ctx(cl, ssl_ops, ssl_ctx, verify);
329 cl->timeout_msecs = timeout * 1000;
331 rc = uclient_connect(cl);
337 rc = uclient_http_set_request_type(cl, post_data ? "POST" : "GET");
341 uclient_http_reset_headers(cl);
342 uclient_http_set_header(cl, "User-Agent", user_agent);
344 check_resume_offset(cl);
347 uclient_http_set_header(cl, "Content-Type", "application/x-www-form-urlencoded");
348 uclient_write(cl, post_data, strlen(post_data));
351 rc = uclient_request(cl);
358 static void request_done(struct uclient *cl)
360 const char *proxy_url;
363 proxy_url = get_proxy_url(*urls);
365 uclient_set_url(cl, proxy_url, NULL);
366 uclient_set_proxy_url(cl, *urls, auth_str);
368 uclient_set_url(cl, *urls, auth_str);
372 error_ret = init_request(cl);
377 if (output_fd >= 0 && !opt_output_file) {
381 uclient_disconnect(cl);
386 static void eof_cb(struct uclient *cl)
389 pmt_update(&pmt_timer);
390 uloop_timeout_cancel(&pmt_timer);
391 fprintf(stderr, "\n");
396 fprintf(stderr, "Connection reset prematurely\n");
399 fprintf(stderr, "Download completed (%"PRIu64" bytes)\n", (uint64_t) out_bytes);
404 static void handle_uclient_error(struct uclient *cl, int code)
406 const char *type = "Unknown error";
410 case UCLIENT_ERROR_CONNECT:
411 type = "Connection failed";
414 case UCLIENT_ERROR_TIMEDOUT:
415 type = "Connection timed out";
418 case UCLIENT_ERROR_SSL_INVALID_CERT:
419 type = "Invalid SSL certificate";
423 case UCLIENT_ERROR_SSL_CN_MISMATCH:
424 type = "Server hostname does not match SSL certificate";
434 fprintf(stderr, "Connection error: %s%s\n", type, ignore ? " (ignored)" : "");
442 static const struct uclient_cb cb = {
443 .header_done = header_done_cb,
444 .data_read = read_data_cb,
446 .error = handle_uclient_error,
449 static int usage(const char *progname)
452 "Usage: %s [options] <URL>\n"
454 " -4 Use IPv4 only\n"
455 " -6 Use IPv6 only\n"
456 " -q Turn off status messages\n"
457 " -O <file> Redirect output to file (use \"-\" for stdout)\n"
458 " -P <dir> Set directory for output files\n"
459 " --user=<user> HTTP authentication username\n"
460 " --password=<password> HTTP authentication password\n"
461 " --user-agent|-U <str> Set HTTP user agent\n"
462 " --post-data=STRING use the POST method; send STRING as the data\n"
463 " --spider|-s Spider mode - only check file existence\n"
464 " --timeout=N|-T N Set connect/request timeout to N seconds\n"
465 " --proxy=on|off|-Y on|off Enable/disable env var configured proxy\n"
468 " --ca-certificate=<cert> Load CA certificates from file <cert>\n"
469 " --no-check-certificate don't validate the server's certificate\n"
474 static void init_ca_cert(void)
479 glob("/etc/ssl/certs/*.crt", 0, NULL, &gl);
480 for (i = 0; i < gl.gl_pathc; i++)
481 ssl_ops->context_add_ca_crt_file(ssl_ctx, gl.gl_pathv[i]);
484 static void init_ustream_ssl(void)
488 dlh = dlopen("libustream-ssl." LIB_EXT, RTLD_LAZY | RTLD_LOCAL);
492 ssl_ops = dlsym(dlh, "ustream_ssl_ops");
496 ssl_ctx = ssl_ops->context_new(false);
499 static int no_ssl(const char *progname)
502 "%s: SSL support not available, please install one of the "
503 "libustream-.*[ssl|tls] packages as well as the ca-bundle and "
504 "ca-certificates packages.\n",
511 L_NO_CHECK_CERTIFICATE,
525 static const struct option longopts[] = {
526 [L_NO_CHECK_CERTIFICATE] = { "no-check-certificate", no_argument },
527 [L_CA_CERTIFICATE] = { "ca-certificate", required_argument },
528 [L_USER] = { "user", required_argument },
529 [L_PASSWORD] = { "password", required_argument },
530 [L_USER_AGENT] = { "user-agent", required_argument },
531 [L_POST_DATA] = { "post-data", required_argument },
532 [L_SPIDER] = { "spider", no_argument },
533 [L_TIMEOUT] = { "timeout", required_argument },
534 [L_CONTINUE] = { "continue", no_argument },
535 [L_PROXY] = { "proxy", required_argument },
536 [L_NO_PROXY] = { "no-proxy", no_argument },
537 [L_QUIET] = { "quiet", no_argument },
543 int main(int argc, char **argv)
545 const char *progname = argv[0];
546 const char *proxy_url;
547 char *username = NULL;
548 char *password = NULL;
551 bool has_cert = false;
556 signal(SIGPIPE, SIG_IGN);
559 while ((ch = getopt_long(argc, argv, "46cO:P:qsT:U:Y:", longopts, &longopt_idx)) != -1) {
562 switch (longopt_idx) {
563 case L_NO_CHECK_CERTIFICATE:
566 case L_CA_CERTIFICATE:
569 ssl_ops->context_add_ca_crt_file(ssl_ctx, optarg);
574 username = strdup(optarg);
575 memset(optarg, '*', strlen(optarg));
580 password = strdup(optarg);
581 memset(optarg, '*', strlen(optarg));
593 timeout = atoi(optarg);
599 if (strcmp(optarg, "on") != 0)
609 return usage(progname);
625 opt_output_file = optarg;
630 perror("Change output directory");
641 timeout = atoi(optarg);
644 if (strcmp(optarg, "on") != 0)
648 return usage(progname);
655 if (verify && !has_cert)
656 default_certs = true;
659 return usage(progname);
662 for (i = 0; i < argc; i++) {
663 if (!strncmp(argv[i], "https", 5))
664 return no_ssl(progname);
675 rc = asprintf(&auth_str, "%s:%s", username, password);
683 fprintf(stderr, "Downloading '%s'\n", argv[0]);
685 proxy_url = get_proxy_url(argv[0]);
687 cl = uclient_new(proxy_url, auth_str, &cb);
689 uclient_set_proxy_url(cl, argv[0], NULL);
691 cl = uclient_new(argv[0], auth_str, &cb);
694 fprintf(stderr, "Failed to allocate uclient context\n");
698 uclient_http_set_address_family(cl, af);
700 if (ssl_ctx && default_certs)
704 rc = init_request(cl);
706 /* no error received, we can enter main loop */
709 fprintf(stderr, "Failed to establish connection\n");
717 if (output_fd >= 0 && output_fd != STDOUT_FILENO)
721 ssl_ops->context_free(ssl_ctx);