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