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.
27 #include <libubox/blobmsg.h>
30 #include "uclient-utils.h"
33 #define LIB_EXT "dylib"
38 static const char *user_agent = "uclient-fetch";
39 static const char *post_data;
40 static struct ustream_ssl_ctx *ssl_ctx;
41 static const struct ustream_ssl_ops *ssl_ops;
42 static int quiet = false;
43 static bool verify = true;
44 static bool default_certs = false;
45 static const char *output_file;
46 static int output_fd = -1;
49 static char *username;
50 static char *password;
51 static char *auth_str;
55 static void request_done(struct uclient *cl);
57 static int open_output_file(const char *path, bool create)
64 flags |= O_CREAT | O_EXCL;
67 if (!strcmp(output_file, "-"))
71 fprintf(stderr, "Writing to stdout\n");
74 return open(output_file, flags, 0644);
77 filename = uclient_get_url_filename(path, "index.html");
79 fprintf(stderr, "Writing to '%s'\n", filename);
80 ret = open(filename, flags, 0644);
86 static void header_done_cb(struct uclient *cl)
90 if (retries < 10 && uclient_http_redirect(cl)) {
92 fprintf(stderr, "Redirected to %s on %s\n", cl->url->location, cl->url->host);
99 switch (cl->status_code) {
102 output_fd = open_output_file(cl->url->location, true);
105 perror("Cannot open output file");
113 fprintf(stderr, "HTTP error %d\n", cl->status_code);
120 static void read_data_cb(struct uclient *cl)
129 len = uclient_read(cl, buf, sizeof(buf));
134 write(output_fd, buf, len);
138 static void msg_connecting(struct uclient *cl)
140 char addr[INET6_ADDRSTRLEN];
146 uclient_get_addr(addr, &port, &cl->remote_addr);
147 fprintf(stderr, "Connecting to %s:%d\n", addr, port);
150 static int init_request(struct uclient *cl)
155 uclient_http_set_ssl_ctx(cl, ssl_ops, ssl_ctx, verify);
157 rc = uclient_connect(cl);
163 rc = uclient_http_set_request_type(cl, post_data ? "POST" : "GET");
167 uclient_http_reset_headers(cl);
168 uclient_http_set_header(cl, "User-Agent", user_agent);
171 uclient_http_set_header(cl, "Content-Type", "application/x-www-form-urlencoded");
172 uclient_write(cl, post_data, strlen(post_data));
175 rc = uclient_request(cl);
182 static void request_done(struct uclient *cl)
185 uclient_set_url(cl, *urls, auth_str);
187 error_ret = init_request(cl);
192 if (output_fd >= 0 && !output_file) {
196 uclient_disconnect(cl);
201 static void eof_cb(struct uclient *cl)
205 fprintf(stderr, "Connection reset prematurely\n");
208 fprintf(stderr, "Download completed (%d bytes)\n", out_bytes);
213 static void handle_uclient_error(struct uclient *cl, int code)
215 const char *type = "Unknown error";
219 case UCLIENT_ERROR_CONNECT:
220 type = "Connection failed";
223 case UCLIENT_ERROR_TIMEDOUT:
224 type = "Connection timed out";
227 case UCLIENT_ERROR_SSL_INVALID_CERT:
228 type = "Invalid SSL certificate";
232 case UCLIENT_ERROR_SSL_CN_MISMATCH:
233 type = "Server hostname does not match SSL certificate";
243 fprintf(stderr, "Connection error: %s%s\n", type, ignore ? " (ignored)" : "");
251 static const struct uclient_cb cb = {
252 .header_done = header_done_cb,
253 .data_read = read_data_cb,
255 .error = handle_uclient_error,
258 static int usage(const char *progname)
261 "Usage: %s [options] <URL>\n"
263 " -q: Turn off status messages\n"
264 " -O <file>: Redirect output to file (use \"-\" for stdout)\n"
265 " --user=<user> HTTP authentication username\n"
266 " --password=<password> HTTP authentication password\n"
267 " --user-agent|-U <str> Set HTTP user agent\n"
268 " --post-data=STRING use the POST method; send STRING as the data\n"
271 " --ca-certificate=<cert>: Load CA certificates from file <cert>\n"
272 " --no-check-certificate: don't validate the server's certificate\n"
277 static void init_ca_cert(void)
282 glob("/etc/ssl/certs/*.crt", 0, NULL, &gl);
283 for (i = 0; i < gl.gl_pathc; i++)
284 ssl_ops->context_add_ca_crt_file(ssl_ctx, gl.gl_pathv[i]);
287 static void init_ustream_ssl(void)
291 dlh = dlopen("libustream-ssl." LIB_EXT, RTLD_LAZY | RTLD_LOCAL);
295 ssl_ops = dlsym(dlh, "ustream_ssl_ops");
299 ssl_ctx = ssl_ops->context_new(false);
302 static int no_ssl(const char *progname)
304 fprintf(stderr, "%s: SSL support not available, please install ustream-ssl\n", progname);
309 L_NO_CHECK_CERTIFICATE,
317 static const struct option longopts[] = {
318 [L_NO_CHECK_CERTIFICATE] = { "no-check-certificate", no_argument },
319 [L_CA_CERTIFICATE] = { "ca-certificate", required_argument },
320 [L_USER] = { "user", required_argument },
321 [L_PASSWORD] = { "password", required_argument },
322 [L_USER_AGENT] = { "user-agent", required_argument },
323 [L_POST_DATA] = { "post-data", required_argument },
329 int main(int argc, char **argv)
331 const char *progname = argv[0];
334 bool has_cert = false;
340 while ((ch = getopt_long(argc, argv, "qO:U:", longopts, &longopt_idx)) != -1) {
343 switch (longopt_idx) {
344 case L_NO_CHECK_CERTIFICATE:
347 case L_CA_CERTIFICATE:
350 ssl_ops->context_add_ca_crt_file(ssl_ctx, optarg);
355 username = strdup(optarg);
356 memset(optarg, '*', strlen(optarg));
361 password = strdup(optarg);
362 memset(optarg, '*', strlen(optarg));
371 return usage(progname);
378 output_file = optarg;
384 return usage(progname);
391 if (verify && !has_cert)
392 default_certs = true;
395 return usage(progname);
398 for (i = 0; i < argc; i++) {
399 if (!strncmp(argv[i], "https", 5))
400 return no_ssl(progname);
411 asprintf(&auth_str, "%s:%s", username, password);
417 fprintf(stderr, "Downloading '%s'\n", argv[0]);
419 cl = uclient_new(argv[0], auth_str, &cb);
421 fprintf(stderr, "Failed to allocate uclient context\n");
425 if (ssl_ctx && default_certs)
428 rc = init_request(cl);
430 /* no error received, we can enter main loop */
433 fprintf(stderr, "Failed to establish connection\n");
441 if (output_fd >= 0 && output_fd != STDOUT_FILENO)
445 ssl_ops->context_free(ssl_ctx);