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.
31 #include <libubox/blobmsg.h>
34 #include "uclient-utils.h"
37 #define LIB_EXT "dylib"
42 static const char *user_agent = "uclient-fetch";
43 static const char *post_data;
44 static struct ustream_ssl_ctx *ssl_ctx;
45 static const struct ustream_ssl_ops *ssl_ops;
46 static int quiet = false;
47 static bool verify = true;
48 static bool proxy = true;
49 static bool default_certs = false;
50 static bool no_output;
51 static const char *output_file;
52 static int output_fd = -1;
55 static char *auth_str;
59 static bool resume, cur_resume;
61 static int init_request(struct uclient *cl);
62 static void request_done(struct uclient *cl);
65 get_proxy_url(char *url)
73 sep = strchr(url, ':');
80 memcpy(prefix, url, sep - url);
81 strcpy(prefix + (sep - url), "_proxy");
82 return getenv(prefix);
85 static int open_output_file(const char *path, uint64_t resume_offset)
87 char *filename = NULL;
94 flags = O_WRONLY | O_EXCL;
99 if (!strcmp(output_file, "-")) {
101 fprintf(stderr, "Writing to stdout\n");
103 return STDOUT_FILENO;
106 filename = uclient_get_url_filename(path, "index.html");
107 output_file = filename;
111 fprintf(stderr, "Writing to '%s'\n", output_file);
112 ret = open(output_file, flags, 0644);
119 lseek(ret, resume_offset, SEEK_SET) < 0) {
121 fprintf(stderr, "Failed to seek %"PRIu64" bytes in output file\n", resume_offset);
126 out_bytes += resume_offset;
131 static void header_done_cb(struct uclient *cl)
133 static const struct blobmsg_policy policy = {
134 .name = "content-range",
135 .type = BLOBMSG_TYPE_STRING
137 struct blob_attr *attr;
138 uint64_t resume_offset = 0, resume_end, resume_size;
141 if (retries < 10 && uclient_http_redirect(cl)) {
143 fprintf(stderr, "Redirected to %s on %s\n", cl->url->location, cl->url->host);
149 if (cl->status_code == 204 && cur_resume) {
150 /* Resume attempt failed, try normal download */
156 switch (cl->status_code) {
159 fprintf(stderr, "File download already fully retrieved; nothing to do.\n");
165 fprintf(stderr, "Error: Partial content received, full content requested\n");
171 blobmsg_parse(&policy, 1, &attr, blob_data(cl->meta), blob_len(cl->meta));
174 fprintf(stderr, "Content-Range header is missing\n");
179 if (sscanf(blobmsg_get_string(attr), "bytes %"PRIu64"-%"PRIu64"/%"PRIu64,
180 &resume_offset, &resume_end, &resume_size) != 3) {
182 fprintf(stderr, "Content-Range header is invalid\n");
190 output_fd = open_output_file(cl->url->location, resume_offset);
193 perror("Cannot open output file");
201 fprintf(stderr, "HTTP error %d\n", cl->status_code);
208 static void read_data_cb(struct uclient *cl)
213 if (!no_output && output_fd < 0)
217 len = uclient_read(cl, buf, sizeof(buf));
223 write(output_fd, buf, len);
227 static void msg_connecting(struct uclient *cl)
229 char addr[INET6_ADDRSTRLEN];
235 uclient_get_addr(addr, &port, &cl->remote_addr);
236 fprintf(stderr, "Connecting to %s:%d\n", addr, port);
239 static void check_resume_offset(struct uclient *cl)
246 file = uclient_get_url_filename(cl->url->location, "index.html");
250 ret = stat(file, &st);
258 snprintf(range_str, sizeof(range_str), "bytes=%"PRIu64"-", (uint64_t) st.st_size);
259 uclient_http_set_header(cl, "Range", range_str);
262 static int init_request(struct uclient *cl)
267 uclient_http_set_ssl_ctx(cl, ssl_ops, ssl_ctx, verify);
270 cl->timeout_msecs = timeout * 1000;
272 rc = uclient_connect(cl);
278 rc = uclient_http_set_request_type(cl, post_data ? "POST" : "GET");
282 uclient_http_reset_headers(cl);
283 uclient_http_set_header(cl, "User-Agent", user_agent);
285 check_resume_offset(cl);
288 uclient_http_set_header(cl, "Content-Type", "application/x-www-form-urlencoded");
289 uclient_write(cl, post_data, strlen(post_data));
292 rc = uclient_request(cl);
299 static void request_done(struct uclient *cl)
301 const char *proxy_url;
304 proxy_url = get_proxy_url(*urls);
306 uclient_set_url(cl, proxy_url, NULL);
307 uclient_set_proxy_url(cl, *urls, auth_str);
309 uclient_set_url(cl, *urls, auth_str);
313 error_ret = init_request(cl);
318 if (output_fd >= 0 && !output_file) {
322 uclient_disconnect(cl);
327 static void eof_cb(struct uclient *cl)
331 fprintf(stderr, "Connection reset prematurely\n");
334 fprintf(stderr, "Download completed (%d bytes)\n", out_bytes);
339 static void handle_uclient_error(struct uclient *cl, int code)
341 const char *type = "Unknown error";
345 case UCLIENT_ERROR_CONNECT:
346 type = "Connection failed";
349 case UCLIENT_ERROR_TIMEDOUT:
350 type = "Connection timed out";
353 case UCLIENT_ERROR_SSL_INVALID_CERT:
354 type = "Invalid SSL certificate";
358 case UCLIENT_ERROR_SSL_CN_MISMATCH:
359 type = "Server hostname does not match SSL certificate";
369 fprintf(stderr, "Connection error: %s%s\n", type, ignore ? " (ignored)" : "");
377 static const struct uclient_cb cb = {
378 .header_done = header_done_cb,
379 .data_read = read_data_cb,
381 .error = handle_uclient_error,
384 static int usage(const char *progname)
387 "Usage: %s [options] <URL>\n"
389 " -q: Turn off status messages\n"
390 " -O <file>: Redirect output to file (use \"-\" for stdout)\n"
391 " -P <dir>: Set directory for output files\n"
392 " --user=<user> HTTP authentication username\n"
393 " --password=<password> HTTP authentication password\n"
394 " --user-agent|-U <str> Set HTTP user agent\n"
395 " --post-data=STRING use the POST method; send STRING as the data\n"
396 " --spider|-s Spider mode - only check file existence\n"
397 " --timeout=N|-T N Set connect/request timeout to N seconds\n"
398 " --proxy=on|off|-Y on|off Enable/disable env var configured proxy\n"
401 " --ca-certificate=<cert>: Load CA certificates from file <cert>\n"
402 " --no-check-certificate: don't validate the server's certificate\n"
407 static void init_ca_cert(void)
412 glob("/etc/ssl/certs/*.crt", 0, NULL, &gl);
413 for (i = 0; i < gl.gl_pathc; i++)
414 ssl_ops->context_add_ca_crt_file(ssl_ctx, gl.gl_pathv[i]);
417 static void init_ustream_ssl(void)
421 dlh = dlopen("libustream-ssl." LIB_EXT, RTLD_LAZY | RTLD_LOCAL);
425 ssl_ops = dlsym(dlh, "ustream_ssl_ops");
429 ssl_ctx = ssl_ops->context_new(false);
432 static int no_ssl(const char *progname)
434 fprintf(stderr, "%s: SSL support not available, please install ustream-ssl\n", progname);
439 L_NO_CHECK_CERTIFICATE,
452 static const struct option longopts[] = {
453 [L_NO_CHECK_CERTIFICATE] = { "no-check-certificate", no_argument },
454 [L_CA_CERTIFICATE] = { "ca-certificate", required_argument },
455 [L_USER] = { "user", required_argument },
456 [L_PASSWORD] = { "password", required_argument },
457 [L_USER_AGENT] = { "user-agent", required_argument },
458 [L_POST_DATA] = { "post-data", required_argument },
459 [L_SPIDER] = { "spider", no_argument },
460 [L_TIMEOUT] = { "timeout", required_argument },
461 [L_CONTINUE] = { "continue", no_argument },
462 [L_PROXY] = { "proxy", required_argument },
463 [L_NO_PROXY] = { "no-proxy", no_argument },
469 int main(int argc, char **argv)
471 const char *progname = argv[0];
472 const char *proxy_url;
473 char *username = NULL;
474 char *password = NULL;
477 bool has_cert = false;
481 signal(SIGPIPE, SIG_IGN);
484 while ((ch = getopt_long(argc, argv, "cO:P:qsU:Y:", longopts, &longopt_idx)) != -1) {
487 switch (longopt_idx) {
488 case L_NO_CHECK_CERTIFICATE:
491 case L_CA_CERTIFICATE:
494 ssl_ops->context_add_ca_crt_file(ssl_ctx, optarg);
499 username = strdup(optarg);
500 memset(optarg, '*', strlen(optarg));
505 password = strdup(optarg);
506 memset(optarg, '*', strlen(optarg));
518 timeout = atoi(optarg);
524 if (strcmp(optarg, "on") != 0)
531 return usage(progname);
541 output_file = optarg;
546 perror("Change output directory");
557 timeout = atoi(optarg);
560 if (strcmp(optarg, "on") != 0)
564 return usage(progname);
571 if (verify && !has_cert)
572 default_certs = true;
575 return usage(progname);
578 for (i = 0; i < argc; i++) {
579 if (!strncmp(argv[i], "https", 5))
580 return no_ssl(progname);
591 asprintf(&auth_str, "%s:%s", username, password);
597 fprintf(stderr, "Downloading '%s'\n", argv[0]);
599 proxy_url = get_proxy_url(argv[0]);
601 cl = uclient_new(proxy_url, auth_str, &cb);
602 uclient_set_proxy_url(cl, argv[0], NULL);
604 cl = uclient_new(argv[0], auth_str, &cb);
607 fprintf(stderr, "Failed to allocate uclient context\n");
611 if (ssl_ctx && default_certs)
615 rc = init_request(cl);
617 /* no error received, we can enter main loop */
620 fprintf(stderr, "Failed to establish connection\n");
628 if (output_fd >= 0 && output_fd != STDOUT_FILENO)
632 ssl_ops->context_free(ssl_ctx);