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