47c890fca689cd0457108725b5ac91098d59142a
[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_write(struct uclient_http *uh)
655 {
656         struct uclient *uc = &uh->uc;
657         uc->cb->data_sent(uc);
658 }
659
660 static void uclient_notify_read(struct ustream *us, int bytes)
661 {
662         struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
663
664         __uclient_notify_read(uh);
665 }
666
667 static void uclient_notify_write(struct ustream *us, int bytes)
668 {
669         struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
670
671         __uclient_notify_write(uh);
672 }
673
674 static void uclient_notify_state(struct ustream *us)
675 {
676         struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
677
678         uclient_notify_eof(uh);
679 }
680
681 static int uclient_setup_http(struct uclient_http *uh)
682 {
683         struct ustream *us = &uh->ufd.stream;
684         int ret;
685
686         uh->us = us;
687         uh->ssl = false;
688
689         us->string_data = true;
690         us->notify_state = uclient_notify_state;
691         us->notify_read = uclient_notify_read;
692         us->notify_write = uclient_notify_write;
693
694         ret = uclient_do_connect(uh, "80");
695         if (ret)
696                 return UCLIENT_ERROR_CONNECT;
697
698         return 0;
699 }
700
701 static void uclient_ssl_notify_read(struct ustream *us, int bytes)
702 {
703         struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
704
705         __uclient_notify_read(uh);
706 }
707
708 static void uclient_ssl_notify_write(struct ustream *us, int bytes)
709 {
710         struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
711
712         __uclient_notify_write(uh);
713 }
714
715 static void uclient_ssl_notify_state(struct ustream *us)
716 {
717         struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
718
719         uclient_notify_eof(uh);
720 }
721
722 static void uclient_ssl_notify_error(struct ustream_ssl *ssl, int error, const char *str)
723 {
724         struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
725
726         uclient_http_error(uh, UCLIENT_ERROR_CONNECT);
727 }
728
729 static void uclient_ssl_notify_verify_error(struct ustream_ssl *ssl, int error, const char *str)
730 {
731         struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
732
733         if (!uh->ssl_require_validation)
734                 return;
735
736         uclient_http_error(uh, UCLIENT_ERROR_SSL_INVALID_CERT);
737 }
738
739 static void uclient_ssl_notify_connected(struct ustream_ssl *ssl)
740 {
741         struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
742
743         if (!uh->ssl_require_validation)
744                 return;
745
746         if (!uh->ussl.valid_cn)
747                 uclient_http_error(uh, UCLIENT_ERROR_SSL_CN_MISMATCH);
748 }
749
750 static int uclient_setup_https(struct uclient_http *uh)
751 {
752         struct ustream *us = &uh->ussl.stream;
753         int ret;
754
755         uh->ssl = true;
756         uh->us = us;
757
758         if (!uh->ssl_ctx)
759                 return UCLIENT_ERROR_MISSING_SSL_CONTEXT;
760
761         ret = uclient_do_connect(uh, "443");
762         if (ret)
763                 return UCLIENT_ERROR_CONNECT;
764
765         us->string_data = true;
766         us->notify_state = uclient_ssl_notify_state;
767         us->notify_read = uclient_ssl_notify_read;
768         us->notify_write = uclient_ssl_notify_write;
769         uh->ussl.notify_error = uclient_ssl_notify_error;
770         uh->ussl.notify_verify_error = uclient_ssl_notify_verify_error;
771         uh->ussl.notify_connected = uclient_ssl_notify_connected;
772         uh->ssl_ops->init(&uh->ussl, &uh->ufd.stream, uh->ssl_ctx, false);
773         uh->ssl_ops->set_peer_cn(&uh->ussl, uh->uc.url->host);
774
775         return 0;
776 }
777
778 static int uclient_http_connect(struct uclient *cl)
779 {
780         struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
781         int ret;
782
783         uclient_http_init_request(uh);
784
785         if (uh->us)
786                 return 0;
787
788         uh->ssl = cl->url->prefix == PREFIX_HTTPS;
789
790         if (uh->ssl)
791                 ret = uclient_setup_https(uh);
792         else
793                 ret = uclient_setup_http(uh);
794
795         return ret;
796 }
797
798 static void uclient_http_disconnect_cb(struct uloop_timeout *timeout)
799 {
800         struct uclient_http *uh = container_of(timeout, struct uclient_http, disconnect_t);
801
802         uclient_http_disconnect(uh);
803 }
804
805 static struct uclient *uclient_http_alloc(void)
806 {
807         struct uclient_http *uh;
808
809         uh = calloc_a(sizeof(*uh));
810         uh->disconnect_t.cb = uclient_http_disconnect_cb;
811         blob_buf_init(&uh->headers, 0);
812
813         return &uh->uc;
814 }
815
816 static void uclient_http_free_ssl_ctx(struct uclient_http *uh)
817 {
818         uh->ssl_ops = NULL;
819         uh->ssl_ctx = NULL;
820 }
821
822 static void uclient_http_free(struct uclient *cl)
823 {
824         struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
825
826         uclient_http_free_url_state(cl);
827         uclient_http_free_ssl_ctx(uh);
828         blob_buf_free(&uh->headers);
829         blob_buf_free(&uh->meta);
830         free(uh);
831 }
832
833 int
834 uclient_http_set_request_type(struct uclient *cl, const char *type)
835 {
836         struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
837         int i;
838
839         if (cl->backend != &uclient_backend_http)
840                 return -1;
841
842         if (uh->state > HTTP_STATE_INIT)
843                 return -1;
844
845         for (i = 0; i < ARRAY_SIZE(request_types); i++) {
846                 if (strcmp(request_types[i], type) != 0)
847                         continue;
848
849                 uh->req_type = i;
850                 return 0;
851         }
852
853         return -1;
854 }
855
856 int
857 uclient_http_reset_headers(struct uclient *cl)
858 {
859         struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
860
861         blob_buf_init(&uh->headers, 0);
862
863         return 0;
864 }
865
866 int
867 uclient_http_set_header(struct uclient *cl, const char *name, const char *value)
868 {
869         struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
870
871         if (cl->backend != &uclient_backend_http)
872                 return -1;
873
874         if (uh->state > HTTP_STATE_INIT)
875                 return -1;
876
877         blobmsg_add_string(&uh->headers, name, value);
878         return 0;
879 }
880
881 static int
882 uclient_http_send_data(struct uclient *cl, char *buf, unsigned int len)
883 {
884         struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
885
886         if (uh->state >= HTTP_STATE_REQUEST_DONE)
887                 return -1;
888
889         uclient_http_send_headers(uh);
890
891         if (len > 0) {
892                 ustream_printf(uh->us, "%X\r\n", len);
893                 ustream_write(uh->us, buf, len, false);
894                 ustream_printf(uh->us, "\r\n");
895         }
896
897         return len;
898 }
899
900 static int
901 uclient_http_request_done(struct uclient *cl)
902 {
903         struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
904
905         if (uh->state >= HTTP_STATE_REQUEST_DONE)
906                 return -1;
907
908         uclient_http_send_headers(uh);
909         if (uh->req_type == REQ_POST || uh->req_type == REQ_PUT)
910                 ustream_printf(uh->us, "0\r\n\r\n");
911         uh->state = HTTP_STATE_REQUEST_DONE;
912
913         return 0;
914 }
915
916 static int
917 uclient_http_read(struct uclient *cl, char *buf, unsigned int len)
918 {
919         struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
920         int read_len = 0;
921         char *data, *data_end;
922
923         if (uh->state < HTTP_STATE_RECV_DATA || !uh->us)
924                 return 0;
925
926         data = ustream_get_read_buf(uh->us, &read_len);
927         if (!data || !read_len)
928                 return 0;
929
930         data_end = data + read_len;
931         read_len = 0;
932
933         if (uh->read_chunked == 0) {
934                 char *sep;
935
936                 if (data[0] == '\r' && data[1] == '\n') {
937                         data += 2;
938                         read_len += 2;
939                 }
940
941                 sep = strstr(data, "\r\n");
942                 if (!sep)
943                         return 0;
944
945                 *sep = 0;
946                 uh->read_chunked = strtoul(data, NULL, 16);
947
948                 read_len += sep + 2 - data;
949                 data = sep + 2;
950
951                 if (!uh->read_chunked) {
952                         uh->eof = true;
953                         uh->uc.data_eof = true;
954                 }
955         }
956
957         if (len > data_end - data)
958                 len = data_end - data;
959
960         if (uh->read_chunked >= 0) {
961                 if (len > uh->read_chunked)
962                         len = uh->read_chunked;
963
964                 uh->read_chunked -= len;
965         } else if (uh->content_length >= 0) {
966                 if (len > uh->content_length)
967                         len = uh->content_length;
968
969                 uh->content_length -= len;
970                 if (!uh->content_length) {
971                         uh->eof = true;
972                         uh->uc.data_eof = true;
973                 }
974         }
975
976         if (len > 0) {
977                 read_len += len;
978                 memcpy(buf, data, len);
979         }
980
981         if (read_len > 0)
982                 ustream_consume(uh->us, read_len);
983
984         uclient_notify_eof(uh);
985
986         return len;
987 }
988
989 bool uclient_http_redirect(struct uclient *cl)
990 {
991         struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
992         struct blobmsg_policy location = {
993                 .name = "location",
994                 .type = BLOBMSG_TYPE_STRING,
995         };
996         struct uclient_url *url = cl->url;
997         struct blob_attr *tb;
998
999         if (cl->backend != &uclient_backend_http)
1000                 return false;
1001
1002         switch (cl->status_code) {
1003         case 301:
1004         case 302:
1005         case 307:
1006                 break;
1007         default:
1008                 return false;
1009         }
1010
1011         blobmsg_parse(&location, 1, &tb, blob_data(uh->meta.head), blob_len(uh->meta.head));
1012         if (!tb)
1013                 return false;
1014
1015         url = uclient_get_url(blobmsg_data(tb), url->auth);
1016         if (!url)
1017                 return false;
1018
1019         free(cl->url);
1020         cl->url = url;
1021         uclient_http_connect(cl);
1022         uclient_http_request_done(cl);
1023
1024         return true;
1025 }
1026
1027 int uclient_http_set_ssl_ctx(struct uclient *cl, const struct ustream_ssl_ops *ops,
1028                              struct ustream_ssl_ctx *ctx, bool require_validation)
1029 {
1030         struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
1031
1032         if (cl->backend != &uclient_backend_http)
1033                 return -1;
1034
1035         uclient_http_free_url_state(cl);
1036
1037         uclient_http_free_ssl_ctx(uh);
1038         uh->ssl_ops = ops;
1039         uh->ssl_ctx = ctx;
1040         uh->ssl_require_validation = !!ctx && require_validation;
1041
1042         return 0;
1043 }
1044
1045 static void uclient_http_request_disconnect(struct uclient *cl)
1046 {
1047         struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
1048
1049         if (!uh->us)
1050                 return;
1051
1052         uh->eof = true;
1053         uh->disconnect = true;
1054         uloop_timeout_set(&uh->disconnect_t, 1);
1055 }
1056
1057 const struct uclient_backend uclient_backend_http = {
1058         .prefix = uclient_http_prefix,
1059
1060         .alloc = uclient_http_alloc,
1061         .free = uclient_http_free,
1062         .connect = uclient_http_connect,
1063         .disconnect = uclient_http_request_disconnect,
1064         .update_url = uclient_http_free_url_state,
1065
1066         .read = uclient_http_read,
1067         .write = uclient_http_send_data,
1068         .request = uclient_http_request_done,
1069 };