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.
30 #include <libubox/blobmsg.h>
33 #include "uclient-utils.h"
36 #define LIB_EXT "dylib"
41 static const char *user_agent = "uclient-fetch";
42 static const char *post_data;
43 static struct ustream_ssl_ctx *ssl_ctx;
44 static const struct ustream_ssl_ops *ssl_ops;
45 static int quiet = false;
46 static bool verify = true;
47 static bool proxy = true;
48 static bool default_certs = false;
49 static bool no_output;
50 static const char *output_file;
51 static int output_fd = -1;
54 static char *auth_str;
58 static bool resume, cur_resume;
60 static int init_request(struct uclient *cl);
61 static void request_done(struct uclient *cl);
64 get_proxy_url(char *url)
72 sep = strchr(url, ':');
79 memcpy(prefix, url, sep - url);
80 strcpy(prefix + (sep - url), "_proxy");
81 return getenv(prefix);
84 static int open_output_file(const char *path, uint64_t resume_offset)
86 char *filename = NULL;
93 flags = O_WRONLY | O_EXCL;
98 if (!strcmp(output_file, "-")) {
100 fprintf(stderr, "Writing to stdout\n");
102 return STDOUT_FILENO;
105 filename = uclient_get_url_filename(path, "index.html");
106 output_file = filename;
110 fprintf(stderr, "Writing to '%s'\n", output_file);
111 ret = open(output_file, flags, 0644);
118 lseek(ret, resume_offset, SEEK_SET) < 0) {
120 fprintf(stderr, "Failed to seek %"PRIu64" bytes in output file\n", resume_offset);
125 out_bytes += resume_offset;
130 static void header_done_cb(struct uclient *cl)
132 static const struct blobmsg_policy policy = {
133 .name = "content-range",
134 .type = BLOBMSG_TYPE_STRING
136 struct blob_attr *attr;
137 uint64_t resume_offset = 0, resume_end, resume_size;
140 if (retries < 10 && uclient_http_redirect(cl)) {
142 fprintf(stderr, "Redirected to %s on %s\n", cl->url->location, cl->url->host);
148 if (cl->status_code == 204 && cur_resume) {
149 /* Resume attempt failed, try normal download */
155 switch (cl->status_code) {
158 fprintf(stderr, "File download already fully retrieved; nothing to do.\n");
164 fprintf(stderr, "Error: Partial content received, full content requested\n");
170 blobmsg_parse(&policy, 1, &attr, blob_data(cl->meta), blob_len(cl->meta));
173 fprintf(stderr, "Content-Range header is missing\n");
178 if (sscanf(blobmsg_get_string(attr), "bytes %"PRIu64"-%"PRIu64"/%"PRIu64,
179 &resume_offset, &resume_end, &resume_size) != 3) {
181 fprintf(stderr, "Content-Range header is invalid\n");
189 output_fd = open_output_file(cl->url->location, resume_offset);
192 perror("Cannot open output file");
200 fprintf(stderr, "HTTP error %d\n", cl->status_code);
207 static void read_data_cb(struct uclient *cl)
212 if (!no_output && output_fd < 0)
216 len = uclient_read(cl, buf, sizeof(buf));
222 write(output_fd, buf, len);
226 static void msg_connecting(struct uclient *cl)
228 char addr[INET6_ADDRSTRLEN];
234 uclient_get_addr(addr, &port, &cl->remote_addr);
235 fprintf(stderr, "Connecting to %s:%d\n", addr, port);
238 static void check_resume_offset(struct uclient *cl)
245 file = uclient_get_url_filename(cl->url->location, "index.html");
249 ret = stat(file, &st);
257 snprintf(range_str, sizeof(range_str), "bytes=%"PRIu64"-", (uint64_t) st.st_size);
258 uclient_http_set_header(cl, "Range", range_str);
261 static int init_request(struct uclient *cl)
266 uclient_http_set_ssl_ctx(cl, ssl_ops, ssl_ctx, verify);
269 cl->timeout_msecs = timeout * 1000;
271 rc = uclient_connect(cl);
277 rc = uclient_http_set_request_type(cl, post_data ? "POST" : "GET");
281 uclient_http_reset_headers(cl);
282 uclient_http_set_header(cl, "User-Agent", user_agent);
284 check_resume_offset(cl);
287 uclient_http_set_header(cl, "Content-Type", "application/x-www-form-urlencoded");
288 uclient_write(cl, post_data, strlen(post_data));
291 rc = uclient_request(cl);
298 static void request_done(struct uclient *cl)
300 const char *proxy_url;
303 proxy_url = get_proxy_url(*urls);
305 uclient_set_url(cl, proxy_url, NULL);
306 uclient_set_proxy_url(cl, *urls, auth_str);
308 uclient_set_url(cl, *urls, auth_str);
312 error_ret = init_request(cl);
317 if (output_fd >= 0 && !output_file) {
321 uclient_disconnect(cl);
326 static void eof_cb(struct uclient *cl)
330 fprintf(stderr, "Connection reset prematurely\n");
333 fprintf(stderr, "Download completed (%d bytes)\n", out_bytes);
338 static void handle_uclient_error(struct uclient *cl, int code)
340 const char *type = "Unknown error";
344 case UCLIENT_ERROR_CONNECT:
345 type = "Connection failed";
348 case UCLIENT_ERROR_TIMEDOUT:
349 type = "Connection timed out";
352 case UCLIENT_ERROR_SSL_INVALID_CERT:
353 type = "Invalid SSL certificate";
357 case UCLIENT_ERROR_SSL_CN_MISMATCH:
358 type = "Server hostname does not match SSL certificate";
368 fprintf(stderr, "Connection error: %s%s\n", type, ignore ? " (ignored)" : "");
376 static const struct uclient_cb cb = {
377 .header_done = header_done_cb,
378 .data_read = read_data_cb,
380 .error = handle_uclient_error,
383 static int usage(const char *progname)
386 "Usage: %s [options] <URL>\n"
388 " -q: Turn off status messages\n"
389 " -O <file>: Redirect output to file (use \"-\" for stdout)\n"
390 " --user=<user> HTTP authentication username\n"
391 " --password=<password> HTTP authentication password\n"
392 " --user-agent|-U <str> Set HTTP user agent\n"
393 " --post-data=STRING use the POST method; send STRING as the data\n"
394 " --spider|-s Spider mode - only check file existence\n"
395 " --timeout=N|-T N Set connect/request timeout to N seconds\n"
396 " --proxy=on|off|-Y on|off Enable/disable env var configured proxy\n"
399 " --ca-certificate=<cert>: Load CA certificates from file <cert>\n"
400 " --no-check-certificate: don't validate the server's certificate\n"
405 static void init_ca_cert(void)
410 glob("/etc/ssl/certs/*.crt", 0, NULL, &gl);
411 for (i = 0; i < gl.gl_pathc; i++)
412 ssl_ops->context_add_ca_crt_file(ssl_ctx, gl.gl_pathv[i]);
415 static void init_ustream_ssl(void)
419 dlh = dlopen("libustream-ssl." LIB_EXT, RTLD_LAZY | RTLD_LOCAL);
423 ssl_ops = dlsym(dlh, "ustream_ssl_ops");
427 ssl_ctx = ssl_ops->context_new(false);
430 static int no_ssl(const char *progname)
432 fprintf(stderr, "%s: SSL support not available, please install ustream-ssl\n", progname);
437 L_NO_CHECK_CERTIFICATE,
450 static const struct option longopts[] = {
451 [L_NO_CHECK_CERTIFICATE] = { "no-check-certificate", no_argument },
452 [L_CA_CERTIFICATE] = { "ca-certificate", required_argument },
453 [L_USER] = { "user", required_argument },
454 [L_PASSWORD] = { "password", required_argument },
455 [L_USER_AGENT] = { "user-agent", required_argument },
456 [L_POST_DATA] = { "post-data", required_argument },
457 [L_SPIDER] = { "spider", no_argument },
458 [L_TIMEOUT] = { "timeout", required_argument },
459 [L_CONTINUE] = { "continue", no_argument },
460 [L_PROXY] = { "proxy", required_argument },
461 [L_NO_PROXY] = { "no-proxy", no_argument },
467 int main(int argc, char **argv)
469 const char *progname = argv[0];
470 const char *proxy_url;
471 char *username = NULL;
472 char *password = NULL;
475 bool has_cert = false;
481 while ((ch = getopt_long(argc, argv, "cO:qsU:Y:", longopts, &longopt_idx)) != -1) {
484 switch (longopt_idx) {
485 case L_NO_CHECK_CERTIFICATE:
488 case L_CA_CERTIFICATE:
491 ssl_ops->context_add_ca_crt_file(ssl_ctx, optarg);
496 username = strdup(optarg);
497 memset(optarg, '*', strlen(optarg));
502 password = strdup(optarg);
503 memset(optarg, '*', strlen(optarg));
515 timeout = atoi(optarg);
521 if (strcmp(optarg, "on") != 0)
528 return usage(progname);
538 output_file = optarg;
547 timeout = atoi(optarg);
550 if (strcmp(optarg, "on") != 0)
554 return usage(progname);
561 if (verify && !has_cert)
562 default_certs = true;
565 return usage(progname);
568 for (i = 0; i < argc; i++) {
569 if (!strncmp(argv[i], "https", 5))
570 return no_ssl(progname);
581 asprintf(&auth_str, "%s:%s", username, password);
587 fprintf(stderr, "Downloading '%s'\n", argv[0]);
589 proxy_url = get_proxy_url(argv[0]);
591 cl = uclient_new(proxy_url, auth_str, &cb);
592 uclient_set_proxy_url(cl, argv[0], NULL);
594 cl = uclient_new(argv[0], auth_str, &cb);
597 fprintf(stderr, "Failed to allocate uclient context\n");
601 if (ssl_ctx && default_certs)
605 rc = init_request(cl);
607 /* no error received, we can enter main loop */
610 fprintf(stderr, "Failed to establish connection\n");
618 if (output_fd >= 0 && output_fd != STDOUT_FILENO)
622 ssl_ops->context_free(ssl_ctx);