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