core: fix memory leak if url change fails
[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         ustream_printf(uh->us,
544                 "%s %s HTTP/1.1\r\n"
545                 "Host: %s\r\n",
546                 request_types[req_type],
547                 url->location, url->host);
548
549         blobmsg_for_each_attr(cur, uh->headers.head, rem)
550                 ustream_printf(uh->us, "%s: %s\r\n", blobmsg_name(cur), (char *) blobmsg_data(cur));
551
552         if (uh->req_type == REQ_POST || uh->req_type == REQ_PUT)
553                 ustream_printf(uh->us, "Transfer-Encoding: chunked\r\n");
554
555         uclient_http_add_auth_header(uh);
556
557         ustream_printf(uh->us, "\r\n");
558
559         uh->state = HTTP_STATE_HEADERS_SENT;
560 }
561
562 static void uclient_http_headers_complete(struct uclient_http *uh)
563 {
564         enum auth_type auth_type = uh->auth_type;
565         int seq = uh->uc.seq;
566
567         uh->state = HTTP_STATE_RECV_DATA;
568         uh->uc.meta = uh->meta.head;
569         uclient_http_process_headers(uh);
570
571         if (auth_type == AUTH_TYPE_UNKNOWN && uh->uc.status_code == 401 &&
572             (uh->req_type == REQ_HEAD || uh->req_type == REQ_GET)) {
573                 uclient_http_init_request(uh);
574                 uclient_http_send_headers(uh);
575                 uh->state = HTTP_STATE_REQUEST_DONE;
576                 return;
577         }
578
579         if (uh->uc.cb->header_done)
580                 uh->uc.cb->header_done(&uh->uc);
581
582         if (uh->eof || seq != uh->uc.seq)
583                 return;
584
585         if (uh->req_type == REQ_HEAD || uh->uc.status_code == 204) {
586                 uh->eof = true;
587                 uclient_notify_eof(uh);
588         }
589 }
590
591 static void uclient_parse_http_line(struct uclient_http *uh, char *data)
592 {
593         char *name;
594         char *sep;
595
596         if (uh->state == HTTP_STATE_REQUEST_DONE) {
597                 char *code;
598
599                 if (!strlen(data))
600                         return;
601
602                 /* HTTP/1.1 */
603                 strsep(&data, " ");
604
605                 code = strsep(&data, " ");
606                 if (!code)
607                         goto error;
608
609                 uh->uc.status_code = strtoul(code, &sep, 10);
610                 if (sep && *sep)
611                         goto error;
612
613                 uh->state = HTTP_STATE_RECV_HEADERS;
614                 return;
615         }
616
617         if (!*data) {
618                 uclient_http_headers_complete(uh);
619                 return;
620         }
621
622         sep = strchr(data, ':');
623         if (!sep)
624                 return;
625
626         *(sep++) = 0;
627
628         for (name = data; *name; name++)
629                 *name = tolower(*name);
630
631         name = data;
632         while (isspace(*sep))
633                 sep++;
634
635         blobmsg_add_string(&uh->meta, name, sep);
636         return;
637
638 error:
639         uh->uc.status_code = 400;
640         uh->eof = true;
641         uclient_notify_eof(uh);
642 }
643
644 static void __uclient_notify_read(struct uclient_http *uh)
645 {
646         struct uclient *uc = &uh->uc;
647         unsigned int seq = uh->seq;
648         char *data;
649         int len;
650
651         if (uh->state < HTTP_STATE_REQUEST_DONE || uh->state == HTTP_STATE_ERROR)
652                 return;
653
654         data = ustream_get_read_buf(uh->us, &len);
655         if (!data || !len)
656                 return;
657
658         if (uh->state < HTTP_STATE_RECV_DATA) {
659                 char *sep;
660                 int cur_len;
661
662                 do {
663                         sep = strstr(data, "\r\n");
664                         if (!sep)
665                                 break;
666
667                         /* Check for multi-line HTTP headers */
668                         if (sep > data) {
669                                 if (!sep[2])
670                                         return;
671
672                                 if (isspace(sep[2]) && sep[2] != '\r') {
673                                         sep[0] = ' ';
674                                         sep[1] = ' ';
675                                         continue;
676                                 }
677                         }
678
679                         *sep = 0;
680                         cur_len = sep + 2 - data;
681                         uclient_parse_http_line(uh, data);
682                         if (seq != uh->seq)
683                                 return;
684
685                         ustream_consume(uh->us, cur_len);
686                         len -= cur_len;
687
688                         if (uh->eof)
689                                 return;
690
691                         data = ustream_get_read_buf(uh->us, &len);
692                 } while (data && uh->state < HTTP_STATE_RECV_DATA);
693
694                 if (!len)
695                         return;
696         }
697
698         if (uh->eof)
699                 return;
700
701         if (uh->state == HTTP_STATE_RECV_DATA) {
702                 /* Now it's uclient user turn to read some data */
703                 uloop_timeout_cancel(&uc->connection_timeout);
704
705                 if (uc->cb->data_read)
706                         uc->cb->data_read(uc);
707         }
708 }
709
710 static void __uclient_notify_write(struct uclient_http *uh)
711 {
712         struct uclient *uc = &uh->uc;
713
714         if (uc->cb->data_sent)
715                 uc->cb->data_sent(uc);
716 }
717
718 static void uclient_notify_read(struct ustream *us, int bytes)
719 {
720         struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
721
722         __uclient_notify_read(uh);
723 }
724
725 static void uclient_notify_write(struct ustream *us, int bytes)
726 {
727         struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
728
729         __uclient_notify_write(uh);
730 }
731
732 static void uclient_notify_state(struct ustream *us)
733 {
734         struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
735
736         uclient_notify_eof(uh);
737 }
738
739 static int uclient_setup_http(struct uclient_http *uh)
740 {
741         struct ustream *us = &uh->ufd.stream;
742         int ret;
743
744         uh->us = us;
745         uh->ssl = false;
746
747         us->string_data = true;
748         us->notify_state = uclient_notify_state;
749         us->notify_read = uclient_notify_read;
750         us->notify_write = uclient_notify_write;
751
752         ret = uclient_do_connect(uh, "80");
753         if (ret)
754                 return UCLIENT_ERROR_CONNECT;
755
756         return 0;
757 }
758
759 static void uclient_ssl_notify_read(struct ustream *us, int bytes)
760 {
761         struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
762
763         __uclient_notify_read(uh);
764 }
765
766 static void uclient_ssl_notify_write(struct ustream *us, int bytes)
767 {
768         struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
769
770         __uclient_notify_write(uh);
771 }
772
773 static void uclient_ssl_notify_state(struct ustream *us)
774 {
775         struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
776
777         uclient_notify_eof(uh);
778 }
779
780 static void uclient_ssl_notify_error(struct ustream_ssl *ssl, int error, const char *str)
781 {
782         struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
783
784         uclient_http_error(uh, UCLIENT_ERROR_CONNECT);
785 }
786
787 static void uclient_ssl_notify_verify_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         if (!uh->ssl_require_validation)
792                 return;
793
794         uclient_http_error(uh, UCLIENT_ERROR_SSL_INVALID_CERT);
795 }
796
797 static void uclient_ssl_notify_connected(struct ustream_ssl *ssl)
798 {
799         struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
800
801         if (!uh->ssl_require_validation)
802                 return;
803
804         if (!uh->ussl.valid_cn)
805                 uclient_http_error(uh, UCLIENT_ERROR_SSL_CN_MISMATCH);
806 }
807
808 static int uclient_setup_https(struct uclient_http *uh)
809 {
810         struct ustream *us = &uh->ussl.stream;
811         int ret;
812
813         uh->ssl = true;
814         uh->us = us;
815
816         if (!uh->ssl_ctx)
817                 return UCLIENT_ERROR_MISSING_SSL_CONTEXT;
818
819         ret = uclient_do_connect(uh, "443");
820         if (ret)
821                 return UCLIENT_ERROR_CONNECT;
822
823         us->string_data = true;
824         us->notify_state = uclient_ssl_notify_state;
825         us->notify_read = uclient_ssl_notify_read;
826         us->notify_write = uclient_ssl_notify_write;
827         uh->ussl.notify_error = uclient_ssl_notify_error;
828         uh->ussl.notify_verify_error = uclient_ssl_notify_verify_error;
829         uh->ussl.notify_connected = uclient_ssl_notify_connected;
830         uh->ussl.server_name = uh->uc.url->host;
831         uh->ssl_ops->init(&uh->ussl, &uh->ufd.stream, uh->ssl_ctx, false);
832         uh->ssl_ops->set_peer_cn(&uh->ussl, uh->uc.url->host);
833
834         return 0;
835 }
836
837 static int uclient_http_connect(struct uclient *cl)
838 {
839         struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
840         int ret;
841
842         if (!cl->eof || uh->disconnect)
843                 uclient_http_disconnect(uh);
844
845         uclient_http_init_request(uh);
846
847         if (uh->us)
848                 return 0;
849
850         uh->ssl = cl->url->prefix == PREFIX_HTTPS;
851
852         if (uh->ssl)
853                 ret = uclient_setup_https(uh);
854         else
855                 ret = uclient_setup_http(uh);
856
857         return ret;
858 }
859
860 static void uclient_http_disconnect_cb(struct uloop_timeout *timeout)
861 {
862         struct uclient_http *uh = container_of(timeout, struct uclient_http, disconnect_t);
863
864         uclient_http_disconnect(uh);
865 }
866
867 static struct uclient *uclient_http_alloc(void)
868 {
869         struct uclient_http *uh;
870
871         uh = calloc_a(sizeof(*uh));
872         uh->disconnect_t.cb = uclient_http_disconnect_cb;
873         blob_buf_init(&uh->headers, 0);
874
875         return &uh->uc;
876 }
877
878 static void uclient_http_free_ssl_ctx(struct uclient_http *uh)
879 {
880         uh->ssl_ops = NULL;
881         uh->ssl_ctx = NULL;
882 }
883
884 static void uclient_http_free(struct uclient *cl)
885 {
886         struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
887
888         uclient_http_free_url_state(cl);
889         uclient_http_free_ssl_ctx(uh);
890         blob_buf_free(&uh->headers);
891         blob_buf_free(&uh->meta);
892         free(uh);
893 }
894
895 int
896 uclient_http_set_request_type(struct uclient *cl, const char *type)
897 {
898         struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
899         int i;
900
901         if (cl->backend != &uclient_backend_http)
902                 return -1;
903
904         if (uh->state > HTTP_STATE_INIT)
905                 return -1;
906
907         for (i = 0; i < ARRAY_SIZE(request_types); i++) {
908                 if (strcmp(request_types[i], type) != 0)
909                         continue;
910
911                 uh->req_type = i;
912                 return 0;
913         }
914
915         return -1;
916 }
917
918 int
919 uclient_http_reset_headers(struct uclient *cl)
920 {
921         struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
922
923         blob_buf_init(&uh->headers, 0);
924
925         return 0;
926 }
927
928 int
929 uclient_http_set_header(struct uclient *cl, const char *name, const char *value)
930 {
931         struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
932
933         if (cl->backend != &uclient_backend_http)
934                 return -1;
935
936         if (uh->state > HTTP_STATE_INIT)
937                 return -1;
938
939         blobmsg_add_string(&uh->headers, name, value);
940         return 0;
941 }
942
943 static int
944 uclient_http_send_data(struct uclient *cl, const char *buf, unsigned int len)
945 {
946         struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
947
948         if (uh->state >= HTTP_STATE_REQUEST_DONE)
949                 return -1;
950
951         uclient_http_send_headers(uh);
952
953         if (len > 0) {
954                 ustream_printf(uh->us, "%X\r\n", len);
955                 ustream_write(uh->us, buf, len, false);
956                 ustream_printf(uh->us, "\r\n");
957         }
958
959         return len;
960 }
961
962 static int
963 uclient_http_request_done(struct uclient *cl)
964 {
965         struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
966
967         if (uh->state >= HTTP_STATE_REQUEST_DONE)
968                 return -1;
969
970         uclient_http_send_headers(uh);
971         if (uh->req_type == REQ_POST || uh->req_type == REQ_PUT)
972                 ustream_printf(uh->us, "0\r\n\r\n");
973         uh->state = HTTP_STATE_REQUEST_DONE;
974
975         return 0;
976 }
977
978 static int
979 uclient_http_read(struct uclient *cl, char *buf, unsigned int len)
980 {
981         struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
982         int read_len = 0;
983         char *data, *data_end;
984
985         if (uh->state < HTTP_STATE_RECV_DATA || !uh->us)
986                 return 0;
987
988         data = ustream_get_read_buf(uh->us, &read_len);
989         if (!data || !read_len)
990                 return 0;
991
992         data_end = data + read_len;
993         read_len = 0;
994
995         if (uh->read_chunked == 0) {
996                 char *sep;
997
998                 if (data[0] == '\r' && data[1] == '\n') {
999                         data += 2;
1000                         read_len += 2;
1001                 }
1002
1003                 sep = strstr(data, "\r\n");
1004                 if (!sep)
1005                         return 0;
1006
1007                 *sep = 0;
1008                 uh->read_chunked = strtoul(data, NULL, 16);
1009
1010                 read_len += sep + 2 - data;
1011                 data = sep + 2;
1012
1013                 if (!uh->read_chunked) {
1014                         uh->eof = true;
1015                         uh->uc.data_eof = true;
1016                 }
1017         }
1018
1019         if (len > data_end - data)
1020                 len = data_end - data;
1021
1022         if (uh->read_chunked >= 0) {
1023                 if (len > uh->read_chunked)
1024                         len = uh->read_chunked;
1025
1026                 uh->read_chunked -= len;
1027         } else if (uh->content_length >= 0) {
1028                 if (len > uh->content_length)
1029                         len = uh->content_length;
1030
1031                 uh->content_length -= len;
1032                 if (!uh->content_length) {
1033                         uh->eof = true;
1034                         uh->uc.data_eof = true;
1035                 }
1036         }
1037
1038         if (len > 0) {
1039                 read_len += len;
1040                 memcpy(buf, data, len);
1041         }
1042
1043         if (read_len > 0)
1044                 ustream_consume(uh->us, read_len);
1045
1046         uclient_notify_eof(uh);
1047
1048         /* Now that we consumed something and if this isn't EOF, start timer again */
1049         if (!uh->uc.eof && !cl->connection_timeout.pending)
1050                 uloop_timeout_set(&cl->connection_timeout, cl->timeout_msecs);
1051
1052         return len;
1053 }
1054
1055 bool uclient_http_redirect(struct uclient *cl)
1056 {
1057         struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
1058         struct blobmsg_policy location = {
1059                 .name = "location",
1060                 .type = BLOBMSG_TYPE_STRING,
1061         };
1062         struct uclient_url *url = cl->url;
1063         struct blob_attr *tb;
1064
1065         if (cl->backend != &uclient_backend_http)
1066                 return false;
1067
1068         switch (cl->status_code) {
1069         case 301:
1070         case 302:
1071         case 307:
1072                 break;
1073         default:
1074                 return false;
1075         }
1076
1077         blobmsg_parse(&location, 1, &tb, blob_data(uh->meta.head), blob_len(uh->meta.head));
1078         if (!tb)
1079                 return false;
1080
1081         url = uclient_get_url(blobmsg_data(tb), url->auth);
1082         if (!url)
1083                 return false;
1084
1085         free(cl->url);
1086         cl->url = url;
1087         uclient_http_connect(cl);
1088         uclient_http_request_done(cl);
1089
1090         return true;
1091 }
1092
1093 int uclient_http_set_ssl_ctx(struct uclient *cl, const struct ustream_ssl_ops *ops,
1094                              struct ustream_ssl_ctx *ctx, bool require_validation)
1095 {
1096         struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
1097
1098         if (cl->backend != &uclient_backend_http)
1099                 return -1;
1100
1101         uclient_http_free_url_state(cl);
1102
1103         uclient_http_free_ssl_ctx(uh);
1104         uh->ssl_ops = ops;
1105         uh->ssl_ctx = ctx;
1106         uh->ssl_require_validation = !!ctx && require_validation;
1107
1108         return 0;
1109 }
1110
1111 const struct uclient_backend uclient_backend_http = {
1112         .prefix = uclient_http_prefix,
1113
1114         .alloc = uclient_http_alloc,
1115         .free = uclient_http_free,
1116         .connect = uclient_http_connect,
1117         .disconnect = uclient_http_request_disconnect,
1118         .update_url = uclient_http_free_url_state,
1119
1120         .read = uclient_http_read,
1121         .write = uclient_http_send_data,
1122         .request = uclient_http_request_done,
1123 };