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 = strchr(data, '\n');
675 if (sep > data && sep[-1] == '\r')
678 /* Check for multi-line HTTP headers */
683 if (isspace(*next) && *next != '\r' && *next != '\n') {
692 cur_len = next - data;
693 uclient_parse_http_line(uh, data);
697 ustream_consume(uh->us, cur_len);
703 data = ustream_get_read_buf(uh->us, &len);
704 } while (data && uh->state < HTTP_STATE_RECV_DATA);
713 if (uh->state == HTTP_STATE_RECV_DATA) {
714 /* Now it's uclient user turn to read some data */
715 uloop_timeout_cancel(&uc->connection_timeout);
717 if (uc->cb->data_read)
718 uc->cb->data_read(uc);
722 static void __uclient_notify_write(struct uclient_http *uh)
724 struct uclient *uc = &uh->uc;
726 if (uc->cb->data_sent)
727 uc->cb->data_sent(uc);
730 static void uclient_notify_read(struct ustream *us, int bytes)
732 struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
734 __uclient_notify_read(uh);
737 static void uclient_notify_write(struct ustream *us, int bytes)
739 struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
741 __uclient_notify_write(uh);
744 static void uclient_notify_state(struct ustream *us)
746 struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
748 if (uh->ufd.stream.write_error) {
749 uclient_http_error(uh, UCLIENT_ERROR_CONNECT);
752 uclient_notify_eof(uh);
755 static int uclient_setup_http(struct uclient_http *uh)
757 struct ustream *us = &uh->ufd.stream;
763 us->string_data = true;
764 us->notify_state = uclient_notify_state;
765 us->notify_read = uclient_notify_read;
766 us->notify_write = uclient_notify_write;
768 ret = uclient_do_connect(uh, "80");
770 return UCLIENT_ERROR_CONNECT;
775 static void uclient_ssl_notify_read(struct ustream *us, int bytes)
777 struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
779 __uclient_notify_read(uh);
782 static void uclient_ssl_notify_write(struct ustream *us, int bytes)
784 struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
786 __uclient_notify_write(uh);
789 static void uclient_ssl_notify_state(struct ustream *us)
791 struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
793 uclient_notify_eof(uh);
796 static void uclient_ssl_notify_error(struct ustream_ssl *ssl, int error, const char *str)
798 struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
800 uclient_http_error(uh, UCLIENT_ERROR_CONNECT);
803 static void uclient_ssl_notify_verify_error(struct ustream_ssl *ssl, int error, const char *str)
805 struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
807 if (!uh->ssl_require_validation)
810 uclient_http_error(uh, UCLIENT_ERROR_SSL_INVALID_CERT);
813 static void uclient_ssl_notify_connected(struct ustream_ssl *ssl)
815 struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
817 if (!uh->ssl_require_validation)
820 if (!uh->ussl.valid_cn)
821 uclient_http_error(uh, UCLIENT_ERROR_SSL_CN_MISMATCH);
824 static int uclient_setup_https(struct uclient_http *uh)
826 struct ustream *us = &uh->ussl.stream;
833 return UCLIENT_ERROR_MISSING_SSL_CONTEXT;
835 ret = uclient_do_connect(uh, "443");
837 return UCLIENT_ERROR_CONNECT;
839 us->string_data = true;
840 us->notify_state = uclient_ssl_notify_state;
841 us->notify_read = uclient_ssl_notify_read;
842 us->notify_write = uclient_ssl_notify_write;
843 uh->ussl.notify_error = uclient_ssl_notify_error;
844 uh->ussl.notify_verify_error = uclient_ssl_notify_verify_error;
845 uh->ussl.notify_connected = uclient_ssl_notify_connected;
846 uh->ussl.server_name = uh->uc.url->host;
847 uh->ssl_ops->init(&uh->ussl, &uh->ufd.stream, uh->ssl_ctx, false);
848 uh->ssl_ops->set_peer_cn(&uh->ussl, uh->uc.url->host);
853 static int uclient_http_connect(struct uclient *cl)
855 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
858 if (!cl->eof || uh->disconnect || uh->connection_close)
859 uclient_http_disconnect(uh);
861 uclient_http_init_request(uh);
866 uh->ssl = cl->url->prefix == PREFIX_HTTPS;
869 ret = uclient_setup_https(uh);
871 ret = uclient_setup_http(uh);
876 static void uclient_http_disconnect_cb(struct uloop_timeout *timeout)
878 struct uclient_http *uh = container_of(timeout, struct uclient_http, disconnect_t);
880 uclient_http_disconnect(uh);
883 static struct uclient *uclient_http_alloc(void)
885 struct uclient_http *uh;
887 uh = calloc_a(sizeof(*uh));
888 uh->disconnect_t.cb = uclient_http_disconnect_cb;
889 blob_buf_init(&uh->headers, 0);
894 static void uclient_http_free_ssl_ctx(struct uclient_http *uh)
900 static void uclient_http_free(struct uclient *cl)
902 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
904 uclient_http_free_url_state(cl);
905 uclient_http_free_ssl_ctx(uh);
906 blob_buf_free(&uh->headers);
907 blob_buf_free(&uh->meta);
912 uclient_http_set_request_type(struct uclient *cl, const char *type)
914 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
917 if (cl->backend != &uclient_backend_http)
920 if (uh->state > HTTP_STATE_INIT)
923 for (i = 0; i < ARRAY_SIZE(request_types); i++) {
924 if (strcmp(request_types[i], type) != 0)
935 uclient_http_reset_headers(struct uclient *cl)
937 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
939 blob_buf_init(&uh->headers, 0);
945 uclient_http_set_header(struct uclient *cl, const char *name, const char *value)
947 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
949 if (cl->backend != &uclient_backend_http)
952 if (uh->state > HTTP_STATE_INIT)
955 blobmsg_add_string(&uh->headers, name, value);
960 uclient_http_send_data(struct uclient *cl, const char *buf, unsigned int len)
962 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
964 if (uh->state >= HTTP_STATE_REQUEST_DONE)
967 uclient_http_send_headers(uh);
970 ustream_printf(uh->us, "%X\r\n", len);
971 ustream_write(uh->us, buf, len, false);
972 ustream_printf(uh->us, "\r\n");
979 uclient_http_request_done(struct uclient *cl)
981 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
983 if (uh->state >= HTTP_STATE_REQUEST_DONE)
986 uclient_http_send_headers(uh);
987 if (uh->req_type == REQ_POST || uh->req_type == REQ_PUT)
988 ustream_printf(uh->us, "0\r\n\r\n");
989 uh->state = HTTP_STATE_REQUEST_DONE;
995 uclient_http_read(struct uclient *cl, char *buf, unsigned int len)
997 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
999 char *data, *data_end;
1001 if (uh->state < HTTP_STATE_RECV_DATA || !uh->us)
1004 data = ustream_get_read_buf(uh->us, &read_len);
1005 if (!data || !read_len)
1008 data_end = data + read_len;
1011 if (uh->read_chunked == 0) {
1014 if (data[0] == '\r' && data[1] == '\n') {
1019 sep = strstr(data, "\r\n");
1024 uh->read_chunked = strtoul(data, NULL, 16);
1026 read_len += sep + 2 - data;
1029 if (!uh->read_chunked) {
1031 uh->uc.data_eof = true;
1035 if (len > data_end - data)
1036 len = data_end - data;
1038 if (uh->read_chunked >= 0) {
1039 if (len > uh->read_chunked)
1040 len = uh->read_chunked;
1042 uh->read_chunked -= len;
1043 } else if (uh->content_length >= 0) {
1044 if (len > uh->content_length)
1045 len = uh->content_length;
1047 uh->content_length -= len;
1048 if (!uh->content_length) {
1050 uh->uc.data_eof = true;
1056 memcpy(buf, data, len);
1060 ustream_consume(uh->us, read_len);
1062 uclient_notify_eof(uh);
1064 /* Now that we consumed something and if this isn't EOF, start timer again */
1065 if (!uh->uc.eof && !cl->connection_timeout.pending)
1066 uloop_timeout_set(&cl->connection_timeout, cl->timeout_msecs);
1071 int uclient_http_redirect(struct uclient *cl)
1073 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
1074 struct blobmsg_policy location = {
1076 .type = BLOBMSG_TYPE_STRING,
1078 struct uclient_url *url = cl->url;
1079 struct blob_attr *tb;
1081 if (cl->backend != &uclient_backend_http)
1084 switch (cl->status_code) {
1093 blobmsg_parse(&location, 1, &tb, blob_data(uh->meta.head), blob_len(uh->meta.head));
1097 url = uclient_get_url(blobmsg_data(tb), url->auth);
1103 if (uclient_http_connect(cl))
1106 uclient_http_request_done(cl);
1111 int uclient_http_set_ssl_ctx(struct uclient *cl, const struct ustream_ssl_ops *ops,
1112 struct ustream_ssl_ctx *ctx, bool require_validation)
1114 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
1116 if (cl->backend != &uclient_backend_http)
1119 uclient_http_free_url_state(cl);
1121 uclient_http_free_ssl_ctx(uh);
1124 uh->ssl_require_validation = !!ctx && require_validation;
1129 const struct uclient_backend uclient_backend_http = {
1130 .prefix = uclient_http_prefix,
1132 .alloc = uclient_http_alloc,
1133 .free = uclient_http_free,
1134 .connect = uclient_http_connect,
1135 .disconnect = uclient_http_request_disconnect,
1136 .update_url = uclient_http_free_url_state,
1137 .update_proxy_url = uclient_http_free_url_state,
1139 .read = uclient_http_read,
1140 .write = uclient_http_send_data,
1141 .request = uclient_http_request_done,