uclient-http: make username/password variables local
[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 *auth_str;
54 static char **urls;
55 static int n_urls;
56 static int timeout;
57 static bool resume, cur_resume;
58
59 static int init_request(struct uclient *cl);
60 static void request_done(struct uclient *cl);
61
62 static int open_output_file(const char *path, uint64_t resume_offset)
63 {
64 char *filename = NULL;
65 int flags;
66 int ret;
67
68 if (cur_resume)
69 flags = O_RDWR;
70 else
71 flags = O_WRONLY | O_EXCL;
72
73 flags |= O_CREAT;
74
75 if (output_file) {
76 if (!strcmp(output_file, "-")) {
77 if (!quiet)
78 fprintf(stderr, "Writing to stdout\n");
79
80 return STDOUT_FILENO;
81 }
82 } else {
83 filename = uclient_get_url_filename(path, "index.html");
84 output_file = filename;
85 }
86
87 if (!quiet)
88 fprintf(stderr, "Writing to '%s'\n", output_file);
89 ret = open(output_file, flags, 0644);
90 free(filename);
91
92 if (ret < 0)
93 return ret;
94
95 if (resume_offset &&
96 lseek(ret, resume_offset, SEEK_SET) < 0) {
97 if (!quiet)
98 fprintf(stderr, "Failed to seek %"PRIu64" bytes in output file\n", resume_offset);
99 close(ret);
100 return -1;
101 }
102
103 out_bytes += resume_offset;
104
105 return ret;
106 }
107
108 static void header_done_cb(struct uclient *cl)
109 {
110 static const struct blobmsg_policy policy = {
111 .name = "content-range",
112 .type = BLOBMSG_TYPE_STRING
113 };
114 struct blob_attr *attr;
115 uint64_t resume_offset = 0, resume_end, resume_size;
116 static int retries;
117
118 if (retries < 10 && uclient_http_redirect(cl)) {
119 if (!quiet)
120 fprintf(stderr, "Redirected to %s on %s\n", cl->url->location, cl->url->host);
121
122 retries++;
123 return;
124 }
125
126 if (cl->status_code == 204 && cur_resume) {
127 /* Resume attempt failed, try normal download */
128 cur_resume = false;
129 init_request(cl);
130 return;
131 }
132
133 switch (cl->status_code) {
134 case 416:
135 if (!quiet)
136 fprintf(stderr, "File download already fully retrieved; nothing to do.\n");
137 request_done(cl);
138 break;
139 case 206:
140 if (!cur_resume) {
141 if (!quiet)
142 fprintf(stderr, "Error: Partial content received, full content requested\n");
143 error_ret = 8;
144 request_done(cl);
145 break;
146 }
147
148 blobmsg_parse(&policy, 1, &attr, blob_data(cl->meta), blob_len(cl->meta));
149 if (!attr) {
150 if (!quiet)
151 fprintf(stderr, "Content-Range header is missing\n");
152 error_ret = 8;
153 break;
154 }
155
156 if (sscanf(blobmsg_get_string(attr), "bytes %"PRIu64"-%"PRIu64"/%"PRIu64,
157 &resume_offset, &resume_end, &resume_size) != 3) {
158 if (!quiet)
159 fprintf(stderr, "Content-Range header is invalid\n");
160 error_ret = 8;
161 break;
162 }
163 case 204:
164 case 200:
165 if (no_output)
166 break;
167 output_fd = open_output_file(cl->url->location, resume_offset);
168 if (output_fd < 0) {
169 if (!quiet)
170 perror("Cannot open output file");
171 error_ret = 3;
172 request_done(cl);
173 }
174 break;
175
176 default:
177 if (!quiet)
178 fprintf(stderr, "HTTP error %d\n", cl->status_code);
179 request_done(cl);
180 error_ret = 8;
181 break;
182 }
183 }
184
185 static void read_data_cb(struct uclient *cl)
186 {
187 char buf[256];
188 int len;
189
190 if (!no_output && output_fd < 0)
191 return;
192
193 while (1) {
194 len = uclient_read(cl, buf, sizeof(buf));
195 if (!len)
196 return;
197
198 out_bytes += len;
199 if (!no_output)
200 write(output_fd, buf, len);
201 }
202 }
203
204 static void msg_connecting(struct uclient *cl)
205 {
206 char addr[INET6_ADDRSTRLEN];
207 int port;
208
209 if (quiet)
210 return;
211
212 uclient_get_addr(addr, &port, &cl->remote_addr);
213 fprintf(stderr, "Connecting to %s:%d\n", addr, port);
214 }
215
216 static void check_resume_offset(struct uclient *cl)
217 {
218 char range_str[64];
219 struct stat st;
220 char *file;
221 int ret;
222
223 file = uclient_get_url_filename(cl->url->location, "index.html");
224 if (!file)
225 return;
226
227 ret = stat(file, &st);
228 free(file);
229 if (ret)
230 return;
231
232 if (!st.st_size)
233 return;
234
235 snprintf(range_str, sizeof(range_str), "bytes=%"PRIu64"-", (uint64_t) st.st_size);
236 uclient_http_set_header(cl, "Range", range_str);
237 }
238
239 static int init_request(struct uclient *cl)
240 {
241 int rc;
242
243 out_bytes = 0;
244 uclient_http_set_ssl_ctx(cl, ssl_ops, ssl_ctx, verify);
245
246 if (timeout)
247 cl->timeout_msecs = timeout * 1000;
248
249 rc = uclient_connect(cl);
250 if (rc)
251 return rc;
252
253 msg_connecting(cl);
254
255 rc = uclient_http_set_request_type(cl, post_data ? "POST" : "GET");
256 if (rc)
257 return rc;
258
259 uclient_http_reset_headers(cl);
260 uclient_http_set_header(cl, "User-Agent", user_agent);
261 if (cur_resume)
262 check_resume_offset(cl);
263
264 if (post_data) {
265 uclient_http_set_header(cl, "Content-Type", "application/x-www-form-urlencoded");
266 uclient_write(cl, post_data, strlen(post_data));
267 }
268
269 rc = uclient_request(cl);
270 if (rc)
271 return rc;
272
273 return 0;
274 }
275
276 static void request_done(struct uclient *cl)
277 {
278 if (n_urls) {
279 uclient_set_url(cl, *urls, auth_str);
280 n_urls--;
281 cur_resume = resume;
282 error_ret = init_request(cl);
283 if (error_ret == 0)
284 return;
285 }
286
287 if (output_fd >= 0 && !output_file) {
288 close(output_fd);
289 output_fd = -1;
290 }
291 uclient_disconnect(cl);
292 uloop_end();
293 }
294
295
296 static void eof_cb(struct uclient *cl)
297 {
298 if (!cl->data_eof) {
299 if (!quiet)
300 fprintf(stderr, "Connection reset prematurely\n");
301 error_ret = 4;
302 } else if (!quiet) {
303 fprintf(stderr, "Download completed (%d bytes)\n", out_bytes);
304 }
305 request_done(cl);
306 }
307
308 static void handle_uclient_error(struct uclient *cl, int code)
309 {
310 const char *type = "Unknown error";
311 bool ignore = false;
312
313 switch(code) {
314 case UCLIENT_ERROR_CONNECT:
315 type = "Connection failed";
316 error_ret = 4;
317 break;
318 case UCLIENT_ERROR_TIMEDOUT:
319 type = "Connection timed out";
320 error_ret = 4;
321 break;
322 case UCLIENT_ERROR_SSL_INVALID_CERT:
323 type = "Invalid SSL certificate";
324 ignore = !verify;
325 error_ret = 5;
326 break;
327 case UCLIENT_ERROR_SSL_CN_MISMATCH:
328 type = "Server hostname does not match SSL certificate";
329 ignore = !verify;
330 error_ret = 5;
331 break;
332 default:
333 error_ret = 1;
334 break;
335 }
336
337 if (!quiet)
338 fprintf(stderr, "Connection error: %s%s\n", type, ignore ? " (ignored)" : "");
339
340 if (ignore)
341 error_ret = 0;
342 else
343 request_done(cl);
344 }
345
346 static const struct uclient_cb cb = {
347 .header_done = header_done_cb,
348 .data_read = read_data_cb,
349 .data_eof = eof_cb,
350 .error = handle_uclient_error,
351 };
352
353 static int usage(const char *progname)
354 {
355 fprintf(stderr,
356 "Usage: %s [options] <URL>\n"
357 "Options:\n"
358 " -q: Turn off status messages\n"
359 " -O <file>: Redirect output to file (use \"-\" for stdout)\n"
360 " --user=<user> HTTP authentication username\n"
361 " --password=<password> HTTP authentication password\n"
362 " --user-agent|-U <str> Set HTTP user agent\n"
363 " --post-data=STRING use the POST method; send STRING as the data\n"
364 " --spider|-s Spider mode - only check file existence\n"
365 " --timeout=N|-T N Set connect/request timeout to N seconds\n"
366 "\n"
367 "HTTPS options:\n"
368 " --ca-certificate=<cert>: Load CA certificates from file <cert>\n"
369 " --no-check-certificate: don't validate the server's certificate\n"
370 "\n", progname);
371 return 1;
372 }
373
374 static void init_ca_cert(void)
375 {
376 glob_t gl;
377 int i;
378
379 glob("/etc/ssl/certs/*.crt", 0, NULL, &gl);
380 for (i = 0; i < gl.gl_pathc; i++)
381 ssl_ops->context_add_ca_crt_file(ssl_ctx, gl.gl_pathv[i]);
382 }
383
384 static void init_ustream_ssl(void)
385 {
386 void *dlh;
387
388 dlh = dlopen("libustream-ssl." LIB_EXT, RTLD_LAZY | RTLD_LOCAL);
389 if (!dlh)
390 return;
391
392 ssl_ops = dlsym(dlh, "ustream_ssl_ops");
393 if (!ssl_ops)
394 return;
395
396 ssl_ctx = ssl_ops->context_new(false);
397 }
398
399 static int no_ssl(const char *progname)
400 {
401 fprintf(stderr, "%s: SSL support not available, please install ustream-ssl\n", progname);
402 return 1;
403 }
404
405 enum {
406 L_NO_CHECK_CERTIFICATE,
407 L_CA_CERTIFICATE,
408 L_USER,
409 L_PASSWORD,
410 L_USER_AGENT,
411 L_POST_DATA,
412 L_SPIDER,
413 L_TIMEOUT,
414 L_CONTINUE,
415 };
416
417 static const struct option longopts[] = {
418 [L_NO_CHECK_CERTIFICATE] = { "no-check-certificate", no_argument },
419 [L_CA_CERTIFICATE] = { "ca-certificate", required_argument },
420 [L_USER] = { "user", required_argument },
421 [L_PASSWORD] = { "password", required_argument },
422 [L_USER_AGENT] = { "user-agent", required_argument },
423 [L_POST_DATA] = { "post-data", required_argument },
424 [L_SPIDER] = { "spider", no_argument },
425 [L_TIMEOUT] = { "timeout", required_argument },
426 [L_CONTINUE] = { "continue", no_argument },
427 {}
428 };
429
430
431
432 int main(int argc, char **argv)
433 {
434 const char *progname = argv[0];
435 char *username = NULL;
436 char *password = NULL;
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 }