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