uclient-fetch: add support for resuming downloads
[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
30 #include <libubox/blobmsg.h>
31
32 #include "uclient.h"
33 #include "uclient-utils.h"
34
35 #ifdef __APPLE__
36 #define LIB_EXT "dylib"
37 #else
38 #define LIB_EXT "so"
39 #endif
40
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;
51 static int error_ret;
52 static int out_bytes;
53 static char *username;
54 static char *password;
55 static char *auth_str;
56 static char **urls;
57 static int n_urls;
58 static int timeout;
59 static bool resume, cur_resume;
60
61 static int init_request(struct uclient *cl);
62 static void request_done(struct uclient *cl);
63
64 static int open_output_file(const char *path, uint64_t resume_offset)
65 {
66 char *filename = NULL;
67 int flags;
68 int ret;
69
70 if (cur_resume)
71 flags = O_RDWR;
72 else
73 flags = O_WRONLY | O_EXCL;
74
75 flags |= O_CREAT;
76
77 if (output_file) {
78 if (!strcmp(output_file, "-")) {
79 if (!quiet)
80 fprintf(stderr, "Writing to stdout\n");
81
82 return STDOUT_FILENO;
83 }
84 } else {
85 filename = uclient_get_url_filename(path, "index.html");
86 output_file = filename;
87 }
88
89 if (!quiet)
90 fprintf(stderr, "Writing to '%s'\n", output_file);
91 ret = open(output_file, flags, 0644);
92 free(filename);
93
94 if (ret < 0)
95 return ret;
96
97 if (resume_offset &&
98 lseek(ret, resume_offset, SEEK_SET) < 0) {
99 if (!quiet)
100 fprintf(stderr, "Failed to seek %"PRIu64" bytes in output file\n", resume_offset);
101 close(ret);
102 return -1;
103 }
104
105 out_bytes += resume_offset;
106
107 return ret;
108 }
109
110 static void header_done_cb(struct uclient *cl)
111 {
112 static const struct blobmsg_policy policy = {
113 .name = "content-range",
114 .type = BLOBMSG_TYPE_STRING
115 };
116 struct blob_attr *attr;
117 uint64_t resume_offset = 0, resume_end, resume_size;
118 static int retries;
119
120 if (retries < 10 && uclient_http_redirect(cl)) {
121 if (!quiet)
122 fprintf(stderr, "Redirected to %s on %s\n", cl->url->location, cl->url->host);
123
124 retries++;
125 return;
126 }
127
128 if (cl->status_code == 204 && cur_resume) {
129 /* Resume attempt failed, try normal download */
130 cur_resume = false;
131 init_request(cl);
132 return;
133 }
134
135 switch (cl->status_code) {
136 case 416:
137 if (!quiet)
138 fprintf(stderr, "File download already fully retrieved; nothing to do.\n");
139 request_done(cl);
140 break;
141 case 206:
142 if (!cur_resume) {
143 if (!quiet)
144 fprintf(stderr, "Error: Partial content received, full content requested\n");
145 error_ret = 8;
146 request_done(cl);
147 break;
148 }
149
150 blobmsg_parse(&policy, 1, &attr, blob_data(cl->meta), blob_len(cl->meta));
151 if (!attr) {
152 if (!quiet)
153 fprintf(stderr, "Content-Range header is missing\n");
154 error_ret = 8;
155 break;
156 }
157
158 if (sscanf(blobmsg_get_string(attr), "bytes %"PRIu64"-%"PRIu64"/%"PRIu64,
159 &resume_offset, &resume_end, &resume_size) != 3) {
160 if (!quiet)
161 fprintf(stderr, "Content-Range header is invalid\n");
162 error_ret = 8;
163 break;
164 }
165 case 204:
166 case 200:
167 if (no_output)
168 break;
169 output_fd = open_output_file(cl->url->location, resume_offset);
170 if (output_fd < 0) {
171 if (!quiet)
172 perror("Cannot open output file");
173 error_ret = 3;
174 request_done(cl);
175 }
176 break;
177
178 default:
179 if (!quiet)
180 fprintf(stderr, "HTTP error %d\n", cl->status_code);
181 request_done(cl);
182 error_ret = 8;
183 break;
184 }
185 }
186
187 static void read_data_cb(struct uclient *cl)
188 {
189 char buf[256];
190 int len;
191
192 if (!no_output && output_fd < 0)
193 return;
194
195 while (1) {
196 len = uclient_read(cl, buf, sizeof(buf));
197 if (!len)
198 return;
199
200 out_bytes += len;
201 if (!no_output)
202 write(output_fd, buf, len);
203 }
204 }
205
206 static void msg_connecting(struct uclient *cl)
207 {
208 char addr[INET6_ADDRSTRLEN];
209 int port;
210
211 if (quiet)
212 return;
213
214 uclient_get_addr(addr, &port, &cl->remote_addr);
215 fprintf(stderr, "Connecting to %s:%d\n", addr, port);
216 }
217
218 static void check_resume_offset(struct uclient *cl)
219 {
220 char range_str[64];
221 struct stat st;
222 char *file;
223 int ret;
224
225 file = uclient_get_url_filename(cl->url->location, "index.html");
226 if (!file)
227 return;
228
229 ret = stat(file, &st);
230 free(file);
231 if (ret)
232 return;
233
234 if (!st.st_size)
235 return;
236
237 snprintf(range_str, sizeof(range_str), "bytes=%"PRIu64"-", (uint64_t) st.st_size);
238 uclient_http_set_header(cl, "Range", range_str);
239 }
240
241 static int init_request(struct uclient *cl)
242 {
243 int rc;
244
245 out_bytes = 0;
246 uclient_http_set_ssl_ctx(cl, ssl_ops, ssl_ctx, verify);
247
248 if (timeout)
249 cl->timeout_msecs = timeout * 1000;
250
251 rc = uclient_connect(cl);
252 if (rc)
253 return rc;
254
255 msg_connecting(cl);
256
257 rc = uclient_http_set_request_type(cl, post_data ? "POST" : "GET");
258 if (rc)
259 return rc;
260
261 uclient_http_reset_headers(cl);
262 uclient_http_set_header(cl, "User-Agent", user_agent);
263 if (cur_resume)
264 check_resume_offset(cl);
265
266 if (post_data) {
267 uclient_http_set_header(cl, "Content-Type", "application/x-www-form-urlencoded");
268 uclient_write(cl, post_data, strlen(post_data));
269 }
270
271 rc = uclient_request(cl);
272 if (rc)
273 return rc;
274
275 return 0;
276 }
277
278 static void request_done(struct uclient *cl)
279 {
280 if (n_urls) {
281 uclient_set_url(cl, *urls, auth_str);
282 n_urls--;
283 cur_resume = resume;
284 error_ret = init_request(cl);
285 if (error_ret == 0)
286 return;
287 }
288
289 if (output_fd >= 0 && !output_file) {
290 close(output_fd);
291 output_fd = -1;
292 }
293 uclient_disconnect(cl);
294 uloop_end();
295 }
296
297
298 static void eof_cb(struct uclient *cl)
299 {
300 if (!cl->data_eof) {
301 if (!quiet)
302 fprintf(stderr, "Connection reset prematurely\n");
303 error_ret = 4;
304 } else if (!quiet) {
305 fprintf(stderr, "Download completed (%d bytes)\n", out_bytes);
306 }
307 request_done(cl);
308 }
309
310 static void handle_uclient_error(struct uclient *cl, int code)
311 {
312 const char *type = "Unknown error";
313 bool ignore = false;
314
315 switch(code) {
316 case UCLIENT_ERROR_CONNECT:
317 type = "Connection failed";
318 error_ret = 4;
319 break;
320 case UCLIENT_ERROR_TIMEDOUT:
321 type = "Connection timed out";
322 error_ret = 4;
323 break;
324 case UCLIENT_ERROR_SSL_INVALID_CERT:
325 type = "Invalid SSL certificate";
326 ignore = !verify;
327 error_ret = 5;
328 break;
329 case UCLIENT_ERROR_SSL_CN_MISMATCH:
330 type = "Server hostname does not match SSL certificate";
331 ignore = !verify;
332 error_ret = 5;
333 break;
334 default:
335 error_ret = 1;
336 break;
337 }
338
339 if (!quiet)
340 fprintf(stderr, "Connection error: %s%s\n", type, ignore ? " (ignored)" : "");
341
342 if (ignore)
343 error_ret = 0;
344 else
345 request_done(cl);
346 }
347
348 static const struct uclient_cb cb = {
349 .header_done = header_done_cb,
350 .data_read = read_data_cb,
351 .data_eof = eof_cb,
352 .error = handle_uclient_error,
353 };
354
355 static int usage(const char *progname)
356 {
357 fprintf(stderr,
358 "Usage: %s [options] <URL>\n"
359 "Options:\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"
368 "\n"
369 "HTTPS options:\n"
370 " --ca-certificate=<cert>: Load CA certificates from file <cert>\n"
371 " --no-check-certificate: don't validate the server's certificate\n"
372 "\n", progname);
373 return 1;
374 }
375
376 static void init_ca_cert(void)
377 {
378 glob_t gl;
379 int i;
380
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]);
384 }
385
386 static void init_ustream_ssl(void)
387 {
388 void *dlh;
389
390 dlh = dlopen("libustream-ssl." LIB_EXT, RTLD_LAZY | RTLD_LOCAL);
391 if (!dlh)
392 return;
393
394 ssl_ops = dlsym(dlh, "ustream_ssl_ops");
395 if (!ssl_ops)
396 return;
397
398 ssl_ctx = ssl_ops->context_new(false);
399 }
400
401 static int no_ssl(const char *progname)
402 {
403 fprintf(stderr, "%s: SSL support not available, please install ustream-ssl\n", progname);
404 return 1;
405 }
406
407 enum {
408 L_NO_CHECK_CERTIFICATE,
409 L_CA_CERTIFICATE,
410 L_USER,
411 L_PASSWORD,
412 L_USER_AGENT,
413 L_POST_DATA,
414 L_SPIDER,
415 L_TIMEOUT,
416 L_CONTINUE,
417 };
418
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 },
429 {}
430 };
431
432
433
434 int main(int argc, char **argv)
435 {
436 const char *progname = argv[0];
437 struct uclient *cl;
438 int longopt_idx = 0;
439 bool has_cert = false;
440 int i, ch;
441 int rc;
442
443 init_ustream_ssl();
444
445 while ((ch = getopt_long(argc, argv, "cO:qsU:", longopts, &longopt_idx)) != -1) {
446 switch(ch) {
447 case 0:
448 switch (longopt_idx) {
449 case L_NO_CHECK_CERTIFICATE:
450 verify = false;
451 break;
452 case L_CA_CERTIFICATE:
453 has_cert = true;
454 if (ssl_ctx)
455 ssl_ops->context_add_ca_crt_file(ssl_ctx, optarg);
456 break;
457 case L_USER:
458 if (!strlen(optarg))
459 break;
460 username = strdup(optarg);
461 memset(optarg, '*', strlen(optarg));
462 break;
463 case L_PASSWORD:
464 if (!strlen(optarg))
465 break;
466 password = strdup(optarg);
467 memset(optarg, '*', strlen(optarg));
468 break;
469 case L_USER_AGENT:
470 user_agent = optarg;
471 break;
472 case L_POST_DATA:
473 post_data = optarg;
474 break;
475 case L_SPIDER:
476 no_output = true;
477 break;
478 case L_TIMEOUT:
479 timeout = atoi(optarg);
480 break;
481 case L_CONTINUE:
482 resume = true;
483 break;
484 default:
485 return usage(progname);
486 }
487 break;
488 case 'c':
489 resume = true;
490 break;
491 case 'U':
492 user_agent = optarg;
493 break;
494 case 'O':
495 output_file = optarg;
496 break;
497 case 'q':
498 quiet = true;
499 break;
500 case 's':
501 no_output = true;
502 break;
503 case 'T':
504 timeout = atoi(optarg);
505 break;
506 default:
507 return usage(progname);
508 }
509 }
510
511 argv += optind;
512 argc -= optind;
513
514 if (verify && !has_cert)
515 default_certs = true;
516
517 if (argc < 1)
518 return usage(progname);
519
520 if (!ssl_ctx) {
521 for (i = 0; i < argc; i++) {
522 if (!strncmp(argv[i], "https", 5))
523 return no_ssl(progname);
524 }
525 }
526
527 urls = argv + 1;
528 n_urls = argc - 1;
529
530 uloop_init();
531
532 if (username) {
533 if (password)
534 asprintf(&auth_str, "%s:%s", username, password);
535 else
536 auth_str = username;
537 }
538
539 if (!quiet)
540 fprintf(stderr, "Downloading '%s'\n", argv[0]);
541
542 cl = uclient_new(argv[0], auth_str, &cb);
543 if (!cl) {
544 fprintf(stderr, "Failed to allocate uclient context\n");
545 return 1;
546 }
547
548 if (ssl_ctx && default_certs)
549 init_ca_cert();
550
551 cur_resume = resume;
552 rc = init_request(cl);
553 if (!rc) {
554 /* no error received, we can enter main loop */
555 uloop_run();
556 } else {
557 fprintf(stderr, "Failed to establish connection\n");
558 error_ret = 4;
559 }
560
561 uloop_done();
562
563 uclient_free(cl);
564
565 if (output_fd >= 0 && output_fd != STDOUT_FILENO)
566 close(output_fd);
567
568 if (ssl_ctx)
569 ssl_ops->context_free(ssl_ctx);
570
571 return error_ret;
572 }