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