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