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_notify_eof(struct uclient_http *uh)
164 struct ustream *us = uh->us;
170 if (!us->eof && !us->write_error)
173 if (ustream_pending_data(us, false))
177 uclient_backend_set_eof(&uh->uc);
179 if (uh->connection_close)
180 uclient_http_disconnect(uh);
183 static void uclient_http_reset_state(struct uclient_http *uh)
185 uclient_backend_reset_state(&uh->uc);
186 uh->read_chunked = -1;
187 uh->content_length = -1;
189 uh->disconnect = false;
190 uh->connection_close = false;
191 uh->state = HTTP_STATE_INIT;
193 if (uh->auth_type == AUTH_TYPE_UNKNOWN && !uh->uc.url->auth)
194 uh->auth_type = AUTH_TYPE_NONE;
197 static void uclient_http_init_request(struct uclient_http *uh)
199 uclient_http_reset_state(uh);
200 blob_buf_init(&uh->meta, 0);
203 static enum auth_type
204 uclient_http_update_auth_type(struct uclient_http *uh)
207 return AUTH_TYPE_NONE;
209 if (!strncasecmp(uh->auth_str, "basic", 5))
210 return AUTH_TYPE_BASIC;
212 if (!strncasecmp(uh->auth_str, "digest", 6))
213 return AUTH_TYPE_DIGEST;
215 return AUTH_TYPE_NONE;
218 static void uclient_http_process_headers(struct uclient_http *uh)
221 HTTP_HDR_TRANSFER_ENCODING,
223 HTTP_HDR_CONTENT_LENGTH,
227 static const struct blobmsg_policy hdr_policy[__HTTP_HDR_MAX] = {
228 #define hdr(_name) { .name = _name, .type = BLOBMSG_TYPE_STRING }
229 [HTTP_HDR_TRANSFER_ENCODING] = hdr("transfer-encoding"),
230 [HTTP_HDR_CONNECTION] = hdr("connection"),
231 [HTTP_HDR_CONTENT_LENGTH] = hdr("content-length"),
232 [HTTP_HDR_AUTH] = hdr("www-authenticate"),
235 struct blob_attr *tb[__HTTP_HDR_MAX];
236 struct blob_attr *cur;
238 blobmsg_parse(hdr_policy, __HTTP_HDR_MAX, tb, blob_data(uh->meta.head), blob_len(uh->meta.head));
240 cur = tb[HTTP_HDR_TRANSFER_ENCODING];
241 if (cur && strstr(blobmsg_data(cur), "chunked"))
242 uh->read_chunked = 0;
244 cur = tb[HTTP_HDR_CONNECTION];
245 if (cur && strstr(blobmsg_data(cur), "close"))
246 uh->connection_close = true;
248 cur = tb[HTTP_HDR_CONTENT_LENGTH];
250 uh->content_length = strtoul(blobmsg_data(cur), NULL, 10);
252 cur = tb[HTTP_HDR_AUTH];
255 uh->auth_str = strdup(blobmsg_data(cur));
258 uh->auth_type = uclient_http_update_auth_type(uh);
262 uclient_http_add_auth_basic(struct uclient_http *uh)
264 struct uclient_url *url = uh->uc.url;
265 int auth_len = strlen(url->auth);
271 auth_buf = alloca(base64_len(auth_len) + 1);
272 base64_encode(url->auth, auth_len, auth_buf);
273 ustream_printf(uh->us, "Authorization: Basic %s\r\n", auth_buf);
276 static char *digest_unquote_sep(char **str)
278 char *cur = *str + 1;
310 static bool strmatch(char **str, const char *prefix)
312 int len = strlen(prefix);
314 if (strncmp(*str, prefix, len) != 0 || (*str)[len] != '=')
322 get_cnonce(char *dest)
327 f = fopen("/dev/urandom", "r");
329 fread(&val, sizeof(val), 1, f);
333 bin_to_hex(dest, &val, sizeof(val));
336 static void add_field(char **buf, int *ofs, int *len, const char *name, const char *val)
338 int available = *len - *ofs;
346 required = strlen(name) + 4 + strlen(val) * 2;
347 if (required > available)
348 *len += required - available + 64;
350 *buf = realloc(*buf, *len);
355 cur += sprintf(cur, ", %s=\"", name);
357 while ((next = strchr(val, '"'))) {
359 memcpy(cur, val, next - val);
363 cur += sprintf(cur, "\\\"");
367 cur += sprintf(cur, "%s\"", val);
372 uclient_http_add_auth_digest(struct uclient_http *uh)
374 struct uclient_url *url = uh->uc.url;
375 const char *realm = NULL, *opaque = NULL;
376 const char *user, *password;
385 struct http_digest_data data = {
387 .cnonce = cnonce_str,
391 len = strlen(uh->auth_str) + 1;
396 strcpy(buf, uh->auth_str);
403 const char **dest = NULL;
405 while (isspace(*next))
408 if (strmatch(&next, "realm"))
410 else if (strmatch(&next, "qop"))
412 else if (strmatch(&next, "nonce"))
414 else if (strmatch(&next, "opaque"))
419 *dest = digest_unquote_sep(&next);
422 if (!realm || !data.qop || !data.nonce)
425 sprintf(nc_str, "%08x", uh->nc++);
426 get_cnonce(cnonce_str);
429 data.uri = url->location;
430 data.method = request_types[uh->req_type];
432 password = strchr(url->auth, ':');
436 len = password - url->auth;
440 user_buf = alloca(len + 1);
441 strncpy(user_buf, url->auth, len);
450 http_digest_calculate_auth_hash(ahash, user, realm, password);
451 http_digest_calculate_response(hash, &data);
457 add_field(&buf, &ofs, &len, "username", user);
458 add_field(&buf, &ofs, &len, "realm", realm);
459 add_field(&buf, &ofs, &len, "nonce", data.nonce);
460 add_field(&buf, &ofs, &len, "uri", data.uri);
461 add_field(&buf, &ofs, &len, "cnonce", data.cnonce);
462 add_field(&buf, &ofs, &len, "response", hash);
464 add_field(&buf, &ofs, &len, "opaque", opaque);
466 ustream_printf(uh->us, "Authorization: Digest nc=%s, qop=%s%s\r\n", data.nc, data.qop, buf);
471 uclient_http_add_auth_header(struct uclient_http *uh)
473 if (!uh->uc.url->auth)
476 switch (uh->auth_type) {
477 case AUTH_TYPE_UNKNOWN:
480 case AUTH_TYPE_BASIC:
481 uclient_http_add_auth_basic(uh);
483 case AUTH_TYPE_DIGEST:
484 uclient_http_add_auth_digest(uh);
490 uclient_http_send_headers(struct uclient_http *uh)
492 struct uclient_url *url = uh->uc.url;
493 struct blob_attr *cur;
494 enum request_type req_type = uh->req_type;
497 if (uh->state >= HTTP_STATE_HEADERS_SENT)
500 if (uh->auth_type == AUTH_TYPE_UNKNOWN)
503 ustream_printf(uh->us,
506 request_types[req_type],
507 url->location, url->host);
509 blobmsg_for_each_attr(cur, uh->headers.head, rem)
510 ustream_printf(uh->us, "%s: %s\n", blobmsg_name(cur), (char *) blobmsg_data(cur));
512 if (uh->req_type == REQ_POST || uh->req_type == REQ_PUT)
513 ustream_printf(uh->us, "Transfer-Encoding: chunked\r\n");
515 uclient_http_add_auth_header(uh);
517 ustream_printf(uh->us, "\r\n");
519 uh->state = HTTP_STATE_HEADERS_SENT;
522 static void uclient_http_headers_complete(struct uclient_http *uh)
524 enum auth_type auth_type = uh->auth_type;
526 uh->state = HTTP_STATE_RECV_DATA;
527 uh->uc.meta = uh->meta.head;
528 uclient_http_process_headers(uh);
530 if (auth_type == AUTH_TYPE_UNKNOWN) {
531 uclient_http_init_request(uh);
532 uclient_http_send_headers(uh);
533 uh->state = HTTP_STATE_REQUEST_DONE;
537 if (uh->uc.cb->header_done)
538 uh->uc.cb->header_done(&uh->uc);
543 if (uh->req_type == REQ_HEAD || uh->uc.status_code == 204) {
545 uclient_notify_eof(uh);
549 static void uclient_parse_http_line(struct uclient_http *uh, char *data)
554 if (uh->state == HTTP_STATE_REQUEST_DONE) {
560 code = strsep(&data, " ");
564 uh->uc.status_code = strtoul(code, &sep, 10);
568 uh->state = HTTP_STATE_RECV_HEADERS;
573 uclient_http_headers_complete(uh);
577 sep = strchr(data, ':');
583 for (name = data; *name; name++)
584 *name = tolower(*name);
587 while (isspace(*sep))
590 blobmsg_add_string(&uh->meta, name, sep);
594 uh->uc.status_code = 400;
596 uclient_notify_eof(uh);
599 static void __uclient_notify_read(struct uclient_http *uh)
601 struct uclient *uc = &uh->uc;
605 if (uh->state < HTTP_STATE_REQUEST_DONE || uh->state == HTTP_STATE_ERROR)
608 data = ustream_get_read_buf(uh->us, &len);
612 if (uh->state < HTTP_STATE_RECV_DATA) {
617 sep = strstr(data, "\r\n");
621 /* Check for multi-line HTTP headers */
626 if (isspace(sep[2]) && sep[2] != '\r') {
634 cur_len = sep + 2 - data;
635 uclient_parse_http_line(uh, data);
636 ustream_consume(uh->us, cur_len);
642 data = ustream_get_read_buf(uh->us, &len);
643 } while (data && uh->state < HTTP_STATE_RECV_DATA);
652 if (uh->state == HTTP_STATE_RECV_DATA && uc->cb->data_read)
653 uc->cb->data_read(uc);
656 static void uclient_notify_read(struct ustream *us, int bytes)
658 struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
660 __uclient_notify_read(uh);
663 static void uclient_notify_state(struct ustream *us)
665 struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
667 uclient_notify_eof(uh);
670 static int uclient_setup_http(struct uclient_http *uh)
672 struct ustream *us = &uh->ufd.stream;
678 us->string_data = true;
679 us->notify_state = uclient_notify_state;
680 us->notify_read = uclient_notify_read;
682 ret = uclient_do_connect(uh, "80");
684 return UCLIENT_ERROR_CONNECT;
689 static void uclient_ssl_notify_read(struct ustream *us, int bytes)
691 struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
693 __uclient_notify_read(uh);
696 static void uclient_ssl_notify_state(struct ustream *us)
698 struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
700 uclient_notify_eof(uh);
703 static void uclient_ssl_notify_error(struct ustream_ssl *ssl, int error, const char *str)
705 struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
707 uclient_http_error(uh, UCLIENT_ERROR_CONNECT);
710 static void uclient_ssl_notify_verify_error(struct ustream_ssl *ssl, int error, const char *str)
712 struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
714 if (!uh->ssl_require_validation)
717 uclient_http_error(uh, UCLIENT_ERROR_SSL_INVALID_CERT);
720 static void uclient_ssl_notify_connected(struct ustream_ssl *ssl)
722 struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
724 if (!uh->ssl_require_validation)
727 if (!uh->ussl.valid_cn)
728 uclient_http_error(uh, UCLIENT_ERROR_SSL_CN_MISMATCH);
731 static int uclient_setup_https(struct uclient_http *uh)
733 struct ustream *us = &uh->ussl.stream;
740 return UCLIENT_ERROR_MISSING_SSL_CONTEXT;
742 ret = uclient_do_connect(uh, "443");
744 return UCLIENT_ERROR_CONNECT;
746 us->string_data = true;
747 us->notify_state = uclient_ssl_notify_state;
748 us->notify_read = uclient_ssl_notify_read;
749 uh->ussl.notify_error = uclient_ssl_notify_error;
750 uh->ussl.notify_verify_error = uclient_ssl_notify_verify_error;
751 uh->ussl.notify_connected = uclient_ssl_notify_connected;
752 uh->ssl_ops->init(&uh->ussl, &uh->ufd.stream, uh->ssl_ctx, false);
753 uh->ssl_ops->set_peer_cn(&uh->ussl, uh->uc.url->host);
758 static int uclient_http_connect(struct uclient *cl)
760 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
763 uclient_http_init_request(uh);
768 uh->ssl = cl->url->prefix == PREFIX_HTTPS;
771 ret = uclient_setup_https(uh);
773 ret = uclient_setup_http(uh);
778 static void uclient_http_disconnect_cb(struct uloop_timeout *timeout)
780 struct uclient_http *uh = container_of(timeout, struct uclient_http, disconnect_t);
782 uclient_http_disconnect(uh);
785 static struct uclient *uclient_http_alloc(void)
787 struct uclient_http *uh;
789 uh = calloc_a(sizeof(*uh));
790 uh->disconnect_t.cb = uclient_http_disconnect_cb;
791 blob_buf_init(&uh->headers, 0);
796 static void uclient_http_free_ssl_ctx(struct uclient_http *uh)
802 static void uclient_http_free(struct uclient *cl)
804 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
806 uclient_http_free_url_state(cl);
807 uclient_http_free_ssl_ctx(uh);
808 blob_buf_free(&uh->headers);
809 blob_buf_free(&uh->meta);
814 uclient_http_set_request_type(struct uclient *cl, const char *type)
816 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
819 if (cl->backend != &uclient_backend_http)
822 if (uh->state > HTTP_STATE_INIT)
825 for (i = 0; i < ARRAY_SIZE(request_types); i++) {
826 if (strcmp(request_types[i], type) != 0)
837 uclient_http_reset_headers(struct uclient *cl)
839 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
841 blob_buf_init(&uh->headers, 0);
847 uclient_http_set_header(struct uclient *cl, const char *name, const char *value)
849 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
851 if (cl->backend != &uclient_backend_http)
854 if (uh->state > HTTP_STATE_INIT)
857 blobmsg_add_string(&uh->headers, name, value);
862 uclient_http_send_data(struct uclient *cl, char *buf, unsigned int len)
864 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
866 if (uh->state >= HTTP_STATE_REQUEST_DONE)
869 uclient_http_send_headers(uh);
872 ustream_printf(uh->us, "%X\r\n", len);
873 ustream_write(uh->us, buf, len, false);
874 ustream_printf(uh->us, "\r\n");
881 uclient_http_request_done(struct uclient *cl)
883 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
885 if (uh->state >= HTTP_STATE_REQUEST_DONE)
888 uclient_http_send_headers(uh);
889 if (uh->req_type == REQ_POST || uh->req_type == REQ_PUT)
890 ustream_printf(uh->us, "0\r\n\r\n");
891 uh->state = HTTP_STATE_REQUEST_DONE;
897 uclient_http_read(struct uclient *cl, char *buf, unsigned int len)
899 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
901 char *data, *data_end;
903 if (uh->state < HTTP_STATE_RECV_DATA || !uh->us)
906 data = ustream_get_read_buf(uh->us, &read_len);
907 if (!data || !read_len)
910 data_end = data + read_len;
913 if (uh->read_chunked == 0) {
916 if (data[0] == '\r' && data[1] == '\n') {
921 sep = strstr(data, "\r\n");
926 uh->read_chunked = strtoul(data, NULL, 16);
928 read_len += sep + 2 - data;
931 if (!uh->read_chunked) {
933 uh->uc.data_eof = true;
937 if (len > data_end - data)
938 len = data_end - data;
940 if (uh->read_chunked >= 0) {
941 if (len > uh->read_chunked)
942 len = uh->read_chunked;
944 uh->read_chunked -= len;
945 } else if (uh->content_length >= 0) {
946 if (len > uh->content_length)
947 len = uh->content_length;
949 uh->content_length -= len;
950 if (!uh->content_length) {
952 uh->uc.data_eof = true;
958 memcpy(buf, data, len);
962 ustream_consume(uh->us, read_len);
964 uclient_notify_eof(uh);
969 bool uclient_http_redirect(struct uclient *cl)
971 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
972 struct blobmsg_policy location = {
974 .type = BLOBMSG_TYPE_STRING,
976 struct uclient_url *url = cl->url;
977 struct blob_attr *tb;
979 if (cl->backend != &uclient_backend_http)
982 switch (cl->status_code) {
991 blobmsg_parse(&location, 1, &tb, blob_data(uh->meta.head), blob_len(uh->meta.head));
995 url = uclient_get_url(blobmsg_data(tb), url->auth);
1001 uclient_http_connect(cl);
1002 uclient_http_request_done(cl);
1007 int uclient_http_set_ssl_ctx(struct uclient *cl, const struct ustream_ssl_ops *ops,
1008 struct ustream_ssl_ctx *ctx, bool require_validation)
1010 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
1012 if (cl->backend != &uclient_backend_http)
1015 uclient_http_free_url_state(cl);
1017 uclient_http_free_ssl_ctx(uh);
1020 uh->ssl_require_validation = !!ctx && require_validation;
1025 static void uclient_http_request_disconnect(struct uclient *cl)
1027 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
1033 uh->disconnect = true;
1034 uloop_timeout_set(&uh->disconnect_t, 1);
1037 const struct uclient_backend uclient_backend_http = {
1038 .prefix = uclient_http_prefix,
1040 .alloc = uclient_http_alloc,
1041 .free = uclient_http_free,
1042 .connect = uclient_http_connect,
1043 .disconnect = uclient_http_request_disconnect,
1044 .update_url = uclient_http_free_url_state,
1046 .read = uclient_http_read,
1047 .write = uclient_http_send_data,
1048 .request = uclient_http_request_done,