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>
36 #include "uclient-utils.h"
39 #define LIB_EXT "dylib"
44 static const char *user_agent
= "uclient-fetch";
45 static const char *post_data
;
46 static const char *post_file
;
47 static struct ustream_ssl_ctx
*ssl_ctx
;
48 static const struct ustream_ssl_ops
*ssl_ops
;
49 static int quiet
= false;
50 static bool verify
= true;
51 static bool proxy
= true;
52 static bool default_certs
= false;
53 static bool no_output
;
54 static const char *opt_output_file
;
55 static int output_fd
= -1;
57 static off_t out_offset
;
58 static off_t out_bytes
;
60 static char *auth_str
;
64 static bool resume
, cur_resume
;
66 static struct progress pmt
;
67 static struct uloop_timeout pmt_timer
;
69 static int init_request(struct uclient
*cl
);
70 static void request_done(struct uclient
*cl
);
72 static void pmt_update(struct uloop_timeout
*t
)
74 progress_update(&pmt
, out_offset
, out_bytes
, out_len
);
75 uloop_timeout_set(t
, 1000);
79 get_proxy_url(char *url
)
87 sep
= strchr(url
, ':');
94 memcpy(prefix
, url
, sep
- url
);
95 strcpy(prefix
+ (sep
- url
), "_proxy");
96 return getenv(prefix
);
99 static int open_output_file(const char *path
, uint64_t resume_offset
)
101 const char *output_file
= opt_output_file
;
102 char *filename
= NULL
;
109 flags
= O_WRONLY
| O_TRUNC
;
111 if (!cur_resume
&& !output_file
)
117 if (!strcmp(output_file
, "-")) {
119 fprintf(stderr
, "Writing to stdout\n");
125 filename
= uclient_get_url_filename(path
, "index.html");
131 output_file
= filename
;
135 fprintf(stderr
, "Writing to '%s'\n", output_file
);
136 ret
= open(output_file
, flags
, 0644);
141 lseek(ret
, resume_offset
, SEEK_SET
) < 0) {
143 fprintf(stderr
, "Failed to seek %"PRIu64
" bytes in output file\n", resume_offset
);
149 out_offset
= resume_offset
;
150 out_bytes
+= resume_offset
;
153 progress_init(&pmt
, output_file
);
154 pmt_timer
.cb
= pmt_update
;
155 pmt_timer
.cb(&pmt_timer
);
164 static void header_done_cb(struct uclient
*cl
)
171 static const struct blobmsg_policy policy
[__H_MAX
] = {
172 [H_RANGE
] = { .name
= "content-range", .type
= BLOBMSG_TYPE_STRING
},
173 [H_LEN
] = { .name
= "content-length", .type
= BLOBMSG_TYPE_STRING
},
175 struct blob_attr
*tb
[__H_MAX
];
176 uint64_t resume_offset
= 0, resume_end
, resume_size
;
180 int ret
= uclient_http_redirect(cl
);
183 fprintf(stderr
, "Failed to redirect to %s on %s\n", cl
->url
->location
, cl
->url
->host
);
190 fprintf(stderr
, "Redirected to %s on %s\n", cl
->url
->location
, cl
->url
->host
);
197 if (cl
->status_code
== 204 && cur_resume
) {
198 /* Resume attempt failed, try normal download */
204 blobmsg_parse(policy
, __H_MAX
, tb
, blob_data(cl
->meta
), blob_len(cl
->meta
));
206 switch (cl
->status_code
) {
209 fprintf(stderr
, "File download already fully retrieved; nothing to do.\n");
215 fprintf(stderr
, "Error: Partial content received, full content requested\n");
223 fprintf(stderr
, "Content-Range header is missing\n");
228 if (sscanf(blobmsg_get_string(tb
[H_RANGE
]),
229 "bytes %"PRIu64
"-%"PRIu64
"/%"PRIu64
,
230 &resume_offset
, &resume_end
, &resume_size
) != 3) {
232 fprintf(stderr
, "Content-Range header is invalid\n");
243 out_len
= strtoul(blobmsg_get_string(tb
[H_LEN
]), NULL
, 10);
245 output_fd
= open_output_file(cl
->url
->location
, resume_offset
);
248 perror("Cannot open output file");
256 fprintf(stderr
, "HTTP error %d\n", cl
->status_code
);
263 static void read_data_cb(struct uclient
*cl
)
269 if (!no_output
&& output_fd
< 0)
273 len
= uclient_read(cl
, buf
, sizeof(buf
));
279 n
= write(output_fd
, buf
, len
);
286 static void msg_connecting(struct uclient
*cl
)
288 char addr
[INET6_ADDRSTRLEN
];
294 uclient_get_addr(addr
, &port
, &cl
->remote_addr
);
295 fprintf(stderr
, "Connecting to %s:%d\n", addr
, port
);
298 static void check_resume_offset(struct uclient
*cl
)
305 file
= uclient_get_url_filename(cl
->url
->location
, "index.html");
309 ret
= stat(file
, &st
);
317 snprintf(range_str
, sizeof(range_str
), "bytes=%"PRIu64
"-", (uint64_t) st
.st_size
);
318 uclient_http_set_header(cl
, "Range", range_str
);
321 static int init_request(struct uclient
*cl
)
328 uclient_http_set_ssl_ctx(cl
, ssl_ops
, ssl_ctx
, verify
);
331 cl
->timeout_msecs
= timeout
* 1000;
333 rc
= uclient_connect(cl
);
339 rc
= uclient_http_set_request_type(cl
, post_data
|| post_file
? "POST" : "GET");
343 uclient_http_reset_headers(cl
);
344 uclient_http_set_header(cl
, "User-Agent", user_agent
);
346 check_resume_offset(cl
);
349 uclient_http_set_header(cl
, "Content-Type", "application/x-www-form-urlencoded");
350 uclient_write(cl
, post_data
, strlen(post_data
));
355 uclient_http_set_header(cl
, "Content-Type", "application/x-www-form-urlencoded");
357 input_file
= fopen(post_file
, "r");
365 rlen
= fread(tbuf
, 1, sizeof(tbuf
), input_file
);
366 uclient_write(cl
, tbuf
, rlen
);
373 rc
= uclient_request(cl
);
380 static void request_done(struct uclient
*cl
)
382 const char *proxy_url
;
385 proxy_url
= get_proxy_url(*urls
);
387 uclient_set_url(cl
, proxy_url
, NULL
);
388 uclient_set_proxy_url(cl
, *urls
, auth_str
);
390 uclient_set_url(cl
, *urls
, auth_str
);
394 error_ret
= init_request(cl
);
399 if (output_fd
>= 0 && !opt_output_file
) {
403 uclient_disconnect(cl
);
408 static void eof_cb(struct uclient
*cl
)
411 pmt_update(&pmt_timer
);
412 uloop_timeout_cancel(&pmt_timer
);
413 fprintf(stderr
, "\n");
418 fprintf(stderr
, "Connection reset prematurely\n");
421 fprintf(stderr
, "Download completed (%"PRIu64
" bytes)\n", (uint64_t) out_bytes
);
426 static void handle_uclient_error(struct uclient
*cl
, int code
)
428 const char *type
= "Unknown error";
432 case UCLIENT_ERROR_CONNECT
:
433 type
= "Connection failed";
436 case UCLIENT_ERROR_TIMEDOUT
:
437 type
= "Connection timed out";
440 case UCLIENT_ERROR_SSL_INVALID_CERT
:
441 type
= "Invalid SSL certificate";
445 case UCLIENT_ERROR_SSL_CN_MISMATCH
:
446 type
= "Server hostname does not match SSL certificate";
456 fprintf(stderr
, "Connection error: %s%s\n", type
, ignore
? " (ignored)" : "");
464 static const struct uclient_cb cb
= {
465 .header_done
= header_done_cb
,
466 .data_read
= read_data_cb
,
468 .error
= handle_uclient_error
,
471 static int usage(const char *progname
)
474 "Usage: %s [options] <URL>\n"
476 " -4 Use IPv4 only\n"
477 " -6 Use IPv6 only\n"
478 " -q Turn off status messages\n"
479 " -O <file> Redirect output to file (use \"-\" for stdout)\n"
480 " -P <dir> Set directory for output files\n"
481 " --user=<user> HTTP authentication username\n"
482 " --password=<password> HTTP authentication password\n"
483 " --user-agent|-U <str> Set HTTP user agent\n"
484 " --post-data=STRING use the POST method; send STRING as the data\n"
485 " --post-file=FILE use the POST method; send FILE as the data\n"
486 " --spider|-s Spider mode - only check file existence\n"
487 " --timeout=N|-T N Set connect/request timeout to N seconds\n"
488 " --proxy=on|off|-Y on|off Enable/disable env var configured proxy\n"
491 " --ca-certificate=<cert> Load CA certificates from file <cert>\n"
492 " --no-check-certificate don't validate the server's certificate\n"
493 " --ciphers=<cipherlist> Set the cipher list string\n"
498 static void init_ca_cert(void)
503 glob("/etc/ssl/certs/*.crt", 0, NULL
, &gl
);
504 for (i
= 0; i
< gl
.gl_pathc
; i
++)
505 ssl_ops
->context_add_ca_crt_file(ssl_ctx
, gl
.gl_pathv
[i
]);
508 static void init_ustream_ssl(void)
512 dlh
= dlopen("libustream-ssl." LIB_EXT
, RTLD_LAZY
| RTLD_LOCAL
);
516 ssl_ops
= dlsym(dlh
, "ustream_ssl_ops");
520 ssl_ctx
= ssl_ops
->context_new(false);
523 static int no_ssl(const char *progname
)
526 "%s: SSL support not available, please install one of the "
527 "libustream-.*[ssl|tls] packages as well as the ca-bundle and "
528 "ca-certificates packages.\n",
535 L_NO_CHECK_CERTIFICATE
,
551 static const struct option longopts
[] = {
552 [L_NO_CHECK_CERTIFICATE
] = { "no-check-certificate", no_argument
, NULL
, 0 },
553 [L_CA_CERTIFICATE
] = { "ca-certificate", required_argument
, NULL
, 0 },
554 [L_CIPHERS
] = { "ciphers", required_argument
, NULL
, 0 },
555 [L_USER
] = { "user", required_argument
, NULL
, 0 },
556 [L_PASSWORD
] = { "password", required_argument
, NULL
, 0 },
557 [L_USER_AGENT
] = { "user-agent", required_argument
, NULL
, 0 },
558 [L_POST_DATA
] = { "post-data", required_argument
, NULL
, 0 },
559 [L_POST_FILE
] = { "post-file", required_argument
, NULL
, 0 },
560 [L_SPIDER
] = { "spider", no_argument
, NULL
, 0 },
561 [L_TIMEOUT
] = { "timeout", required_argument
, NULL
, 0 },
562 [L_CONTINUE
] = { "continue", no_argument
, NULL
, 0 },
563 [L_PROXY
] = { "proxy", required_argument
, NULL
, 0 },
564 [L_NO_PROXY
] = { "no-proxy", no_argument
, NULL
, 0 },
565 [L_QUIET
] = { "quiet", no_argument
, NULL
, 0 },
571 int main(int argc
, char **argv
)
573 const char *progname
= argv
[0];
574 const char *proxy_url
;
575 char *username
= NULL
;
576 char *password
= NULL
;
579 bool has_cert
= false;
584 signal(SIGPIPE
, SIG_IGN
);
587 while ((ch
= getopt_long(argc
, argv
, "46cO:P:qsT:U:Y:", longopts
, &longopt_idx
)) != -1) {
590 switch (longopt_idx
) {
591 case L_NO_CHECK_CERTIFICATE
:
594 case L_CA_CERTIFICATE
:
597 ssl_ops
->context_add_ca_crt_file(ssl_ctx
, optarg
);
601 if (ssl_ops
->context_set_ciphers(ssl_ctx
, optarg
)) {
603 fprintf(stderr
, "No recognized ciphers in cipher list\n");
611 username
= strdupa(optarg
);
612 memset(optarg
, '*', strlen(optarg
));
617 password
= strdupa(optarg
);
618 memset(optarg
, '*', strlen(optarg
));
633 timeout
= atoi(optarg
);
639 if (strcmp(optarg
, "on") != 0)
649 return usage(progname
);
665 opt_output_file
= optarg
;
670 perror("Change output directory");
681 timeout
= atoi(optarg
);
684 if (strcmp(optarg
, "on") != 0)
688 return usage(progname
);
695 if (verify
&& !has_cert
)
696 default_certs
= true;
699 return usage(progname
);
702 for (i
= 0; i
< argc
; i
++) {
703 if (!strncmp(argv
[i
], "https", 5))
704 return no_ssl(progname
);
715 rc
= asprintf(&auth_str
, "%s:%s", username
, password
);
723 fprintf(stderr
, "Downloading '%s'\n", argv
[0]);
725 proxy_url
= get_proxy_url(argv
[0]);
727 cl
= uclient_new(proxy_url
, auth_str
, &cb
);
729 uclient_set_proxy_url(cl
, argv
[0], NULL
);
731 cl
= uclient_new(argv
[0], auth_str
, &cb
);
734 fprintf(stderr
, "Failed to allocate uclient context\n");
738 uclient_http_set_address_family(cl
, af
);
740 if (ssl_ctx
&& default_certs
)
744 rc
= init_request(cl
);
746 /* no error received, we can enter main loop */
749 fprintf(stderr
, "Failed to send request: %s\n", strerror(rc
));
757 if (output_fd
>= 0 && output_fd
!= STDOUT_FILENO
)
761 ssl_ops
->context_free(ssl_ctx
);