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