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.
24 #include <libubox/ustream.h>
25 #include <libubox/ustream-ssl.h>
26 #include <libubox/usock.h>
27 #include <libubox/blobmsg.h>
30 #include "uclient-utils.h"
31 #include "uclient-backend.h"
51 HTTP_STATE_HEADERS_SENT,
52 HTTP_STATE_REQUEST_DONE,
53 HTTP_STATE_RECV_HEADERS,
58 static const char * const request_types[__REQ_MAX] = {
63 [REQ_DELETE] = "DELETE",
69 const struct ustream_ssl_ops *ssl_ops;
70 struct ustream_ssl_ctx *ssl_ctx;
73 struct ustream_fd ufd;
74 struct ustream_ssl ussl;
76 struct uloop_timeout disconnect_t;
79 bool ssl_require_validation;
82 bool connection_close;
84 enum request_type req_type;
85 enum http_state state;
87 enum auth_type auth_type;
95 struct blob_buf headers;
105 static const char * const uclient_http_prefix[] = {
106 [PREFIX_HTTP] = "http://",
107 [PREFIX_HTTPS] = "https://",
108 [__PREFIX_MAX] = NULL
111 static int uclient_http_connect(struct uclient *cl);
113 static int uclient_do_connect(struct uclient_http *uh, const char *port)
118 if (uh->uc.url->port)
119 port = uh->uc.url->port;
121 memset(&uh->uc.remote_addr, 0, sizeof(uh->uc.remote_addr));
123 fd = usock_inet(USOCK_TCP, uh->uc.url->host, port, &uh->uc.remote_addr);
127 fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
128 ustream_fd_init(&uh->ufd, fd);
130 sl = sizeof(uh->uc.local_addr);
131 memset(&uh->uc.local_addr, 0, sl);
132 getsockname(fd, &uh->uc.local_addr.sa, &sl);
137 static void uclient_http_disconnect(struct uclient_http *uh)
139 uloop_timeout_cancel(&uh->disconnect_t);
144 ustream_free(&uh->ussl.stream);
145 ustream_free(&uh->ufd.stream);
146 close(uh->ufd.fd.fd);
150 static void uclient_http_free_url_state(struct uclient *cl)
152 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
154 uh->auth_type = AUTH_TYPE_UNKNOWN;
157 uclient_http_disconnect(uh);
160 static void uclient_http_error(struct uclient_http *uh, int code)
162 uh->state = HTTP_STATE_ERROR;
164 ustream_state_change(uh->us);
165 uclient_backend_set_error(&uh->uc, code);
168 static void uclient_http_request_disconnect(struct uclient *cl)
170 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
176 uh->disconnect = true;
177 uloop_timeout_set(&uh->disconnect_t, 1);
180 static void uclient_notify_eof(struct uclient_http *uh)
182 struct ustream *us = uh->us;
188 if (!us->eof && !us->write_error)
191 if (ustream_pending_data(us, false))
195 uclient_backend_set_eof(&uh->uc);
197 if (uh->connection_close)
198 uclient_http_request_disconnect(&uh->uc);
201 static void uclient_http_reset_state(struct uclient_http *uh)
204 uclient_backend_reset_state(&uh->uc);
205 uh->read_chunked = -1;
206 uh->content_length = -1;
208 uh->disconnect = false;
209 uh->connection_close = false;
210 uh->state = HTTP_STATE_INIT;
212 if (uh->auth_type == AUTH_TYPE_UNKNOWN && !uh->uc.url->auth)
213 uh->auth_type = AUTH_TYPE_NONE;
216 static void uclient_http_init_request(struct uclient_http *uh)
219 uclient_http_reset_state(uh);
220 blob_buf_init(&uh->meta, 0);
223 static enum auth_type
224 uclient_http_update_auth_type(struct uclient_http *uh)
227 return AUTH_TYPE_NONE;
229 if (!strncasecmp(uh->auth_str, "basic", 5))
230 return AUTH_TYPE_BASIC;
232 if (!strncasecmp(uh->auth_str, "digest", 6))
233 return AUTH_TYPE_DIGEST;
235 return AUTH_TYPE_NONE;
238 static void uclient_http_process_headers(struct uclient_http *uh)
241 HTTP_HDR_TRANSFER_ENCODING,
243 HTTP_HDR_CONTENT_LENGTH,
247 static const struct blobmsg_policy hdr_policy[__HTTP_HDR_MAX] = {
248 #define hdr(_name) { .name = _name, .type = BLOBMSG_TYPE_STRING }
249 [HTTP_HDR_TRANSFER_ENCODING] = hdr("transfer-encoding"),
250 [HTTP_HDR_CONNECTION] = hdr("connection"),
251 [HTTP_HDR_CONTENT_LENGTH] = hdr("content-length"),
252 [HTTP_HDR_AUTH] = hdr("www-authenticate"),
255 struct blob_attr *tb[__HTTP_HDR_MAX];
256 struct blob_attr *cur;
258 blobmsg_parse(hdr_policy, __HTTP_HDR_MAX, tb, blob_data(uh->meta.head), blob_len(uh->meta.head));
260 cur = tb[HTTP_HDR_TRANSFER_ENCODING];
261 if (cur && strstr(blobmsg_data(cur), "chunked"))
262 uh->read_chunked = 0;
264 cur = tb[HTTP_HDR_CONNECTION];
265 if (cur && strstr(blobmsg_data(cur), "close"))
266 uh->connection_close = true;
268 cur = tb[HTTP_HDR_CONTENT_LENGTH];
270 uh->content_length = strtoul(blobmsg_data(cur), NULL, 10);
272 cur = tb[HTTP_HDR_AUTH];
275 uh->auth_str = strdup(blobmsg_data(cur));
278 uh->auth_type = uclient_http_update_auth_type(uh);
282 uclient_http_add_auth_basic(struct uclient_http *uh)
284 struct uclient_url *url = uh->uc.url;
285 int auth_len = strlen(url->auth);
291 auth_buf = alloca(base64_len(auth_len) + 1);
292 base64_encode(url->auth, auth_len, auth_buf);
293 ustream_printf(uh->us, "Authorization: Basic %s\r\n", auth_buf);
296 static char *digest_unquote_sep(char **str)
298 char *cur = *str + 1;
330 static char *digest_sep(char **str)
335 next = strchr(*str, ',');
340 *str += strlen(*str);
346 static bool strmatch(char **str, const char *prefix)
348 int len = strlen(prefix);
350 if (strncmp(*str, prefix, len) != 0 || (*str)[len] != '=')
358 get_cnonce(char *dest)
363 f = fopen("/dev/urandom", "r");
365 fread(&val, sizeof(val), 1, f);
369 bin_to_hex(dest, &val, sizeof(val));
372 static void add_field(char **buf, int *ofs, int *len, const char *name, const char *val)
374 int available = *len - *ofs;
382 required = strlen(name) + 4 + strlen(val) * 2;
383 if (required > available)
384 *len += required - available + 64;
386 *buf = realloc(*buf, *len);
391 cur += sprintf(cur, ", %s=\"", name);
393 while ((next = strchr(val, '"'))) {
395 memcpy(cur, val, next - val);
399 cur += sprintf(cur, "\\\"");
403 cur += sprintf(cur, "%s\"", val);
408 uclient_http_add_auth_digest(struct uclient_http *uh)
410 struct uclient_url *url = uh->uc.url;
411 const char *realm = NULL, *opaque = NULL;
412 const char *user, *password;
421 struct http_digest_data data = {
423 .cnonce = cnonce_str,
427 len = strlen(uh->auth_str) + 1;
432 strcpy(buf, uh->auth_str);
439 const char **dest = NULL;
442 while (*next && isspace(*next))
445 if (strmatch(&next, "realm"))
447 else if (strmatch(&next, "qop"))
449 else if (strmatch(&next, "nonce"))
451 else if (strmatch(&next, "opaque"))
453 else if (strmatch(&next, "stale") ||
454 strmatch(&next, "algorithm") ||
455 strmatch(&next, "auth-param")) {
458 } else if (strmatch(&next, "domain") ||
459 strmatch(&next, "qop-options"))
466 *dest = digest_unquote_sep(&next);
469 if (!realm || !data.qop || !data.nonce)
472 sprintf(nc_str, "%08x", uh->nc++);
473 get_cnonce(cnonce_str);
476 data.uri = url->location;
477 data.method = request_types[uh->req_type];
479 password = strchr(url->auth, ':');
483 len = password - url->auth;
487 user_buf = alloca(len + 1);
488 strncpy(user_buf, url->auth, len);
497 http_digest_calculate_auth_hash(ahash, user, realm, password);
498 http_digest_calculate_response(hash, &data);
504 add_field(&buf, &ofs, &len, "username", user);
505 add_field(&buf, &ofs, &len, "realm", realm);
506 add_field(&buf, &ofs, &len, "nonce", data.nonce);
507 add_field(&buf, &ofs, &len, "uri", data.uri);
508 add_field(&buf, &ofs, &len, "cnonce", data.cnonce);
509 add_field(&buf, &ofs, &len, "response", hash);
511 add_field(&buf, &ofs, &len, "opaque", opaque);
513 ustream_printf(uh->us, "Authorization: Digest nc=%s, qop=%s%s\r\n", data.nc, data.qop, buf);
518 uclient_http_add_auth_header(struct uclient_http *uh)
520 if (!uh->uc.url->auth)
523 switch (uh->auth_type) {
524 case AUTH_TYPE_UNKNOWN:
527 case AUTH_TYPE_BASIC:
528 uclient_http_add_auth_basic(uh);
530 case AUTH_TYPE_DIGEST:
531 uclient_http_add_auth_digest(uh);
537 uclient_http_send_headers(struct uclient_http *uh)
539 struct uclient_url *url = uh->uc.url;
540 struct blob_attr *cur;
541 enum request_type req_type = uh->req_type;
544 if (uh->state >= HTTP_STATE_HEADERS_SENT)
547 if (uh->uc.proxy_url)
548 url = uh->uc.proxy_url;
550 ustream_printf(uh->us,
553 request_types[req_type],
554 url->location, url->host);
556 blobmsg_for_each_attr(cur, uh->headers.head, rem)
557 ustream_printf(uh->us, "%s: %s\r\n", blobmsg_name(cur), (char *) blobmsg_data(cur));
559 if (uh->req_type == REQ_POST || uh->req_type == REQ_PUT)
560 ustream_printf(uh->us, "Transfer-Encoding: chunked\r\n");
562 uclient_http_add_auth_header(uh);
564 ustream_printf(uh->us, "\r\n");
566 uh->state = HTTP_STATE_HEADERS_SENT;
569 static void uclient_http_headers_complete(struct uclient_http *uh)
571 enum auth_type auth_type = uh->auth_type;
572 int seq = uh->uc.seq;
574 uh->state = HTTP_STATE_RECV_DATA;
575 uh->uc.meta = uh->meta.head;
576 uclient_http_process_headers(uh);
578 if (auth_type == AUTH_TYPE_UNKNOWN && uh->uc.status_code == 401 &&
579 (uh->req_type == REQ_HEAD || uh->req_type == REQ_GET)) {
580 uclient_http_connect(&uh->uc);
581 uclient_http_send_headers(uh);
582 uh->state = HTTP_STATE_REQUEST_DONE;
586 if (uh->uc.cb->header_done)
587 uh->uc.cb->header_done(&uh->uc);
589 if (uh->eof || seq != uh->uc.seq)
592 if (uh->req_type == REQ_HEAD || uh->uc.status_code == 204) {
594 uclient_notify_eof(uh);
598 static void uclient_parse_http_line(struct uclient_http *uh, char *data)
603 if (uh->state == HTTP_STATE_REQUEST_DONE) {
612 code = strsep(&data, " ");
616 uh->uc.status_code = strtoul(code, &sep, 10);
620 uh->state = HTTP_STATE_RECV_HEADERS;
625 uclient_http_headers_complete(uh);
629 sep = strchr(data, ':');
635 for (name = data; *name; name++)
636 *name = tolower(*name);
639 while (isspace(*sep))
642 blobmsg_add_string(&uh->meta, name, sep);
646 uh->uc.status_code = 400;
648 uclient_notify_eof(uh);
651 static void __uclient_notify_read(struct uclient_http *uh)
653 struct uclient *uc = &uh->uc;
654 unsigned int seq = uh->seq;
658 if (uh->state < HTTP_STATE_REQUEST_DONE || uh->state == HTTP_STATE_ERROR)
661 data = ustream_get_read_buf(uh->us, &len);
665 if (uh->state < HTTP_STATE_RECV_DATA) {
670 sep = strstr(data, "\r\n");
674 /* Check for multi-line HTTP headers */
679 if (isspace(sep[2]) && sep[2] != '\r') {
687 cur_len = sep + 2 - data;
688 uclient_parse_http_line(uh, data);
692 ustream_consume(uh->us, cur_len);
698 data = ustream_get_read_buf(uh->us, &len);
699 } while (data && uh->state < HTTP_STATE_RECV_DATA);
708 if (uh->state == HTTP_STATE_RECV_DATA) {
709 /* Now it's uclient user turn to read some data */
710 uloop_timeout_cancel(&uc->connection_timeout);
712 if (uc->cb->data_read)
713 uc->cb->data_read(uc);
717 static void __uclient_notify_write(struct uclient_http *uh)
719 struct uclient *uc = &uh->uc;
721 if (uc->cb->data_sent)
722 uc->cb->data_sent(uc);
725 static void uclient_notify_read(struct ustream *us, int bytes)
727 struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
729 __uclient_notify_read(uh);
732 static void uclient_notify_write(struct ustream *us, int bytes)
734 struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
736 __uclient_notify_write(uh);
739 static void uclient_notify_state(struct ustream *us)
741 struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
743 if (uh->ufd.stream.write_error) {
744 uclient_http_error(uh, UCLIENT_ERROR_CONNECT);
747 uclient_notify_eof(uh);
750 static int uclient_setup_http(struct uclient_http *uh)
752 struct ustream *us = &uh->ufd.stream;
758 us->string_data = true;
759 us->notify_state = uclient_notify_state;
760 us->notify_read = uclient_notify_read;
761 us->notify_write = uclient_notify_write;
763 ret = uclient_do_connect(uh, "80");
765 return UCLIENT_ERROR_CONNECT;
770 static void uclient_ssl_notify_read(struct ustream *us, int bytes)
772 struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
774 __uclient_notify_read(uh);
777 static void uclient_ssl_notify_write(struct ustream *us, int bytes)
779 struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
781 __uclient_notify_write(uh);
784 static void uclient_ssl_notify_state(struct ustream *us)
786 struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
788 uclient_notify_eof(uh);
791 static void uclient_ssl_notify_error(struct ustream_ssl *ssl, int error, const char *str)
793 struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
795 uclient_http_error(uh, UCLIENT_ERROR_CONNECT);
798 static void uclient_ssl_notify_verify_error(struct ustream_ssl *ssl, int error, const char *str)
800 struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
802 if (!uh->ssl_require_validation)
805 uclient_http_error(uh, UCLIENT_ERROR_SSL_INVALID_CERT);
808 static void uclient_ssl_notify_connected(struct ustream_ssl *ssl)
810 struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
812 if (!uh->ssl_require_validation)
815 if (!uh->ussl.valid_cn)
816 uclient_http_error(uh, UCLIENT_ERROR_SSL_CN_MISMATCH);
819 static int uclient_setup_https(struct uclient_http *uh)
821 struct ustream *us = &uh->ussl.stream;
828 return UCLIENT_ERROR_MISSING_SSL_CONTEXT;
830 ret = uclient_do_connect(uh, "443");
832 return UCLIENT_ERROR_CONNECT;
834 us->string_data = true;
835 us->notify_state = uclient_ssl_notify_state;
836 us->notify_read = uclient_ssl_notify_read;
837 us->notify_write = uclient_ssl_notify_write;
838 uh->ussl.notify_error = uclient_ssl_notify_error;
839 uh->ussl.notify_verify_error = uclient_ssl_notify_verify_error;
840 uh->ussl.notify_connected = uclient_ssl_notify_connected;
841 uh->ussl.server_name = uh->uc.url->host;
842 uh->ssl_ops->init(&uh->ussl, &uh->ufd.stream, uh->ssl_ctx, false);
843 uh->ssl_ops->set_peer_cn(&uh->ussl, uh->uc.url->host);
848 static int uclient_http_connect(struct uclient *cl)
850 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
853 if (!cl->eof || uh->disconnect || uh->connection_close)
854 uclient_http_disconnect(uh);
856 uclient_http_init_request(uh);
861 uh->ssl = cl->url->prefix == PREFIX_HTTPS;
864 ret = uclient_setup_https(uh);
866 ret = uclient_setup_http(uh);
871 static void uclient_http_disconnect_cb(struct uloop_timeout *timeout)
873 struct uclient_http *uh = container_of(timeout, struct uclient_http, disconnect_t);
875 uclient_http_disconnect(uh);
878 static struct uclient *uclient_http_alloc(void)
880 struct uclient_http *uh;
882 uh = calloc_a(sizeof(*uh));
883 uh->disconnect_t.cb = uclient_http_disconnect_cb;
884 blob_buf_init(&uh->headers, 0);
889 static void uclient_http_free_ssl_ctx(struct uclient_http *uh)
895 static void uclient_http_free(struct uclient *cl)
897 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
899 uclient_http_free_url_state(cl);
900 uclient_http_free_ssl_ctx(uh);
901 blob_buf_free(&uh->headers);
902 blob_buf_free(&uh->meta);
907 uclient_http_set_request_type(struct uclient *cl, const char *type)
909 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
912 if (cl->backend != &uclient_backend_http)
915 if (uh->state > HTTP_STATE_INIT)
918 for (i = 0; i < ARRAY_SIZE(request_types); i++) {
919 if (strcmp(request_types[i], type) != 0)
930 uclient_http_reset_headers(struct uclient *cl)
932 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
934 blob_buf_init(&uh->headers, 0);
940 uclient_http_set_header(struct uclient *cl, const char *name, const char *value)
942 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
944 if (cl->backend != &uclient_backend_http)
947 if (uh->state > HTTP_STATE_INIT)
950 blobmsg_add_string(&uh->headers, name, value);
955 uclient_http_send_data(struct uclient *cl, const char *buf, unsigned int len)
957 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
959 if (uh->state >= HTTP_STATE_REQUEST_DONE)
962 uclient_http_send_headers(uh);
965 ustream_printf(uh->us, "%X\r\n", len);
966 ustream_write(uh->us, buf, len, false);
967 ustream_printf(uh->us, "\r\n");
974 uclient_http_request_done(struct uclient *cl)
976 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
978 if (uh->state >= HTTP_STATE_REQUEST_DONE)
981 uclient_http_send_headers(uh);
982 if (uh->req_type == REQ_POST || uh->req_type == REQ_PUT)
983 ustream_printf(uh->us, "0\r\n\r\n");
984 uh->state = HTTP_STATE_REQUEST_DONE;
990 uclient_http_read(struct uclient *cl, char *buf, unsigned int len)
992 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
994 char *data, *data_end;
996 if (uh->state < HTTP_STATE_RECV_DATA || !uh->us)
999 data = ustream_get_read_buf(uh->us, &read_len);
1000 if (!data || !read_len)
1003 data_end = data + read_len;
1006 if (uh->read_chunked == 0) {
1009 if (data[0] == '\r' && data[1] == '\n') {
1014 sep = strstr(data, "\r\n");
1019 uh->read_chunked = strtoul(data, NULL, 16);
1021 read_len += sep + 2 - data;
1024 if (!uh->read_chunked) {
1026 uh->uc.data_eof = true;
1030 if (len > data_end - data)
1031 len = data_end - data;
1033 if (uh->read_chunked >= 0) {
1034 if (len > uh->read_chunked)
1035 len = uh->read_chunked;
1037 uh->read_chunked -= len;
1038 } else if (uh->content_length >= 0) {
1039 if (len > uh->content_length)
1040 len = uh->content_length;
1042 uh->content_length -= len;
1043 if (!uh->content_length) {
1045 uh->uc.data_eof = true;
1051 memcpy(buf, data, len);
1055 ustream_consume(uh->us, read_len);
1057 uclient_notify_eof(uh);
1059 /* Now that we consumed something and if this isn't EOF, start timer again */
1060 if (!uh->uc.eof && !cl->connection_timeout.pending)
1061 uloop_timeout_set(&cl->connection_timeout, cl->timeout_msecs);
1066 bool uclient_http_redirect(struct uclient *cl)
1068 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
1069 struct blobmsg_policy location = {
1071 .type = BLOBMSG_TYPE_STRING,
1073 struct uclient_url *url = cl->url;
1074 struct blob_attr *tb;
1076 if (cl->backend != &uclient_backend_http)
1079 switch (cl->status_code) {
1088 blobmsg_parse(&location, 1, &tb, blob_data(uh->meta.head), blob_len(uh->meta.head));
1092 url = uclient_get_url(blobmsg_data(tb), url->auth);
1098 uclient_http_connect(cl);
1099 uclient_http_request_done(cl);
1104 int uclient_http_set_ssl_ctx(struct uclient *cl, const struct ustream_ssl_ops *ops,
1105 struct ustream_ssl_ctx *ctx, bool require_validation)
1107 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
1109 if (cl->backend != &uclient_backend_http)
1112 uclient_http_free_url_state(cl);
1114 uclient_http_free_ssl_ctx(uh);
1117 uh->ssl_require_validation = !!ctx && require_validation;
1122 const struct uclient_backend uclient_backend_http = {
1123 .prefix = uclient_http_prefix,
1125 .alloc = uclient_http_alloc,
1126 .free = uclient_http_free,
1127 .connect = uclient_http_connect,
1128 .disconnect = uclient_http_request_disconnect,
1129 .update_url = uclient_http_free_url_state,
1130 .update_proxy_url = uclient_http_free_url_state,
1132 .read = uclient_http_read,
1133 .write = uclient_http_send_data,
1134 .request = uclient_http_request_done,