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