uclient-fetch: fix short command line option for timeout
[project/uclient.git] / uclient-fetch.c
1 /*
2 * uclient - ustream based protocol client library
3 *
4 * Copyright (C) 2014 Felix Fietkau <nbd@openwrt.org>
5 *
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.
9 *
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.
17 */
18
19 #define _GNU_SOURCE
20 #include <sys/stat.h>
21 #include <unistd.h>
22 #include <stdio.h>
23 #include <dlfcn.h>
24 #include <getopt.h>
25 #include <fcntl.h>
26 #include <glob.h>
27 #include <stdint.h>
28 #include <inttypes.h>
29 #include <signal.h>
30
31 #include <libubox/blobmsg.h>
32
33 #include "progress.h"
34 #include "uclient.h"
35 #include "uclient-utils.h"
36
37 #ifdef __APPLE__
38 #define LIB_EXT "dylib"
39 #else
40 #define LIB_EXT "so"
41 #endif
42
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;
54 static int error_ret;
55 static off_t out_offset;
56 static off_t out_bytes;
57 static off_t out_len;
58 static char *auth_str;
59 static char **urls;
60 static int n_urls;
61 static int timeout;
62 static bool resume, cur_resume;
63
64 static struct progress pmt;
65 static struct uloop_timeout pmt_timer;
66
67 static int init_request(struct uclient *cl);
68 static void request_done(struct uclient *cl);
69
70 static void pmt_update(struct uloop_timeout *t)
71 {
72 progress_update(&pmt, out_offset, out_bytes, out_len);
73 uloop_timeout_set(t, 1000);
74 }
75
76 static const char *
77 get_proxy_url(char *url)
78 {
79 char prefix[16];
80 char *sep;
81
82 if (!proxy)
83 return NULL;
84
85 sep = strchr(url, ':');
86 if (!sep)
87 return NULL;
88
89 if (sep - url > 5)
90 return NULL;
91
92 memcpy(prefix, url, sep - url);
93 strcpy(prefix + (sep - url), "_proxy");
94 return getenv(prefix);
95 }
96
97 static int open_output_file(const char *path, uint64_t resume_offset)
98 {
99 char *filename = NULL;
100 int flags;
101 int ret;
102
103 if (cur_resume)
104 flags = O_RDWR;
105 else
106 flags = O_WRONLY | O_EXCL;
107
108 flags |= O_CREAT;
109
110 if (output_file) {
111 if (!strcmp(output_file, "-")) {
112 if (!quiet)
113 fprintf(stderr, "Writing to stdout\n");
114
115 return STDOUT_FILENO;
116 }
117 } else {
118 filename = uclient_get_url_filename(path, "index.html");
119 output_file = filename;
120 }
121
122 if (!quiet)
123 fprintf(stderr, "Writing to '%s'\n", output_file);
124 ret = open(output_file, flags, 0644);
125 if (ret < 0)
126 goto free;
127
128 if (resume_offset &&
129 lseek(ret, resume_offset, SEEK_SET) < 0) {
130 if (!quiet)
131 fprintf(stderr, "Failed to seek %"PRIu64" bytes in output file\n", resume_offset);
132 close(ret);
133 ret = -1;
134 goto free;
135 }
136
137 out_offset = resume_offset;
138 out_bytes += resume_offset;
139 if (!quiet) {
140 progress_init(&pmt, output_file);
141 pmt_timer.cb = pmt_update;
142 pmt_timer.cb(&pmt_timer);
143 }
144
145 free:
146 free(filename);
147 return ret;
148 }
149
150 static void header_done_cb(struct uclient *cl)
151 {
152 enum {
153 H_RANGE,
154 H_LEN,
155 __H_MAX
156 };
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 },
160 };
161 struct blob_attr *tb[__H_MAX];
162 uint64_t resume_offset = 0, resume_end, resume_size;
163 static int retries;
164
165 if (retries < 10 && uclient_http_redirect(cl)) {
166 if (!quiet)
167 fprintf(stderr, "Redirected to %s on %s\n", cl->url->location, cl->url->host);
168
169 retries++;
170 return;
171 }
172
173 if (cl->status_code == 204 && cur_resume) {
174 /* Resume attempt failed, try normal download */
175 cur_resume = false;
176 init_request(cl);
177 return;
178 }
179
180 blobmsg_parse(policy, __H_MAX, tb, blob_data(cl->meta), blob_len(cl->meta));
181
182 switch (cl->status_code) {
183 case 416:
184 if (!quiet)
185 fprintf(stderr, "File download already fully retrieved; nothing to do.\n");
186 request_done(cl);
187 break;
188 case 206:
189 if (!cur_resume) {
190 if (!quiet)
191 fprintf(stderr, "Error: Partial content received, full content requested\n");
192 error_ret = 8;
193 request_done(cl);
194 break;
195 }
196
197 if (!tb[H_RANGE]) {
198 if (!quiet)
199 fprintf(stderr, "Content-Range header is missing\n");
200 error_ret = 8;
201 break;
202 }
203
204 if (sscanf(blobmsg_get_string(tb[H_RANGE]),
205 "bytes %"PRIu64"-%"PRIu64"/%"PRIu64,
206 &resume_offset, &resume_end, &resume_size) != 3) {
207 if (!quiet)
208 fprintf(stderr, "Content-Range header is invalid\n");
209 error_ret = 8;
210 break;
211 }
212 case 204:
213 case 200:
214 if (no_output)
215 break;
216
217 if (tb[H_LEN])
218 out_len = strtoul(blobmsg_get_string(tb[H_LEN]), NULL, 10);
219
220 output_fd = open_output_file(cl->url->location, resume_offset);
221 if (output_fd < 0) {
222 if (!quiet)
223 perror("Cannot open output file");
224 error_ret = 3;
225 request_done(cl);
226 }
227 break;
228
229 default:
230 if (!quiet)
231 fprintf(stderr, "HTTP error %d\n", cl->status_code);
232 request_done(cl);
233 error_ret = 8;
234 break;
235 }
236 }
237
238 static void read_data_cb(struct uclient *cl)
239 {
240 char buf[256];
241 int len;
242
243 if (!no_output && output_fd < 0)
244 return;
245
246 while (1) {
247 len = uclient_read(cl, buf, sizeof(buf));
248 if (!len)
249 return;
250
251 out_bytes += len;
252 if (!no_output)
253 write(output_fd, buf, len);
254 }
255 }
256
257 static void msg_connecting(struct uclient *cl)
258 {
259 char addr[INET6_ADDRSTRLEN];
260 int port;
261
262 if (quiet)
263 return;
264
265 uclient_get_addr(addr, &port, &cl->remote_addr);
266 fprintf(stderr, "Connecting to %s:%d\n", addr, port);
267 }
268
269 static void check_resume_offset(struct uclient *cl)
270 {
271 char range_str[64];
272 struct stat st;
273 char *file;
274 int ret;
275
276 file = uclient_get_url_filename(cl->url->location, "index.html");
277 if (!file)
278 return;
279
280 ret = stat(file, &st);
281 free(file);
282 if (ret)
283 return;
284
285 if (!st.st_size)
286 return;
287
288 snprintf(range_str, sizeof(range_str), "bytes=%"PRIu64"-", (uint64_t) st.st_size);
289 uclient_http_set_header(cl, "Range", range_str);
290 }
291
292 static int init_request(struct uclient *cl)
293 {
294 int rc;
295
296 out_offset = 0;
297 out_bytes = 0;
298 out_len = 0;
299 uclient_http_set_ssl_ctx(cl, ssl_ops, ssl_ctx, verify);
300
301 if (timeout)
302 cl->timeout_msecs = timeout * 1000;
303
304 rc = uclient_connect(cl);
305 if (rc)
306 return rc;
307
308 msg_connecting(cl);
309
310 rc = uclient_http_set_request_type(cl, post_data ? "POST" : "GET");
311 if (rc)
312 return rc;
313
314 uclient_http_reset_headers(cl);
315 uclient_http_set_header(cl, "User-Agent", user_agent);
316 if (cur_resume)
317 check_resume_offset(cl);
318
319 if (post_data) {
320 uclient_http_set_header(cl, "Content-Type", "application/x-www-form-urlencoded");
321 uclient_write(cl, post_data, strlen(post_data));
322 }
323
324 rc = uclient_request(cl);
325 if (rc)
326 return rc;
327
328 return 0;
329 }
330
331 static void request_done(struct uclient *cl)
332 {
333 const char *proxy_url;
334
335 if (n_urls) {
336 proxy_url = get_proxy_url(*urls);
337 if (proxy_url) {
338 uclient_set_url(cl, proxy_url, NULL);
339 uclient_set_proxy_url(cl, *urls, auth_str);
340 } else {
341 uclient_set_url(cl, *urls, auth_str);
342 }
343 n_urls--;
344 cur_resume = resume;
345 error_ret = init_request(cl);
346 if (error_ret == 0)
347 return;
348 }
349
350 if (output_fd >= 0 && !output_file) {
351 close(output_fd);
352 output_fd = -1;
353 }
354 uclient_disconnect(cl);
355 uloop_end();
356 }
357
358
359 static void eof_cb(struct uclient *cl)
360 {
361 if (!quiet) {
362 pmt_update(&pmt_timer);
363 uloop_timeout_cancel(&pmt_timer);
364 fprintf(stderr, "\n");
365 }
366
367 if (!cl->data_eof) {
368 if (!quiet)
369 fprintf(stderr, "Connection reset prematurely\n");
370 error_ret = 4;
371 } else if (!quiet) {
372 fprintf(stderr, "Download completed (%"PRIu64" bytes)\n", (uint64_t) out_bytes);
373 }
374 request_done(cl);
375 }
376
377 static void handle_uclient_error(struct uclient *cl, int code)
378 {
379 const char *type = "Unknown error";
380 bool ignore = false;
381
382 switch(code) {
383 case UCLIENT_ERROR_CONNECT:
384 type = "Connection failed";
385 error_ret = 4;
386 break;
387 case UCLIENT_ERROR_TIMEDOUT:
388 type = "Connection timed out";
389 error_ret = 4;
390 break;
391 case UCLIENT_ERROR_SSL_INVALID_CERT:
392 type = "Invalid SSL certificate";
393 ignore = !verify;
394 error_ret = 5;
395 break;
396 case UCLIENT_ERROR_SSL_CN_MISMATCH:
397 type = "Server hostname does not match SSL certificate";
398 ignore = !verify;
399 error_ret = 5;
400 break;
401 default:
402 error_ret = 1;
403 break;
404 }
405
406 if (!quiet)
407 fprintf(stderr, "Connection error: %s%s\n", type, ignore ? " (ignored)" : "");
408
409 if (ignore)
410 error_ret = 0;
411 else
412 request_done(cl);
413 }
414
415 static const struct uclient_cb cb = {
416 .header_done = header_done_cb,
417 .data_read = read_data_cb,
418 .data_eof = eof_cb,
419 .error = handle_uclient_error,
420 };
421
422 static int usage(const char *progname)
423 {
424 fprintf(stderr,
425 "Usage: %s [options] <URL>\n"
426 "Options:\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"
437 "\n"
438 "HTTPS options:\n"
439 " --ca-certificate=<cert>: Load CA certificates from file <cert>\n"
440 " --no-check-certificate: don't validate the server's certificate\n"
441 "\n", progname);
442 return 1;
443 }
444
445 static void init_ca_cert(void)
446 {
447 glob_t gl;
448 int i;
449
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]);
453 }
454
455 static void init_ustream_ssl(void)
456 {
457 void *dlh;
458
459 dlh = dlopen("libustream-ssl." LIB_EXT, RTLD_LAZY | RTLD_LOCAL);
460 if (!dlh)
461 return;
462
463 ssl_ops = dlsym(dlh, "ustream_ssl_ops");
464 if (!ssl_ops)
465 return;
466
467 ssl_ctx = ssl_ops->context_new(false);
468 }
469
470 static int no_ssl(const char *progname)
471 {
472 fprintf(stderr, "%s: SSL support not available, please install ustream-ssl\n", progname);
473 return 1;
474 }
475
476 enum {
477 L_NO_CHECK_CERTIFICATE,
478 L_CA_CERTIFICATE,
479 L_USER,
480 L_PASSWORD,
481 L_USER_AGENT,
482 L_POST_DATA,
483 L_SPIDER,
484 L_TIMEOUT,
485 L_CONTINUE,
486 L_PROXY,
487 L_NO_PROXY,
488 };
489
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 },
502 {}
503 };
504
505
506
507 int main(int argc, char **argv)
508 {
509 const char *progname = argv[0];
510 const char *proxy_url;
511 char *username = NULL;
512 char *password = NULL;
513 struct uclient *cl;
514 int longopt_idx = 0;
515 bool has_cert = false;
516 int i, ch;
517 int rc;
518
519 signal(SIGPIPE, SIG_IGN);
520 init_ustream_ssl();
521
522 while ((ch = getopt_long(argc, argv, "cO:P:qsT:U:Y:", longopts, &longopt_idx)) != -1) {
523 switch(ch) {
524 case 0:
525 switch (longopt_idx) {
526 case L_NO_CHECK_CERTIFICATE:
527 verify = false;
528 break;
529 case L_CA_CERTIFICATE:
530 has_cert = true;
531 if (ssl_ctx)
532 ssl_ops->context_add_ca_crt_file(ssl_ctx, optarg);
533 break;
534 case L_USER:
535 if (!strlen(optarg))
536 break;
537 username = strdup(optarg);
538 memset(optarg, '*', strlen(optarg));
539 break;
540 case L_PASSWORD:
541 if (!strlen(optarg))
542 break;
543 password = strdup(optarg);
544 memset(optarg, '*', strlen(optarg));
545 break;
546 case L_USER_AGENT:
547 user_agent = optarg;
548 break;
549 case L_POST_DATA:
550 post_data = optarg;
551 break;
552 case L_SPIDER:
553 no_output = true;
554 break;
555 case L_TIMEOUT:
556 timeout = atoi(optarg);
557 break;
558 case L_CONTINUE:
559 resume = true;
560 break;
561 case L_PROXY:
562 if (strcmp(optarg, "on") != 0)
563 proxy = false;
564 break;
565 case L_NO_PROXY:
566 proxy = false;
567 break;
568 default:
569 return usage(progname);
570 }
571 break;
572 case 'c':
573 resume = true;
574 break;
575 case 'U':
576 user_agent = optarg;
577 break;
578 case 'O':
579 output_file = optarg;
580 break;
581 case 'P':
582 if (chdir(optarg)) {
583 if (!quiet)
584 perror("Change output directory");
585 exit(1);
586 }
587 break;
588 case 'q':
589 quiet = true;
590 break;
591 case 's':
592 no_output = true;
593 break;
594 case 'T':
595 timeout = atoi(optarg);
596 break;
597 case 'Y':
598 if (strcmp(optarg, "on") != 0)
599 proxy = false;
600 break;
601 default:
602 return usage(progname);
603 }
604 }
605
606 argv += optind;
607 argc -= optind;
608
609 if (verify && !has_cert)
610 default_certs = true;
611
612 if (argc < 1)
613 return usage(progname);
614
615 if (!ssl_ctx) {
616 for (i = 0; i < argc; i++) {
617 if (!strncmp(argv[i], "https", 5))
618 return no_ssl(progname);
619 }
620 }
621
622 urls = argv + 1;
623 n_urls = argc - 1;
624
625 uloop_init();
626
627 if (username) {
628 if (password)
629 asprintf(&auth_str, "%s:%s", username, password);
630 else
631 auth_str = username;
632 }
633
634 if (!quiet)
635 fprintf(stderr, "Downloading '%s'\n", argv[0]);
636
637 proxy_url = get_proxy_url(argv[0]);
638 if (proxy_url) {
639 cl = uclient_new(proxy_url, auth_str, &cb);
640 uclient_set_proxy_url(cl, argv[0], NULL);
641 } else {
642 cl = uclient_new(argv[0], auth_str, &cb);
643 }
644 if (!cl) {
645 fprintf(stderr, "Failed to allocate uclient context\n");
646 return 1;
647 }
648
649 if (ssl_ctx && default_certs)
650 init_ca_cert();
651
652 cur_resume = resume;
653 rc = init_request(cl);
654 if (!rc) {
655 /* no error received, we can enter main loop */
656 uloop_run();
657 } else {
658 fprintf(stderr, "Failed to establish connection\n");
659 error_ret = 4;
660 }
661
662 uloop_done();
663
664 uclient_free(cl);
665
666 if (output_fd >= 0 && output_fd != STDOUT_FILENO)
667 close(output_fd);
668
669 if (ssl_ctx)
670 ssl_ops->context_free(ssl_ctx);
671
672 return error_ret;
673 }