pass auth_str to uclient_new()
[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
501 static void uclient_http_headers_complete(struct uclient_http *uh)
502 {
503         enum auth_type auth_type = uh->auth_type;
504
505         uh->state = HTTP_STATE_RECV_DATA;
506         uh->uc.meta = uh->meta.head;
507         uclient_http_process_headers(uh);
508
509         if (auth_type == AUTH_TYPE_UNKNOWN) {
510                 uclient_http_init_request(uh);
511                 uclient_http_send_headers(uh);
512                 uh->state = HTTP_STATE_REQUEST_DONE;
513                 return;
514         }
515
516         if (uh->uc.cb->header_done)
517                 uh->uc.cb->header_done(&uh->uc);
518
519         if (uh->req_type == REQ_HEAD) {
520                 uh->eof = true;
521                 uclient_notify_eof(uh);
522         }
523 }
524
525 static void uclient_parse_http_line(struct uclient_http *uh, char *data)
526 {
527         char *name;
528         char *sep;
529
530         if (uh->state == HTTP_STATE_REQUEST_DONE) {
531                 char *code;
532
533                 /* HTTP/1.1 */
534                 strsep(&data, " ");
535
536                 code = strsep(&data, " ");
537                 if (!code)
538                         goto error;
539
540                 uh->uc.status_code = strtoul(code, &sep, 10);
541                 if (sep && *sep)
542                         goto error;
543
544                 uh->state = HTTP_STATE_RECV_HEADERS;
545                 return;
546         }
547
548         if (!*data) {
549                 uclient_http_headers_complete(uh);
550                 return;
551         }
552
553         sep = strchr(data, ':');
554         if (!sep)
555                 return;
556
557         *(sep++) = 0;
558
559         for (name = data; *name; name++)
560                 *name = tolower(*name);
561
562         name = data;
563         while (isspace(*sep))
564                 sep++;
565
566         blobmsg_add_string(&uh->meta, name, sep);
567         return;
568
569 error:
570         uh->uc.status_code = 400;
571         uh->eof = true;
572         uclient_notify_eof(uh);
573 }
574
575 static void __uclient_notify_read(struct uclient_http *uh)
576 {
577         struct uclient *uc = &uh->uc;
578         char *data;
579         int len;
580
581         if (uh->state < HTTP_STATE_REQUEST_DONE || uh->state == HTTP_STATE_ERROR)
582                 return;
583
584         data = ustream_get_read_buf(uh->us, &len);
585         if (!data || !len)
586                 return;
587
588         if (uh->state < HTTP_STATE_RECV_DATA) {
589                 char *sep;
590                 int cur_len;
591
592                 do {
593                         sep = strstr(data, "\r\n");
594                         if (!sep)
595                                 break;
596
597                         /* Check for multi-line HTTP headers */
598                         if (sep > data) {
599                                 if (!sep[2])
600                                         return;
601
602                                 if (isspace(sep[2]) && sep[2] != '\r') {
603                                         sep[0] = ' ';
604                                         sep[1] = ' ';
605                                         continue;
606                                 }
607                         }
608
609                         *sep = 0;
610                         cur_len = sep + 2 - data;
611                         uclient_parse_http_line(uh, data);
612                         ustream_consume(uh->us, cur_len);
613                         len -= cur_len;
614
615                         data = ustream_get_read_buf(uh->us, &len);
616                 } while (data && uh->state < HTTP_STATE_RECV_DATA);
617
618                 if (!len)
619                         return;
620         }
621
622         if (uh->state == HTTP_STATE_RECV_DATA && uc->cb->data_read)
623                 uc->cb->data_read(uc);
624 }
625
626 static void uclient_notify_read(struct ustream *us, int bytes)
627 {
628         struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
629
630         __uclient_notify_read(uh);
631 }
632
633 static void uclient_notify_state(struct ustream *us)
634 {
635         struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
636
637         uclient_notify_eof(uh);
638 }
639
640 static int uclient_setup_http(struct uclient_http *uh)
641 {
642         struct ustream *us = &uh->ufd.stream;
643         int ret;
644
645         uh->us = us;
646         us->string_data = true;
647         us->notify_state = uclient_notify_state;
648         us->notify_read = uclient_notify_read;
649
650         ret = uclient_do_connect(uh, "80");
651         if (ret)
652                 return ret;
653
654         return 0;
655 }
656
657 static void uclient_ssl_notify_read(struct ustream *us, int bytes)
658 {
659         struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
660
661         __uclient_notify_read(uh);
662 }
663
664 static void uclient_ssl_notify_state(struct ustream *us)
665 {
666         struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
667
668         uclient_notify_eof(uh);
669 }
670
671 static void uclient_ssl_notify_error(struct ustream_ssl *ssl, int error, const char *str)
672 {
673         struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
674
675         uclient_http_error(uh, UCLIENT_ERROR_CONNECT);
676 }
677
678 static void uclient_ssl_notify_verify_error(struct ustream_ssl *ssl, int error, const char *str)
679 {
680         struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
681
682         if (!uh->ssl_require_validation)
683                 return;
684
685         uclient_http_error(uh, UCLIENT_ERROR_SSL_INVALID_CERT);
686 }
687
688 static void uclient_ssl_notify_connected(struct ustream_ssl *ssl)
689 {
690         struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
691
692         if (!uh->ssl_require_validation)
693                 return;
694
695         if (!uh->ussl.valid_cn)
696                 uclient_http_error(uh, UCLIENT_ERROR_SSL_CN_MISMATCH);
697 }
698
699 static int uclient_setup_https(struct uclient_http *uh)
700 {
701         struct ustream *us = &uh->ussl.stream;
702         int ret;
703
704         uh->ssl = true;
705         uh->us = us;
706
707         ret = uclient_do_connect(uh, "443");
708         if (ret)
709                 return ret;
710
711         if (!uh->ssl_ctx)
712                 uh->ssl_ctx = ustream_ssl_context_new(false);
713
714         us->string_data = true;
715         us->notify_state = uclient_ssl_notify_state;
716         us->notify_read = uclient_ssl_notify_read;
717         uh->ussl.notify_error = uclient_ssl_notify_error;
718         uh->ussl.notify_verify_error = uclient_ssl_notify_verify_error;
719         uh->ussl.notify_connected = uclient_ssl_notify_connected;
720         ustream_ssl_init(&uh->ussl, &uh->ufd.stream, uh->ssl_ctx, false);
721         ustream_ssl_set_peer_cn(&uh->ussl, uh->uc.url->host);
722
723         return 0;
724 }
725
726 static int uclient_http_connect(struct uclient *cl)
727 {
728         struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
729         int ret;
730
731         uclient_http_init_request(uh);
732
733         if (uh->us)
734                 return 0;
735
736         uh->ssl = cl->url->prefix == PREFIX_HTTPS;
737
738         if (uh->ssl)
739                 ret = uclient_setup_https(uh);
740         else
741                 ret = uclient_setup_http(uh);
742
743         if (ret)
744                 uclient_http_error(uh, UCLIENT_ERROR_CONNECT);
745
746         return ret;
747 }
748
749 static struct uclient *uclient_http_alloc(void)
750 {
751         struct uclient_http *uh;
752
753         uh = calloc_a(sizeof(*uh));
754         blob_buf_init(&uh->headers, 0);
755
756         return &uh->uc;
757 }
758
759 static void uclient_http_free_ssl_ctx(struct uclient_http *uh)
760 {
761         if (uh->ssl_ctx && !uh->ssl_ctx_ext)
762                 ustream_ssl_context_free(uh->ssl_ctx);
763
764         uh->ssl_ctx_ext = false;
765 }
766
767 static void uclient_http_free(struct uclient *cl)
768 {
769         struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
770
771         uclient_http_free_ssl_ctx(uh);
772         uclient_http_free_url_state(cl);
773         blob_buf_free(&uh->headers);
774         blob_buf_free(&uh->meta);
775         free(uh);
776 }
777
778 int
779 uclient_http_set_request_type(struct uclient *cl, const char *type)
780 {
781         struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
782         int i;
783
784         if (cl->backend != &uclient_backend_http)
785                 return -1;
786
787         if (uh->state > HTTP_STATE_INIT)
788                 return -1;
789
790         for (i = 0; i < ARRAY_SIZE(request_types); i++) {
791                 if (strcmp(request_types[i], type) != 0)
792                         continue;
793
794                 uh->req_type = i;
795                 return 0;
796         }
797
798         return -1;
799 }
800
801 int
802 uclient_http_reset_headers(struct uclient *cl, const char *name, const char *value)
803 {
804         struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
805
806         blob_buf_init(&uh->headers, 0);
807
808         return 0;
809 }
810
811 int
812 uclient_http_set_header(struct uclient *cl, const char *name, const char *value)
813 {
814         struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
815
816         if (cl->backend != &uclient_backend_http)
817                 return -1;
818
819         if (uh->state > HTTP_STATE_INIT)
820                 return -1;
821
822         blobmsg_add_string(&uh->headers, name, value);
823         return 0;
824 }
825
826 static int
827 uclient_http_send_data(struct uclient *cl, char *buf, unsigned int len)
828 {
829         struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
830
831         if (uh->state >= HTTP_STATE_REQUEST_DONE)
832                 return -1;
833
834         uclient_http_send_headers(uh);
835
836         ustream_printf(uh->us, "%X\r\n", len);
837         if (len > 0)
838                 ustream_write(uh->us, buf, len, false);
839         ustream_printf(uh->us, "\r\n");
840
841         return len;
842 }
843
844 static int
845 uclient_http_request_done(struct uclient *cl)
846 {
847         struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
848
849         if (uh->state >= HTTP_STATE_REQUEST_DONE)
850                 return -1;
851
852         uclient_http_send_headers(uh);
853         uh->state = HTTP_STATE_REQUEST_DONE;
854
855         return 0;
856 }
857
858 static int
859 uclient_http_read(struct uclient *cl, char *buf, unsigned int len)
860 {
861         struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
862         int read_len = 0;
863         char *data, *data_end;
864
865         if (uh->state < HTTP_STATE_RECV_DATA || !uh->us)
866                 return 0;
867
868         data = ustream_get_read_buf(uh->us, &read_len);
869         if (!data || !read_len)
870                 return 0;
871
872         data_end = data + read_len;
873         read_len = 0;
874
875         if (uh->read_chunked == 0) {
876                 char *sep;
877
878                 if (data[0] == '\r' && data[1] == '\n') {
879                         data += 2;
880                         read_len += 2;
881                 }
882
883                 sep = strstr(data, "\r\n");
884                 if (!sep)
885                         return 0;
886
887                 *sep = 0;
888                 uh->read_chunked = strtoul(data, NULL, 16);
889
890                 read_len += sep + 2 - data;
891                 data = sep + 2;
892
893                 if (!uh->read_chunked)
894                         uh->eof = true;
895         }
896
897         if (len > data_end - data)
898                 len = data_end - data;
899
900         if (uh->read_chunked >= 0) {
901                 if (len > uh->read_chunked)
902                         len = uh->read_chunked;
903
904                 uh->read_chunked -= len;
905         } else if (uh->content_length >= 0) {
906                 if (len > uh->content_length)
907                         len = uh->content_length;
908
909                 uh->content_length -= len;
910                 if (!uh->content_length)
911                         uh->eof = true;
912         }
913
914         if (len > 0) {
915                 read_len += len;
916                 memcpy(buf, data, len);
917         }
918
919         if (read_len > 0)
920                 ustream_consume(uh->us, read_len);
921
922         uclient_notify_eof(uh);
923
924         return len;
925 }
926
927 bool uclient_http_redirect(struct uclient *cl)
928 {
929         struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
930         struct blobmsg_policy location = {
931                 .name = "location",
932                 .type = BLOBMSG_TYPE_STRING,
933         };
934         struct uclient_url *url = cl->url;
935         struct blob_attr *tb;
936
937         if (cl->backend != &uclient_backend_http)
938                 return false;
939
940         switch (cl->status_code) {
941         case 301:
942         case 302:
943         case 307:
944                 break;
945         default:
946                 return false;
947         }
948
949         blobmsg_parse(&location, 1, &tb, blob_data(uh->meta.head), blob_len(uh->meta.head));
950         if (!tb)
951                 return false;
952
953         url = uclient_get_url(blobmsg_data(tb), url->auth);
954         if (!url)
955                 return false;
956
957         free(cl->url);
958         cl->url = url;
959         uclient_http_connect(cl);
960         uclient_http_request_done(cl);
961
962         return true;
963 }
964
965 int uclient_http_set_ssl_ctx(struct uclient *cl, struct ustream_ssl_ctx *ctx, bool require_validation)
966 {
967         struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
968
969         if (cl->backend != &uclient_backend_http)
970                 return -1;
971
972         uclient_http_free_url_state(cl);
973
974         uclient_http_free_ssl_ctx(uh);
975         uh->ssl_ctx = ctx;
976         uh->ssl_ctx_ext = !!ctx;
977         uh->ssl_require_validation = !!ctx && require_validation;
978
979         return 0;
980 }
981
982 const struct uclient_backend uclient_backend_http = {
983         .prefix = uclient_http_prefix,
984
985         .alloc = uclient_http_alloc,
986         .free = uclient_http_free,
987         .connect = uclient_http_connect,
988         .update_url = uclient_http_free_url_state,
989
990         .read = uclient_http_read,
991         .write = uclient_http_send_data,
992         .request = uclient_http_request_done,
993 };