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