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 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;
565 int seq = uh->uc.seq;
567 uh->state = HTTP_STATE_RECV_DATA;
568 uh->uc.meta = uh->meta.head;
569 uclient_http_process_headers(uh);
571 if (auth_type == AUTH_TYPE_UNKNOWN && uh->uc.status_code == 401 &&
572 (uh->req_type == REQ_HEAD || uh->req_type == REQ_GET)) {
573 uclient_http_init_request(uh);
574 uclient_http_send_headers(uh);
575 uh->state = HTTP_STATE_REQUEST_DONE;
579 if (uh->uc.cb->header_done)
580 uh->uc.cb->header_done(&uh->uc);
582 if (uh->eof || seq != uh->uc.seq)
585 if (uh->req_type == REQ_HEAD || uh->uc.status_code == 204) {
587 uclient_notify_eof(uh);
591 static void uclient_parse_http_line(struct uclient_http *uh, char *data)
596 if (uh->state == HTTP_STATE_REQUEST_DONE) {
605 code = strsep(&data, " ");
609 uh->uc.status_code = strtoul(code, &sep, 10);
613 uh->state = HTTP_STATE_RECV_HEADERS;
618 uclient_http_headers_complete(uh);
622 sep = strchr(data, ':');
628 for (name = data; *name; name++)
629 *name = tolower(*name);
632 while (isspace(*sep))
635 blobmsg_add_string(&uh->meta, name, sep);
639 uh->uc.status_code = 400;
641 uclient_notify_eof(uh);
644 static void __uclient_notify_read(struct uclient_http *uh)
646 struct uclient *uc = &uh->uc;
647 unsigned int seq = uh->seq;
651 if (uh->state < HTTP_STATE_REQUEST_DONE || uh->state == HTTP_STATE_ERROR)
654 data = ustream_get_read_buf(uh->us, &len);
658 if (uh->state < HTTP_STATE_RECV_DATA) {
663 sep = strstr(data, "\r\n");
667 /* Check for multi-line HTTP headers */
672 if (isspace(sep[2]) && sep[2] != '\r') {
680 cur_len = sep + 2 - data;
681 uclient_parse_http_line(uh, data);
685 ustream_consume(uh->us, cur_len);
691 data = ustream_get_read_buf(uh->us, &len);
692 } while (data && uh->state < HTTP_STATE_RECV_DATA);
701 if (uh->state == HTTP_STATE_RECV_DATA) {
702 /* Now it's uclient user turn to read some data */
703 uloop_timeout_cancel(&uc->connection_timeout);
705 if (uc->cb->data_read)
706 uc->cb->data_read(uc);
710 static void __uclient_notify_write(struct uclient_http *uh)
712 struct uclient *uc = &uh->uc;
714 if (uc->cb->data_sent)
715 uc->cb->data_sent(uc);
718 static void uclient_notify_read(struct ustream *us, int bytes)
720 struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
722 __uclient_notify_read(uh);
725 static void uclient_notify_write(struct ustream *us, int bytes)
727 struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
729 __uclient_notify_write(uh);
732 static void uclient_notify_state(struct ustream *us)
734 struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
736 uclient_notify_eof(uh);
739 static int uclient_setup_http(struct uclient_http *uh)
741 struct ustream *us = &uh->ufd.stream;
747 us->string_data = true;
748 us->notify_state = uclient_notify_state;
749 us->notify_read = uclient_notify_read;
750 us->notify_write = uclient_notify_write;
752 ret = uclient_do_connect(uh, "80");
754 return UCLIENT_ERROR_CONNECT;
759 static void uclient_ssl_notify_read(struct ustream *us, int bytes)
761 struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
763 __uclient_notify_read(uh);
766 static void uclient_ssl_notify_write(struct ustream *us, int bytes)
768 struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
770 __uclient_notify_write(uh);
773 static void uclient_ssl_notify_state(struct ustream *us)
775 struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
777 uclient_notify_eof(uh);
780 static void uclient_ssl_notify_error(struct ustream_ssl *ssl, int error, const char *str)
782 struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
784 uclient_http_error(uh, UCLIENT_ERROR_CONNECT);
787 static void uclient_ssl_notify_verify_error(struct ustream_ssl *ssl, int error, const char *str)
789 struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
791 if (!uh->ssl_require_validation)
794 uclient_http_error(uh, UCLIENT_ERROR_SSL_INVALID_CERT);
797 static void uclient_ssl_notify_connected(struct ustream_ssl *ssl)
799 struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
801 if (!uh->ssl_require_validation)
804 if (!uh->ussl.valid_cn)
805 uclient_http_error(uh, UCLIENT_ERROR_SSL_CN_MISMATCH);
808 static int uclient_setup_https(struct uclient_http *uh)
810 struct ustream *us = &uh->ussl.stream;
817 return UCLIENT_ERROR_MISSING_SSL_CONTEXT;
819 ret = uclient_do_connect(uh, "443");
821 return UCLIENT_ERROR_CONNECT;
823 us->string_data = true;
824 us->notify_state = uclient_ssl_notify_state;
825 us->notify_read = uclient_ssl_notify_read;
826 us->notify_write = uclient_ssl_notify_write;
827 uh->ussl.notify_error = uclient_ssl_notify_error;
828 uh->ussl.notify_verify_error = uclient_ssl_notify_verify_error;
829 uh->ussl.notify_connected = uclient_ssl_notify_connected;
830 uh->ussl.server_name = uh->uc.url->host;
831 uh->ssl_ops->init(&uh->ussl, &uh->ufd.stream, uh->ssl_ctx, false);
832 uh->ssl_ops->set_peer_cn(&uh->ussl, uh->uc.url->host);
837 static int uclient_http_connect(struct uclient *cl)
839 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
842 if (!cl->eof || uh->disconnect)
843 uclient_http_disconnect(uh);
845 uclient_http_init_request(uh);
850 uh->ssl = cl->url->prefix == PREFIX_HTTPS;
853 ret = uclient_setup_https(uh);
855 ret = uclient_setup_http(uh);
860 static void uclient_http_disconnect_cb(struct uloop_timeout *timeout)
862 struct uclient_http *uh = container_of(timeout, struct uclient_http, disconnect_t);
864 uclient_http_disconnect(uh);
867 static struct uclient *uclient_http_alloc(void)
869 struct uclient_http *uh;
871 uh = calloc_a(sizeof(*uh));
872 uh->disconnect_t.cb = uclient_http_disconnect_cb;
873 blob_buf_init(&uh->headers, 0);
878 static void uclient_http_free_ssl_ctx(struct uclient_http *uh)
884 static void uclient_http_free(struct uclient *cl)
886 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
888 uclient_http_free_url_state(cl);
889 uclient_http_free_ssl_ctx(uh);
890 blob_buf_free(&uh->headers);
891 blob_buf_free(&uh->meta);
896 uclient_http_set_request_type(struct uclient *cl, const char *type)
898 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
901 if (cl->backend != &uclient_backend_http)
904 if (uh->state > HTTP_STATE_INIT)
907 for (i = 0; i < ARRAY_SIZE(request_types); i++) {
908 if (strcmp(request_types[i], type) != 0)
919 uclient_http_reset_headers(struct uclient *cl)
921 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
923 blob_buf_init(&uh->headers, 0);
929 uclient_http_set_header(struct uclient *cl, const char *name, const char *value)
931 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
933 if (cl->backend != &uclient_backend_http)
936 if (uh->state > HTTP_STATE_INIT)
939 blobmsg_add_string(&uh->headers, name, value);
944 uclient_http_send_data(struct uclient *cl, const char *buf, unsigned int len)
946 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
948 if (uh->state >= HTTP_STATE_REQUEST_DONE)
951 uclient_http_send_headers(uh);
954 ustream_printf(uh->us, "%X\r\n", len);
955 ustream_write(uh->us, buf, len, false);
956 ustream_printf(uh->us, "\r\n");
963 uclient_http_request_done(struct uclient *cl)
965 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
967 if (uh->state >= HTTP_STATE_REQUEST_DONE)
970 uclient_http_send_headers(uh);
971 if (uh->req_type == REQ_POST || uh->req_type == REQ_PUT)
972 ustream_printf(uh->us, "0\r\n\r\n");
973 uh->state = HTTP_STATE_REQUEST_DONE;
979 uclient_http_read(struct uclient *cl, char *buf, unsigned int len)
981 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
983 char *data, *data_end;
985 if (uh->state < HTTP_STATE_RECV_DATA || !uh->us)
988 data = ustream_get_read_buf(uh->us, &read_len);
989 if (!data || !read_len)
992 data_end = data + read_len;
995 if (uh->read_chunked == 0) {
998 if (data[0] == '\r' && data[1] == '\n') {
1003 sep = strstr(data, "\r\n");
1008 uh->read_chunked = strtoul(data, NULL, 16);
1010 read_len += sep + 2 - data;
1013 if (!uh->read_chunked) {
1015 uh->uc.data_eof = true;
1019 if (len > data_end - data)
1020 len = data_end - data;
1022 if (uh->read_chunked >= 0) {
1023 if (len > uh->read_chunked)
1024 len = uh->read_chunked;
1026 uh->read_chunked -= len;
1027 } else if (uh->content_length >= 0) {
1028 if (len > uh->content_length)
1029 len = uh->content_length;
1031 uh->content_length -= len;
1032 if (!uh->content_length) {
1034 uh->uc.data_eof = true;
1040 memcpy(buf, data, len);
1044 ustream_consume(uh->us, read_len);
1046 uclient_notify_eof(uh);
1048 /* Now that we consumed something and if this isn't EOF, start timer again */
1049 if (!uh->uc.eof && !cl->connection_timeout.pending)
1050 uloop_timeout_set(&cl->connection_timeout, cl->timeout_msecs);
1055 bool uclient_http_redirect(struct uclient *cl)
1057 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
1058 struct blobmsg_policy location = {
1060 .type = BLOBMSG_TYPE_STRING,
1062 struct uclient_url *url = cl->url;
1063 struct blob_attr *tb;
1065 if (cl->backend != &uclient_backend_http)
1068 switch (cl->status_code) {
1077 blobmsg_parse(&location, 1, &tb, blob_data(uh->meta.head), blob_len(uh->meta.head));
1081 url = uclient_get_url(blobmsg_data(tb), url->auth);
1087 uclient_http_connect(cl);
1088 uclient_http_request_done(cl);
1093 int uclient_http_set_ssl_ctx(struct uclient *cl, const struct ustream_ssl_ops *ops,
1094 struct ustream_ssl_ctx *ctx, bool require_validation)
1096 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
1098 if (cl->backend != &uclient_backend_http)
1101 uclient_http_free_url_state(cl);
1103 uclient_http_free_ssl_ctx(uh);
1106 uh->ssl_require_validation = !!ctx && require_validation;
1111 const struct uclient_backend uclient_backend_http = {
1112 .prefix = uclient_http_prefix,
1114 .alloc = uclient_http_alloc,
1115 .free = uclient_http_free,
1116 .connect = uclient_http_connect,
1117 .disconnect = uclient_http_request_disconnect,
1118 .update_url = uclient_http_free_url_state,
1120 .read = uclient_http_read,
1121 .write = uclient_http_send_data,
1122 .request = uclient_http_request_done,