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