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