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 default_certs
= false;
48 static bool no_output
;
49 static const char *output_file
;
50 static int output_fd
= -1;
53 static char *auth_str
;
57 static bool resume
, cur_resume
;
59 static int init_request(struct uclient
*cl
);
60 static void request_done(struct uclient
*cl
);
62 static int open_output_file(const char *path
, uint64_t resume_offset
)
64 char *filename
= NULL
;
71 flags
= O_WRONLY
| O_EXCL
;
76 if (!strcmp(output_file
, "-")) {
78 fprintf(stderr
, "Writing to stdout\n");
83 filename
= uclient_get_url_filename(path
, "index.html");
84 output_file
= filename
;
88 fprintf(stderr
, "Writing to '%s'\n", output_file
);
89 ret
= open(output_file
, flags
, 0644);
96 lseek(ret
, resume_offset
, SEEK_SET
) < 0) {
98 fprintf(stderr
, "Failed to seek %"PRIu64
" bytes in output file\n", resume_offset
);
103 out_bytes
+= resume_offset
;
108 static void header_done_cb(struct uclient
*cl
)
110 static const struct blobmsg_policy policy
= {
111 .name
= "content-range",
112 .type
= BLOBMSG_TYPE_STRING
114 struct blob_attr
*attr
;
115 uint64_t resume_offset
= 0, resume_end
, resume_size
;
118 if (retries
< 10 && uclient_http_redirect(cl
)) {
120 fprintf(stderr
, "Redirected to %s on %s\n", cl
->url
->location
, cl
->url
->host
);
126 if (cl
->status_code
== 204 && cur_resume
) {
127 /* Resume attempt failed, try normal download */
133 switch (cl
->status_code
) {
136 fprintf(stderr
, "File download already fully retrieved; nothing to do.\n");
142 fprintf(stderr
, "Error: Partial content received, full content requested\n");
148 blobmsg_parse(&policy
, 1, &attr
, blob_data(cl
->meta
), blob_len(cl
->meta
));
151 fprintf(stderr
, "Content-Range header is missing\n");
156 if (sscanf(blobmsg_get_string(attr
), "bytes %"PRIu64
"-%"PRIu64
"/%"PRIu64
,
157 &resume_offset
, &resume_end
, &resume_size
) != 3) {
159 fprintf(stderr
, "Content-Range header is invalid\n");
167 output_fd
= open_output_file(cl
->url
->location
, resume_offset
);
170 perror("Cannot open output file");
178 fprintf(stderr
, "HTTP error %d\n", cl
->status_code
);
185 static void read_data_cb(struct uclient
*cl
)
190 if (!no_output
&& output_fd
< 0)
194 len
= uclient_read(cl
, buf
, sizeof(buf
));
200 write(output_fd
, buf
, len
);
204 static void msg_connecting(struct uclient
*cl
)
206 char addr
[INET6_ADDRSTRLEN
];
212 uclient_get_addr(addr
, &port
, &cl
->remote_addr
);
213 fprintf(stderr
, "Connecting to %s:%d\n", addr
, port
);
216 static void check_resume_offset(struct uclient
*cl
)
223 file
= uclient_get_url_filename(cl
->url
->location
, "index.html");
227 ret
= stat(file
, &st
);
235 snprintf(range_str
, sizeof(range_str
), "bytes=%"PRIu64
"-", (uint64_t) st
.st_size
);
236 uclient_http_set_header(cl
, "Range", range_str
);
239 static int init_request(struct uclient
*cl
)
244 uclient_http_set_ssl_ctx(cl
, ssl_ops
, ssl_ctx
, verify
);
247 cl
->timeout_msecs
= timeout
* 1000;
249 rc
= uclient_connect(cl
);
255 rc
= uclient_http_set_request_type(cl
, post_data
? "POST" : "GET");
259 uclient_http_reset_headers(cl
);
260 uclient_http_set_header(cl
, "User-Agent", user_agent
);
262 check_resume_offset(cl
);
265 uclient_http_set_header(cl
, "Content-Type", "application/x-www-form-urlencoded");
266 uclient_write(cl
, post_data
, strlen(post_data
));
269 rc
= uclient_request(cl
);
276 static void request_done(struct uclient
*cl
)
279 uclient_set_url(cl
, *urls
, auth_str
);
282 error_ret
= init_request(cl
);
287 if (output_fd
>= 0 && !output_file
) {
291 uclient_disconnect(cl
);
296 static void eof_cb(struct uclient
*cl
)
300 fprintf(stderr
, "Connection reset prematurely\n");
303 fprintf(stderr
, "Download completed (%d bytes)\n", out_bytes
);
308 static void handle_uclient_error(struct uclient
*cl
, int code
)
310 const char *type
= "Unknown error";
314 case UCLIENT_ERROR_CONNECT
:
315 type
= "Connection failed";
318 case UCLIENT_ERROR_TIMEDOUT
:
319 type
= "Connection timed out";
322 case UCLIENT_ERROR_SSL_INVALID_CERT
:
323 type
= "Invalid SSL certificate";
327 case UCLIENT_ERROR_SSL_CN_MISMATCH
:
328 type
= "Server hostname does not match SSL certificate";
338 fprintf(stderr
, "Connection error: %s%s\n", type
, ignore
? " (ignored)" : "");
346 static const struct uclient_cb cb
= {
347 .header_done
= header_done_cb
,
348 .data_read
= read_data_cb
,
350 .error
= handle_uclient_error
,
353 static int usage(const char *progname
)
356 "Usage: %s [options] <URL>\n"
358 " -q: Turn off status messages\n"
359 " -O <file>: Redirect output to file (use \"-\" for stdout)\n"
360 " --user=<user> HTTP authentication username\n"
361 " --password=<password> HTTP authentication password\n"
362 " --user-agent|-U <str> Set HTTP user agent\n"
363 " --post-data=STRING use the POST method; send STRING as the data\n"
364 " --spider|-s Spider mode - only check file existence\n"
365 " --timeout=N|-T N Set connect/request timeout to N seconds\n"
368 " --ca-certificate=<cert>: Load CA certificates from file <cert>\n"
369 " --no-check-certificate: don't validate the server's certificate\n"
374 static void init_ca_cert(void)
379 glob("/etc/ssl/certs/*.crt", 0, NULL
, &gl
);
380 for (i
= 0; i
< gl
.gl_pathc
; i
++)
381 ssl_ops
->context_add_ca_crt_file(ssl_ctx
, gl
.gl_pathv
[i
]);
384 static void init_ustream_ssl(void)
388 dlh
= dlopen("libustream-ssl." LIB_EXT
, RTLD_LAZY
| RTLD_LOCAL
);
392 ssl_ops
= dlsym(dlh
, "ustream_ssl_ops");
396 ssl_ctx
= ssl_ops
->context_new(false);
399 static int no_ssl(const char *progname
)
401 fprintf(stderr
, "%s: SSL support not available, please install ustream-ssl\n", progname
);
406 L_NO_CHECK_CERTIFICATE
,
417 static const struct option longopts
[] = {
418 [L_NO_CHECK_CERTIFICATE
] = { "no-check-certificate", no_argument
},
419 [L_CA_CERTIFICATE
] = { "ca-certificate", required_argument
},
420 [L_USER
] = { "user", required_argument
},
421 [L_PASSWORD
] = { "password", required_argument
},
422 [L_USER_AGENT
] = { "user-agent", required_argument
},
423 [L_POST_DATA
] = { "post-data", required_argument
},
424 [L_SPIDER
] = { "spider", no_argument
},
425 [L_TIMEOUT
] = { "timeout", required_argument
},
426 [L_CONTINUE
] = { "continue", no_argument
},
432 int main(int argc
, char **argv
)
434 const char *progname
= argv
[0];
435 char *username
= NULL
;
436 char *password
= NULL
;
439 bool has_cert
= false;
445 while ((ch
= getopt_long(argc
, argv
, "cO:qsU:", longopts
, &longopt_idx
)) != -1) {
448 switch (longopt_idx
) {
449 case L_NO_CHECK_CERTIFICATE
:
452 case L_CA_CERTIFICATE
:
455 ssl_ops
->context_add_ca_crt_file(ssl_ctx
, optarg
);
460 username
= strdup(optarg
);
461 memset(optarg
, '*', strlen(optarg
));
466 password
= strdup(optarg
);
467 memset(optarg
, '*', strlen(optarg
));
479 timeout
= atoi(optarg
);
485 return usage(progname
);
495 output_file
= optarg
;
504 timeout
= atoi(optarg
);
507 return usage(progname
);
514 if (verify
&& !has_cert
)
515 default_certs
= true;
518 return usage(progname
);
521 for (i
= 0; i
< argc
; i
++) {
522 if (!strncmp(argv
[i
], "https", 5))
523 return no_ssl(progname
);
534 asprintf(&auth_str
, "%s:%s", username
, password
);
540 fprintf(stderr
, "Downloading '%s'\n", argv
[0]);
542 cl
= uclient_new(argv
[0], auth_str
, &cb
);
544 fprintf(stderr
, "Failed to allocate uclient context\n");
548 if (ssl_ctx
&& default_certs
)
552 rc
= init_request(cl
);
554 /* no error received, we can enter main loop */
557 fprintf(stderr
, "Failed to establish connection\n");
565 if (output_fd
>= 0 && output_fd
!= STDOUT_FILENO
)
569 ssl_ops
->context_free(ssl_ctx
);