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.
21 #include <sys/socket.h>
32 #include <libubox/blobmsg.h>
33 #include <libubox/list.h>
37 #include "uclient-utils.h"
40 #define strdupa(x) strcpy(alloca(strlen(x)+1),x)
44 struct list_head list
;
49 static const char *user_agent
= "uclient-fetch";
50 static const char *post_data
;
51 static const char *post_file
;
52 static struct ustream_ssl_ctx
*ssl_ctx
;
53 static const struct ustream_ssl_ops
*ssl_ops
;
54 static int quiet
= false;
55 static bool verify
= true;
56 static bool proxy
= true;
57 static bool default_certs
= false;
58 static bool no_output
;
59 static const char *opt_output_file
;
60 static int output_fd
= -1;
62 static off_t out_offset
;
63 static off_t out_bytes
;
65 static char *auth_str
;
69 static bool resume
, cur_resume
;
70 static LIST_HEAD(headers
);
72 static struct progress pmt
;
73 static struct uloop_timeout pmt_timer
;
75 static int init_request(struct uclient
*cl
);
76 static void request_done(struct uclient
*cl
);
78 static void pmt_update(struct uloop_timeout
*t
)
80 progress_update(&pmt
, out_offset
, out_bytes
, out_len
);
81 uloop_timeout_set(t
, 1000);
85 get_proxy_url(char *url
)
93 sep
= strchr(url
, ':');
100 memcpy(prefix
, url
, sep
- url
);
101 strcpy(prefix
+ (sep
- url
), "_proxy");
102 return getenv(prefix
);
105 static int open_output_file(const char *path
, uint64_t resume_offset
)
107 const char *output_file
= opt_output_file
;
108 char *filename
= NULL
;
115 flags
= O_WRONLY
| O_TRUNC
;
117 if (!cur_resume
&& !output_file
)
123 if (!strcmp(output_file
, "-")) {
125 fprintf(stderr
, "Writing to stdout\n");
131 filename
= uclient_get_url_filename(path
, "index.html");
137 output_file
= filename
;
141 fprintf(stderr
, "Writing to '%s'\n", output_file
);
142 ret
= open(output_file
, flags
, 0644);
147 lseek(ret
, resume_offset
, SEEK_SET
) < 0) {
149 fprintf(stderr
, "Failed to seek %"PRIu64
" bytes in output file\n", resume_offset
);
155 out_offset
= resume_offset
;
156 out_bytes
+= resume_offset
;
159 progress_init(&pmt
, output_file
);
160 pmt_timer
.cb
= pmt_update
;
161 pmt_timer
.cb(&pmt_timer
);
170 static void header_done_cb(struct uclient
*cl
)
177 static const struct blobmsg_policy policy
[__H_MAX
] = {
178 [H_RANGE
] = { .name
= "content-range", .type
= BLOBMSG_TYPE_STRING
},
179 [H_LEN
] = { .name
= "content-length", .type
= BLOBMSG_TYPE_STRING
},
181 struct blob_attr
*tb
[__H_MAX
];
182 uint64_t resume_offset
= 0, resume_end
, resume_size
;
186 int ret
= uclient_http_redirect(cl
);
189 fprintf(stderr
, "Failed to redirect to %s on %s\n", cl
->url
->location
, cl
->url
->host
);
196 fprintf(stderr
, "Redirected to %s on %s\n", cl
->url
->location
, cl
->url
->host
);
203 if (cl
->status_code
== 204 && cur_resume
) {
204 /* Resume attempt failed, try normal download */
210 blobmsg_parse(policy
, __H_MAX
, tb
, blob_data(cl
->meta
), blob_len(cl
->meta
));
212 switch (cl
->status_code
) {
215 fprintf(stderr
, "File download already fully retrieved; nothing to do.\n");
221 fprintf(stderr
, "Error: Partial content received, full content requested\n");
229 fprintf(stderr
, "Content-Range header is missing\n");
234 if (sscanf(blobmsg_get_string(tb
[H_RANGE
]),
235 "bytes %"PRIu64
"-%"PRIu64
"/%"PRIu64
,
236 &resume_offset
, &resume_end
, &resume_size
) != 3) {
238 fprintf(stderr
, "Content-Range header is invalid\n");
249 out_len
= strtoul(blobmsg_get_string(tb
[H_LEN
]), NULL
, 10);
251 output_fd
= open_output_file(cl
->url
->location
, resume_offset
);
254 perror("Cannot open output file");
262 fprintf(stderr
, "HTTP error %d\n", cl
->status_code
);
269 static void read_data_cb(struct uclient
*cl
)
275 if (!no_output
&& output_fd
< 0)
279 len
= uclient_read(cl
, buf
, sizeof(buf
));
285 n
= write(output_fd
, buf
, len
);
292 static void msg_connecting(struct uclient
*cl
)
294 char addr
[INET6_ADDRSTRLEN
];
300 uclient_get_addr(addr
, &port
, &cl
->remote_addr
);
301 fprintf(stderr
, "Connecting to %s:%d\n", addr
, port
);
304 static void check_resume_offset(struct uclient
*cl
)
311 file
= uclient_get_url_filename(cl
->url
->location
, "index.html");
315 ret
= stat(file
, &st
);
323 snprintf(range_str
, sizeof(range_str
), "bytes=%"PRIu64
"-", (uint64_t) st
.st_size
);
324 uclient_http_set_header(cl
, "Range", range_str
);
327 static int init_request(struct uclient
*cl
)
330 char *content_type
= "application/x-www-form-urlencoded";
336 uclient_http_set_ssl_ctx(cl
, ssl_ops
, ssl_ctx
, verify
);
339 cl
->timeout_msecs
= timeout
* 1000;
341 rc
= uclient_connect(cl
);
347 rc
= uclient_http_set_request_type(cl
, post_data
|| post_file
? "POST" : "GET");
351 uclient_http_reset_headers(cl
);
353 list_for_each_entry(h
, &headers
, list
) {
354 if (!strcasecmp(h
->name
, "Content-Type")) {
355 if (!post_data
&& !post_file
)
358 content_type
= h
->value
;
359 } else if (!strcasecmp(h
->name
, "User-Agent")) {
360 user_agent
= h
->value
;
362 uclient_http_set_header(cl
, h
->name
, h
->value
);
366 uclient_http_set_header(cl
, "User-Agent", user_agent
);
369 check_resume_offset(cl
);
372 uclient_http_set_header(cl
, "Content-Type", content_type
);
373 uclient_write(cl
, post_data
, strlen(post_data
));
378 uclient_http_set_header(cl
, "Content-Type", content_type
);
380 input_file
= fopen(post_file
, "r");
388 rlen
= fread(tbuf
, 1, sizeof(tbuf
), input_file
);
389 uclient_write(cl
, tbuf
, rlen
);
396 rc
= uclient_request(cl
);
403 static void request_done(struct uclient
*cl
)
405 const char *proxy_url
;
408 proxy_url
= get_proxy_url(*urls
);
410 uclient_set_url(cl
, proxy_url
, NULL
);
411 uclient_set_proxy_url(cl
, *urls
, auth_str
);
413 uclient_set_url(cl
, *urls
, auth_str
);
417 error_ret
= init_request(cl
);
422 if (output_fd
>= 0 && !opt_output_file
) {
426 uclient_disconnect(cl
);
431 static void eof_cb(struct uclient
*cl
)
434 pmt_update(&pmt_timer
);
435 uloop_timeout_cancel(&pmt_timer
);
436 fprintf(stderr
, "\n");
441 fprintf(stderr
, "Connection reset prematurely\n");
444 fprintf(stderr
, "Download completed (%"PRIu64
" bytes)\n", (uint64_t) out_bytes
);
450 handle_uclient_log_msg(struct uclient
*cl
, enum uclient_log_type type
, const char *msg
)
452 static const char * const type_str_list
[] = {
453 [UCLIENT_LOG_SSL_ERROR
] = "SSL error",
454 [UCLIENT_LOG_SSL_VERIFY_ERROR
] = "SSL verify error",
456 const char *type_str
= NULL
;
458 if (type
< ARRAY_SIZE(type_str_list
))
459 type_str
= type_str_list
[type
];
461 type_str
= "Unknown";
463 fprintf(stderr
, "%s: %s\n", type_str
, msg
);
466 static void handle_uclient_error(struct uclient
*cl
, int code
)
468 const char *type
= "Unknown error";
472 case UCLIENT_ERROR_CONNECT
:
473 type
= "Connection failed";
476 case UCLIENT_ERROR_TIMEDOUT
:
477 type
= "Connection timed out";
480 case UCLIENT_ERROR_SSL_INVALID_CERT
:
481 type
= "Invalid SSL certificate";
485 case UCLIENT_ERROR_SSL_CN_MISMATCH
:
486 type
= "Server hostname does not match SSL certificate";
496 fprintf(stderr
, "Connection error: %s%s\n", type
, ignore
? " (ignored)" : "");
504 static const struct uclient_cb cb
= {
505 .header_done
= header_done_cb
,
506 .data_read
= read_data_cb
,
508 .error
= handle_uclient_error
,
509 .log_msg
= handle_uclient_log_msg
,
512 static void usage(const char *progname
)
515 "Usage: %s [options] <URL>\n"
517 " -4 Use IPv4 only\n"
518 " -6 Use IPv6 only\n"
519 " -O <file> Redirect output to file (use \"-\" for stdout)\n"
520 " -P <dir> Set directory for output files\n"
521 " --quiet | -q Turn off status messages\n"
522 " --continue | -c Continue a partially-downloaded file\n"
523 " --header='Header: value' Add HTTP header. Multiple allowed\n"
524 " --user=<user> HTTP authentication username\n"
525 " --password=<password> HTTP authentication password\n"
526 " --user-agent | -U <str> Set HTTP user agent\n"
527 " --post-data=STRING use the POST method; send STRING as the data\n"
528 " --post-file=FILE use the POST method; send FILE as the data\n"
529 " --spider | -s Spider mode - only check file existence\n"
530 " --timeout=N | -T N Set connect/request timeout to N seconds\n"
531 " --proxy=on | -Y on Enable interpretation of proxy env vars (default)\n"
532 " --proxy=off | -Y off |\n"
533 " --no-proxy Disable interpretation of proxy env vars\n"
536 " --ca-certificate=<cert> Load CA certificates from file <cert>\n"
537 " --no-check-certificate don't validate the server's certificate\n"
538 " --ciphers=<cipherlist> Set the cipher list string\n"
543 static void init_ca_cert(void)
548 glob("/etc/ssl/certs/*.crt", 0, NULL
, &gl
);
549 for (i
= 0; i
< gl
.gl_pathc
; i
++)
550 ssl_ops
->context_add_ca_crt_file(ssl_ctx
, gl
.gl_pathv
[i
]);
554 static void no_ssl(const char *progname
)
557 "%s: SSL support not available, please install one of the "
558 "libustream-.*[ssl|tls] packages as well as the ca-bundle and "
559 "ca-certificates packages.\n",
564 static void debug_cb(void *priv
, int level
, const char *msg
)
566 fprintf(stderr
, "%s\n", msg
);
569 static bool is_valid_header(char *str
)
573 /* First character must be a letter */
577 /* Subsequent characters must be letters, numbers or dashes */
578 while (*(++tmp
) != '\0') {
579 if (!isalnum(*tmp
) && *tmp
!= '-')
587 L_NO_CHECK_CERTIFICATE
,
605 static const struct option longopts
[] = {
606 [L_NO_CHECK_CERTIFICATE
] = { "no-check-certificate", no_argument
, NULL
, 0 },
607 [L_CA_CERTIFICATE
] = { "ca-certificate", required_argument
, NULL
, 0 },
608 [L_CIPHERS
] = { "ciphers", required_argument
, NULL
, 0 },
609 [L_USER
] = { "user", required_argument
, NULL
, 0 },
610 [L_PASSWORD
] = { "password", required_argument
, NULL
, 0 },
611 [L_USER_AGENT
] = { "user-agent", required_argument
, NULL
, 0 },
612 [L_POST_DATA
] = { "post-data", required_argument
, NULL
, 0 },
613 [L_POST_FILE
] = { "post-file", required_argument
, NULL
, 0 },
614 [L_SPIDER
] = { "spider", no_argument
, NULL
, 0 },
615 [L_TIMEOUT
] = { "timeout", required_argument
, NULL
, 0 },
616 [L_CONTINUE
] = { "continue", no_argument
, NULL
, 0 },
617 [L_PROXY
] = { "proxy", required_argument
, NULL
, 0 },
618 [L_NO_PROXY
] = { "no-proxy", no_argument
, NULL
, 0 },
619 [L_QUIET
] = { "quiet", no_argument
, NULL
, 0 },
620 [L_VERBOSE
] = { "verbose", no_argument
, NULL
, 0 },
621 [L_HEADER
] = { "header", required_argument
, NULL
, 0 },
627 int main(int argc
, char **argv
)
629 const char *progname
= argv
[0];
630 const char *proxy_url
;
631 char *username
= NULL
;
632 char *password
= NULL
;
633 struct uclient
*cl
= NULL
;
635 bool has_cert
= false;
636 struct header
*h
, *th
;
643 signal(SIGPIPE
, SIG_IGN
);
644 ssl_ctx
= uclient_new_ssl_context(&ssl_ops
);
646 while ((ch
= getopt_long(argc
, argv
, "46cO:P:qsT:U:vY:", longopts
, &longopt_idx
)) != -1) {
649 switch (longopt_idx
) {
650 case L_NO_CHECK_CERTIFICATE
:
653 ssl_ops
->context_set_require_validation(ssl_ctx
, verify
);
655 case L_CA_CERTIFICATE
:
658 ssl_ops
->context_add_ca_crt_file(ssl_ctx
, optarg
);
662 if (ssl_ops
->context_set_ciphers(ssl_ctx
, optarg
)) {
664 fprintf(stderr
, "No recognized ciphers in cipher list\n");
672 username
= strdupa(optarg
);
673 memset(optarg
, '*', strlen(optarg
));
678 password
= strdupa(optarg
);
679 memset(optarg
, '*', strlen(optarg
));
694 timeout
= atoi(optarg
);
700 if (strcmp(optarg
, "on") != 0)
713 tmp
= strchr(optarg
, ':');
719 while (isspace(*tmp
))
722 if (*tmp
== '\0' || !is_valid_header(optarg
) || strchr(tmp
, '\n')) {
726 h
= malloc(sizeof(*h
));
728 perror("Set HTTP header");
734 list_add_tail(&h
->list
, &headers
);
754 opt_output_file
= optarg
;
759 perror("Change output directory");
771 timeout
= atoi(optarg
);
777 if (strcmp(optarg
, "on") != 0)
790 ssl_ops
->context_set_debug(ssl_ctx
, debug_level
, debug_cb
, NULL
);
792 if (verify
&& !has_cert
)
793 default_certs
= true;
801 for (i
= 0; i
< argc
; i
++) {
802 if (!strncmp(argv
[i
], "https", 5)) {
816 rc
= asprintf(&auth_str
, "%s:%s", username
, password
);
826 fprintf(stderr
, "Downloading '%s'\n", argv
[0]);
828 proxy_url
= get_proxy_url(argv
[0]);
830 cl
= uclient_new(proxy_url
, auth_str
, &cb
);
832 uclient_set_proxy_url(cl
, argv
[0], NULL
);
834 cl
= uclient_new(argv
[0], auth_str
, &cb
);
837 fprintf(stderr
, "Failed to allocate uclient context\n");
842 uclient_http_set_address_family(cl
, af
);
844 if (ssl_ctx
&& default_certs
)
848 rc
= init_request(cl
);
850 /* no error received, we can enter main loop */
853 fprintf(stderr
, "Failed to send request: %s\n", strerror(rc
));
864 if (output_fd
>= 0 && output_fd
!= STDOUT_FILENO
)
868 ssl_ops
->context_free(ssl_ctx
);
870 list_for_each_entry_safe(h
, th
, &headers
, list
) {