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)
214 uclient_http_reset_state(uh);
215 blob_buf_init(&uh->meta, 0);
218 static enum auth_type
219 uclient_http_update_auth_type(struct uclient_http *uh)
222 return AUTH_TYPE_NONE;
224 if (!strncasecmp(uh->auth_str, "basic", 5))
225 return AUTH_TYPE_BASIC;
227 if (!strncasecmp(uh->auth_str, "digest", 6))
228 return AUTH_TYPE_DIGEST;
230 return AUTH_TYPE_NONE;
233 static void uclient_http_process_headers(struct uclient_http *uh)
236 HTTP_HDR_TRANSFER_ENCODING,
238 HTTP_HDR_CONTENT_LENGTH,
242 static const struct blobmsg_policy hdr_policy[__HTTP_HDR_MAX] = {
243 #define hdr(_name) { .name = _name, .type = BLOBMSG_TYPE_STRING }
244 [HTTP_HDR_TRANSFER_ENCODING] = hdr("transfer-encoding"),
245 [HTTP_HDR_CONNECTION] = hdr("connection"),
246 [HTTP_HDR_CONTENT_LENGTH] = hdr("content-length"),
247 [HTTP_HDR_AUTH] = hdr("www-authenticate"),
250 struct blob_attr *tb[__HTTP_HDR_MAX];
251 struct blob_attr *cur;
253 blobmsg_parse(hdr_policy, __HTTP_HDR_MAX, tb, blob_data(uh->meta.head), blob_len(uh->meta.head));
255 cur = tb[HTTP_HDR_TRANSFER_ENCODING];
256 if (cur && strstr(blobmsg_data(cur), "chunked"))
257 uh->read_chunked = 0;
259 cur = tb[HTTP_HDR_CONNECTION];
260 if (cur && strstr(blobmsg_data(cur), "close"))
261 uh->connection_close = true;
263 cur = tb[HTTP_HDR_CONTENT_LENGTH];
265 uh->content_length = strtoul(blobmsg_data(cur), NULL, 10);
267 cur = tb[HTTP_HDR_AUTH];
270 uh->auth_str = strdup(blobmsg_data(cur));
273 uh->auth_type = uclient_http_update_auth_type(uh);
277 uclient_http_add_auth_basic(struct uclient_http *uh)
279 struct uclient_url *url = uh->uc.url;
280 int auth_len = strlen(url->auth);
286 auth_buf = alloca(base64_len(auth_len) + 1);
287 base64_encode(url->auth, auth_len, auth_buf);
288 ustream_printf(uh->us, "Authorization: Basic %s\r\n", auth_buf);
291 static char *digest_unquote_sep(char **str)
293 char *cur = *str + 1;
325 static char *digest_sep(char **str)
330 next = strchr(*str, ',');
335 *str += strlen(*str);
341 static bool strmatch(char **str, const char *prefix)
343 int len = strlen(prefix);
345 if (strncmp(*str, prefix, len) != 0 || (*str)[len] != '=')
353 get_cnonce(char *dest)
358 f = fopen("/dev/urandom", "r");
360 fread(&val, sizeof(val), 1, f);
364 bin_to_hex(dest, &val, sizeof(val));
367 static void add_field(char **buf, int *ofs, int *len, const char *name, const char *val)
369 int available = *len - *ofs;
377 required = strlen(name) + 4 + strlen(val) * 2;
378 if (required > available)
379 *len += required - available + 64;
381 *buf = realloc(*buf, *len);
386 cur += sprintf(cur, ", %s=\"", name);
388 while ((next = strchr(val, '"'))) {
390 memcpy(cur, val, next - val);
394 cur += sprintf(cur, "\\\"");
398 cur += sprintf(cur, "%s\"", val);
403 uclient_http_add_auth_digest(struct uclient_http *uh)
405 struct uclient_url *url = uh->uc.url;
406 const char *realm = NULL, *opaque = NULL;
407 const char *user, *password;
416 struct http_digest_data data = {
418 .cnonce = cnonce_str,
422 len = strlen(uh->auth_str) + 1;
427 strcpy(buf, uh->auth_str);
434 const char **dest = NULL;
437 while (*next && isspace(*next))
440 if (strmatch(&next, "realm"))
442 else if (strmatch(&next, "qop"))
444 else if (strmatch(&next, "nonce"))
446 else if (strmatch(&next, "opaque"))
448 else if (strmatch(&next, "stale") ||
449 strmatch(&next, "algorithm") ||
450 strmatch(&next, "auth-param")) {
453 } else if (strmatch(&next, "domain") ||
454 strmatch(&next, "qop-options"))
461 *dest = digest_unquote_sep(&next);
464 if (!realm || !data.qop || !data.nonce)
467 sprintf(nc_str, "%08x", uh->nc++);
468 get_cnonce(cnonce_str);
471 data.uri = url->location;
472 data.method = request_types[uh->req_type];
474 password = strchr(url->auth, ':');
478 len = password - url->auth;
482 user_buf = alloca(len + 1);
483 strncpy(user_buf, url->auth, len);
492 http_digest_calculate_auth_hash(ahash, user, realm, password);
493 http_digest_calculate_response(hash, &data);
499 add_field(&buf, &ofs, &len, "username", user);
500 add_field(&buf, &ofs, &len, "realm", realm);
501 add_field(&buf, &ofs, &len, "nonce", data.nonce);
502 add_field(&buf, &ofs, &len, "uri", data.uri);
503 add_field(&buf, &ofs, &len, "cnonce", data.cnonce);
504 add_field(&buf, &ofs, &len, "response", hash);
506 add_field(&buf, &ofs, &len, "opaque", opaque);
508 ustream_printf(uh->us, "Authorization: Digest nc=%s, qop=%s%s\r\n", data.nc, data.qop, buf);
513 uclient_http_add_auth_header(struct uclient_http *uh)
515 if (!uh->uc.url->auth)
518 switch (uh->auth_type) {
519 case AUTH_TYPE_UNKNOWN:
522 case AUTH_TYPE_BASIC:
523 uclient_http_add_auth_basic(uh);
525 case AUTH_TYPE_DIGEST:
526 uclient_http_add_auth_digest(uh);
532 uclient_http_send_headers(struct uclient_http *uh)
534 struct uclient_url *url = uh->uc.url;
535 struct blob_attr *cur;
536 enum request_type req_type = uh->req_type;
539 if (uh->state >= HTTP_STATE_HEADERS_SENT)
542 ustream_printf(uh->us,
545 request_types[req_type],
546 url->location, url->host);
548 blobmsg_for_each_attr(cur, uh->headers.head, rem)
549 ustream_printf(uh->us, "%s: %s\r\n", blobmsg_name(cur), (char *) blobmsg_data(cur));
551 if (uh->req_type == REQ_POST || uh->req_type == REQ_PUT)
552 ustream_printf(uh->us, "Transfer-Encoding: chunked\r\n");
554 uclient_http_add_auth_header(uh);
556 ustream_printf(uh->us, "\r\n");
558 uh->state = HTTP_STATE_HEADERS_SENT;
561 static void uclient_http_headers_complete(struct uclient_http *uh)
563 enum auth_type auth_type = uh->auth_type;
565 uh->state = HTTP_STATE_RECV_DATA;
566 uh->uc.meta = uh->meta.head;
567 uclient_http_process_headers(uh);
569 if (auth_type == AUTH_TYPE_UNKNOWN && uh->uc.status_code == 401 &&
570 (uh->req_type == REQ_HEAD || uh->req_type == REQ_GET)) {
571 uclient_http_init_request(uh);
572 uclient_http_send_headers(uh);
573 uh->state = HTTP_STATE_REQUEST_DONE;
577 if (uh->uc.cb->header_done)
578 uh->uc.cb->header_done(&uh->uc);
583 if (uh->req_type == REQ_HEAD || uh->uc.status_code == 204) {
585 uclient_notify_eof(uh);
589 static void uclient_parse_http_line(struct uclient_http *uh, char *data)
594 if (uh->state == HTTP_STATE_REQUEST_DONE) {
603 code = strsep(&data, " ");
607 uh->uc.status_code = strtoul(code, &sep, 10);
611 uh->state = HTTP_STATE_RECV_HEADERS;
616 uclient_http_headers_complete(uh);
620 sep = strchr(data, ':');
626 for (name = data; *name; name++)
627 *name = tolower(*name);
630 while (isspace(*sep))
633 blobmsg_add_string(&uh->meta, name, sep);
637 uh->uc.status_code = 400;
639 uclient_notify_eof(uh);
642 static void __uclient_notify_read(struct uclient_http *uh)
644 struct uclient *uc = &uh->uc;
645 unsigned int seq = uh->seq;
649 if (uh->state < HTTP_STATE_REQUEST_DONE || uh->state == HTTP_STATE_ERROR)
652 data = ustream_get_read_buf(uh->us, &len);
656 if (uh->state < HTTP_STATE_RECV_DATA) {
661 sep = strstr(data, "\r\n");
665 /* Check for multi-line HTTP headers */
670 if (isspace(sep[2]) && sep[2] != '\r') {
678 cur_len = sep + 2 - data;
679 uclient_parse_http_line(uh, data);
683 ustream_consume(uh->us, cur_len);
689 data = ustream_get_read_buf(uh->us, &len);
690 } while (data && uh->state < HTTP_STATE_RECV_DATA);
699 if (uh->state == HTTP_STATE_RECV_DATA) {
700 /* Now it's uclient user turn to read some data */
701 uloop_timeout_cancel(&uc->connection_timeout);
703 if (uc->cb->data_read)
704 uc->cb->data_read(uc);
708 static void __uclient_notify_write(struct uclient_http *uh)
710 struct uclient *uc = &uh->uc;
712 if (uc->cb->data_sent)
713 uc->cb->data_sent(uc);
716 static void uclient_notify_read(struct ustream *us, int bytes)
718 struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
720 __uclient_notify_read(uh);
723 static void uclient_notify_write(struct ustream *us, int bytes)
725 struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
727 __uclient_notify_write(uh);
730 static void uclient_notify_state(struct ustream *us)
732 struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
734 uclient_notify_eof(uh);
737 static int uclient_setup_http(struct uclient_http *uh)
739 struct ustream *us = &uh->ufd.stream;
745 us->string_data = true;
746 us->notify_state = uclient_notify_state;
747 us->notify_read = uclient_notify_read;
748 us->notify_write = uclient_notify_write;
750 ret = uclient_do_connect(uh, "80");
752 return UCLIENT_ERROR_CONNECT;
757 static void uclient_ssl_notify_read(struct ustream *us, int bytes)
759 struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
761 __uclient_notify_read(uh);
764 static void uclient_ssl_notify_write(struct ustream *us, int bytes)
766 struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
768 __uclient_notify_write(uh);
771 static void uclient_ssl_notify_state(struct ustream *us)
773 struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
775 uclient_notify_eof(uh);
778 static void uclient_ssl_notify_error(struct ustream_ssl *ssl, int error, const char *str)
780 struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
782 uclient_http_error(uh, UCLIENT_ERROR_CONNECT);
785 static void uclient_ssl_notify_verify_error(struct ustream_ssl *ssl, int error, const char *str)
787 struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
789 if (!uh->ssl_require_validation)
792 uclient_http_error(uh, UCLIENT_ERROR_SSL_INVALID_CERT);
795 static void uclient_ssl_notify_connected(struct ustream_ssl *ssl)
797 struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
799 if (!uh->ssl_require_validation)
802 if (!uh->ussl.valid_cn)
803 uclient_http_error(uh, UCLIENT_ERROR_SSL_CN_MISMATCH);
806 static int uclient_setup_https(struct uclient_http *uh)
808 struct ustream *us = &uh->ussl.stream;
815 return UCLIENT_ERROR_MISSING_SSL_CONTEXT;
817 ret = uclient_do_connect(uh, "443");
819 return UCLIENT_ERROR_CONNECT;
821 us->string_data = true;
822 us->notify_state = uclient_ssl_notify_state;
823 us->notify_read = uclient_ssl_notify_read;
824 us->notify_write = uclient_ssl_notify_write;
825 uh->ussl.notify_error = uclient_ssl_notify_error;
826 uh->ussl.notify_verify_error = uclient_ssl_notify_verify_error;
827 uh->ussl.notify_connected = uclient_ssl_notify_connected;
828 uh->ussl.server_name = uh->uc.url->host;
829 uh->ssl_ops->init(&uh->ussl, &uh->ufd.stream, uh->ssl_ctx, false);
830 uh->ssl_ops->set_peer_cn(&uh->ussl, uh->uc.url->host);
835 static int uclient_http_connect(struct uclient *cl)
837 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
840 if (!cl->eof || uh->disconnect)
841 uclient_http_disconnect(uh);
843 uclient_http_init_request(uh);
848 uh->ssl = cl->url->prefix == PREFIX_HTTPS;
851 ret = uclient_setup_https(uh);
853 ret = uclient_setup_http(uh);
858 static void uclient_http_disconnect_cb(struct uloop_timeout *timeout)
860 struct uclient_http *uh = container_of(timeout, struct uclient_http, disconnect_t);
862 uclient_http_disconnect(uh);
865 static struct uclient *uclient_http_alloc(void)
867 struct uclient_http *uh;
869 uh = calloc_a(sizeof(*uh));
870 uh->disconnect_t.cb = uclient_http_disconnect_cb;
871 blob_buf_init(&uh->headers, 0);
876 static void uclient_http_free_ssl_ctx(struct uclient_http *uh)
882 static void uclient_http_free(struct uclient *cl)
884 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
886 uclient_http_free_url_state(cl);
887 uclient_http_free_ssl_ctx(uh);
888 blob_buf_free(&uh->headers);
889 blob_buf_free(&uh->meta);
894 uclient_http_set_request_type(struct uclient *cl, const char *type)
896 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
899 if (cl->backend != &uclient_backend_http)
902 if (uh->state > HTTP_STATE_INIT)
905 for (i = 0; i < ARRAY_SIZE(request_types); i++) {
906 if (strcmp(request_types[i], type) != 0)
917 uclient_http_reset_headers(struct uclient *cl)
919 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
921 blob_buf_init(&uh->headers, 0);
927 uclient_http_set_header(struct uclient *cl, const char *name, const char *value)
929 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
931 if (cl->backend != &uclient_backend_http)
934 if (uh->state > HTTP_STATE_INIT)
937 blobmsg_add_string(&uh->headers, name, value);
942 uclient_http_send_data(struct uclient *cl, const char *buf, unsigned int len)
944 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
946 if (uh->state >= HTTP_STATE_REQUEST_DONE)
949 uclient_http_send_headers(uh);
952 ustream_printf(uh->us, "%X\r\n", len);
953 ustream_write(uh->us, buf, len, false);
954 ustream_printf(uh->us, "\r\n");
961 uclient_http_request_done(struct uclient *cl)
963 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
965 if (uh->state >= HTTP_STATE_REQUEST_DONE)
968 uclient_http_send_headers(uh);
969 if (uh->req_type == REQ_POST || uh->req_type == REQ_PUT)
970 ustream_printf(uh->us, "0\r\n\r\n");
971 uh->state = HTTP_STATE_REQUEST_DONE;
977 uclient_http_read(struct uclient *cl, char *buf, unsigned int len)
979 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
981 char *data, *data_end;
983 if (uh->state < HTTP_STATE_RECV_DATA || !uh->us)
986 data = ustream_get_read_buf(uh->us, &read_len);
987 if (!data || !read_len)
990 data_end = data + read_len;
993 if (uh->read_chunked == 0) {
996 if (data[0] == '\r' && data[1] == '\n') {
1001 sep = strstr(data, "\r\n");
1006 uh->read_chunked = strtoul(data, NULL, 16);
1008 read_len += sep + 2 - data;
1011 if (!uh->read_chunked) {
1013 uh->uc.data_eof = true;
1017 if (len > data_end - data)
1018 len = data_end - data;
1020 if (uh->read_chunked >= 0) {
1021 if (len > uh->read_chunked)
1022 len = uh->read_chunked;
1024 uh->read_chunked -= len;
1025 } else if (uh->content_length >= 0) {
1026 if (len > uh->content_length)
1027 len = uh->content_length;
1029 uh->content_length -= len;
1030 if (!uh->content_length) {
1032 uh->uc.data_eof = true;
1038 memcpy(buf, data, len);
1042 ustream_consume(uh->us, read_len);
1044 uclient_notify_eof(uh);
1046 /* Now that we consumed something and if this isn't EOF, start timer again */
1047 if (!uh->uc.eof && !cl->connection_timeout.pending)
1048 uloop_timeout_set(&cl->connection_timeout, cl->timeout_msecs);
1053 bool uclient_http_redirect(struct uclient *cl)
1055 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
1056 struct blobmsg_policy location = {
1058 .type = BLOBMSG_TYPE_STRING,
1060 struct uclient_url *url = cl->url;
1061 struct blob_attr *tb;
1063 if (cl->backend != &uclient_backend_http)
1066 switch (cl->status_code) {
1075 blobmsg_parse(&location, 1, &tb, blob_data(uh->meta.head), blob_len(uh->meta.head));
1079 url = uclient_get_url(blobmsg_data(tb), url->auth);
1085 uclient_http_connect(cl);
1086 uclient_http_request_done(cl);
1091 int uclient_http_set_ssl_ctx(struct uclient *cl, const struct ustream_ssl_ops *ops,
1092 struct ustream_ssl_ctx *ctx, bool require_validation)
1094 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
1096 if (cl->backend != &uclient_backend_http)
1099 uclient_http_free_url_state(cl);
1101 uclient_http_free_ssl_ctx(uh);
1104 uh->ssl_require_validation = !!ctx && require_validation;
1109 const struct uclient_backend uclient_backend_http = {
1110 .prefix = uclient_http_prefix,
1112 .alloc = uclient_http_alloc,
1113 .free = uclient_http_free,
1114 .connect = uclient_http_connect,
1115 .disconnect = uclient_http_request_disconnect,
1116 .update_url = uclient_http_free_url_state,
1118 .read = uclient_http_read,
1119 .write = uclient_http_send_data,
1120 .request = uclient_http_request_done,