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"
49 HTTP_STATE_HEADERS_SENT,
50 HTTP_STATE_REQUEST_DONE,
51 HTTP_STATE_RECV_HEADERS,
56 static const char * const request_types[__REQ_MAX] = {
66 const struct ustream_ssl_ops *ssl_ops;
67 struct ustream_ssl_ctx *ssl_ctx;
70 struct ustream_fd ufd;
71 struct ustream_ssl ussl;
73 struct uloop_timeout disconnect_t;
75 bool ssl_require_validation;
78 bool connection_close;
80 enum request_type req_type;
81 enum http_state state;
83 enum auth_type auth_type;
91 struct blob_buf headers;
101 static const char * const uclient_http_prefix[] = {
102 [PREFIX_HTTP] = "http://",
103 [PREFIX_HTTPS] = "https://",
104 [__PREFIX_MAX] = NULL
107 static int uclient_do_connect(struct uclient_http *uh, const char *port)
112 if (uh->uc.url->port)
113 port = uh->uc.url->port;
115 fd = usock(USOCK_TCP | USOCK_NONBLOCK, uh->uc.url->host, port);
119 ustream_fd_init(&uh->ufd, fd);
121 memset(&uh->uc.local_addr, 0, sizeof(uh->uc.local_addr));
122 memset(&uh->uc.remote_addr, 0, sizeof(uh->uc.remote_addr));
124 sl = sizeof(uh->uc.local_addr);
125 getsockname(fd, &uh->uc.local_addr.sa, &sl);
126 getpeername(fd, &uh->uc.remote_addr.sa, &sl);
131 static void uclient_http_disconnect(struct uclient_http *uh)
133 uloop_timeout_cancel(&uh->disconnect_t);
138 ustream_free(&uh->ussl.stream);
139 ustream_free(&uh->ufd.stream);
140 close(uh->ufd.fd.fd);
144 static void uclient_http_free_url_state(struct uclient *cl)
146 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
148 uh->auth_type = AUTH_TYPE_UNKNOWN;
151 uclient_http_disconnect(uh);
154 static void uclient_http_error(struct uclient_http *uh, int code)
156 uh->state = HTTP_STATE_ERROR;
158 ustream_state_change(uh->us);
159 uclient_backend_set_error(&uh->uc, code);
162 static void uclient_http_request_disconnect(struct uclient *cl)
164 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
170 uh->disconnect = true;
171 uloop_timeout_set(&uh->disconnect_t, 1);
174 static void uclient_notify_eof(struct uclient_http *uh)
176 struct ustream *us = uh->us;
182 if (!us->eof && !us->write_error)
185 if (ustream_pending_data(us, false))
189 uclient_backend_set_eof(&uh->uc);
191 if (uh->connection_close)
192 uclient_http_request_disconnect(&uh->uc);
195 static void uclient_http_reset_state(struct uclient_http *uh)
197 uclient_backend_reset_state(&uh->uc);
198 uh->read_chunked = -1;
199 uh->content_length = -1;
201 uh->disconnect = false;
202 uh->connection_close = false;
203 uh->state = HTTP_STATE_INIT;
205 if (uh->auth_type == AUTH_TYPE_UNKNOWN && !uh->uc.url->auth)
206 uh->auth_type = AUTH_TYPE_NONE;
209 static void uclient_http_init_request(struct uclient_http *uh)
211 uclient_http_reset_state(uh);
212 blob_buf_init(&uh->meta, 0);
215 static enum auth_type
216 uclient_http_update_auth_type(struct uclient_http *uh)
219 return AUTH_TYPE_NONE;
221 if (!strncasecmp(uh->auth_str, "basic", 5))
222 return AUTH_TYPE_BASIC;
224 if (!strncasecmp(uh->auth_str, "digest", 6))
225 return AUTH_TYPE_DIGEST;
227 return AUTH_TYPE_NONE;
230 static void uclient_http_process_headers(struct uclient_http *uh)
233 HTTP_HDR_TRANSFER_ENCODING,
235 HTTP_HDR_CONTENT_LENGTH,
239 static const struct blobmsg_policy hdr_policy[__HTTP_HDR_MAX] = {
240 #define hdr(_name) { .name = _name, .type = BLOBMSG_TYPE_STRING }
241 [HTTP_HDR_TRANSFER_ENCODING] = hdr("transfer-encoding"),
242 [HTTP_HDR_CONNECTION] = hdr("connection"),
243 [HTTP_HDR_CONTENT_LENGTH] = hdr("content-length"),
244 [HTTP_HDR_AUTH] = hdr("www-authenticate"),
247 struct blob_attr *tb[__HTTP_HDR_MAX];
248 struct blob_attr *cur;
250 blobmsg_parse(hdr_policy, __HTTP_HDR_MAX, tb, blob_data(uh->meta.head), blob_len(uh->meta.head));
252 cur = tb[HTTP_HDR_TRANSFER_ENCODING];
253 if (cur && strstr(blobmsg_data(cur), "chunked"))
254 uh->read_chunked = 0;
256 cur = tb[HTTP_HDR_CONNECTION];
257 if (cur && strstr(blobmsg_data(cur), "close"))
258 uh->connection_close = true;
260 cur = tb[HTTP_HDR_CONTENT_LENGTH];
262 uh->content_length = strtoul(blobmsg_data(cur), NULL, 10);
264 cur = tb[HTTP_HDR_AUTH];
267 uh->auth_str = strdup(blobmsg_data(cur));
270 uh->auth_type = uclient_http_update_auth_type(uh);
274 uclient_http_add_auth_basic(struct uclient_http *uh)
276 struct uclient_url *url = uh->uc.url;
277 int auth_len = strlen(url->auth);
283 auth_buf = alloca(base64_len(auth_len) + 1);
284 base64_encode(url->auth, auth_len, auth_buf);
285 ustream_printf(uh->us, "Authorization: Basic %s\r\n", auth_buf);
288 static char *digest_unquote_sep(char **str)
290 char *cur = *str + 1;
322 static char *digest_sep(char **str)
327 next = strchr(*str, ',');
332 *str += strlen(*str);
338 static bool strmatch(char **str, const char *prefix)
340 int len = strlen(prefix);
342 if (strncmp(*str, prefix, len) != 0 || (*str)[len] != '=')
350 get_cnonce(char *dest)
355 f = fopen("/dev/urandom", "r");
357 fread(&val, sizeof(val), 1, f);
361 bin_to_hex(dest, &val, sizeof(val));
364 static void add_field(char **buf, int *ofs, int *len, const char *name, const char *val)
366 int available = *len - *ofs;
374 required = strlen(name) + 4 + strlen(val) * 2;
375 if (required > available)
376 *len += required - available + 64;
378 *buf = realloc(*buf, *len);
383 cur += sprintf(cur, ", %s=\"", name);
385 while ((next = strchr(val, '"'))) {
387 memcpy(cur, val, next - val);
391 cur += sprintf(cur, "\\\"");
395 cur += sprintf(cur, "%s\"", val);
400 uclient_http_add_auth_digest(struct uclient_http *uh)
402 struct uclient_url *url = uh->uc.url;
403 const char *realm = NULL, *opaque = NULL;
404 const char *user, *password;
413 struct http_digest_data data = {
415 .cnonce = cnonce_str,
419 len = strlen(uh->auth_str) + 1;
424 strcpy(buf, uh->auth_str);
431 const char **dest = NULL;
434 while (*next && isspace(*next))
437 if (strmatch(&next, "realm"))
439 else if (strmatch(&next, "qop"))
441 else if (strmatch(&next, "nonce"))
443 else if (strmatch(&next, "opaque"))
445 else if (strmatch(&next, "stale") ||
446 strmatch(&next, "algorithm") ||
447 strmatch(&next, "auth-param")) {
450 } else if (strmatch(&next, "domain") ||
451 strmatch(&next, "qop-options"))
458 *dest = digest_unquote_sep(&next);
461 if (!realm || !data.qop || !data.nonce)
464 sprintf(nc_str, "%08x", uh->nc++);
465 get_cnonce(cnonce_str);
468 data.uri = url->location;
469 data.method = request_types[uh->req_type];
471 password = strchr(url->auth, ':');
475 len = password - url->auth;
479 user_buf = alloca(len + 1);
480 strncpy(user_buf, url->auth, len);
489 http_digest_calculate_auth_hash(ahash, user, realm, password);
490 http_digest_calculate_response(hash, &data);
496 add_field(&buf, &ofs, &len, "username", user);
497 add_field(&buf, &ofs, &len, "realm", realm);
498 add_field(&buf, &ofs, &len, "nonce", data.nonce);
499 add_field(&buf, &ofs, &len, "uri", data.uri);
500 add_field(&buf, &ofs, &len, "cnonce", data.cnonce);
501 add_field(&buf, &ofs, &len, "response", hash);
503 add_field(&buf, &ofs, &len, "opaque", opaque);
505 ustream_printf(uh->us, "Authorization: Digest nc=%s, qop=%s%s\r\n", data.nc, data.qop, buf);
510 uclient_http_add_auth_header(struct uclient_http *uh)
512 if (!uh->uc.url->auth)
515 switch (uh->auth_type) {
516 case AUTH_TYPE_UNKNOWN:
519 case AUTH_TYPE_BASIC:
520 uclient_http_add_auth_basic(uh);
522 case AUTH_TYPE_DIGEST:
523 uclient_http_add_auth_digest(uh);
529 uclient_http_send_headers(struct uclient_http *uh)
531 struct uclient_url *url = uh->uc.url;
532 struct blob_attr *cur;
533 enum request_type req_type = uh->req_type;
536 if (uh->state >= HTTP_STATE_HEADERS_SENT)
539 ustream_printf(uh->us,
542 request_types[req_type],
543 url->location, url->host);
545 blobmsg_for_each_attr(cur, uh->headers.head, rem)
546 ustream_printf(uh->us, "%s: %s\n", blobmsg_name(cur), (char *) blobmsg_data(cur));
548 if (uh->req_type == REQ_POST || uh->req_type == REQ_PUT)
549 ustream_printf(uh->us, "Transfer-Encoding: chunked\r\n");
551 uclient_http_add_auth_header(uh);
553 ustream_printf(uh->us, "\r\n");
555 uh->state = HTTP_STATE_HEADERS_SENT;
558 static void uclient_http_headers_complete(struct uclient_http *uh)
560 enum auth_type auth_type = uh->auth_type;
562 uh->state = HTTP_STATE_RECV_DATA;
563 uh->uc.meta = uh->meta.head;
564 uclient_http_process_headers(uh);
566 if (auth_type == AUTH_TYPE_UNKNOWN && uh->uc.status_code == 401 &&
567 (uh->req_type == REQ_HEAD || uh->req_type == REQ_GET)) {
568 uclient_http_init_request(uh);
569 uclient_http_send_headers(uh);
570 uh->state = HTTP_STATE_REQUEST_DONE;
574 if (uh->uc.cb->header_done)
575 uh->uc.cb->header_done(&uh->uc);
580 if (uh->req_type == REQ_HEAD || uh->uc.status_code == 204) {
582 uclient_notify_eof(uh);
586 static void uclient_parse_http_line(struct uclient_http *uh, char *data)
591 if (uh->state == HTTP_STATE_REQUEST_DONE) {
600 code = strsep(&data, " ");
604 uh->uc.status_code = strtoul(code, &sep, 10);
608 uh->state = HTTP_STATE_RECV_HEADERS;
613 uclient_http_headers_complete(uh);
617 sep = strchr(data, ':');
623 for (name = data; *name; name++)
624 *name = tolower(*name);
627 while (isspace(*sep))
630 blobmsg_add_string(&uh->meta, name, sep);
634 uh->uc.status_code = 400;
636 uclient_notify_eof(uh);
639 static void __uclient_notify_read(struct uclient_http *uh)
641 struct uclient *uc = &uh->uc;
645 if (uh->state < HTTP_STATE_REQUEST_DONE || uh->state == HTTP_STATE_ERROR)
648 data = ustream_get_read_buf(uh->us, &len);
652 if (uh->state < HTTP_STATE_RECV_DATA) {
657 sep = strstr(data, "\r\n");
661 /* Check for multi-line HTTP headers */
666 if (isspace(sep[2]) && sep[2] != '\r') {
674 cur_len = sep + 2 - data;
675 uclient_parse_http_line(uh, data);
676 ustream_consume(uh->us, cur_len);
682 data = ustream_get_read_buf(uh->us, &len);
683 } while (data && uh->state < HTTP_STATE_RECV_DATA);
692 if (uh->state == HTTP_STATE_RECV_DATA && uc->cb->data_read)
693 uc->cb->data_read(uc);
696 static void __uclient_notify_write(struct uclient_http *uh)
698 struct uclient *uc = &uh->uc;
700 if (uc->cb->data_sent)
701 uc->cb->data_sent(uc);
704 static void uclient_notify_read(struct ustream *us, int bytes)
706 struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
708 __uclient_notify_read(uh);
711 static void uclient_notify_write(struct ustream *us, int bytes)
713 struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
715 __uclient_notify_write(uh);
718 static void uclient_notify_state(struct ustream *us)
720 struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
722 uclient_notify_eof(uh);
725 static int uclient_setup_http(struct uclient_http *uh)
727 struct ustream *us = &uh->ufd.stream;
733 us->string_data = true;
734 us->notify_state = uclient_notify_state;
735 us->notify_read = uclient_notify_read;
736 us->notify_write = uclient_notify_write;
738 ret = uclient_do_connect(uh, "80");
740 return UCLIENT_ERROR_CONNECT;
745 static void uclient_ssl_notify_read(struct ustream *us, int bytes)
747 struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
749 __uclient_notify_read(uh);
752 static void uclient_ssl_notify_write(struct ustream *us, int bytes)
754 struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
756 __uclient_notify_write(uh);
759 static void uclient_ssl_notify_state(struct ustream *us)
761 struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
763 uclient_notify_eof(uh);
766 static void uclient_ssl_notify_error(struct ustream_ssl *ssl, int error, const char *str)
768 struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
770 uclient_http_error(uh, UCLIENT_ERROR_CONNECT);
773 static void uclient_ssl_notify_verify_error(struct ustream_ssl *ssl, int error, const char *str)
775 struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
777 if (!uh->ssl_require_validation)
780 uclient_http_error(uh, UCLIENT_ERROR_SSL_INVALID_CERT);
783 static void uclient_ssl_notify_connected(struct ustream_ssl *ssl)
785 struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
787 if (!uh->ssl_require_validation)
790 if (!uh->ussl.valid_cn)
791 uclient_http_error(uh, UCLIENT_ERROR_SSL_CN_MISMATCH);
794 static int uclient_setup_https(struct uclient_http *uh)
796 struct ustream *us = &uh->ussl.stream;
803 return UCLIENT_ERROR_MISSING_SSL_CONTEXT;
805 ret = uclient_do_connect(uh, "443");
807 return UCLIENT_ERROR_CONNECT;
809 us->string_data = true;
810 us->notify_state = uclient_ssl_notify_state;
811 us->notify_read = uclient_ssl_notify_read;
812 us->notify_write = uclient_ssl_notify_write;
813 uh->ussl.notify_error = uclient_ssl_notify_error;
814 uh->ussl.notify_verify_error = uclient_ssl_notify_verify_error;
815 uh->ussl.notify_connected = uclient_ssl_notify_connected;
816 uh->ssl_ops->init(&uh->ussl, &uh->ufd.stream, uh->ssl_ctx, false);
817 uh->ssl_ops->set_peer_cn(&uh->ussl, uh->uc.url->host);
822 static int uclient_http_connect(struct uclient *cl)
824 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
827 if (!cl->eof || uh->disconnect)
828 uclient_http_disconnect(uh);
830 uclient_http_init_request(uh);
835 uh->ssl = cl->url->prefix == PREFIX_HTTPS;
838 ret = uclient_setup_https(uh);
840 ret = uclient_setup_http(uh);
845 static void uclient_http_disconnect_cb(struct uloop_timeout *timeout)
847 struct uclient_http *uh = container_of(timeout, struct uclient_http, disconnect_t);
849 uclient_http_disconnect(uh);
852 static struct uclient *uclient_http_alloc(void)
854 struct uclient_http *uh;
856 uh = calloc_a(sizeof(*uh));
857 uh->disconnect_t.cb = uclient_http_disconnect_cb;
858 blob_buf_init(&uh->headers, 0);
863 static void uclient_http_free_ssl_ctx(struct uclient_http *uh)
869 static void uclient_http_free(struct uclient *cl)
871 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
873 uclient_http_free_url_state(cl);
874 uclient_http_free_ssl_ctx(uh);
875 blob_buf_free(&uh->headers);
876 blob_buf_free(&uh->meta);
881 uclient_http_set_request_type(struct uclient *cl, const char *type)
883 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
886 if (cl->backend != &uclient_backend_http)
889 if (uh->state > HTTP_STATE_INIT)
892 for (i = 0; i < ARRAY_SIZE(request_types); i++) {
893 if (strcmp(request_types[i], type) != 0)
904 uclient_http_reset_headers(struct uclient *cl)
906 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
908 blob_buf_init(&uh->headers, 0);
914 uclient_http_set_header(struct uclient *cl, const char *name, const char *value)
916 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
918 if (cl->backend != &uclient_backend_http)
921 if (uh->state > HTTP_STATE_INIT)
924 blobmsg_add_string(&uh->headers, name, value);
929 uclient_http_send_data(struct uclient *cl, char *buf, unsigned int len)
931 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
933 if (uh->state >= HTTP_STATE_REQUEST_DONE)
936 uclient_http_send_headers(uh);
939 ustream_printf(uh->us, "%X\r\n", len);
940 ustream_write(uh->us, buf, len, false);
941 ustream_printf(uh->us, "\r\n");
948 uclient_http_request_done(struct uclient *cl)
950 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
952 if (uh->state >= HTTP_STATE_REQUEST_DONE)
955 uclient_http_send_headers(uh);
956 if (uh->req_type == REQ_POST || uh->req_type == REQ_PUT)
957 ustream_printf(uh->us, "0\r\n\r\n");
958 uh->state = HTTP_STATE_REQUEST_DONE;
964 uclient_http_read(struct uclient *cl, char *buf, unsigned int len)
966 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
968 char *data, *data_end;
970 if (uh->state < HTTP_STATE_RECV_DATA || !uh->us)
973 data = ustream_get_read_buf(uh->us, &read_len);
974 if (!data || !read_len)
977 data_end = data + read_len;
980 if (uh->read_chunked == 0) {
983 if (data[0] == '\r' && data[1] == '\n') {
988 sep = strstr(data, "\r\n");
993 uh->read_chunked = strtoul(data, NULL, 16);
995 read_len += sep + 2 - data;
998 if (!uh->read_chunked) {
1000 uh->uc.data_eof = true;
1004 if (len > data_end - data)
1005 len = data_end - data;
1007 if (uh->read_chunked >= 0) {
1008 if (len > uh->read_chunked)
1009 len = uh->read_chunked;
1011 uh->read_chunked -= len;
1012 } else if (uh->content_length >= 0) {
1013 if (len > uh->content_length)
1014 len = uh->content_length;
1016 uh->content_length -= len;
1017 if (!uh->content_length) {
1019 uh->uc.data_eof = true;
1025 memcpy(buf, data, len);
1029 ustream_consume(uh->us, read_len);
1031 uclient_notify_eof(uh);
1036 bool uclient_http_redirect(struct uclient *cl)
1038 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
1039 struct blobmsg_policy location = {
1041 .type = BLOBMSG_TYPE_STRING,
1043 struct uclient_url *url = cl->url;
1044 struct blob_attr *tb;
1046 if (cl->backend != &uclient_backend_http)
1049 switch (cl->status_code) {
1058 blobmsg_parse(&location, 1, &tb, blob_data(uh->meta.head), blob_len(uh->meta.head));
1062 url = uclient_get_url(blobmsg_data(tb), url->auth);
1068 uclient_http_connect(cl);
1069 uclient_http_request_done(cl);
1074 int uclient_http_set_ssl_ctx(struct uclient *cl, const struct ustream_ssl_ops *ops,
1075 struct ustream_ssl_ctx *ctx, bool require_validation)
1077 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
1079 if (cl->backend != &uclient_backend_http)
1082 uclient_http_free_url_state(cl);
1084 uclient_http_free_ssl_ctx(uh);
1087 uh->ssl_require_validation = !!ctx && require_validation;
1092 const struct uclient_backend uclient_backend_http = {
1093 .prefix = uclient_http_prefix,
1095 .alloc = uclient_http_alloc,
1096 .free = uclient_http_free,
1097 .connect = uclient_http_connect,
1098 .disconnect = uclient_http_request_disconnect,
1099 .update_url = uclient_http_free_url_state,
1101 .read = uclient_http_read,
1102 .write = uclient_http_send_data,
1103 .request = uclient_http_request_done,