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