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