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