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 *username
;
54 static char *password
;
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
);
64 static int open_output_file(const char *path
, uint64_t resume_offset
)
66 char *filename
= NULL
;
73 flags
= O_WRONLY
| O_EXCL
;
78 if (!strcmp(output_file
, "-")) {
80 fprintf(stderr
, "Writing to stdout\n");
85 filename
= uclient_get_url_filename(path
, "index.html");
86 output_file
= filename
;
90 fprintf(stderr
, "Writing to '%s'\n", output_file
);
91 ret
= open(output_file
, flags
, 0644);
98 lseek(ret
, resume_offset
, SEEK_SET
) < 0) {
100 fprintf(stderr
, "Failed to seek %"PRIu64
" bytes in output file\n", resume_offset
);
105 out_bytes
+= resume_offset
;
110 static void header_done_cb(struct uclient
*cl
)
112 static const struct blobmsg_policy policy
= {
113 .name
= "content-range",
114 .type
= BLOBMSG_TYPE_STRING
116 struct blob_attr
*attr
;
117 uint64_t resume_offset
= 0, resume_end
, resume_size
;
120 if (retries
< 10 && uclient_http_redirect(cl
)) {
122 fprintf(stderr
, "Redirected to %s on %s\n", cl
->url
->location
, cl
->url
->host
);
128 if (cl
->status_code
== 204 && cur_resume
) {
129 /* Resume attempt failed, try normal download */
135 switch (cl
->status_code
) {
138 fprintf(stderr
, "File download already fully retrieved; nothing to do.\n");
144 fprintf(stderr
, "Error: Partial content received, full content requested\n");
150 blobmsg_parse(&policy
, 1, &attr
, blob_data(cl
->meta
), blob_len(cl
->meta
));
153 fprintf(stderr
, "Content-Range header is missing\n");
158 if (sscanf(blobmsg_get_string(attr
), "bytes %"PRIu64
"-%"PRIu64
"/%"PRIu64
,
159 &resume_offset
, &resume_end
, &resume_size
) != 3) {
161 fprintf(stderr
, "Content-Range header is invalid\n");
169 output_fd
= open_output_file(cl
->url
->location
, resume_offset
);
172 perror("Cannot open output file");
180 fprintf(stderr
, "HTTP error %d\n", cl
->status_code
);
187 static void read_data_cb(struct uclient
*cl
)
192 if (!no_output
&& output_fd
< 0)
196 len
= uclient_read(cl
, buf
, sizeof(buf
));
202 write(output_fd
, buf
, len
);
206 static void msg_connecting(struct uclient
*cl
)
208 char addr
[INET6_ADDRSTRLEN
];
214 uclient_get_addr(addr
, &port
, &cl
->remote_addr
);
215 fprintf(stderr
, "Connecting to %s:%d\n", addr
, port
);
218 static void check_resume_offset(struct uclient
*cl
)
225 file
= uclient_get_url_filename(cl
->url
->location
, "index.html");
229 ret
= stat(file
, &st
);
237 snprintf(range_str
, sizeof(range_str
), "bytes=%"PRIu64
"-", (uint64_t) st
.st_size
);
238 uclient_http_set_header(cl
, "Range", range_str
);
241 static int init_request(struct uclient
*cl
)
246 uclient_http_set_ssl_ctx(cl
, ssl_ops
, ssl_ctx
, verify
);
249 cl
->timeout_msecs
= timeout
* 1000;
251 rc
= uclient_connect(cl
);
257 rc
= uclient_http_set_request_type(cl
, post_data
? "POST" : "GET");
261 uclient_http_reset_headers(cl
);
262 uclient_http_set_header(cl
, "User-Agent", user_agent
);
264 check_resume_offset(cl
);
267 uclient_http_set_header(cl
, "Content-Type", "application/x-www-form-urlencoded");
268 uclient_write(cl
, post_data
, strlen(post_data
));
271 rc
= uclient_request(cl
);
278 static void request_done(struct uclient
*cl
)
281 uclient_set_url(cl
, *urls
, auth_str
);
284 error_ret
= init_request(cl
);
289 if (output_fd
>= 0 && !output_file
) {
293 uclient_disconnect(cl
);
298 static void eof_cb(struct uclient
*cl
)
302 fprintf(stderr
, "Connection reset prematurely\n");
305 fprintf(stderr
, "Download completed (%d bytes)\n", out_bytes
);
310 static void handle_uclient_error(struct uclient
*cl
, int code
)
312 const char *type
= "Unknown error";
316 case UCLIENT_ERROR_CONNECT
:
317 type
= "Connection failed";
320 case UCLIENT_ERROR_TIMEDOUT
:
321 type
= "Connection timed out";
324 case UCLIENT_ERROR_SSL_INVALID_CERT
:
325 type
= "Invalid SSL certificate";
329 case UCLIENT_ERROR_SSL_CN_MISMATCH
:
330 type
= "Server hostname does not match SSL certificate";
340 fprintf(stderr
, "Connection error: %s%s\n", type
, ignore
? " (ignored)" : "");
348 static const struct uclient_cb cb
= {
349 .header_done
= header_done_cb
,
350 .data_read
= read_data_cb
,
352 .error
= handle_uclient_error
,
355 static int usage(const char *progname
)
358 "Usage: %s [options] <URL>\n"
360 " -q: Turn off status messages\n"
361 " -O <file>: Redirect output to file (use \"-\" for stdout)\n"
362 " --user=<user> HTTP authentication username\n"
363 " --password=<password> HTTP authentication password\n"
364 " --user-agent|-U <str> Set HTTP user agent\n"
365 " --post-data=STRING use the POST method; send STRING as the data\n"
366 " --spider|-s Spider mode - only check file existence\n"
367 " --timeout=N|-T N Set connect/request timeout to N seconds\n"
370 " --ca-certificate=<cert>: Load CA certificates from file <cert>\n"
371 " --no-check-certificate: don't validate the server's certificate\n"
376 static void init_ca_cert(void)
381 glob("/etc/ssl/certs/*.crt", 0, NULL
, &gl
);
382 for (i
= 0; i
< gl
.gl_pathc
; i
++)
383 ssl_ops
->context_add_ca_crt_file(ssl_ctx
, gl
.gl_pathv
[i
]);
386 static void init_ustream_ssl(void)
390 dlh
= dlopen("libustream-ssl." LIB_EXT
, RTLD_LAZY
| RTLD_LOCAL
);
394 ssl_ops
= dlsym(dlh
, "ustream_ssl_ops");
398 ssl_ctx
= ssl_ops
->context_new(false);
401 static int no_ssl(const char *progname
)
403 fprintf(stderr
, "%s: SSL support not available, please install ustream-ssl\n", progname
);
408 L_NO_CHECK_CERTIFICATE
,
419 static const struct option longopts
[] = {
420 [L_NO_CHECK_CERTIFICATE
] = { "no-check-certificate", no_argument
},
421 [L_CA_CERTIFICATE
] = { "ca-certificate", required_argument
},
422 [L_USER
] = { "user", required_argument
},
423 [L_PASSWORD
] = { "password", required_argument
},
424 [L_USER_AGENT
] = { "user-agent", required_argument
},
425 [L_POST_DATA
] = { "post-data", required_argument
},
426 [L_SPIDER
] = { "spider", no_argument
},
427 [L_TIMEOUT
] = { "timeout", required_argument
},
428 [L_CONTINUE
] = { "continue", no_argument
},
434 int main(int argc
, char **argv
)
436 const char *progname
= argv
[0];
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
);