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_do_connect(struct uclient_http *uh, const char *port)
116 if (uh->uc.url->port)
117 port = uh->uc.url->port;
119 memset(&uh->uc.remote_addr, 0, sizeof(uh->uc.remote_addr));
121 fd = usock_inet(USOCK_TCP, uh->uc.url->host, port, &uh->uc.remote_addr);
125 fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
126 ustream_fd_init(&uh->ufd, fd);
128 sl = sizeof(uh->uc.local_addr);
129 memset(&uh->uc.local_addr, 0, sl);
130 getsockname(fd, &uh->uc.local_addr.sa, &sl);
135 static void uclient_http_disconnect(struct uclient_http *uh)
137 uloop_timeout_cancel(&uh->disconnect_t);
142 ustream_free(&uh->ussl.stream);
143 ustream_free(&uh->ufd.stream);
144 close(uh->ufd.fd.fd);
148 static void uclient_http_free_url_state(struct uclient *cl)
150 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
152 uh->auth_type = AUTH_TYPE_UNKNOWN;
155 uclient_http_disconnect(uh);
158 static void uclient_http_error(struct uclient_http *uh, int code)
160 uh->state = HTTP_STATE_ERROR;
162 ustream_state_change(uh->us);
163 uclient_backend_set_error(&uh->uc, code);
166 static void uclient_http_request_disconnect(struct uclient *cl)
168 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
174 uh->disconnect = true;
175 uloop_timeout_set(&uh->disconnect_t, 1);
178 static void uclient_notify_eof(struct uclient_http *uh)
180 struct ustream *us = uh->us;
186 if (!us->eof && !us->write_error)
189 if (ustream_pending_data(us, false))
193 uclient_backend_set_eof(&uh->uc);
195 if (uh->connection_close)
196 uclient_http_request_disconnect(&uh->uc);
199 static void uclient_http_reset_state(struct uclient_http *uh)
202 uclient_backend_reset_state(&uh->uc);
203 uh->read_chunked = -1;
204 uh->content_length = -1;
206 uh->disconnect = false;
207 uh->connection_close = false;
208 uh->state = HTTP_STATE_INIT;
210 if (uh->auth_type == AUTH_TYPE_UNKNOWN && !uh->uc.url->auth)
211 uh->auth_type = AUTH_TYPE_NONE;
214 static void uclient_http_init_request(struct uclient_http *uh)
217 uclient_http_reset_state(uh);
218 blob_buf_init(&uh->meta, 0);
221 static enum auth_type
222 uclient_http_update_auth_type(struct uclient_http *uh)
225 return AUTH_TYPE_NONE;
227 if (!strncasecmp(uh->auth_str, "basic", 5))
228 return AUTH_TYPE_BASIC;
230 if (!strncasecmp(uh->auth_str, "digest", 6))
231 return AUTH_TYPE_DIGEST;
233 return AUTH_TYPE_NONE;
236 static void uclient_http_process_headers(struct uclient_http *uh)
239 HTTP_HDR_TRANSFER_ENCODING,
241 HTTP_HDR_CONTENT_LENGTH,
245 static const struct blobmsg_policy hdr_policy[__HTTP_HDR_MAX] = {
246 #define hdr(_name) { .name = _name, .type = BLOBMSG_TYPE_STRING }
247 [HTTP_HDR_TRANSFER_ENCODING] = hdr("transfer-encoding"),
248 [HTTP_HDR_CONNECTION] = hdr("connection"),
249 [HTTP_HDR_CONTENT_LENGTH] = hdr("content-length"),
250 [HTTP_HDR_AUTH] = hdr("www-authenticate"),
253 struct blob_attr *tb[__HTTP_HDR_MAX];
254 struct blob_attr *cur;
256 blobmsg_parse(hdr_policy, __HTTP_HDR_MAX, tb, blob_data(uh->meta.head), blob_len(uh->meta.head));
258 cur = tb[HTTP_HDR_TRANSFER_ENCODING];
259 if (cur && strstr(blobmsg_data(cur), "chunked"))
260 uh->read_chunked = 0;
262 cur = tb[HTTP_HDR_CONNECTION];
263 if (cur && strstr(blobmsg_data(cur), "close"))
264 uh->connection_close = true;
266 cur = tb[HTTP_HDR_CONTENT_LENGTH];
268 uh->content_length = strtoul(blobmsg_data(cur), NULL, 10);
270 cur = tb[HTTP_HDR_AUTH];
273 uh->auth_str = strdup(blobmsg_data(cur));
276 uh->auth_type = uclient_http_update_auth_type(uh);
280 uclient_http_add_auth_basic(struct uclient_http *uh)
282 struct uclient_url *url = uh->uc.url;
283 int auth_len = strlen(url->auth);
289 auth_buf = alloca(base64_len(auth_len) + 1);
290 base64_encode(url->auth, auth_len, auth_buf);
291 ustream_printf(uh->us, "Authorization: Basic %s\r\n", auth_buf);
294 static char *digest_unquote_sep(char **str)
296 char *cur = *str + 1;
328 static char *digest_sep(char **str)
333 next = strchr(*str, ',');
338 *str += strlen(*str);
344 static bool strmatch(char **str, const char *prefix)
346 int len = strlen(prefix);
348 if (strncmp(*str, prefix, len) != 0 || (*str)[len] != '=')
356 get_cnonce(char *dest)
361 f = fopen("/dev/urandom", "r");
363 fread(&val, sizeof(val), 1, f);
367 bin_to_hex(dest, &val, sizeof(val));
370 static void add_field(char **buf, int *ofs, int *len, const char *name, const char *val)
372 int available = *len - *ofs;
380 required = strlen(name) + 4 + strlen(val) * 2;
381 if (required > available)
382 *len += required - available + 64;
384 *buf = realloc(*buf, *len);
389 cur += sprintf(cur, ", %s=\"", name);
391 while ((next = strchr(val, '"'))) {
393 memcpy(cur, val, next - val);
397 cur += sprintf(cur, "\\\"");
401 cur += sprintf(cur, "%s\"", val);
406 uclient_http_add_auth_digest(struct uclient_http *uh)
408 struct uclient_url *url = uh->uc.url;
409 const char *realm = NULL, *opaque = NULL;
410 const char *user, *password;
419 struct http_digest_data data = {
421 .cnonce = cnonce_str,
425 len = strlen(uh->auth_str) + 1;
430 strcpy(buf, uh->auth_str);
437 const char **dest = NULL;
440 while (*next && isspace(*next))
443 if (strmatch(&next, "realm"))
445 else if (strmatch(&next, "qop"))
447 else if (strmatch(&next, "nonce"))
449 else if (strmatch(&next, "opaque"))
451 else if (strmatch(&next, "stale") ||
452 strmatch(&next, "algorithm") ||
453 strmatch(&next, "auth-param")) {
456 } else if (strmatch(&next, "domain") ||
457 strmatch(&next, "qop-options"))
464 *dest = digest_unquote_sep(&next);
467 if (!realm || !data.qop || !data.nonce)
470 sprintf(nc_str, "%08x", uh->nc++);
471 get_cnonce(cnonce_str);
474 data.uri = url->location;
475 data.method = request_types[uh->req_type];
477 password = strchr(url->auth, ':');
481 len = password - url->auth;
485 user_buf = alloca(len + 1);
486 strncpy(user_buf, url->auth, len);
495 http_digest_calculate_auth_hash(ahash, user, realm, password);
496 http_digest_calculate_response(hash, &data);
502 add_field(&buf, &ofs, &len, "username", user);
503 add_field(&buf, &ofs, &len, "realm", realm);
504 add_field(&buf, &ofs, &len, "nonce", data.nonce);
505 add_field(&buf, &ofs, &len, "uri", data.uri);
506 add_field(&buf, &ofs, &len, "cnonce", data.cnonce);
507 add_field(&buf, &ofs, &len, "response", hash);
509 add_field(&buf, &ofs, &len, "opaque", opaque);
511 ustream_printf(uh->us, "Authorization: Digest nc=%s, qop=%s%s\r\n", data.nc, data.qop, buf);
516 uclient_http_add_auth_header(struct uclient_http *uh)
518 if (!uh->uc.url->auth)
521 switch (uh->auth_type) {
522 case AUTH_TYPE_UNKNOWN:
525 case AUTH_TYPE_BASIC:
526 uclient_http_add_auth_basic(uh);
528 case AUTH_TYPE_DIGEST:
529 uclient_http_add_auth_digest(uh);
535 uclient_http_send_headers(struct uclient_http *uh)
537 struct uclient_url *url = uh->uc.url;
538 struct blob_attr *cur;
539 enum request_type req_type = uh->req_type;
542 if (uh->state >= HTTP_STATE_HEADERS_SENT)
545 if (uh->uc.proxy_url)
546 url = uh->uc.proxy_url;
548 ustream_printf(uh->us,
551 request_types[req_type],
552 url->location, url->host);
554 blobmsg_for_each_attr(cur, uh->headers.head, rem)
555 ustream_printf(uh->us, "%s: %s\r\n", blobmsg_name(cur), (char *) blobmsg_data(cur));
557 if (uh->req_type == REQ_POST || uh->req_type == REQ_PUT)
558 ustream_printf(uh->us, "Transfer-Encoding: chunked\r\n");
560 uclient_http_add_auth_header(uh);
562 ustream_printf(uh->us, "\r\n");
564 uh->state = HTTP_STATE_HEADERS_SENT;
567 static void uclient_http_headers_complete(struct uclient_http *uh)
569 enum auth_type auth_type = uh->auth_type;
570 int seq = uh->uc.seq;
572 uh->state = HTTP_STATE_RECV_DATA;
573 uh->uc.meta = uh->meta.head;
574 uclient_http_process_headers(uh);
576 if (auth_type == AUTH_TYPE_UNKNOWN && uh->uc.status_code == 401 &&
577 (uh->req_type == REQ_HEAD || uh->req_type == REQ_GET)) {
578 uclient_http_init_request(uh);
579 uclient_http_send_headers(uh);
580 uh->state = HTTP_STATE_REQUEST_DONE;
584 if (uh->uc.cb->header_done)
585 uh->uc.cb->header_done(&uh->uc);
587 if (uh->eof || seq != uh->uc.seq)
590 if (uh->req_type == REQ_HEAD || uh->uc.status_code == 204) {
592 uclient_notify_eof(uh);
596 static void uclient_parse_http_line(struct uclient_http *uh, char *data)
601 if (uh->state == HTTP_STATE_REQUEST_DONE) {
610 code = strsep(&data, " ");
614 uh->uc.status_code = strtoul(code, &sep, 10);
618 uh->state = HTTP_STATE_RECV_HEADERS;
623 uclient_http_headers_complete(uh);
627 sep = strchr(data, ':');
633 for (name = data; *name; name++)
634 *name = tolower(*name);
637 while (isspace(*sep))
640 blobmsg_add_string(&uh->meta, name, sep);
644 uh->uc.status_code = 400;
646 uclient_notify_eof(uh);
649 static void __uclient_notify_read(struct uclient_http *uh)
651 struct uclient *uc = &uh->uc;
652 unsigned int seq = uh->seq;
656 if (uh->state < HTTP_STATE_REQUEST_DONE || uh->state == HTTP_STATE_ERROR)
659 data = ustream_get_read_buf(uh->us, &len);
663 if (uh->state < HTTP_STATE_RECV_DATA) {
668 sep = strstr(data, "\r\n");
672 /* Check for multi-line HTTP headers */
677 if (isspace(sep[2]) && sep[2] != '\r') {
685 cur_len = sep + 2 - data;
686 uclient_parse_http_line(uh, data);
690 ustream_consume(uh->us, cur_len);
696 data = ustream_get_read_buf(uh->us, &len);
697 } while (data && uh->state < HTTP_STATE_RECV_DATA);
706 if (uh->state == HTTP_STATE_RECV_DATA) {
707 /* Now it's uclient user turn to read some data */
708 uloop_timeout_cancel(&uc->connection_timeout);
710 if (uc->cb->data_read)
711 uc->cb->data_read(uc);
715 static void __uclient_notify_write(struct uclient_http *uh)
717 struct uclient *uc = &uh->uc;
719 if (uc->cb->data_sent)
720 uc->cb->data_sent(uc);
723 static void uclient_notify_read(struct ustream *us, int bytes)
725 struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
727 __uclient_notify_read(uh);
730 static void uclient_notify_write(struct ustream *us, int bytes)
732 struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
734 __uclient_notify_write(uh);
737 static void uclient_notify_state(struct ustream *us)
739 struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
741 if (uh->ufd.stream.write_error) {
742 uclient_http_error(uh, UCLIENT_ERROR_CONNECT);
745 uclient_notify_eof(uh);
748 static int uclient_setup_http(struct uclient_http *uh)
750 struct ustream *us = &uh->ufd.stream;
756 us->string_data = true;
757 us->notify_state = uclient_notify_state;
758 us->notify_read = uclient_notify_read;
759 us->notify_write = uclient_notify_write;
761 ret = uclient_do_connect(uh, "80");
763 return UCLIENT_ERROR_CONNECT;
768 static void uclient_ssl_notify_read(struct ustream *us, int bytes)
770 struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
772 __uclient_notify_read(uh);
775 static void uclient_ssl_notify_write(struct ustream *us, int bytes)
777 struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
779 __uclient_notify_write(uh);
782 static void uclient_ssl_notify_state(struct ustream *us)
784 struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
786 uclient_notify_eof(uh);
789 static void uclient_ssl_notify_error(struct ustream_ssl *ssl, int error, const char *str)
791 struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
793 uclient_http_error(uh, UCLIENT_ERROR_CONNECT);
796 static void uclient_ssl_notify_verify_error(struct ustream_ssl *ssl, int error, const char *str)
798 struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
800 if (!uh->ssl_require_validation)
803 uclient_http_error(uh, UCLIENT_ERROR_SSL_INVALID_CERT);
806 static void uclient_ssl_notify_connected(struct ustream_ssl *ssl)
808 struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
810 if (!uh->ssl_require_validation)
813 if (!uh->ussl.valid_cn)
814 uclient_http_error(uh, UCLIENT_ERROR_SSL_CN_MISMATCH);
817 static int uclient_setup_https(struct uclient_http *uh)
819 struct ustream *us = &uh->ussl.stream;
826 return UCLIENT_ERROR_MISSING_SSL_CONTEXT;
828 ret = uclient_do_connect(uh, "443");
830 return UCLIENT_ERROR_CONNECT;
832 us->string_data = true;
833 us->notify_state = uclient_ssl_notify_state;
834 us->notify_read = uclient_ssl_notify_read;
835 us->notify_write = uclient_ssl_notify_write;
836 uh->ussl.notify_error = uclient_ssl_notify_error;
837 uh->ussl.notify_verify_error = uclient_ssl_notify_verify_error;
838 uh->ussl.notify_connected = uclient_ssl_notify_connected;
839 uh->ussl.server_name = uh->uc.url->host;
840 uh->ssl_ops->init(&uh->ussl, &uh->ufd.stream, uh->ssl_ctx, false);
841 uh->ssl_ops->set_peer_cn(&uh->ussl, uh->uc.url->host);
846 static int uclient_http_connect(struct uclient *cl)
848 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
851 if (!cl->eof || uh->disconnect)
852 uclient_http_disconnect(uh);
854 uclient_http_init_request(uh);
859 uh->ssl = cl->url->prefix == PREFIX_HTTPS;
862 ret = uclient_setup_https(uh);
864 ret = uclient_setup_http(uh);
869 static void uclient_http_disconnect_cb(struct uloop_timeout *timeout)
871 struct uclient_http *uh = container_of(timeout, struct uclient_http, disconnect_t);
873 uclient_http_disconnect(uh);
876 static struct uclient *uclient_http_alloc(void)
878 struct uclient_http *uh;
880 uh = calloc_a(sizeof(*uh));
881 uh->disconnect_t.cb = uclient_http_disconnect_cb;
882 blob_buf_init(&uh->headers, 0);
887 static void uclient_http_free_ssl_ctx(struct uclient_http *uh)
893 static void uclient_http_free(struct uclient *cl)
895 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
897 uclient_http_free_url_state(cl);
898 uclient_http_free_ssl_ctx(uh);
899 blob_buf_free(&uh->headers);
900 blob_buf_free(&uh->meta);
905 uclient_http_set_request_type(struct uclient *cl, const char *type)
907 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
910 if (cl->backend != &uclient_backend_http)
913 if (uh->state > HTTP_STATE_INIT)
916 for (i = 0; i < ARRAY_SIZE(request_types); i++) {
917 if (strcmp(request_types[i], type) != 0)
928 uclient_http_reset_headers(struct uclient *cl)
930 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
932 blob_buf_init(&uh->headers, 0);
938 uclient_http_set_header(struct uclient *cl, const char *name, const char *value)
940 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
942 if (cl->backend != &uclient_backend_http)
945 if (uh->state > HTTP_STATE_INIT)
948 blobmsg_add_string(&uh->headers, name, value);
953 uclient_http_send_data(struct uclient *cl, const char *buf, unsigned int len)
955 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
957 if (uh->state >= HTTP_STATE_REQUEST_DONE)
960 uclient_http_send_headers(uh);
963 ustream_printf(uh->us, "%X\r\n", len);
964 ustream_write(uh->us, buf, len, false);
965 ustream_printf(uh->us, "\r\n");
972 uclient_http_request_done(struct uclient *cl)
974 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
976 if (uh->state >= HTTP_STATE_REQUEST_DONE)
979 uclient_http_send_headers(uh);
980 if (uh->req_type == REQ_POST || uh->req_type == REQ_PUT)
981 ustream_printf(uh->us, "0\r\n\r\n");
982 uh->state = HTTP_STATE_REQUEST_DONE;
988 uclient_http_read(struct uclient *cl, char *buf, unsigned int len)
990 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
992 char *data, *data_end;
994 if (uh->state < HTTP_STATE_RECV_DATA || !uh->us)
997 data = ustream_get_read_buf(uh->us, &read_len);
998 if (!data || !read_len)
1001 data_end = data + read_len;
1004 if (uh->read_chunked == 0) {
1007 if (data[0] == '\r' && data[1] == '\n') {
1012 sep = strstr(data, "\r\n");
1017 uh->read_chunked = strtoul(data, NULL, 16);
1019 read_len += sep + 2 - data;
1022 if (!uh->read_chunked) {
1024 uh->uc.data_eof = true;
1028 if (len > data_end - data)
1029 len = data_end - data;
1031 if (uh->read_chunked >= 0) {
1032 if (len > uh->read_chunked)
1033 len = uh->read_chunked;
1035 uh->read_chunked -= len;
1036 } else if (uh->content_length >= 0) {
1037 if (len > uh->content_length)
1038 len = uh->content_length;
1040 uh->content_length -= len;
1041 if (!uh->content_length) {
1043 uh->uc.data_eof = true;
1049 memcpy(buf, data, len);
1053 ustream_consume(uh->us, read_len);
1055 uclient_notify_eof(uh);
1057 /* Now that we consumed something and if this isn't EOF, start timer again */
1058 if (!uh->uc.eof && !cl->connection_timeout.pending)
1059 uloop_timeout_set(&cl->connection_timeout, cl->timeout_msecs);
1064 bool uclient_http_redirect(struct uclient *cl)
1066 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
1067 struct blobmsg_policy location = {
1069 .type = BLOBMSG_TYPE_STRING,
1071 struct uclient_url *url = cl->url;
1072 struct blob_attr *tb;
1074 if (cl->backend != &uclient_backend_http)
1077 switch (cl->status_code) {
1086 blobmsg_parse(&location, 1, &tb, blob_data(uh->meta.head), blob_len(uh->meta.head));
1090 url = uclient_get_url(blobmsg_data(tb), url->auth);
1096 uclient_http_connect(cl);
1097 uclient_http_request_done(cl);
1102 int uclient_http_set_ssl_ctx(struct uclient *cl, const struct ustream_ssl_ops *ops,
1103 struct ustream_ssl_ctx *ctx, bool require_validation)
1105 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
1107 if (cl->backend != &uclient_backend_http)
1110 uclient_http_free_url_state(cl);
1112 uclient_http_free_ssl_ctx(uh);
1115 uh->ssl_require_validation = !!ctx && require_validation;
1120 const struct uclient_backend uclient_backend_http = {
1121 .prefix = uclient_http_prefix,
1123 .alloc = uclient_http_alloc,
1124 .free = uclient_http_free,
1125 .connect = uclient_http_connect,
1126 .disconnect = uclient_http_request_disconnect,
1127 .update_url = uclient_http_free_url_state,
1128 .update_proxy_url = uclient_http_free_url_state,
1130 .read = uclient_http_read,
1131 .write = uclient_http_send_data,
1132 .request = uclient_http_request_done,