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>
35 #include "uclient-utils.h"
38 #define LIB_EXT "dylib"
43 static const char *user_agent
= "uclient-fetch";
44 static const char *post_data
;
45 static struct ustream_ssl_ctx
*ssl_ctx
;
46 static const struct ustream_ssl_ops
*ssl_ops
;
47 static int quiet
= false;
48 static bool verify
= true;
49 static bool proxy
= true;
50 static bool default_certs
= false;
51 static bool no_output
;
52 static const char *output_file
;
53 static int output_fd
= -1;
55 static off_t out_offset
;
56 static off_t out_bytes
;
58 static char *auth_str
;
62 static bool resume
, cur_resume
;
64 static struct progress pmt
;
65 static struct uloop_timeout pmt_timer
;
67 static int init_request(struct uclient
*cl
);
68 static void request_done(struct uclient
*cl
);
70 static void pmt_update(struct uloop_timeout
*t
)
72 progress_update(&pmt
, out_offset
, out_bytes
, out_len
);
73 uloop_timeout_set(t
, 1000);
77 get_proxy_url(char *url
)
85 sep
= strchr(url
, ':');
92 memcpy(prefix
, url
, sep
- url
);
93 strcpy(prefix
+ (sep
- url
), "_proxy");
94 return getenv(prefix
);
97 static int open_output_file(const char *path
, uint64_t resume_offset
)
99 char *filename
= NULL
;
106 flags
= O_WRONLY
| O_EXCL
;
111 if (!strcmp(output_file
, "-")) {
113 fprintf(stderr
, "Writing to stdout\n");
115 return STDOUT_FILENO
;
118 filename
= uclient_get_url_filename(path
, "index.html");
119 output_file
= filename
;
123 fprintf(stderr
, "Writing to '%s'\n", output_file
);
124 ret
= open(output_file
, flags
, 0644);
129 lseek(ret
, resume_offset
, SEEK_SET
) < 0) {
131 fprintf(stderr
, "Failed to seek %"PRIu64
" bytes in output file\n", resume_offset
);
137 out_offset
= resume_offset
;
138 out_bytes
+= resume_offset
;
140 progress_init(&pmt
, output_file
);
141 pmt_timer
.cb
= pmt_update
;
142 pmt_timer
.cb(&pmt_timer
);
150 static void header_done_cb(struct uclient
*cl
)
157 static const struct blobmsg_policy policy
[__H_MAX
] = {
158 [H_RANGE
] = { .name
= "content-range", .type
= BLOBMSG_TYPE_STRING
},
159 [H_LEN
] = { .name
= "content-length", .type
= BLOBMSG_TYPE_STRING
},
161 struct blob_attr
*tb
[__H_MAX
];
162 uint64_t resume_offset
= 0, resume_end
, resume_size
;
165 if (retries
< 10 && uclient_http_redirect(cl
)) {
167 fprintf(stderr
, "Redirected to %s on %s\n", cl
->url
->location
, cl
->url
->host
);
173 if (cl
->status_code
== 204 && cur_resume
) {
174 /* Resume attempt failed, try normal download */
180 blobmsg_parse(policy
, __H_MAX
, tb
, blob_data(cl
->meta
), blob_len(cl
->meta
));
182 switch (cl
->status_code
) {
185 fprintf(stderr
, "File download already fully retrieved; nothing to do.\n");
191 fprintf(stderr
, "Error: Partial content received, full content requested\n");
199 fprintf(stderr
, "Content-Range header is missing\n");
204 if (sscanf(blobmsg_get_string(tb
[H_RANGE
]),
205 "bytes %"PRIu64
"-%"PRIu64
"/%"PRIu64
,
206 &resume_offset
, &resume_end
, &resume_size
) != 3) {
208 fprintf(stderr
, "Content-Range header is invalid\n");
218 out_len
= strtoul(blobmsg_get_string(tb
[H_LEN
]), NULL
, 10);
220 output_fd
= open_output_file(cl
->url
->location
, resume_offset
);
223 perror("Cannot open output file");
231 fprintf(stderr
, "HTTP error %d\n", cl
->status_code
);
238 static void read_data_cb(struct uclient
*cl
)
243 if (!no_output
&& output_fd
< 0)
247 len
= uclient_read(cl
, buf
, sizeof(buf
));
253 write(output_fd
, buf
, len
);
257 static void msg_connecting(struct uclient
*cl
)
259 char addr
[INET6_ADDRSTRLEN
];
265 uclient_get_addr(addr
, &port
, &cl
->remote_addr
);
266 fprintf(stderr
, "Connecting to %s:%d\n", addr
, port
);
269 static void check_resume_offset(struct uclient
*cl
)
276 file
= uclient_get_url_filename(cl
->url
->location
, "index.html");
280 ret
= stat(file
, &st
);
288 snprintf(range_str
, sizeof(range_str
), "bytes=%"PRIu64
"-", (uint64_t) st
.st_size
);
289 uclient_http_set_header(cl
, "Range", range_str
);
292 static int init_request(struct uclient
*cl
)
299 uclient_http_set_ssl_ctx(cl
, ssl_ops
, ssl_ctx
, verify
);
302 cl
->timeout_msecs
= timeout
* 1000;
304 rc
= uclient_connect(cl
);
310 rc
= uclient_http_set_request_type(cl
, post_data
? "POST" : "GET");
314 uclient_http_reset_headers(cl
);
315 uclient_http_set_header(cl
, "User-Agent", user_agent
);
317 check_resume_offset(cl
);
320 uclient_http_set_header(cl
, "Content-Type", "application/x-www-form-urlencoded");
321 uclient_write(cl
, post_data
, strlen(post_data
));
324 rc
= uclient_request(cl
);
331 static void request_done(struct uclient
*cl
)
333 const char *proxy_url
;
336 proxy_url
= get_proxy_url(*urls
);
338 uclient_set_url(cl
, proxy_url
, NULL
);
339 uclient_set_proxy_url(cl
, *urls
, auth_str
);
341 uclient_set_url(cl
, *urls
, auth_str
);
345 error_ret
= init_request(cl
);
350 if (output_fd
>= 0 && !output_file
) {
354 uclient_disconnect(cl
);
359 static void eof_cb(struct uclient
*cl
)
362 pmt_update(&pmt_timer
);
363 uloop_timeout_cancel(&pmt_timer
);
364 fprintf(stderr
, "\n");
369 fprintf(stderr
, "Connection reset prematurely\n");
372 fprintf(stderr
, "Download completed (%"PRIu64
" bytes)\n", (uint64_t) out_bytes
);
377 static void handle_uclient_error(struct uclient
*cl
, int code
)
379 const char *type
= "Unknown error";
383 case UCLIENT_ERROR_CONNECT
:
384 type
= "Connection failed";
387 case UCLIENT_ERROR_TIMEDOUT
:
388 type
= "Connection timed out";
391 case UCLIENT_ERROR_SSL_INVALID_CERT
:
392 type
= "Invalid SSL certificate";
396 case UCLIENT_ERROR_SSL_CN_MISMATCH
:
397 type
= "Server hostname does not match SSL certificate";
407 fprintf(stderr
, "Connection error: %s%s\n", type
, ignore
? " (ignored)" : "");
415 static const struct uclient_cb cb
= {
416 .header_done
= header_done_cb
,
417 .data_read
= read_data_cb
,
419 .error
= handle_uclient_error
,
422 static int usage(const char *progname
)
425 "Usage: %s [options] <URL>\n"
427 " -q: Turn off status messages\n"
428 " -O <file>: Redirect output to file (use \"-\" for stdout)\n"
429 " -P <dir>: Set directory for output files\n"
430 " --user=<user> HTTP authentication username\n"
431 " --password=<password> HTTP authentication password\n"
432 " --user-agent|-U <str> Set HTTP user agent\n"
433 " --post-data=STRING use the POST method; send STRING as the data\n"
434 " --spider|-s Spider mode - only check file existence\n"
435 " --timeout=N|-T N Set connect/request timeout to N seconds\n"
436 " --proxy=on|off|-Y on|off Enable/disable env var configured proxy\n"
439 " --ca-certificate=<cert>: Load CA certificates from file <cert>\n"
440 " --no-check-certificate: don't validate the server's certificate\n"
445 static void init_ca_cert(void)
450 glob("/etc/ssl/certs/*.crt", 0, NULL
, &gl
);
451 for (i
= 0; i
< gl
.gl_pathc
; i
++)
452 ssl_ops
->context_add_ca_crt_file(ssl_ctx
, gl
.gl_pathv
[i
]);
455 static void init_ustream_ssl(void)
459 dlh
= dlopen("libustream-ssl." LIB_EXT
, RTLD_LAZY
| RTLD_LOCAL
);
463 ssl_ops
= dlsym(dlh
, "ustream_ssl_ops");
467 ssl_ctx
= ssl_ops
->context_new(false);
470 static int no_ssl(const char *progname
)
472 fprintf(stderr
, "%s: SSL support not available, please install ustream-ssl\n", progname
);
477 L_NO_CHECK_CERTIFICATE
,
490 static const struct option longopts
[] = {
491 [L_NO_CHECK_CERTIFICATE
] = { "no-check-certificate", no_argument
},
492 [L_CA_CERTIFICATE
] = { "ca-certificate", required_argument
},
493 [L_USER
] = { "user", required_argument
},
494 [L_PASSWORD
] = { "password", required_argument
},
495 [L_USER_AGENT
] = { "user-agent", required_argument
},
496 [L_POST_DATA
] = { "post-data", required_argument
},
497 [L_SPIDER
] = { "spider", no_argument
},
498 [L_TIMEOUT
] = { "timeout", required_argument
},
499 [L_CONTINUE
] = { "continue", no_argument
},
500 [L_PROXY
] = { "proxy", required_argument
},
501 [L_NO_PROXY
] = { "no-proxy", no_argument
},
507 int main(int argc
, char **argv
)
509 const char *progname
= argv
[0];
510 const char *proxy_url
;
511 char *username
= NULL
;
512 char *password
= NULL
;
515 bool has_cert
= false;
519 signal(SIGPIPE
, SIG_IGN
);
522 while ((ch
= getopt_long(argc
, argv
, "cO:P:qsU:Y:", longopts
, &longopt_idx
)) != -1) {
525 switch (longopt_idx
) {
526 case L_NO_CHECK_CERTIFICATE
:
529 case L_CA_CERTIFICATE
:
532 ssl_ops
->context_add_ca_crt_file(ssl_ctx
, optarg
);
537 username
= strdup(optarg
);
538 memset(optarg
, '*', strlen(optarg
));
543 password
= strdup(optarg
);
544 memset(optarg
, '*', strlen(optarg
));
556 timeout
= atoi(optarg
);
562 if (strcmp(optarg
, "on") != 0)
569 return usage(progname
);
579 output_file
= optarg
;
584 perror("Change output directory");
595 timeout
= atoi(optarg
);
598 if (strcmp(optarg
, "on") != 0)
602 return usage(progname
);
609 if (verify
&& !has_cert
)
610 default_certs
= true;
613 return usage(progname
);
616 for (i
= 0; i
< argc
; i
++) {
617 if (!strncmp(argv
[i
], "https", 5))
618 return no_ssl(progname
);
629 asprintf(&auth_str
, "%s:%s", username
, password
);
635 fprintf(stderr
, "Downloading '%s'\n", argv
[0]);
637 proxy_url
= get_proxy_url(argv
[0]);
639 cl
= uclient_new(proxy_url
, auth_str
, &cb
);
640 uclient_set_proxy_url(cl
, argv
[0], NULL
);
642 cl
= uclient_new(argv
[0], auth_str
, &cb
);
645 fprintf(stderr
, "Failed to allocate uclient context\n");
649 if (ssl_ctx
&& default_certs
)
653 rc
= init_request(cl
);
655 /* no error received, we can enter main loop */
658 fprintf(stderr
, "Failed to establish connection\n");
666 if (output_fd
>= 0 && output_fd
!= STDOUT_FILENO
)
670 ssl_ops
->context_free(ssl_ctx
);