uclient-http: Handle memory allocation failure
[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 int
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 -EINVAL;
311
312 auth_buf = alloca(base64_len(auth_len) + 1);
313 if (!auth_buf)
314 return -ENOMEM;
315
316 base64_encode(url->auth, auth_len, auth_buf);
317 ustream_printf(uh->us, "Authorization: Basic %s\r\n", auth_buf);
318
319 return 0;
320 }
321
322 static char *digest_unquote_sep(char **str)
323 {
324 char *cur = *str + 1;
325 char *start = cur;
326 char *out;
327
328 if (**str != '"')
329 return NULL;
330
331 out = cur;
332 while (1) {
333 if (!*cur)
334 return NULL;
335
336 if (*cur == '"') {
337 cur++;
338 break;
339 }
340
341 if (*cur == '\\')
342 cur++;
343
344 *(out++) = *(cur++);
345 }
346
347 if (*cur == ',')
348 cur++;
349
350 *out = 0;
351 *str = cur;
352
353 return start;
354 }
355
356 static char *digest_sep(char **str)
357 {
358 char *cur, *next;
359
360 cur = *str;
361 next = strchr(*str, ',');
362 if (next) {
363 *str = next + 1;
364 *next = 0;
365 } else {
366 *str += strlen(*str);
367 }
368
369 return cur;
370 }
371
372 static bool strmatch(char **str, const char *prefix)
373 {
374 int len = strlen(prefix);
375
376 if (strncmp(*str, prefix, len) != 0 || (*str)[len] != '=')
377 return false;
378
379 *str += len + 1;
380 return true;
381 }
382
383 static void
384 get_cnonce(char *dest)
385 {
386 uint32_t val = 0;
387 FILE *f;
388 size_t n;
389
390 f = fopen("/dev/urandom", "r");
391 if (f) {
392 n = fread(&val, sizeof(val), 1, f);
393 fclose(f);
394 if (n != 1)
395 return;
396 }
397
398 bin_to_hex(dest, &val, sizeof(val));
399 }
400
401 static void add_field(char **buf, int *ofs, int *len, const char *name, const char *val)
402 {
403 int available = *len - *ofs;
404 int required;
405 const char *next;
406 char *cur;
407
408 if (*len && !*buf)
409 return;
410
411 required = strlen(name) + 4 + strlen(val) * 2;
412 if (required > available)
413 *len += required - available + 64;
414
415 *buf = realloc(*buf, *len);
416 if (!*buf)
417 return;
418
419 cur = *buf + *ofs;
420 cur += sprintf(cur, ", %s=\"", name);
421
422 while ((next = strchr(val, '"'))) {
423 if (next > val) {
424 memcpy(cur, val, next - val);
425 cur += next - val;
426 }
427
428 cur += sprintf(cur, "\\\"");
429 val = next + 1;
430 }
431
432 cur += sprintf(cur, "%s\"", val);
433 *ofs = cur - *buf;
434 }
435
436 static int
437 uclient_http_add_auth_digest(struct uclient_http *uh)
438 {
439 int err = 0;
440 struct uclient_url *url = uh->uc.url;
441 const char *realm = NULL, *opaque = NULL;
442 const char *user, *password;
443 char *buf, *next, *buf_orig;
444 int len, ofs;
445
446 char cnonce_str[9];
447 char nc_str[9];
448 char ahash[33];
449 char hash[33];
450
451 struct http_digest_data data = {
452 .nc = nc_str,
453 .cnonce = cnonce_str,
454 .auth_hash = ahash,
455 };
456
457 len = strlen(uh->auth_str) + 1;
458 if (len > 512) {
459 err = -EINVAL;
460 goto fail;
461 }
462
463 buf = alloca(len);
464 if (!buf) {
465 err = -ENOMEM;
466 goto fail;
467 }
468
469 strcpy(buf, uh->auth_str);
470
471 /* skip auth type */
472 buf_orig = strsep(&buf, " ");
473
474 next = buf;
475 while (*next) {
476 const char **dest = NULL;
477 const char *tmp;
478
479 while (*next && isspace(*next))
480 next++;
481
482 if (strmatch(&next, "realm"))
483 dest = &realm;
484 else if (strmatch(&next, "qop"))
485 dest = &data.qop;
486 else if (strmatch(&next, "nonce"))
487 dest = &data.nonce;
488 else if (strmatch(&next, "opaque"))
489 dest = &opaque;
490 else if (strmatch(&next, "stale") ||
491 strmatch(&next, "algorithm") ||
492 strmatch(&next, "auth-param")) {
493 digest_sep(&next);
494 continue;
495 } else if (strmatch(&next, "domain") ||
496 strmatch(&next, "qop-options"))
497 dest = &tmp;
498 else {
499 digest_sep(&next);
500 continue;
501 }
502
503 *dest = digest_unquote_sep(&next);
504 }
505
506 if (!realm || !data.qop || !data.nonce) {
507 err = -EINVAL;
508 goto fail_buf;
509 }
510
511 sprintf(nc_str, "%08x", uh->nc++);
512 get_cnonce(cnonce_str);
513
514 data.qop = "auth";
515 data.uri = url->location;
516 data.method = request_types[uh->req_type];
517
518 password = strchr(url->auth, ':');
519 if (password) {
520 char *user_buf;
521
522 len = password - url->auth;
523 if (len > 256) {
524 err = -EINVAL;
525 goto fail_buf;
526 }
527
528 user_buf = alloca(len + 1);
529 if (!user_buf) {
530 err = -ENOMEM;
531 goto fail_buf;
532 }
533
534 strncpy(user_buf, url->auth, len);
535 user_buf[len] = 0;
536 user = user_buf;
537 password++;
538 } else {
539 user = url->auth;
540 password = "";
541 }
542
543 http_digest_calculate_auth_hash(ahash, user, realm, password);
544 http_digest_calculate_response(hash, &data);
545
546 buf = NULL;
547 len = 0;
548 ofs = 0;
549
550 add_field(&buf, &ofs, &len, "username", user);
551 add_field(&buf, &ofs, &len, "realm", realm);
552 add_field(&buf, &ofs, &len, "nonce", data.nonce);
553 add_field(&buf, &ofs, &len, "uri", data.uri);
554 add_field(&buf, &ofs, &len, "cnonce", data.cnonce);
555 add_field(&buf, &ofs, &len, "response", hash);
556 if (opaque)
557 add_field(&buf, &ofs, &len, "opaque", opaque);
558
559 ustream_printf(uh->us, "Authorization: Digest nc=%s, qop=%s%s\r\n", data.nc, data.qop, buf);
560
561 free(buf);
562
563 return 0;
564
565 fail_buf:
566 free(buf_orig);
567 fail:
568 return err;
569 }
570
571 static void
572 uclient_http_add_auth_header(struct uclient_http *uh)
573 {
574 if (!uh->uc.url->auth)
575 return;
576
577 switch (uh->auth_type) {
578 case AUTH_TYPE_UNKNOWN:
579 case AUTH_TYPE_NONE:
580 break;
581 case AUTH_TYPE_BASIC:
582 uclient_http_add_auth_basic(uh);
583 break;
584 case AUTH_TYPE_DIGEST:
585 uclient_http_add_auth_digest(uh);
586 break;
587 }
588 }
589
590 static void
591 uclient_http_send_headers(struct uclient_http *uh)
592 {
593 struct uclient_url *url = uh->uc.url;
594 struct blob_attr *cur;
595 enum request_type req_type = uh->req_type;
596 bool literal_ipv6;
597 int rem;
598
599 if (uh->state >= HTTP_STATE_HEADERS_SENT)
600 return;
601
602 if (uh->uc.proxy_url)
603 url = uh->uc.proxy_url;
604
605 literal_ipv6 = strchr(url->host, ':');
606
607 ustream_printf(uh->us,
608 "%s %s HTTP/1.1\r\n"
609 "Host: %s%s%s%s%s\r\n",
610 request_types[req_type], url->location,
611 literal_ipv6 ? "[" : "",
612 url->host,
613 literal_ipv6 ? "]" : "",
614 url->port ? ":" : "",
615 url->port ? url->port : "");
616
617 blobmsg_for_each_attr(cur, uh->headers.head, rem)
618 ustream_printf(uh->us, "%s: %s\r\n", blobmsg_name(cur), (char *) blobmsg_data(cur));
619
620 if (uclient_request_supports_body(uh->req_type))
621 ustream_printf(uh->us, "Transfer-Encoding: chunked\r\n");
622
623 uclient_http_add_auth_header(uh);
624
625 ustream_printf(uh->us, "\r\n");
626
627 uh->state = HTTP_STATE_HEADERS_SENT;
628 }
629
630 static void uclient_http_headers_complete(struct uclient_http *uh)
631 {
632 enum auth_type auth_type = uh->auth_type;
633 int seq = uh->uc.seq;
634
635 uh->state = HTTP_STATE_RECV_DATA;
636 uh->uc.meta = uh->meta.head;
637 uclient_http_process_headers(uh);
638
639 if (auth_type == AUTH_TYPE_UNKNOWN && uh->uc.status_code == 401 &&
640 (uh->req_type == REQ_HEAD || uh->req_type == REQ_GET)) {
641 uclient_http_connect(&uh->uc);
642 uclient_http_send_headers(uh);
643 uh->state = HTTP_STATE_REQUEST_DONE;
644 return;
645 }
646
647 if (uh->uc.cb->header_done)
648 uh->uc.cb->header_done(&uh->uc);
649
650 if (uh->eof || seq != uh->uc.seq)
651 return;
652
653 if (uh->req_type == REQ_HEAD || uh->uc.status_code == 204) {
654 uh->eof = true;
655 uclient_notify_eof(uh);
656 }
657 }
658
659 static void uclient_parse_http_line(struct uclient_http *uh, char *data)
660 {
661 char *name;
662 char *sep;
663
664 if (uh->state == HTTP_STATE_REQUEST_DONE) {
665 char *code;
666
667 if (!strlen(data))
668 return;
669
670 /* HTTP/1.1 */
671 strsep(&data, " ");
672
673 code = strsep(&data, " ");
674 if (!code)
675 goto error;
676
677 uh->uc.status_code = strtoul(code, &sep, 10);
678 if (sep && *sep)
679 goto error;
680
681 uh->state = HTTP_STATE_RECV_HEADERS;
682 return;
683 }
684
685 if (!*data) {
686 uclient_http_headers_complete(uh);
687 return;
688 }
689
690 sep = strchr(data, ':');
691 if (!sep)
692 return;
693
694 *(sep++) = 0;
695
696 for (name = data; *name; name++)
697 *name = tolower(*name);
698
699 name = data;
700 while (isspace(*sep))
701 sep++;
702
703 blobmsg_add_string(&uh->meta, name, sep);
704 return;
705
706 error:
707 uh->uc.status_code = 400;
708 uh->eof = true;
709 uclient_notify_eof(uh);
710 }
711
712 static void __uclient_notify_read(struct uclient_http *uh)
713 {
714 struct uclient *uc = &uh->uc;
715 unsigned int seq = uh->seq;
716 char *data;
717 int len;
718
719 if (uh->state < HTTP_STATE_REQUEST_DONE || uh->state == HTTP_STATE_ERROR)
720 return;
721
722 data = ustream_get_read_buf(uh->us, &len);
723 if (!data || !len)
724 return;
725
726 if (uh->state < HTTP_STATE_RECV_DATA) {
727 char *sep, *next;
728 int cur_len;
729
730 do {
731 sep = strchr(data, '\n');
732 if (!sep)
733 break;
734
735 next = sep + 1;
736 if (sep > data && sep[-1] == '\r')
737 sep--;
738
739 /* Check for multi-line HTTP headers */
740 if (sep > data) {
741 if (!*next)
742 return;
743
744 if (isspace(*next) && *next != '\r' && *next != '\n') {
745 sep[0] = ' ';
746 if (sep + 1 < next)
747 sep[1] = ' ';
748 continue;
749 }
750 }
751
752 *sep = 0;
753 cur_len = next - data;
754 uclient_parse_http_line(uh, data);
755 if (seq != uh->seq)
756 return;
757
758 ustream_consume(uh->us, cur_len);
759 len -= cur_len;
760
761 if (uh->eof)
762 return;
763
764 data = ustream_get_read_buf(uh->us, &len);
765 } while (data && uh->state < HTTP_STATE_RECV_DATA);
766
767 if (!len)
768 return;
769 }
770
771 if (uh->eof)
772 return;
773
774 if (uh->state == HTTP_STATE_RECV_DATA) {
775 /* Now it's uclient user turn to read some data */
776 uloop_timeout_cancel(&uc->connection_timeout);
777
778 if (uc->cb->data_read)
779 uc->cb->data_read(uc);
780 }
781 }
782
783 static void __uclient_notify_write(struct uclient_http *uh)
784 {
785 struct uclient *uc = &uh->uc;
786
787 if (uc->cb->data_sent)
788 uc->cb->data_sent(uc);
789 }
790
791 static void uclient_notify_read(struct ustream *us, int bytes)
792 {
793 struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
794
795 __uclient_notify_read(uh);
796 }
797
798 static void uclient_notify_write(struct ustream *us, int bytes)
799 {
800 struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
801
802 __uclient_notify_write(uh);
803 }
804
805 static void uclient_notify_state(struct ustream *us)
806 {
807 struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
808
809 if (uh->ufd.stream.write_error) {
810 uclient_http_error(uh, UCLIENT_ERROR_CONNECT);
811 return;
812 }
813 uclient_notify_eof(uh);
814 }
815
816 static int uclient_setup_http(struct uclient_http *uh)
817 {
818 struct ustream *us = &uh->ufd.stream;
819 int ret;
820
821 uh->us = us;
822 uh->ssl = false;
823
824 us->string_data = true;
825 us->notify_state = uclient_notify_state;
826 us->notify_read = uclient_notify_read;
827 us->notify_write = uclient_notify_write;
828
829 ret = uclient_do_connect(uh, "80");
830 if (ret)
831 return UCLIENT_ERROR_CONNECT;
832
833 return 0;
834 }
835
836 static void uclient_ssl_notify_read(struct ustream *us, int bytes)
837 {
838 struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
839
840 __uclient_notify_read(uh);
841 }
842
843 static void uclient_ssl_notify_write(struct ustream *us, int bytes)
844 {
845 struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
846
847 __uclient_notify_write(uh);
848 }
849
850 static void uclient_ssl_notify_state(struct ustream *us)
851 {
852 struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
853
854 uclient_notify_eof(uh);
855 }
856
857 static void uclient_ssl_notify_error(struct ustream_ssl *ssl, int error, const char *str)
858 {
859 struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
860
861 uclient_http_error(uh, UCLIENT_ERROR_CONNECT);
862 }
863
864 static void uclient_ssl_notify_verify_error(struct ustream_ssl *ssl, int error, const char *str)
865 {
866 struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
867
868 if (!uh->ssl_require_validation)
869 return;
870
871 uclient_http_error(uh, UCLIENT_ERROR_SSL_INVALID_CERT);
872 }
873
874 static void uclient_ssl_notify_connected(struct ustream_ssl *ssl)
875 {
876 struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
877
878 if (!uh->ssl_require_validation)
879 return;
880
881 if (!uh->ussl.valid_cn)
882 uclient_http_error(uh, UCLIENT_ERROR_SSL_CN_MISMATCH);
883 }
884
885 static int uclient_setup_https(struct uclient_http *uh)
886 {
887 struct ustream *us = &uh->ussl.stream;
888 int ret;
889
890 uh->ssl = true;
891 uh->us = us;
892
893 if (!uh->ssl_ctx)
894 return UCLIENT_ERROR_MISSING_SSL_CONTEXT;
895
896 ret = uclient_do_connect(uh, "443");
897 if (ret)
898 return UCLIENT_ERROR_CONNECT;
899
900 us->string_data = true;
901 us->notify_state = uclient_ssl_notify_state;
902 us->notify_read = uclient_ssl_notify_read;
903 us->notify_write = uclient_ssl_notify_write;
904 uh->ussl.notify_error = uclient_ssl_notify_error;
905 uh->ussl.notify_verify_error = uclient_ssl_notify_verify_error;
906 uh->ussl.notify_connected = uclient_ssl_notify_connected;
907 uh->ussl.server_name = uh->uc.url->host;
908 uh->ssl_ops->init(&uh->ussl, &uh->ufd.stream, uh->ssl_ctx, false);
909 uh->ssl_ops->set_peer_cn(&uh->ussl, uh->uc.url->host);
910
911 return 0;
912 }
913
914 static int uclient_http_connect(struct uclient *cl)
915 {
916 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
917 int ret;
918
919 if (!cl->eof || uh->disconnect || uh->connection_close)
920 uclient_http_disconnect(uh);
921
922 uclient_http_init_request(uh);
923
924 if (uh->us)
925 return 0;
926
927 uh->ssl = cl->url->prefix == PREFIX_HTTPS;
928
929 if (uh->ssl)
930 ret = uclient_setup_https(uh);
931 else
932 ret = uclient_setup_http(uh);
933
934 return ret;
935 }
936
937 static void uclient_http_disconnect_cb(struct uloop_timeout *timeout)
938 {
939 struct uclient_http *uh = container_of(timeout, struct uclient_http, disconnect_t);
940
941 uclient_http_disconnect(uh);
942 }
943
944 static struct uclient *uclient_http_alloc(void)
945 {
946 struct uclient_http *uh;
947
948 uh = calloc_a(sizeof(*uh));
949 if (!uh)
950 return NULL;
951
952 uh->disconnect_t.cb = uclient_http_disconnect_cb;
953 blob_buf_init(&uh->headers, 0);
954
955 return &uh->uc;
956 }
957
958 static void uclient_http_free_ssl_ctx(struct uclient_http *uh)
959 {
960 uh->ssl_ops = NULL;
961 uh->ssl_ctx = NULL;
962 }
963
964 static void uclient_http_free(struct uclient *cl)
965 {
966 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
967
968 uclient_http_free_url_state(cl);
969 uclient_http_free_ssl_ctx(uh);
970 blob_buf_free(&uh->headers);
971 blob_buf_free(&uh->meta);
972 free(uh);
973 }
974
975 int
976 uclient_http_set_request_type(struct uclient *cl, const char *type)
977 {
978 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
979 int i;
980
981 if (cl->backend != &uclient_backend_http)
982 return -1;
983
984 if (uh->state > HTTP_STATE_INIT)
985 return -1;
986
987 for (i = 0; i < ARRAY_SIZE(request_types); i++) {
988 if (strcmp(request_types[i], type) != 0)
989 continue;
990
991 uh->req_type = i;
992 return 0;
993 }
994
995 return -1;
996 }
997
998 int
999 uclient_http_reset_headers(struct uclient *cl)
1000 {
1001 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
1002
1003 blob_buf_init(&uh->headers, 0);
1004
1005 return 0;
1006 }
1007
1008 int
1009 uclient_http_set_header(struct uclient *cl, const char *name, const char *value)
1010 {
1011 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
1012
1013 if (cl->backend != &uclient_backend_http)
1014 return -1;
1015
1016 if (uh->state > HTTP_STATE_INIT)
1017 return -1;
1018
1019 blobmsg_add_string(&uh->headers, name, value);
1020 return 0;
1021 }
1022
1023 static int
1024 uclient_http_send_data(struct uclient *cl, const char *buf, unsigned int len)
1025 {
1026 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
1027
1028 if (uh->state >= HTTP_STATE_REQUEST_DONE)
1029 return -1;
1030
1031 uclient_http_send_headers(uh);
1032
1033 if (len > 0) {
1034 ustream_printf(uh->us, "%X\r\n", len);
1035 ustream_write(uh->us, buf, len, false);
1036 ustream_printf(uh->us, "\r\n");
1037 }
1038
1039 return len;
1040 }
1041
1042 static int
1043 uclient_http_request_done(struct uclient *cl)
1044 {
1045 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
1046
1047 if (uh->state >= HTTP_STATE_REQUEST_DONE)
1048 return -1;
1049
1050 uclient_http_send_headers(uh);
1051 if (uclient_request_supports_body(uh->req_type))
1052 ustream_printf(uh->us, "0\r\n\r\n");
1053 uh->state = HTTP_STATE_REQUEST_DONE;
1054
1055 return 0;
1056 }
1057
1058 static int
1059 uclient_http_read(struct uclient *cl, char *buf, unsigned int len)
1060 {
1061 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
1062 int read_len = 0;
1063 char *data, *data_end;
1064
1065 if (uh->state < HTTP_STATE_RECV_DATA || !uh->us)
1066 return 0;
1067
1068 data = ustream_get_read_buf(uh->us, &read_len);
1069 if (!data || !read_len)
1070 return 0;
1071
1072 data_end = data + read_len;
1073 read_len = 0;
1074
1075 if (uh->read_chunked == 0) {
1076 char *sep;
1077
1078 if (data[0] == '\r' && data[1] == '\n') {
1079 data += 2;
1080 read_len += 2;
1081 }
1082
1083 sep = strstr(data, "\r\n");
1084 if (!sep)
1085 return 0;
1086
1087 *sep = 0;
1088 uh->read_chunked = strtoul(data, NULL, 16);
1089
1090 read_len += sep + 2 - data;
1091 data = sep + 2;
1092
1093 if (!uh->read_chunked) {
1094 uh->eof = true;
1095 uh->uc.data_eof = true;
1096 }
1097 }
1098
1099 if (len > data_end - data)
1100 len = data_end - data;
1101
1102 if (uh->read_chunked >= 0) {
1103 if (len > uh->read_chunked)
1104 len = uh->read_chunked;
1105
1106 uh->read_chunked -= len;
1107 } else if (uh->content_length >= 0) {
1108 if (len > uh->content_length)
1109 len = uh->content_length;
1110
1111 uh->content_length -= len;
1112 if (!uh->content_length) {
1113 uh->eof = true;
1114 uh->uc.data_eof = true;
1115 }
1116 }
1117
1118 if (len > 0) {
1119 read_len += len;
1120 memcpy(buf, data, len);
1121 }
1122
1123 if (read_len > 0)
1124 ustream_consume(uh->us, read_len);
1125
1126 uclient_notify_eof(uh);
1127
1128 /* Now that we consumed something and if this isn't EOF, start timer again */
1129 if (!uh->uc.eof && !cl->connection_timeout.pending)
1130 uloop_timeout_set(&cl->connection_timeout, cl->timeout_msecs);
1131
1132 return len;
1133 }
1134
1135 int uclient_http_redirect(struct uclient *cl)
1136 {
1137 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
1138 struct blobmsg_policy location = {
1139 .name = "location",
1140 .type = BLOBMSG_TYPE_STRING,
1141 };
1142 struct uclient_url *url = cl->url;
1143 struct blob_attr *tb;
1144
1145 if (cl->backend != &uclient_backend_http)
1146 return false;
1147
1148 switch (cl->status_code) {
1149 case 301:
1150 case 302:
1151 case 307:
1152 break;
1153 default:
1154 return false;
1155 }
1156
1157 blobmsg_parse(&location, 1, &tb, blob_data(uh->meta.head), blob_len(uh->meta.head));
1158 if (!tb)
1159 return false;
1160
1161 url = uclient_get_url_location(url, blobmsg_data(tb));
1162 if (!url)
1163 return false;
1164
1165 free(cl->url);
1166 cl->url = url;
1167 if (uclient_http_connect(cl))
1168 return -1;
1169
1170 uclient_http_request_done(cl);
1171
1172 return true;
1173 }
1174
1175 int uclient_http_set_ssl_ctx(struct uclient *cl, const struct ustream_ssl_ops *ops,
1176 struct ustream_ssl_ctx *ctx, bool require_validation)
1177 {
1178 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
1179
1180 if (cl->backend != &uclient_backend_http)
1181 return -1;
1182
1183 uclient_http_free_url_state(cl);
1184
1185 uclient_http_free_ssl_ctx(uh);
1186 uh->ssl_ops = ops;
1187 uh->ssl_ctx = ctx;
1188 uh->ssl_require_validation = !!ctx && require_validation;
1189
1190 return 0;
1191 }
1192
1193 int uclient_http_set_address_family(struct uclient *cl, int af)
1194 {
1195 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
1196
1197 if (cl->backend != &uclient_backend_http)
1198 return -1;
1199
1200 switch (af) {
1201 case AF_INET:
1202 uh->usock_flags = USOCK_IPV4ONLY;
1203 break;
1204 case AF_INET6:
1205 uh->usock_flags = USOCK_IPV6ONLY;
1206 break;
1207 default:
1208 uh->usock_flags = 0;
1209 break;
1210 }
1211
1212 return 0;
1213 }
1214
1215 const struct uclient_backend uclient_backend_http = {
1216 .prefix = uclient_http_prefix,
1217
1218 .alloc = uclient_http_alloc,
1219 .free = uclient_http_free,
1220 .connect = uclient_http_connect,
1221 .disconnect = uclient_http_request_disconnect,
1222 .update_url = uclient_http_free_url_state,
1223 .update_proxy_url = uclient_http_free_url_state,
1224
1225 .read = uclient_http_read,
1226 .write = uclient_http_send_data,
1227 .request = uclient_http_request_done,
1228 };