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