uclient-http: fix Host: header for literal IPv6 addresses
[project/uclient.git] / uclient-http.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 #include <sys/socket.h>
19 #include <stdio.h>
20 #include <ctype.h>
21 #include <unistd.h>
22 #include <stdint.h>
23 #include <string.h>
24 #include <fcntl.h>
25
26 #include <libubox/ustream.h>
27 #include <libubox/ustream-ssl.h>
28 #include <libubox/usock.h>
29 #include <libubox/blobmsg.h>
30
31 #include "uclient.h"
32 #include "uclient-utils.h"
33 #include "uclient-backend.h"
34
35 enum auth_type {
36 AUTH_TYPE_UNKNOWN,
37 AUTH_TYPE_NONE,
38 AUTH_TYPE_BASIC,
39 AUTH_TYPE_DIGEST,
40 };
41
42 enum request_type {
43 REQ_GET,
44 REQ_HEAD,
45 REQ_POST,
46 REQ_PUT,
47 REQ_DELETE,
48 __REQ_MAX
49 };
50
51 enum http_state {
52 HTTP_STATE_INIT,
53 HTTP_STATE_HEADERS_SENT,
54 HTTP_STATE_REQUEST_DONE,
55 HTTP_STATE_RECV_HEADERS,
56 HTTP_STATE_RECV_DATA,
57 HTTP_STATE_ERROR,
58 };
59
60 static const char * const request_types[__REQ_MAX] = {
61 [REQ_GET] = "GET",
62 [REQ_HEAD] = "HEAD",
63 [REQ_POST] = "POST",
64 [REQ_PUT] = "PUT",
65 [REQ_DELETE] = "DELETE",
66 };
67
68 struct uclient_http {
69 struct uclient uc;
70
71 const struct ustream_ssl_ops *ssl_ops;
72 struct ustream_ssl_ctx *ssl_ctx;
73 struct ustream *us;
74
75 struct ustream_fd ufd;
76 struct ustream_ssl ussl;
77
78 struct uloop_timeout disconnect_t;
79 unsigned int seq;
80
81 bool ssl_require_validation;
82 bool ssl;
83 bool eof;
84 bool connection_close;
85 bool disconnect;
86 enum request_type req_type;
87 enum http_state state;
88
89 enum auth_type auth_type;
90 char *auth_str;
91
92 long read_chunked;
93 long content_length;
94
95 int usock_flags;
96
97 uint32_t nc;
98
99 struct blob_buf headers;
100 struct blob_buf meta;
101 };
102
103 enum {
104 PREFIX_HTTP,
105 PREFIX_HTTPS,
106 __PREFIX_MAX,
107 };
108
109 static const char * const uclient_http_prefix[] = {
110 [PREFIX_HTTP] = "http://",
111 [PREFIX_HTTPS] = "https://",
112 [__PREFIX_MAX] = NULL
113 };
114
115 static int uclient_http_connect(struct uclient *cl);
116
117 static int uclient_do_connect(struct uclient_http *uh, const char *port)
118 {
119 socklen_t sl;
120 int fd;
121
122 if (uh->uc.url->port)
123 port = uh->uc.url->port;
124
125 memset(&uh->uc.remote_addr, 0, sizeof(uh->uc.remote_addr));
126
127 fd = usock_inet_timeout(USOCK_TCP | USOCK_NONBLOCK | uh->usock_flags,
128 uh->uc.url->host, port, &uh->uc.remote_addr,
129 uh->uc.timeout_msecs);
130 if (fd < 0)
131 return -1;
132
133 fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
134 ustream_fd_init(&uh->ufd, fd);
135
136 sl = sizeof(uh->uc.local_addr);
137 memset(&uh->uc.local_addr, 0, sl);
138 getsockname(fd, &uh->uc.local_addr.sa, &sl);
139
140 return 0;
141 }
142
143 static void uclient_http_disconnect(struct uclient_http *uh)
144 {
145 uloop_timeout_cancel(&uh->disconnect_t);
146 if (!uh->us)
147 return;
148
149 if (uh->ssl)
150 ustream_free(&uh->ussl.stream);
151 ustream_free(&uh->ufd.stream);
152 close(uh->ufd.fd.fd);
153 uh->us = NULL;
154 }
155
156 static void uclient_http_free_url_state(struct uclient *cl)
157 {
158 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
159
160 uh->auth_type = AUTH_TYPE_UNKNOWN;
161 free(uh->auth_str);
162 uh->auth_str = NULL;
163 uclient_http_disconnect(uh);
164 }
165
166 static void uclient_http_error(struct uclient_http *uh, int code)
167 {
168 uh->state = HTTP_STATE_ERROR;
169 uh->us->eof = true;
170 ustream_state_change(uh->us);
171 uclient_backend_set_error(&uh->uc, code);
172 }
173
174 static void uclient_http_request_disconnect(struct uclient *cl)
175 {
176 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
177
178 if (!uh->us)
179 return;
180
181 uh->eof = true;
182 uh->disconnect = true;
183 uloop_timeout_set(&uh->disconnect_t, 1);
184 }
185
186 static void uclient_notify_eof(struct uclient_http *uh)
187 {
188 struct ustream *us = uh->us;
189
190 if (uh->disconnect)
191 return;
192
193 if (!uh->eof) {
194 if (!us->eof && !us->write_error)
195 return;
196
197 if (ustream_pending_data(us, false))
198 return;
199 }
200
201 if (uh->content_length < 0 && uh->read_chunked >= 0)
202 uh->uc.data_eof = true;
203
204 uclient_backend_set_eof(&uh->uc);
205
206 if (uh->connection_close)
207 uclient_http_request_disconnect(&uh->uc);
208 }
209
210 static void uclient_http_reset_state(struct uclient_http *uh)
211 {
212 uh->seq++;
213 uclient_backend_reset_state(&uh->uc);
214 uh->read_chunked = -1;
215 uh->content_length = -1;
216 uh->eof = false;
217 uh->disconnect = false;
218 uh->connection_close = false;
219 uh->state = HTTP_STATE_INIT;
220
221 if (uh->auth_type == AUTH_TYPE_UNKNOWN && !uh->uc.url->auth)
222 uh->auth_type = AUTH_TYPE_NONE;
223 }
224
225 static void uclient_http_init_request(struct uclient_http *uh)
226 {
227 uh->seq++;
228 uclient_http_reset_state(uh);
229 blob_buf_init(&uh->meta, 0);
230 }
231
232 static enum auth_type
233 uclient_http_update_auth_type(struct uclient_http *uh)
234 {
235 if (!uh->auth_str)
236 return AUTH_TYPE_NONE;
237
238 if (!strncasecmp(uh->auth_str, "basic", 5))
239 return AUTH_TYPE_BASIC;
240
241 if (!strncasecmp(uh->auth_str, "digest", 6))
242 return AUTH_TYPE_DIGEST;
243
244 return AUTH_TYPE_NONE;
245 }
246
247 static void uclient_http_process_headers(struct uclient_http *uh)
248 {
249 enum {
250 HTTP_HDR_TRANSFER_ENCODING,
251 HTTP_HDR_CONNECTION,
252 HTTP_HDR_CONTENT_LENGTH,
253 HTTP_HDR_AUTH,
254 __HTTP_HDR_MAX,
255 };
256 static const struct blobmsg_policy hdr_policy[__HTTP_HDR_MAX] = {
257 #define hdr(_name) { .name = _name, .type = BLOBMSG_TYPE_STRING }
258 [HTTP_HDR_TRANSFER_ENCODING] = hdr("transfer-encoding"),
259 [HTTP_HDR_CONNECTION] = hdr("connection"),
260 [HTTP_HDR_CONTENT_LENGTH] = hdr("content-length"),
261 [HTTP_HDR_AUTH] = hdr("www-authenticate"),
262 #undef hdr
263 };
264 struct blob_attr *tb[__HTTP_HDR_MAX];
265 struct blob_attr *cur;
266
267 blobmsg_parse(hdr_policy, __HTTP_HDR_MAX, tb, blob_data(uh->meta.head), blob_len(uh->meta.head));
268
269 cur = tb[HTTP_HDR_TRANSFER_ENCODING];
270 if (cur && strstr(blobmsg_data(cur), "chunked"))
271 uh->read_chunked = 0;
272
273 cur = tb[HTTP_HDR_CONNECTION];
274 if (cur && strstr(blobmsg_data(cur), "close"))
275 uh->connection_close = true;
276
277 cur = tb[HTTP_HDR_CONTENT_LENGTH];
278 if (cur)
279 uh->content_length = strtoul(blobmsg_data(cur), NULL, 10);
280
281 cur = tb[HTTP_HDR_AUTH];
282 if (cur) {
283 free(uh->auth_str);
284 uh->auth_str = strdup(blobmsg_data(cur));
285 }
286
287 uh->auth_type = uclient_http_update_auth_type(uh);
288 }
289
290 static bool uclient_request_supports_body(enum request_type req_type)
291 {
292 switch (req_type) {
293 case REQ_POST:
294 case REQ_PUT:
295 case REQ_DELETE:
296 return true;
297 default:
298 return false;
299 }
300 }
301
302 static void
303 uclient_http_add_auth_basic(struct uclient_http *uh)
304 {
305 struct uclient_url *url = uh->uc.url;
306 int auth_len = strlen(url->auth);
307 char *auth_buf;
308
309 if (auth_len > 512)
310 return;
311
312 auth_buf = alloca(base64_len(auth_len) + 1);
313 base64_encode(url->auth, auth_len, auth_buf);
314 ustream_printf(uh->us, "Authorization: Basic %s\r\n", auth_buf);
315 }
316
317 static char *digest_unquote_sep(char **str)
318 {
319 char *cur = *str + 1;
320 char *start = cur;
321 char *out;
322
323 if (**str != '"')
324 return NULL;
325
326 out = cur;
327 while (1) {
328 if (!*cur)
329 return NULL;
330
331 if (*cur == '"') {
332 cur++;
333 break;
334 }
335
336 if (*cur == '\\')
337 cur++;
338
339 *(out++) = *(cur++);
340 }
341
342 if (*cur == ',')
343 cur++;
344
345 *out = 0;
346 *str = cur;
347
348 return start;
349 }
350
351 static char *digest_sep(char **str)
352 {
353 char *cur, *next;
354
355 cur = *str;
356 next = strchr(*str, ',');
357 if (next) {
358 *str = next + 1;
359 *next = 0;
360 } else {
361 *str += strlen(*str);
362 }
363
364 return cur;
365 }
366
367 static bool strmatch(char **str, const char *prefix)
368 {
369 int len = strlen(prefix);
370
371 if (strncmp(*str, prefix, len) != 0 || (*str)[len] != '=')
372 return false;
373
374 *str += len + 1;
375 return true;
376 }
377
378 static void
379 get_cnonce(char *dest)
380 {
381 uint32_t val = 0;
382 FILE *f;
383 size_t n;
384
385 f = fopen("/dev/urandom", "r");
386 if (f) {
387 n = fread(&val, sizeof(val), 1, f);
388 fclose(f);
389 if (n != 1)
390 return;
391 }
392
393 bin_to_hex(dest, &val, sizeof(val));
394 }
395
396 static void add_field(char **buf, int *ofs, int *len, const char *name, const char *val)
397 {
398 int available = *len - *ofs;
399 int required;
400 const char *next;
401 char *cur;
402
403 if (*len && !*buf)
404 return;
405
406 required = strlen(name) + 4 + strlen(val) * 2;
407 if (required > available)
408 *len += required - available + 64;
409
410 *buf = realloc(*buf, *len);
411 if (!*buf)
412 return;
413
414 cur = *buf + *ofs;
415 cur += sprintf(cur, ", %s=\"", name);
416
417 while ((next = strchr(val, '"'))) {
418 if (next > val) {
419 memcpy(cur, val, next - val);
420 cur += next - val;
421 }
422
423 cur += sprintf(cur, "\\\"");
424 val = next + 1;
425 }
426
427 cur += sprintf(cur, "%s\"", val);
428 *ofs = cur - *buf;
429 }
430
431 static void
432 uclient_http_add_auth_digest(struct uclient_http *uh)
433 {
434 struct uclient_url *url = uh->uc.url;
435 const char *realm = NULL, *opaque = NULL;
436 const char *user, *password;
437 char *buf, *next;
438 int len, ofs;
439
440 char cnonce_str[9];
441 char nc_str[9];
442 char ahash[33];
443 char hash[33];
444
445 struct http_digest_data data = {
446 .nc = nc_str,
447 .cnonce = cnonce_str,
448 .auth_hash = ahash,
449 };
450
451 len = strlen(uh->auth_str) + 1;
452 if (len > 512)
453 return;
454
455 buf = alloca(len);
456 strcpy(buf, uh->auth_str);
457
458 /* skip auth type */
459 strsep(&buf, " ");
460
461 next = buf;
462 while (*next) {
463 const char **dest = NULL;
464 const char *tmp;
465
466 while (*next && isspace(*next))
467 next++;
468
469 if (strmatch(&next, "realm"))
470 dest = &realm;
471 else if (strmatch(&next, "qop"))
472 dest = &data.qop;
473 else if (strmatch(&next, "nonce"))
474 dest = &data.nonce;
475 else if (strmatch(&next, "opaque"))
476 dest = &opaque;
477 else if (strmatch(&next, "stale") ||
478 strmatch(&next, "algorithm") ||
479 strmatch(&next, "auth-param")) {
480 digest_sep(&next);
481 continue;
482 } else if (strmatch(&next, "domain") ||
483 strmatch(&next, "qop-options"))
484 dest = &tmp;
485 else {
486 digest_sep(&next);
487 continue;
488 }
489
490 *dest = digest_unquote_sep(&next);
491 }
492
493 if (!realm || !data.qop || !data.nonce)
494 return;
495
496 sprintf(nc_str, "%08x", uh->nc++);
497 get_cnonce(cnonce_str);
498
499 data.qop = "auth";
500 data.uri = url->location;
501 data.method = request_types[uh->req_type];
502
503 password = strchr(url->auth, ':');
504 if (password) {
505 char *user_buf;
506
507 len = password - url->auth;
508 if (len > 256)
509 return;
510
511 user_buf = alloca(len + 1);
512 strncpy(user_buf, url->auth, len);
513 user_buf[len] = 0;
514 user = user_buf;
515 password++;
516 } else {
517 user = url->auth;
518 password = "";
519 }
520
521 http_digest_calculate_auth_hash(ahash, user, realm, password);
522 http_digest_calculate_response(hash, &data);
523
524 buf = NULL;
525 len = 0;
526 ofs = 0;
527
528 add_field(&buf, &ofs, &len, "username", user);
529 add_field(&buf, &ofs, &len, "realm", realm);
530 add_field(&buf, &ofs, &len, "nonce", data.nonce);
531 add_field(&buf, &ofs, &len, "uri", data.uri);
532 add_field(&buf, &ofs, &len, "cnonce", data.cnonce);
533 add_field(&buf, &ofs, &len, "response", hash);
534 if (opaque)
535 add_field(&buf, &ofs, &len, "opaque", opaque);
536
537 ustream_printf(uh->us, "Authorization: Digest nc=%s, qop=%s%s\r\n", data.nc, data.qop, buf);
538 free(buf);
539 }
540
541 static void
542 uclient_http_add_auth_header(struct uclient_http *uh)
543 {
544 if (!uh->uc.url->auth)
545 return;
546
547 switch (uh->auth_type) {
548 case AUTH_TYPE_UNKNOWN:
549 case AUTH_TYPE_NONE:
550 break;
551 case AUTH_TYPE_BASIC:
552 uclient_http_add_auth_basic(uh);
553 break;
554 case AUTH_TYPE_DIGEST:
555 uclient_http_add_auth_digest(uh);
556 break;
557 }
558 }
559
560 static void
561 uclient_http_send_headers(struct uclient_http *uh)
562 {
563 struct uclient_url *url = uh->uc.url;
564 struct blob_attr *cur;
565 enum request_type req_type = uh->req_type;
566 bool literal_ipv6;
567 int rem;
568
569 if (uh->state >= HTTP_STATE_HEADERS_SENT)
570 return;
571
572 if (uh->uc.proxy_url)
573 url = uh->uc.proxy_url;
574
575 literal_ipv6 = strchr(url->host, ':');
576
577 ustream_printf(uh->us,
578 "%s %s HTTP/1.1\r\n"
579 "Host: %s%s%s%s%s\r\n",
580 request_types[req_type], url->location,
581 literal_ipv6 ? "[" : "",
582 url->host,
583 literal_ipv6 ? "]" : "",
584 url->port ? ":" : "",
585 url->port ? url->port : "");
586
587 blobmsg_for_each_attr(cur, uh->headers.head, rem)
588 ustream_printf(uh->us, "%s: %s\r\n", blobmsg_name(cur), (char *) blobmsg_data(cur));
589
590 if (uclient_request_supports_body(uh->req_type))
591 ustream_printf(uh->us, "Transfer-Encoding: chunked\r\n");
592
593 uclient_http_add_auth_header(uh);
594
595 ustream_printf(uh->us, "\r\n");
596
597 uh->state = HTTP_STATE_HEADERS_SENT;
598 }
599
600 static void uclient_http_headers_complete(struct uclient_http *uh)
601 {
602 enum auth_type auth_type = uh->auth_type;
603 int seq = uh->uc.seq;
604
605 uh->state = HTTP_STATE_RECV_DATA;
606 uh->uc.meta = uh->meta.head;
607 uclient_http_process_headers(uh);
608
609 if (auth_type == AUTH_TYPE_UNKNOWN && uh->uc.status_code == 401 &&
610 (uh->req_type == REQ_HEAD || uh->req_type == REQ_GET)) {
611 uclient_http_connect(&uh->uc);
612 uclient_http_send_headers(uh);
613 uh->state = HTTP_STATE_REQUEST_DONE;
614 return;
615 }
616
617 if (uh->uc.cb->header_done)
618 uh->uc.cb->header_done(&uh->uc);
619
620 if (uh->eof || seq != uh->uc.seq)
621 return;
622
623 if (uh->req_type == REQ_HEAD || uh->uc.status_code == 204) {
624 uh->eof = true;
625 uclient_notify_eof(uh);
626 }
627 }
628
629 static void uclient_parse_http_line(struct uclient_http *uh, char *data)
630 {
631 char *name;
632 char *sep;
633
634 if (uh->state == HTTP_STATE_REQUEST_DONE) {
635 char *code;
636
637 if (!strlen(data))
638 return;
639
640 /* HTTP/1.1 */
641 strsep(&data, " ");
642
643 code = strsep(&data, " ");
644 if (!code)
645 goto error;
646
647 uh->uc.status_code = strtoul(code, &sep, 10);
648 if (sep && *sep)
649 goto error;
650
651 uh->state = HTTP_STATE_RECV_HEADERS;
652 return;
653 }
654
655 if (!*data) {
656 uclient_http_headers_complete(uh);
657 return;
658 }
659
660 sep = strchr(data, ':');
661 if (!sep)
662 return;
663
664 *(sep++) = 0;
665
666 for (name = data; *name; name++)
667 *name = tolower(*name);
668
669 name = data;
670 while (isspace(*sep))
671 sep++;
672
673 blobmsg_add_string(&uh->meta, name, sep);
674 return;
675
676 error:
677 uh->uc.status_code = 400;
678 uh->eof = true;
679 uclient_notify_eof(uh);
680 }
681
682 static void __uclient_notify_read(struct uclient_http *uh)
683 {
684 struct uclient *uc = &uh->uc;
685 unsigned int seq = uh->seq;
686 char *data;
687 int len;
688
689 if (uh->state < HTTP_STATE_REQUEST_DONE || uh->state == HTTP_STATE_ERROR)
690 return;
691
692 data = ustream_get_read_buf(uh->us, &len);
693 if (!data || !len)
694 return;
695
696 if (uh->state < HTTP_STATE_RECV_DATA) {
697 char *sep, *next;
698 int cur_len;
699
700 do {
701 sep = strchr(data, '\n');
702 if (!sep)
703 break;
704
705 next = sep + 1;
706 if (sep > data && sep[-1] == '\r')
707 sep--;
708
709 /* Check for multi-line HTTP headers */
710 if (sep > data) {
711 if (!*next)
712 return;
713
714 if (isspace(*next) && *next != '\r' && *next != '\n') {
715 sep[0] = ' ';
716 if (sep + 1 < next)
717 sep[1] = ' ';
718 continue;
719 }
720 }
721
722 *sep = 0;
723 cur_len = next - data;
724 uclient_parse_http_line(uh, data);
725 if (seq != uh->seq)
726 return;
727
728 ustream_consume(uh->us, cur_len);
729 len -= cur_len;
730
731 if (uh->eof)
732 return;
733
734 data = ustream_get_read_buf(uh->us, &len);
735 } while (data && uh->state < HTTP_STATE_RECV_DATA);
736
737 if (!len)
738 return;
739 }
740
741 if (uh->eof)
742 return;
743
744 if (uh->state == HTTP_STATE_RECV_DATA) {
745 /* Now it's uclient user turn to read some data */
746 uloop_timeout_cancel(&uc->connection_timeout);
747
748 if (uc->cb->data_read)
749 uc->cb->data_read(uc);
750 }
751 }
752
753 static void __uclient_notify_write(struct uclient_http *uh)
754 {
755 struct uclient *uc = &uh->uc;
756
757 if (uc->cb->data_sent)
758 uc->cb->data_sent(uc);
759 }
760
761 static void uclient_notify_read(struct ustream *us, int bytes)
762 {
763 struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
764
765 __uclient_notify_read(uh);
766 }
767
768 static void uclient_notify_write(struct ustream *us, int bytes)
769 {
770 struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
771
772 __uclient_notify_write(uh);
773 }
774
775 static void uclient_notify_state(struct ustream *us)
776 {
777 struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
778
779 if (uh->ufd.stream.write_error) {
780 uclient_http_error(uh, UCLIENT_ERROR_CONNECT);
781 return;
782 }
783 uclient_notify_eof(uh);
784 }
785
786 static int uclient_setup_http(struct uclient_http *uh)
787 {
788 struct ustream *us = &uh->ufd.stream;
789 int ret;
790
791 uh->us = us;
792 uh->ssl = false;
793
794 us->string_data = true;
795 us->notify_state = uclient_notify_state;
796 us->notify_read = uclient_notify_read;
797 us->notify_write = uclient_notify_write;
798
799 ret = uclient_do_connect(uh, "80");
800 if (ret)
801 return UCLIENT_ERROR_CONNECT;
802
803 return 0;
804 }
805
806 static void uclient_ssl_notify_read(struct ustream *us, int bytes)
807 {
808 struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
809
810 __uclient_notify_read(uh);
811 }
812
813 static void uclient_ssl_notify_write(struct ustream *us, int bytes)
814 {
815 struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
816
817 __uclient_notify_write(uh);
818 }
819
820 static void uclient_ssl_notify_state(struct ustream *us)
821 {
822 struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
823
824 uclient_notify_eof(uh);
825 }
826
827 static void uclient_ssl_notify_error(struct ustream_ssl *ssl, int error, const char *str)
828 {
829 struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
830
831 uclient_http_error(uh, UCLIENT_ERROR_CONNECT);
832 }
833
834 static void uclient_ssl_notify_verify_error(struct ustream_ssl *ssl, int error, const char *str)
835 {
836 struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
837
838 if (!uh->ssl_require_validation)
839 return;
840
841 uclient_http_error(uh, UCLIENT_ERROR_SSL_INVALID_CERT);
842 }
843
844 static void uclient_ssl_notify_connected(struct ustream_ssl *ssl)
845 {
846 struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
847
848 if (!uh->ssl_require_validation)
849 return;
850
851 if (!uh->ussl.valid_cn)
852 uclient_http_error(uh, UCLIENT_ERROR_SSL_CN_MISMATCH);
853 }
854
855 static int uclient_setup_https(struct uclient_http *uh)
856 {
857 struct ustream *us = &uh->ussl.stream;
858 int ret;
859
860 uh->ssl = true;
861 uh->us = us;
862
863 if (!uh->ssl_ctx)
864 return UCLIENT_ERROR_MISSING_SSL_CONTEXT;
865
866 ret = uclient_do_connect(uh, "443");
867 if (ret)
868 return UCLIENT_ERROR_CONNECT;
869
870 us->string_data = true;
871 us->notify_state = uclient_ssl_notify_state;
872 us->notify_read = uclient_ssl_notify_read;
873 us->notify_write = uclient_ssl_notify_write;
874 uh->ussl.notify_error = uclient_ssl_notify_error;
875 uh->ussl.notify_verify_error = uclient_ssl_notify_verify_error;
876 uh->ussl.notify_connected = uclient_ssl_notify_connected;
877 uh->ussl.server_name = uh->uc.url->host;
878 uh->ssl_ops->init(&uh->ussl, &uh->ufd.stream, uh->ssl_ctx, false);
879 uh->ssl_ops->set_peer_cn(&uh->ussl, uh->uc.url->host);
880
881 return 0;
882 }
883
884 static int uclient_http_connect(struct uclient *cl)
885 {
886 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
887 int ret;
888
889 if (!cl->eof || uh->disconnect || uh->connection_close)
890 uclient_http_disconnect(uh);
891
892 uclient_http_init_request(uh);
893
894 if (uh->us)
895 return 0;
896
897 uh->ssl = cl->url->prefix == PREFIX_HTTPS;
898
899 if (uh->ssl)
900 ret = uclient_setup_https(uh);
901 else
902 ret = uclient_setup_http(uh);
903
904 return ret;
905 }
906
907 static void uclient_http_disconnect_cb(struct uloop_timeout *timeout)
908 {
909 struct uclient_http *uh = container_of(timeout, struct uclient_http, disconnect_t);
910
911 uclient_http_disconnect(uh);
912 }
913
914 static struct uclient *uclient_http_alloc(void)
915 {
916 struct uclient_http *uh;
917
918 uh = calloc_a(sizeof(*uh));
919 uh->disconnect_t.cb = uclient_http_disconnect_cb;
920 blob_buf_init(&uh->headers, 0);
921
922 return &uh->uc;
923 }
924
925 static void uclient_http_free_ssl_ctx(struct uclient_http *uh)
926 {
927 uh->ssl_ops = NULL;
928 uh->ssl_ctx = NULL;
929 }
930
931 static void uclient_http_free(struct uclient *cl)
932 {
933 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
934
935 uclient_http_free_url_state(cl);
936 uclient_http_free_ssl_ctx(uh);
937 blob_buf_free(&uh->headers);
938 blob_buf_free(&uh->meta);
939 free(uh);
940 }
941
942 int
943 uclient_http_set_request_type(struct uclient *cl, const char *type)
944 {
945 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
946 int i;
947
948 if (cl->backend != &uclient_backend_http)
949 return -1;
950
951 if (uh->state > HTTP_STATE_INIT)
952 return -1;
953
954 for (i = 0; i < ARRAY_SIZE(request_types); i++) {
955 if (strcmp(request_types[i], type) != 0)
956 continue;
957
958 uh->req_type = i;
959 return 0;
960 }
961
962 return -1;
963 }
964
965 int
966 uclient_http_reset_headers(struct uclient *cl)
967 {
968 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
969
970 blob_buf_init(&uh->headers, 0);
971
972 return 0;
973 }
974
975 int
976 uclient_http_set_header(struct uclient *cl, const char *name, const char *value)
977 {
978 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
979
980 if (cl->backend != &uclient_backend_http)
981 return -1;
982
983 if (uh->state > HTTP_STATE_INIT)
984 return -1;
985
986 blobmsg_add_string(&uh->headers, name, value);
987 return 0;
988 }
989
990 static int
991 uclient_http_send_data(struct uclient *cl, const char *buf, unsigned int len)
992 {
993 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
994
995 if (uh->state >= HTTP_STATE_REQUEST_DONE)
996 return -1;
997
998 uclient_http_send_headers(uh);
999
1000 if (len > 0) {
1001 ustream_printf(uh->us, "%X\r\n", len);
1002 ustream_write(uh->us, buf, len, false);
1003 ustream_printf(uh->us, "\r\n");
1004 }
1005
1006 return len;
1007 }
1008
1009 static int
1010 uclient_http_request_done(struct uclient *cl)
1011 {
1012 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
1013
1014 if (uh->state >= HTTP_STATE_REQUEST_DONE)
1015 return -1;
1016
1017 uclient_http_send_headers(uh);
1018 if (uclient_request_supports_body(uh->req_type))
1019 ustream_printf(uh->us, "0\r\n\r\n");
1020 uh->state = HTTP_STATE_REQUEST_DONE;
1021
1022 return 0;
1023 }
1024
1025 static int
1026 uclient_http_read(struct uclient *cl, char *buf, unsigned int len)
1027 {
1028 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
1029 int read_len = 0;
1030 char *data, *data_end;
1031
1032 if (uh->state < HTTP_STATE_RECV_DATA || !uh->us)
1033 return 0;
1034
1035 data = ustream_get_read_buf(uh->us, &read_len);
1036 if (!data || !read_len)
1037 return 0;
1038
1039 data_end = data + read_len;
1040 read_len = 0;
1041
1042 if (uh->read_chunked == 0) {
1043 char *sep;
1044
1045 if (data[0] == '\r' && data[1] == '\n') {
1046 data += 2;
1047 read_len += 2;
1048 }
1049
1050 sep = strstr(data, "\r\n");
1051 if (!sep)
1052 return 0;
1053
1054 *sep = 0;
1055 uh->read_chunked = strtoul(data, NULL, 16);
1056
1057 read_len += sep + 2 - data;
1058 data = sep + 2;
1059
1060 if (!uh->read_chunked) {
1061 uh->eof = true;
1062 uh->uc.data_eof = true;
1063 }
1064 }
1065
1066 if (len > data_end - data)
1067 len = data_end - data;
1068
1069 if (uh->read_chunked >= 0) {
1070 if (len > uh->read_chunked)
1071 len = uh->read_chunked;
1072
1073 uh->read_chunked -= len;
1074 } else if (uh->content_length >= 0) {
1075 if (len > uh->content_length)
1076 len = uh->content_length;
1077
1078 uh->content_length -= len;
1079 if (!uh->content_length) {
1080 uh->eof = true;
1081 uh->uc.data_eof = true;
1082 }
1083 }
1084
1085 if (len > 0) {
1086 read_len += len;
1087 memcpy(buf, data, len);
1088 }
1089
1090 if (read_len > 0)
1091 ustream_consume(uh->us, read_len);
1092
1093 uclient_notify_eof(uh);
1094
1095 /* Now that we consumed something and if this isn't EOF, start timer again */
1096 if (!uh->uc.eof && !cl->connection_timeout.pending)
1097 uloop_timeout_set(&cl->connection_timeout, cl->timeout_msecs);
1098
1099 return len;
1100 }
1101
1102 int uclient_http_redirect(struct uclient *cl)
1103 {
1104 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
1105 struct blobmsg_policy location = {
1106 .name = "location",
1107 .type = BLOBMSG_TYPE_STRING,
1108 };
1109 struct uclient_url *url = cl->url;
1110 struct blob_attr *tb;
1111
1112 if (cl->backend != &uclient_backend_http)
1113 return false;
1114
1115 switch (cl->status_code) {
1116 case 301:
1117 case 302:
1118 case 307:
1119 break;
1120 default:
1121 return false;
1122 }
1123
1124 blobmsg_parse(&location, 1, &tb, blob_data(uh->meta.head), blob_len(uh->meta.head));
1125 if (!tb)
1126 return false;
1127
1128 url = uclient_get_url_location(url, blobmsg_data(tb));
1129 if (!url)
1130 return false;
1131
1132 free(cl->url);
1133 cl->url = url;
1134 if (uclient_http_connect(cl))
1135 return -1;
1136
1137 uclient_http_request_done(cl);
1138
1139 return true;
1140 }
1141
1142 int uclient_http_set_ssl_ctx(struct uclient *cl, const struct ustream_ssl_ops *ops,
1143 struct ustream_ssl_ctx *ctx, bool require_validation)
1144 {
1145 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
1146
1147 if (cl->backend != &uclient_backend_http)
1148 return -1;
1149
1150 uclient_http_free_url_state(cl);
1151
1152 uclient_http_free_ssl_ctx(uh);
1153 uh->ssl_ops = ops;
1154 uh->ssl_ctx = ctx;
1155 uh->ssl_require_validation = !!ctx && require_validation;
1156
1157 return 0;
1158 }
1159
1160 int uclient_http_set_address_family(struct uclient *cl, int af)
1161 {
1162 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
1163
1164 if (cl->backend != &uclient_backend_http)
1165 return -1;
1166
1167 switch (af) {
1168 case AF_INET:
1169 uh->usock_flags = USOCK_IPV4ONLY;
1170 break;
1171 case AF_INET6:
1172 uh->usock_flags = USOCK_IPV6ONLY;
1173 break;
1174 default:
1175 uh->usock_flags = 0;
1176 break;
1177 }
1178
1179 return 0;
1180 }
1181
1182 const struct uclient_backend uclient_backend_http = {
1183 .prefix = uclient_http_prefix,
1184
1185 .alloc = uclient_http_alloc,
1186 .free = uclient_http_free,
1187 .connect = uclient_http_connect,
1188 .disconnect = uclient_http_request_disconnect,
1189 .update_url = uclient_http_free_url_state,
1190 .update_proxy_url = uclient_http_free_url_state,
1191
1192 .read = uclient_http_read,
1193 .write = uclient_http_send_data,
1194 .request = uclient_http_request_done,
1195 };