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 fd = usock(USOCK_TCP | USOCK_NONBLOCK, uh->uc.url->host, port);
122 ustream_fd_init(&uh->ufd, fd);
124 memset(&uh->uc.local_addr, 0, sizeof(uh->uc.local_addr));
125 memset(&uh->uc.remote_addr, 0, sizeof(uh->uc.remote_addr));
127 sl = sizeof(uh->uc.local_addr);
128 getsockname(fd, &uh->uc.local_addr.sa, &sl);
129 getpeername(fd, &uh->uc.remote_addr.sa, &sl);
134 static void uclient_http_disconnect(struct uclient_http *uh)
136 uloop_timeout_cancel(&uh->disconnect_t);
141 ustream_free(&uh->ussl.stream);
142 ustream_free(&uh->ufd.stream);
143 close(uh->ufd.fd.fd);
147 static void uclient_http_free_url_state(struct uclient *cl)
149 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
151 uh->auth_type = AUTH_TYPE_UNKNOWN;
154 uclient_http_disconnect(uh);
157 static void uclient_http_error(struct uclient_http *uh, int code)
159 uh->state = HTTP_STATE_ERROR;
161 ustream_state_change(uh->us);
162 uclient_backend_set_error(&uh->uc, code);
165 static void uclient_http_request_disconnect(struct uclient *cl)
167 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
173 uh->disconnect = true;
174 uloop_timeout_set(&uh->disconnect_t, 1);
177 static void uclient_notify_eof(struct uclient_http *uh)
179 struct ustream *us = uh->us;
185 if (!us->eof && !us->write_error)
188 if (ustream_pending_data(us, false))
192 uclient_backend_set_eof(&uh->uc);
194 if (uh->connection_close)
195 uclient_http_request_disconnect(&uh->uc);
198 static void uclient_http_reset_state(struct uclient_http *uh)
201 uclient_backend_reset_state(&uh->uc);
202 uh->read_chunked = -1;
203 uh->content_length = -1;
205 uh->disconnect = false;
206 uh->connection_close = false;
207 uh->state = HTTP_STATE_INIT;
209 if (uh->auth_type == AUTH_TYPE_UNKNOWN && !uh->uc.url->auth)
210 uh->auth_type = AUTH_TYPE_NONE;
213 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 ustream_printf(uh->us,
546 request_types[req_type],
547 url->location, url->host);
549 blobmsg_for_each_attr(cur, uh->headers.head, rem)
550 ustream_printf(uh->us, "%s: %s\r\n", blobmsg_name(cur), (char *) blobmsg_data(cur));
552 if (uh->req_type == REQ_POST || uh->req_type == REQ_PUT)
553 ustream_printf(uh->us, "Transfer-Encoding: chunked\r\n");
555 uclient_http_add_auth_header(uh);
557 ustream_printf(uh->us, "\r\n");
559 uh->state = HTTP_STATE_HEADERS_SENT;
562 static void uclient_http_headers_complete(struct uclient_http *uh)
564 enum auth_type auth_type = uh->auth_type;
566 uh->state = HTTP_STATE_RECV_DATA;
567 uh->uc.meta = uh->meta.head;
568 uclient_http_process_headers(uh);
570 if (auth_type == AUTH_TYPE_UNKNOWN && uh->uc.status_code == 401 &&
571 (uh->req_type == REQ_HEAD || uh->req_type == REQ_GET)) {
572 uclient_http_init_request(uh);
573 uclient_http_send_headers(uh);
574 uh->state = HTTP_STATE_REQUEST_DONE;
578 if (uh->uc.cb->header_done)
579 uh->uc.cb->header_done(&uh->uc);
584 if (uh->req_type == REQ_HEAD || uh->uc.status_code == 204) {
586 uclient_notify_eof(uh);
590 static void uclient_parse_http_line(struct uclient_http *uh, char *data)
595 if (uh->state == HTTP_STATE_REQUEST_DONE) {
604 code = strsep(&data, " ");
608 uh->uc.status_code = strtoul(code, &sep, 10);
612 uh->state = HTTP_STATE_RECV_HEADERS;
617 uclient_http_headers_complete(uh);
621 sep = strchr(data, ':');
627 for (name = data; *name; name++)
628 *name = tolower(*name);
631 while (isspace(*sep))
634 blobmsg_add_string(&uh->meta, name, sep);
638 uh->uc.status_code = 400;
640 uclient_notify_eof(uh);
643 static void __uclient_notify_read(struct uclient_http *uh)
645 struct uclient *uc = &uh->uc;
646 unsigned int seq = uh->seq;
650 if (uh->state < HTTP_STATE_REQUEST_DONE || uh->state == HTTP_STATE_ERROR)
653 data = ustream_get_read_buf(uh->us, &len);
657 if (uh->state < HTTP_STATE_RECV_DATA) {
662 sep = strstr(data, "\r\n");
666 /* Check for multi-line HTTP headers */
671 if (isspace(sep[2]) && sep[2] != '\r') {
679 cur_len = sep + 2 - data;
680 uclient_parse_http_line(uh, data);
684 ustream_consume(uh->us, cur_len);
690 data = ustream_get_read_buf(uh->us, &len);
691 } while (data && uh->state < HTTP_STATE_RECV_DATA);
700 if (uh->state == HTTP_STATE_RECV_DATA) {
701 /* Now it's uclient user turn to read some data */
702 uloop_timeout_cancel(&uc->connection_timeout);
704 if (uc->cb->data_read)
705 uc->cb->data_read(uc);
709 static void __uclient_notify_write(struct uclient_http *uh)
711 struct uclient *uc = &uh->uc;
713 if (uc->cb->data_sent)
714 uc->cb->data_sent(uc);
717 static void uclient_notify_read(struct ustream *us, int bytes)
719 struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
721 __uclient_notify_read(uh);
724 static void uclient_notify_write(struct ustream *us, int bytes)
726 struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
728 __uclient_notify_write(uh);
731 static void uclient_notify_state(struct ustream *us)
733 struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
735 uclient_notify_eof(uh);
738 static int uclient_setup_http(struct uclient_http *uh)
740 struct ustream *us = &uh->ufd.stream;
746 us->string_data = true;
747 us->notify_state = uclient_notify_state;
748 us->notify_read = uclient_notify_read;
749 us->notify_write = uclient_notify_write;
751 ret = uclient_do_connect(uh, "80");
753 return UCLIENT_ERROR_CONNECT;
758 static void uclient_ssl_notify_read(struct ustream *us, int bytes)
760 struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
762 __uclient_notify_read(uh);
765 static void uclient_ssl_notify_write(struct ustream *us, int bytes)
767 struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
769 __uclient_notify_write(uh);
772 static void uclient_ssl_notify_state(struct ustream *us)
774 struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
776 uclient_notify_eof(uh);
779 static void uclient_ssl_notify_error(struct ustream_ssl *ssl, int error, const char *str)
781 struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
783 uclient_http_error(uh, UCLIENT_ERROR_CONNECT);
786 static void uclient_ssl_notify_verify_error(struct ustream_ssl *ssl, int error, const char *str)
788 struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
790 if (!uh->ssl_require_validation)
793 uclient_http_error(uh, UCLIENT_ERROR_SSL_INVALID_CERT);
796 static void uclient_ssl_notify_connected(struct ustream_ssl *ssl)
798 struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
800 if (!uh->ssl_require_validation)
803 if (!uh->ussl.valid_cn)
804 uclient_http_error(uh, UCLIENT_ERROR_SSL_CN_MISMATCH);
807 static int uclient_setup_https(struct uclient_http *uh)
809 struct ustream *us = &uh->ussl.stream;
816 return UCLIENT_ERROR_MISSING_SSL_CONTEXT;
818 ret = uclient_do_connect(uh, "443");
820 return UCLIENT_ERROR_CONNECT;
822 us->string_data = true;
823 us->notify_state = uclient_ssl_notify_state;
824 us->notify_read = uclient_ssl_notify_read;
825 us->notify_write = uclient_ssl_notify_write;
826 uh->ussl.notify_error = uclient_ssl_notify_error;
827 uh->ussl.notify_verify_error = uclient_ssl_notify_verify_error;
828 uh->ussl.notify_connected = uclient_ssl_notify_connected;
829 uh->ussl.server_name = uh->uc.url->host;
830 uh->ssl_ops->init(&uh->ussl, &uh->ufd.stream, uh->ssl_ctx, false);
831 uh->ssl_ops->set_peer_cn(&uh->ussl, uh->uc.url->host);
836 static int uclient_http_connect(struct uclient *cl)
838 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
841 if (!cl->eof || uh->disconnect)
842 uclient_http_disconnect(uh);
844 uclient_http_init_request(uh);
849 uh->ssl = cl->url->prefix == PREFIX_HTTPS;
852 ret = uclient_setup_https(uh);
854 ret = uclient_setup_http(uh);
859 static void uclient_http_disconnect_cb(struct uloop_timeout *timeout)
861 struct uclient_http *uh = container_of(timeout, struct uclient_http, disconnect_t);
863 uclient_http_disconnect(uh);
866 static struct uclient *uclient_http_alloc(void)
868 struct uclient_http *uh;
870 uh = calloc_a(sizeof(*uh));
871 uh->disconnect_t.cb = uclient_http_disconnect_cb;
872 blob_buf_init(&uh->headers, 0);
877 static void uclient_http_free_ssl_ctx(struct uclient_http *uh)
883 static void uclient_http_free(struct uclient *cl)
885 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
887 uclient_http_free_url_state(cl);
888 uclient_http_free_ssl_ctx(uh);
889 blob_buf_free(&uh->headers);
890 blob_buf_free(&uh->meta);
895 uclient_http_set_request_type(struct uclient *cl, const char *type)
897 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
900 if (cl->backend != &uclient_backend_http)
903 if (uh->state > HTTP_STATE_INIT)
906 for (i = 0; i < ARRAY_SIZE(request_types); i++) {
907 if (strcmp(request_types[i], type) != 0)
918 uclient_http_reset_headers(struct uclient *cl)
920 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
922 blob_buf_init(&uh->headers, 0);
928 uclient_http_set_header(struct uclient *cl, const char *name, const char *value)
930 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
932 if (cl->backend != &uclient_backend_http)
935 if (uh->state > HTTP_STATE_INIT)
938 blobmsg_add_string(&uh->headers, name, value);
943 uclient_http_send_data(struct uclient *cl, const char *buf, unsigned int len)
945 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
947 if (uh->state >= HTTP_STATE_REQUEST_DONE)
950 uclient_http_send_headers(uh);
953 ustream_printf(uh->us, "%X\r\n", len);
954 ustream_write(uh->us, buf, len, false);
955 ustream_printf(uh->us, "\r\n");
962 uclient_http_request_done(struct uclient *cl)
964 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
966 if (uh->state >= HTTP_STATE_REQUEST_DONE)
969 uclient_http_send_headers(uh);
970 if (uh->req_type == REQ_POST || uh->req_type == REQ_PUT)
971 ustream_printf(uh->us, "0\r\n\r\n");
972 uh->state = HTTP_STATE_REQUEST_DONE;
978 uclient_http_read(struct uclient *cl, char *buf, unsigned int len)
980 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
982 char *data, *data_end;
984 if (uh->state < HTTP_STATE_RECV_DATA || !uh->us)
987 data = ustream_get_read_buf(uh->us, &read_len);
988 if (!data || !read_len)
991 data_end = data + read_len;
994 if (uh->read_chunked == 0) {
997 if (data[0] == '\r' && data[1] == '\n') {
1002 sep = strstr(data, "\r\n");
1007 uh->read_chunked = strtoul(data, NULL, 16);
1009 read_len += sep + 2 - data;
1012 if (!uh->read_chunked) {
1014 uh->uc.data_eof = true;
1018 if (len > data_end - data)
1019 len = data_end - data;
1021 if (uh->read_chunked >= 0) {
1022 if (len > uh->read_chunked)
1023 len = uh->read_chunked;
1025 uh->read_chunked -= len;
1026 } else if (uh->content_length >= 0) {
1027 if (len > uh->content_length)
1028 len = uh->content_length;
1030 uh->content_length -= len;
1031 if (!uh->content_length) {
1033 uh->uc.data_eof = true;
1039 memcpy(buf, data, len);
1043 ustream_consume(uh->us, read_len);
1045 uclient_notify_eof(uh);
1047 /* Now that we consumed something and if this isn't EOF, start timer again */
1048 if (!uh->uc.eof && !cl->connection_timeout.pending)
1049 uloop_timeout_set(&cl->connection_timeout, cl->timeout_msecs);
1054 bool uclient_http_redirect(struct uclient *cl)
1056 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
1057 struct blobmsg_policy location = {
1059 .type = BLOBMSG_TYPE_STRING,
1061 struct uclient_url *url = cl->url;
1062 struct blob_attr *tb;
1064 if (cl->backend != &uclient_backend_http)
1067 switch (cl->status_code) {
1076 blobmsg_parse(&location, 1, &tb, blob_data(uh->meta.head), blob_len(uh->meta.head));
1080 url = uclient_get_url(blobmsg_data(tb), url->auth);
1086 uclient_http_connect(cl);
1087 uclient_http_request_done(cl);
1092 int uclient_http_set_ssl_ctx(struct uclient *cl, const struct ustream_ssl_ops *ops,
1093 struct ustream_ssl_ctx *ctx, bool require_validation)
1095 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
1097 if (cl->backend != &uclient_backend_http)
1100 uclient_http_free_url_state(cl);
1102 uclient_http_free_ssl_ctx(uh);
1105 uh->ssl_require_validation = !!ctx && require_validation;
1110 const struct uclient_backend uclient_backend_http = {
1111 .prefix = uclient_http_prefix,
1113 .alloc = uclient_http_alloc,
1114 .free = uclient_http_free,
1115 .connect = uclient_http_connect,
1116 .disconnect = uclient_http_request_disconnect,
1117 .update_url = uclient_http_free_url_state,
1119 .read = uclient_http_read,
1120 .write = uclient_http_send_data,
1121 .request = uclient_http_request_done,