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