2 * uclient - ustream based protocol client library
4 * Copyright (C) 2014 Felix Fietkau <nbd@openwrt.org>
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.
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.
23 #include <libubox/ustream.h>
24 #include <libubox/ustream-ssl.h>
25 #include <libubox/usock.h>
26 #include <libubox/blobmsg.h>
29 #include "uclient-utils.h"
30 #include "uclient-backend.h"
50 HTTP_STATE_HEADERS_SENT,
51 HTTP_STATE_REQUEST_DONE,
52 HTTP_STATE_RECV_HEADERS,
57 static const char * const request_types[__REQ_MAX] = {
62 [REQ_DELETE] = "DELETE",
68 const struct ustream_ssl_ops *ssl_ops;
69 struct ustream_ssl_ctx *ssl_ctx;
72 struct ustream_fd ufd;
73 struct ustream_ssl ussl;
75 struct uloop_timeout disconnect_t;
78 bool ssl_require_validation;
81 bool connection_close;
83 enum request_type req_type;
84 enum http_state state;
86 enum auth_type auth_type;
94 struct blob_buf headers;
104 static const char * const uclient_http_prefix[] = {
105 [PREFIX_HTTP] = "http://",
106 [PREFIX_HTTPS] = "https://",
107 [__PREFIX_MAX] = NULL
110 static int uclient_do_connect(struct uclient_http *uh, const char *port)
115 if (uh->uc.url->port)
116 port = uh->uc.url->port;
118 memset(&uh->uc.remote_addr, 0, sizeof(uh->uc.remote_addr));
120 fd = usock_inet(USOCK_TCP | USOCK_NONBLOCK, uh->uc.url->host, port, &uh->uc.remote_addr);
124 ustream_fd_init(&uh->ufd, fd);
126 sl = sizeof(uh->uc.local_addr);
127 memset(&uh->uc.local_addr, 0, sl);
128 getsockname(fd, &uh->uc.local_addr.sa, &sl);
133 static void uclient_http_disconnect(struct uclient_http *uh)
135 uloop_timeout_cancel(&uh->disconnect_t);
140 ustream_free(&uh->ussl.stream);
141 ustream_free(&uh->ufd.stream);
142 close(uh->ufd.fd.fd);
146 static void uclient_http_free_url_state(struct uclient *cl)
148 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
150 uh->auth_type = AUTH_TYPE_UNKNOWN;
153 uclient_http_disconnect(uh);
156 static void uclient_http_error(struct uclient_http *uh, int code)
158 uh->state = HTTP_STATE_ERROR;
160 ustream_state_change(uh->us);
161 uclient_backend_set_error(&uh->uc, code);
164 static void uclient_http_request_disconnect(struct uclient *cl)
166 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
172 uh->disconnect = true;
173 uloop_timeout_set(&uh->disconnect_t, 1);
176 static void uclient_notify_eof(struct uclient_http *uh)
178 struct ustream *us = uh->us;
184 if (!us->eof && !us->write_error)
187 if (ustream_pending_data(us, false))
191 uclient_backend_set_eof(&uh->uc);
193 if (uh->connection_close)
194 uclient_http_request_disconnect(&uh->uc);
197 static void uclient_http_reset_state(struct uclient_http *uh)
200 uclient_backend_reset_state(&uh->uc);
201 uh->read_chunked = -1;
202 uh->content_length = -1;
204 uh->disconnect = false;
205 uh->connection_close = false;
206 uh->state = HTTP_STATE_INIT;
208 if (uh->auth_type == AUTH_TYPE_UNKNOWN && !uh->uc.url->auth)
209 uh->auth_type = AUTH_TYPE_NONE;
212 static void uclient_http_init_request(struct uclient_http *uh)
215 uclient_http_reset_state(uh);
216 blob_buf_init(&uh->meta, 0);
219 static enum auth_type
220 uclient_http_update_auth_type(struct uclient_http *uh)
223 return AUTH_TYPE_NONE;
225 if (!strncasecmp(uh->auth_str, "basic", 5))
226 return AUTH_TYPE_BASIC;
228 if (!strncasecmp(uh->auth_str, "digest", 6))
229 return AUTH_TYPE_DIGEST;
231 return AUTH_TYPE_NONE;
234 static void uclient_http_process_headers(struct uclient_http *uh)
237 HTTP_HDR_TRANSFER_ENCODING,
239 HTTP_HDR_CONTENT_LENGTH,
243 static const struct blobmsg_policy hdr_policy[__HTTP_HDR_MAX] = {
244 #define hdr(_name) { .name = _name, .type = BLOBMSG_TYPE_STRING }
245 [HTTP_HDR_TRANSFER_ENCODING] = hdr("transfer-encoding"),
246 [HTTP_HDR_CONNECTION] = hdr("connection"),
247 [HTTP_HDR_CONTENT_LENGTH] = hdr("content-length"),
248 [HTTP_HDR_AUTH] = hdr("www-authenticate"),
251 struct blob_attr *tb[__HTTP_HDR_MAX];
252 struct blob_attr *cur;
254 blobmsg_parse(hdr_policy, __HTTP_HDR_MAX, tb, blob_data(uh->meta.head), blob_len(uh->meta.head));
256 cur = tb[HTTP_HDR_TRANSFER_ENCODING];
257 if (cur && strstr(blobmsg_data(cur), "chunked"))
258 uh->read_chunked = 0;
260 cur = tb[HTTP_HDR_CONNECTION];
261 if (cur && strstr(blobmsg_data(cur), "close"))
262 uh->connection_close = true;
264 cur = tb[HTTP_HDR_CONTENT_LENGTH];
266 uh->content_length = strtoul(blobmsg_data(cur), NULL, 10);
268 cur = tb[HTTP_HDR_AUTH];
271 uh->auth_str = strdup(blobmsg_data(cur));
274 uh->auth_type = uclient_http_update_auth_type(uh);
278 uclient_http_add_auth_basic(struct uclient_http *uh)
280 struct uclient_url *url = uh->uc.url;
281 int auth_len = strlen(url->auth);
287 auth_buf = alloca(base64_len(auth_len) + 1);
288 base64_encode(url->auth, auth_len, auth_buf);
289 ustream_printf(uh->us, "Authorization: Basic %s\r\n", auth_buf);
292 static char *digest_unquote_sep(char **str)
294 char *cur = *str + 1;
326 static char *digest_sep(char **str)
331 next = strchr(*str, ',');
336 *str += strlen(*str);
342 static bool strmatch(char **str, const char *prefix)
344 int len = strlen(prefix);
346 if (strncmp(*str, prefix, len) != 0 || (*str)[len] != '=')
354 get_cnonce(char *dest)
359 f = fopen("/dev/urandom", "r");
361 fread(&val, sizeof(val), 1, f);
365 bin_to_hex(dest, &val, sizeof(val));
368 static void add_field(char **buf, int *ofs, int *len, const char *name, const char *val)
370 int available = *len - *ofs;
378 required = strlen(name) + 4 + strlen(val) * 2;
379 if (required > available)
380 *len += required - available + 64;
382 *buf = realloc(*buf, *len);
387 cur += sprintf(cur, ", %s=\"", name);
389 while ((next = strchr(val, '"'))) {
391 memcpy(cur, val, next - val);
395 cur += sprintf(cur, "\\\"");
399 cur += sprintf(cur, "%s\"", val);
404 uclient_http_add_auth_digest(struct uclient_http *uh)
406 struct uclient_url *url = uh->uc.url;
407 const char *realm = NULL, *opaque = NULL;
408 const char *user, *password;
417 struct http_digest_data data = {
419 .cnonce = cnonce_str,
423 len = strlen(uh->auth_str) + 1;
428 strcpy(buf, uh->auth_str);
435 const char **dest = NULL;
438 while (*next && isspace(*next))
441 if (strmatch(&next, "realm"))
443 else if (strmatch(&next, "qop"))
445 else if (strmatch(&next, "nonce"))
447 else if (strmatch(&next, "opaque"))
449 else if (strmatch(&next, "stale") ||
450 strmatch(&next, "algorithm") ||
451 strmatch(&next, "auth-param")) {
454 } else if (strmatch(&next, "domain") ||
455 strmatch(&next, "qop-options"))
462 *dest = digest_unquote_sep(&next);
465 if (!realm || !data.qop || !data.nonce)
468 sprintf(nc_str, "%08x", uh->nc++);
469 get_cnonce(cnonce_str);
472 data.uri = url->location;
473 data.method = request_types[uh->req_type];
475 password = strchr(url->auth, ':');
479 len = password - url->auth;
483 user_buf = alloca(len + 1);
484 strncpy(user_buf, url->auth, len);
493 http_digest_calculate_auth_hash(ahash, user, realm, password);
494 http_digest_calculate_response(hash, &data);
500 add_field(&buf, &ofs, &len, "username", user);
501 add_field(&buf, &ofs, &len, "realm", realm);
502 add_field(&buf, &ofs, &len, "nonce", data.nonce);
503 add_field(&buf, &ofs, &len, "uri", data.uri);
504 add_field(&buf, &ofs, &len, "cnonce", data.cnonce);
505 add_field(&buf, &ofs, &len, "response", hash);
507 add_field(&buf, &ofs, &len, "opaque", opaque);
509 ustream_printf(uh->us, "Authorization: Digest nc=%s, qop=%s%s\r\n", data.nc, data.qop, buf);
514 uclient_http_add_auth_header(struct uclient_http *uh)
516 if (!uh->uc.url->auth)
519 switch (uh->auth_type) {
520 case AUTH_TYPE_UNKNOWN:
523 case AUTH_TYPE_BASIC:
524 uclient_http_add_auth_basic(uh);
526 case AUTH_TYPE_DIGEST:
527 uclient_http_add_auth_digest(uh);
533 uclient_http_send_headers(struct uclient_http *uh)
535 struct uclient_url *url = uh->uc.url;
536 struct blob_attr *cur;
537 enum request_type req_type = uh->req_type;
540 if (uh->state >= HTTP_STATE_HEADERS_SENT)
543 if (uh->uc.proxy_url)
544 url = uh->uc.proxy_url;
546 ustream_printf(uh->us,
549 request_types[req_type],
550 url->location, url->host);
552 blobmsg_for_each_attr(cur, uh->headers.head, rem)
553 ustream_printf(uh->us, "%s: %s\r\n", blobmsg_name(cur), (char *) blobmsg_data(cur));
555 if (uh->req_type == REQ_POST || uh->req_type == REQ_PUT)
556 ustream_printf(uh->us, "Transfer-Encoding: chunked\r\n");
558 uclient_http_add_auth_header(uh);
560 ustream_printf(uh->us, "\r\n");
562 uh->state = HTTP_STATE_HEADERS_SENT;
565 static void uclient_http_headers_complete(struct uclient_http *uh)
567 enum auth_type auth_type = uh->auth_type;
568 int seq = uh->uc.seq;
570 uh->state = HTTP_STATE_RECV_DATA;
571 uh->uc.meta = uh->meta.head;
572 uclient_http_process_headers(uh);
574 if (auth_type == AUTH_TYPE_UNKNOWN && uh->uc.status_code == 401 &&
575 (uh->req_type == REQ_HEAD || uh->req_type == REQ_GET)) {
576 uclient_http_init_request(uh);
577 uclient_http_send_headers(uh);
578 uh->state = HTTP_STATE_REQUEST_DONE;
582 if (uh->uc.cb->header_done)
583 uh->uc.cb->header_done(&uh->uc);
585 if (uh->eof || seq != uh->uc.seq)
588 if (uh->req_type == REQ_HEAD || uh->uc.status_code == 204) {
590 uclient_notify_eof(uh);
594 static void uclient_parse_http_line(struct uclient_http *uh, char *data)
599 if (uh->state == HTTP_STATE_REQUEST_DONE) {
608 code = strsep(&data, " ");
612 uh->uc.status_code = strtoul(code, &sep, 10);
616 uh->state = HTTP_STATE_RECV_HEADERS;
621 uclient_http_headers_complete(uh);
625 sep = strchr(data, ':');
631 for (name = data; *name; name++)
632 *name = tolower(*name);
635 while (isspace(*sep))
638 blobmsg_add_string(&uh->meta, name, sep);
642 uh->uc.status_code = 400;
644 uclient_notify_eof(uh);
647 static void __uclient_notify_read(struct uclient_http *uh)
649 struct uclient *uc = &uh->uc;
650 unsigned int seq = uh->seq;
654 if (uh->state < HTTP_STATE_REQUEST_DONE || uh->state == HTTP_STATE_ERROR)
657 data = ustream_get_read_buf(uh->us, &len);
661 if (uh->state < HTTP_STATE_RECV_DATA) {
666 sep = strstr(data, "\r\n");
670 /* Check for multi-line HTTP headers */
675 if (isspace(sep[2]) && sep[2] != '\r') {
683 cur_len = sep + 2 - data;
684 uclient_parse_http_line(uh, data);
688 ustream_consume(uh->us, cur_len);
694 data = ustream_get_read_buf(uh->us, &len);
695 } while (data && uh->state < HTTP_STATE_RECV_DATA);
704 if (uh->state == HTTP_STATE_RECV_DATA) {
705 /* Now it's uclient user turn to read some data */
706 uloop_timeout_cancel(&uc->connection_timeout);
708 if (uc->cb->data_read)
709 uc->cb->data_read(uc);
713 static void __uclient_notify_write(struct uclient_http *uh)
715 struct uclient *uc = &uh->uc;
717 if (uc->cb->data_sent)
718 uc->cb->data_sent(uc);
721 static void uclient_notify_read(struct ustream *us, int bytes)
723 struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
725 __uclient_notify_read(uh);
728 static void uclient_notify_write(struct ustream *us, int bytes)
730 struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
732 __uclient_notify_write(uh);
735 static void uclient_notify_state(struct ustream *us)
737 struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
739 uclient_notify_eof(uh);
742 static int uclient_setup_http(struct uclient_http *uh)
744 struct ustream *us = &uh->ufd.stream;
750 us->string_data = true;
751 us->notify_state = uclient_notify_state;
752 us->notify_read = uclient_notify_read;
753 us->notify_write = uclient_notify_write;
755 ret = uclient_do_connect(uh, "80");
757 return UCLIENT_ERROR_CONNECT;
762 static void uclient_ssl_notify_read(struct ustream *us, int bytes)
764 struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
766 __uclient_notify_read(uh);
769 static void uclient_ssl_notify_write(struct ustream *us, int bytes)
771 struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
773 __uclient_notify_write(uh);
776 static void uclient_ssl_notify_state(struct ustream *us)
778 struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
780 uclient_notify_eof(uh);
783 static void uclient_ssl_notify_error(struct ustream_ssl *ssl, int error, const char *str)
785 struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
787 uclient_http_error(uh, UCLIENT_ERROR_CONNECT);
790 static void uclient_ssl_notify_verify_error(struct ustream_ssl *ssl, int error, const char *str)
792 struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
794 if (!uh->ssl_require_validation)
797 uclient_http_error(uh, UCLIENT_ERROR_SSL_INVALID_CERT);
800 static void uclient_ssl_notify_connected(struct ustream_ssl *ssl)
802 struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
804 if (!uh->ssl_require_validation)
807 if (!uh->ussl.valid_cn)
808 uclient_http_error(uh, UCLIENT_ERROR_SSL_CN_MISMATCH);
811 static int uclient_setup_https(struct uclient_http *uh)
813 struct ustream *us = &uh->ussl.stream;
820 return UCLIENT_ERROR_MISSING_SSL_CONTEXT;
822 ret = uclient_do_connect(uh, "443");
824 return UCLIENT_ERROR_CONNECT;
826 us->string_data = true;
827 us->notify_state = uclient_ssl_notify_state;
828 us->notify_read = uclient_ssl_notify_read;
829 us->notify_write = uclient_ssl_notify_write;
830 uh->ussl.notify_error = uclient_ssl_notify_error;
831 uh->ussl.notify_verify_error = uclient_ssl_notify_verify_error;
832 uh->ussl.notify_connected = uclient_ssl_notify_connected;
833 uh->ussl.server_name = uh->uc.url->host;
834 uh->ssl_ops->init(&uh->ussl, &uh->ufd.stream, uh->ssl_ctx, false);
835 uh->ssl_ops->set_peer_cn(&uh->ussl, uh->uc.url->host);
840 static int uclient_http_connect(struct uclient *cl)
842 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
845 if (!cl->eof || uh->disconnect)
846 uclient_http_disconnect(uh);
848 uclient_http_init_request(uh);
853 uh->ssl = cl->url->prefix == PREFIX_HTTPS;
856 ret = uclient_setup_https(uh);
858 ret = uclient_setup_http(uh);
863 static void uclient_http_disconnect_cb(struct uloop_timeout *timeout)
865 struct uclient_http *uh = container_of(timeout, struct uclient_http, disconnect_t);
867 uclient_http_disconnect(uh);
870 static struct uclient *uclient_http_alloc(void)
872 struct uclient_http *uh;
874 uh = calloc_a(sizeof(*uh));
875 uh->disconnect_t.cb = uclient_http_disconnect_cb;
876 blob_buf_init(&uh->headers, 0);
881 static void uclient_http_free_ssl_ctx(struct uclient_http *uh)
887 static void uclient_http_free(struct uclient *cl)
889 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
891 uclient_http_free_url_state(cl);
892 uclient_http_free_ssl_ctx(uh);
893 blob_buf_free(&uh->headers);
894 blob_buf_free(&uh->meta);
899 uclient_http_set_request_type(struct uclient *cl, const char *type)
901 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
904 if (cl->backend != &uclient_backend_http)
907 if (uh->state > HTTP_STATE_INIT)
910 for (i = 0; i < ARRAY_SIZE(request_types); i++) {
911 if (strcmp(request_types[i], type) != 0)
922 uclient_http_reset_headers(struct uclient *cl)
924 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
926 blob_buf_init(&uh->headers, 0);
932 uclient_http_set_header(struct uclient *cl, const char *name, const char *value)
934 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
936 if (cl->backend != &uclient_backend_http)
939 if (uh->state > HTTP_STATE_INIT)
942 blobmsg_add_string(&uh->headers, name, value);
947 uclient_http_send_data(struct uclient *cl, const char *buf, unsigned int len)
949 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
951 if (uh->state >= HTTP_STATE_REQUEST_DONE)
954 uclient_http_send_headers(uh);
957 ustream_printf(uh->us, "%X\r\n", len);
958 ustream_write(uh->us, buf, len, false);
959 ustream_printf(uh->us, "\r\n");
966 uclient_http_request_done(struct uclient *cl)
968 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
970 if (uh->state >= HTTP_STATE_REQUEST_DONE)
973 uclient_http_send_headers(uh);
974 if (uh->req_type == REQ_POST || uh->req_type == REQ_PUT)
975 ustream_printf(uh->us, "0\r\n\r\n");
976 uh->state = HTTP_STATE_REQUEST_DONE;
982 uclient_http_read(struct uclient *cl, char *buf, unsigned int len)
984 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
986 char *data, *data_end;
988 if (uh->state < HTTP_STATE_RECV_DATA || !uh->us)
991 data = ustream_get_read_buf(uh->us, &read_len);
992 if (!data || !read_len)
995 data_end = data + read_len;
998 if (uh->read_chunked == 0) {
1001 if (data[0] == '\r' && data[1] == '\n') {
1006 sep = strstr(data, "\r\n");
1011 uh->read_chunked = strtoul(data, NULL, 16);
1013 read_len += sep + 2 - data;
1016 if (!uh->read_chunked) {
1018 uh->uc.data_eof = true;
1022 if (len > data_end - data)
1023 len = data_end - data;
1025 if (uh->read_chunked >= 0) {
1026 if (len > uh->read_chunked)
1027 len = uh->read_chunked;
1029 uh->read_chunked -= len;
1030 } else if (uh->content_length >= 0) {
1031 if (len > uh->content_length)
1032 len = uh->content_length;
1034 uh->content_length -= len;
1035 if (!uh->content_length) {
1037 uh->uc.data_eof = true;
1043 memcpy(buf, data, len);
1047 ustream_consume(uh->us, read_len);
1049 uclient_notify_eof(uh);
1051 /* Now that we consumed something and if this isn't EOF, start timer again */
1052 if (!uh->uc.eof && !cl->connection_timeout.pending)
1053 uloop_timeout_set(&cl->connection_timeout, cl->timeout_msecs);
1058 bool uclient_http_redirect(struct uclient *cl)
1060 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
1061 struct blobmsg_policy location = {
1063 .type = BLOBMSG_TYPE_STRING,
1065 struct uclient_url *url = cl->url;
1066 struct blob_attr *tb;
1068 if (cl->backend != &uclient_backend_http)
1071 switch (cl->status_code) {
1080 blobmsg_parse(&location, 1, &tb, blob_data(uh->meta.head), blob_len(uh->meta.head));
1084 url = uclient_get_url(blobmsg_data(tb), url->auth);
1090 uclient_http_connect(cl);
1091 uclient_http_request_done(cl);
1096 int uclient_http_set_ssl_ctx(struct uclient *cl, const struct ustream_ssl_ops *ops,
1097 struct ustream_ssl_ctx *ctx, bool require_validation)
1099 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
1101 if (cl->backend != &uclient_backend_http)
1104 uclient_http_free_url_state(cl);
1106 uclient_http_free_ssl_ctx(uh);
1109 uh->ssl_require_validation = !!ctx && require_validation;
1114 const struct uclient_backend uclient_backend_http = {
1115 .prefix = uclient_http_prefix,
1117 .alloc = uclient_http_alloc,
1118 .free = uclient_http_free,
1119 .connect = uclient_http_connect,
1120 .disconnect = uclient_http_request_disconnect,
1121 .update_url = uclient_http_free_url_state,
1122 .update_proxy_url = uclient_http_free_url_state,
1124 .read = uclient_http_read,
1125 .write = uclient_http_send_data,
1126 .request = uclient_http_request_done,