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 bool strmatch(char **str, const char *prefix)
324 int len = strlen(prefix);
326 if (strncmp(*str, prefix, len) != 0 || (*str)[len] != '=')
334 get_cnonce(char *dest)
339 f = fopen("/dev/urandom", "r");
341 fread(&val, sizeof(val), 1, f);
345 bin_to_hex(dest, &val, sizeof(val));
348 static void add_field(char **buf, int *ofs, int *len, const char *name, const char *val)
350 int available = *len - *ofs;
358 required = strlen(name) + 4 + strlen(val) * 2;
359 if (required > available)
360 *len += required - available + 64;
362 *buf = realloc(*buf, *len);
367 cur += sprintf(cur, ", %s=\"", name);
369 while ((next = strchr(val, '"'))) {
371 memcpy(cur, val, next - val);
375 cur += sprintf(cur, "\\\"");
379 cur += sprintf(cur, "%s\"", val);
384 uclient_http_add_auth_digest(struct uclient_http *uh)
386 struct uclient_url *url = uh->uc.url;
387 const char *realm = NULL, *opaque = NULL;
388 const char *user, *password;
397 struct http_digest_data data = {
399 .cnonce = cnonce_str,
403 len = strlen(uh->auth_str) + 1;
408 strcpy(buf, uh->auth_str);
415 const char **dest = NULL;
417 while (isspace(*next))
420 if (strmatch(&next, "realm"))
422 else if (strmatch(&next, "qop"))
424 else if (strmatch(&next, "nonce"))
426 else if (strmatch(&next, "opaque"))
431 *dest = digest_unquote_sep(&next);
434 if (!realm || !data.qop || !data.nonce)
437 sprintf(nc_str, "%08x", uh->nc++);
438 get_cnonce(cnonce_str);
441 data.uri = url->location;
442 data.method = request_types[uh->req_type];
444 password = strchr(url->auth, ':');
448 len = password - url->auth;
452 user_buf = alloca(len + 1);
453 strncpy(user_buf, url->auth, len);
462 http_digest_calculate_auth_hash(ahash, user, realm, password);
463 http_digest_calculate_response(hash, &data);
469 add_field(&buf, &ofs, &len, "username", user);
470 add_field(&buf, &ofs, &len, "realm", realm);
471 add_field(&buf, &ofs, &len, "nonce", data.nonce);
472 add_field(&buf, &ofs, &len, "uri", data.uri);
473 add_field(&buf, &ofs, &len, "cnonce", data.cnonce);
474 add_field(&buf, &ofs, &len, "response", hash);
476 add_field(&buf, &ofs, &len, "opaque", opaque);
478 ustream_printf(uh->us, "Authorization: Digest nc=%s, qop=%s%s\r\n", data.nc, data.qop, buf);
483 uclient_http_add_auth_header(struct uclient_http *uh)
485 if (!uh->uc.url->auth)
488 switch (uh->auth_type) {
489 case AUTH_TYPE_UNKNOWN:
492 case AUTH_TYPE_BASIC:
493 uclient_http_add_auth_basic(uh);
495 case AUTH_TYPE_DIGEST:
496 uclient_http_add_auth_digest(uh);
502 uclient_http_send_headers(struct uclient_http *uh)
504 struct uclient_url *url = uh->uc.url;
505 struct blob_attr *cur;
506 enum request_type req_type = uh->req_type;
509 if (uh->state >= HTTP_STATE_HEADERS_SENT)
512 ustream_printf(uh->us,
515 request_types[req_type],
516 url->location, url->host);
518 blobmsg_for_each_attr(cur, uh->headers.head, rem)
519 ustream_printf(uh->us, "%s: %s\n", blobmsg_name(cur), (char *) blobmsg_data(cur));
521 if (uh->req_type == REQ_POST || uh->req_type == REQ_PUT)
522 ustream_printf(uh->us, "Transfer-Encoding: chunked\r\n");
524 uclient_http_add_auth_header(uh);
526 ustream_printf(uh->us, "\r\n");
528 uh->state = HTTP_STATE_HEADERS_SENT;
531 static void uclient_http_headers_complete(struct uclient_http *uh)
533 enum auth_type auth_type = uh->auth_type;
535 uh->state = HTTP_STATE_RECV_DATA;
536 uh->uc.meta = uh->meta.head;
537 uclient_http_process_headers(uh);
539 if (auth_type == AUTH_TYPE_UNKNOWN && uh->uc.status_code == 401 &&
540 (uh->req_type == REQ_HEAD || uh->req_type == REQ_GET)) {
541 uclient_http_init_request(uh);
542 uclient_http_send_headers(uh);
543 uh->state = HTTP_STATE_REQUEST_DONE;
547 if (uh->uc.cb->header_done)
548 uh->uc.cb->header_done(&uh->uc);
553 if (uh->req_type == REQ_HEAD || uh->uc.status_code == 204) {
555 uclient_notify_eof(uh);
559 static void uclient_parse_http_line(struct uclient_http *uh, char *data)
564 if (uh->state == HTTP_STATE_REQUEST_DONE) {
573 code = strsep(&data, " ");
577 uh->uc.status_code = strtoul(code, &sep, 10);
581 uh->state = HTTP_STATE_RECV_HEADERS;
586 uclient_http_headers_complete(uh);
590 sep = strchr(data, ':');
596 for (name = data; *name; name++)
597 *name = tolower(*name);
600 while (isspace(*sep))
603 blobmsg_add_string(&uh->meta, name, sep);
607 uh->uc.status_code = 400;
609 uclient_notify_eof(uh);
612 static void __uclient_notify_read(struct uclient_http *uh)
614 struct uclient *uc = &uh->uc;
618 if (uh->state < HTTP_STATE_REQUEST_DONE || uh->state == HTTP_STATE_ERROR)
621 data = ustream_get_read_buf(uh->us, &len);
625 if (uh->state < HTTP_STATE_RECV_DATA) {
630 sep = strstr(data, "\r\n");
634 /* Check for multi-line HTTP headers */
639 if (isspace(sep[2]) && sep[2] != '\r') {
647 cur_len = sep + 2 - data;
648 uclient_parse_http_line(uh, data);
649 ustream_consume(uh->us, cur_len);
655 data = ustream_get_read_buf(uh->us, &len);
656 } while (data && uh->state < HTTP_STATE_RECV_DATA);
665 if (uh->state == HTTP_STATE_RECV_DATA && uc->cb->data_read)
666 uc->cb->data_read(uc);
669 static void __uclient_notify_write(struct uclient_http *uh)
671 struct uclient *uc = &uh->uc;
673 if (uc->cb->data_sent)
674 uc->cb->data_sent(uc);
677 static void uclient_notify_read(struct ustream *us, int bytes)
679 struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
681 __uclient_notify_read(uh);
684 static void uclient_notify_write(struct ustream *us, int bytes)
686 struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
688 __uclient_notify_write(uh);
691 static void uclient_notify_state(struct ustream *us)
693 struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
695 uclient_notify_eof(uh);
698 static int uclient_setup_http(struct uclient_http *uh)
700 struct ustream *us = &uh->ufd.stream;
706 us->string_data = true;
707 us->notify_state = uclient_notify_state;
708 us->notify_read = uclient_notify_read;
709 us->notify_write = uclient_notify_write;
711 ret = uclient_do_connect(uh, "80");
713 return UCLIENT_ERROR_CONNECT;
718 static void uclient_ssl_notify_read(struct ustream *us, int bytes)
720 struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
722 __uclient_notify_read(uh);
725 static void uclient_ssl_notify_write(struct ustream *us, int bytes)
727 struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
729 __uclient_notify_write(uh);
732 static void uclient_ssl_notify_state(struct ustream *us)
734 struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
736 uclient_notify_eof(uh);
739 static void uclient_ssl_notify_error(struct ustream_ssl *ssl, int error, const char *str)
741 struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
743 uclient_http_error(uh, UCLIENT_ERROR_CONNECT);
746 static void uclient_ssl_notify_verify_error(struct ustream_ssl *ssl, int error, const char *str)
748 struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
750 if (!uh->ssl_require_validation)
753 uclient_http_error(uh, UCLIENT_ERROR_SSL_INVALID_CERT);
756 static void uclient_ssl_notify_connected(struct ustream_ssl *ssl)
758 struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
760 if (!uh->ssl_require_validation)
763 if (!uh->ussl.valid_cn)
764 uclient_http_error(uh, UCLIENT_ERROR_SSL_CN_MISMATCH);
767 static int uclient_setup_https(struct uclient_http *uh)
769 struct ustream *us = &uh->ussl.stream;
776 return UCLIENT_ERROR_MISSING_SSL_CONTEXT;
778 ret = uclient_do_connect(uh, "443");
780 return UCLIENT_ERROR_CONNECT;
782 us->string_data = true;
783 us->notify_state = uclient_ssl_notify_state;
784 us->notify_read = uclient_ssl_notify_read;
785 us->notify_write = uclient_ssl_notify_write;
786 uh->ussl.notify_error = uclient_ssl_notify_error;
787 uh->ussl.notify_verify_error = uclient_ssl_notify_verify_error;
788 uh->ussl.notify_connected = uclient_ssl_notify_connected;
789 uh->ssl_ops->init(&uh->ussl, &uh->ufd.stream, uh->ssl_ctx, false);
790 uh->ssl_ops->set_peer_cn(&uh->ussl, uh->uc.url->host);
795 static int uclient_http_connect(struct uclient *cl)
797 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
800 if (!cl->eof || uh->disconnect)
801 uclient_http_disconnect(uh);
803 uclient_http_init_request(uh);
808 uh->ssl = cl->url->prefix == PREFIX_HTTPS;
811 ret = uclient_setup_https(uh);
813 ret = uclient_setup_http(uh);
818 static void uclient_http_disconnect_cb(struct uloop_timeout *timeout)
820 struct uclient_http *uh = container_of(timeout, struct uclient_http, disconnect_t);
822 uclient_http_disconnect(uh);
825 static struct uclient *uclient_http_alloc(void)
827 struct uclient_http *uh;
829 uh = calloc_a(sizeof(*uh));
830 uh->disconnect_t.cb = uclient_http_disconnect_cb;
831 blob_buf_init(&uh->headers, 0);
836 static void uclient_http_free_ssl_ctx(struct uclient_http *uh)
842 static void uclient_http_free(struct uclient *cl)
844 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
846 uclient_http_free_url_state(cl);
847 uclient_http_free_ssl_ctx(uh);
848 blob_buf_free(&uh->headers);
849 blob_buf_free(&uh->meta);
854 uclient_http_set_request_type(struct uclient *cl, const char *type)
856 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
859 if (cl->backend != &uclient_backend_http)
862 if (uh->state > HTTP_STATE_INIT)
865 for (i = 0; i < ARRAY_SIZE(request_types); i++) {
866 if (strcmp(request_types[i], type) != 0)
877 uclient_http_reset_headers(struct uclient *cl)
879 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
881 blob_buf_init(&uh->headers, 0);
887 uclient_http_set_header(struct uclient *cl, const char *name, const char *value)
889 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
891 if (cl->backend != &uclient_backend_http)
894 if (uh->state > HTTP_STATE_INIT)
897 blobmsg_add_string(&uh->headers, name, value);
902 uclient_http_send_data(struct uclient *cl, char *buf, unsigned int len)
904 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
906 if (uh->state >= HTTP_STATE_REQUEST_DONE)
909 uclient_http_send_headers(uh);
912 ustream_printf(uh->us, "%X\r\n", len);
913 ustream_write(uh->us, buf, len, false);
914 ustream_printf(uh->us, "\r\n");
921 uclient_http_request_done(struct uclient *cl)
923 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
925 if (uh->state >= HTTP_STATE_REQUEST_DONE)
928 uclient_http_send_headers(uh);
929 if (uh->req_type == REQ_POST || uh->req_type == REQ_PUT)
930 ustream_printf(uh->us, "0\r\n\r\n");
931 uh->state = HTTP_STATE_REQUEST_DONE;
937 uclient_http_read(struct uclient *cl, char *buf, unsigned int len)
939 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
941 char *data, *data_end;
943 if (uh->state < HTTP_STATE_RECV_DATA || !uh->us)
946 data = ustream_get_read_buf(uh->us, &read_len);
947 if (!data || !read_len)
950 data_end = data + read_len;
953 if (uh->read_chunked == 0) {
956 if (data[0] == '\r' && data[1] == '\n') {
961 sep = strstr(data, "\r\n");
966 uh->read_chunked = strtoul(data, NULL, 16);
968 read_len += sep + 2 - data;
971 if (!uh->read_chunked) {
973 uh->uc.data_eof = true;
977 if (len > data_end - data)
978 len = data_end - data;
980 if (uh->read_chunked >= 0) {
981 if (len > uh->read_chunked)
982 len = uh->read_chunked;
984 uh->read_chunked -= len;
985 } else if (uh->content_length >= 0) {
986 if (len > uh->content_length)
987 len = uh->content_length;
989 uh->content_length -= len;
990 if (!uh->content_length) {
992 uh->uc.data_eof = true;
998 memcpy(buf, data, len);
1002 ustream_consume(uh->us, read_len);
1004 uclient_notify_eof(uh);
1009 bool uclient_http_redirect(struct uclient *cl)
1011 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
1012 struct blobmsg_policy location = {
1014 .type = BLOBMSG_TYPE_STRING,
1016 struct uclient_url *url = cl->url;
1017 struct blob_attr *tb;
1019 if (cl->backend != &uclient_backend_http)
1022 switch (cl->status_code) {
1031 blobmsg_parse(&location, 1, &tb, blob_data(uh->meta.head), blob_len(uh->meta.head));
1035 url = uclient_get_url(blobmsg_data(tb), url->auth);
1041 uclient_http_connect(cl);
1042 uclient_http_request_done(cl);
1047 int uclient_http_set_ssl_ctx(struct uclient *cl, const struct ustream_ssl_ops *ops,
1048 struct ustream_ssl_ctx *ctx, bool require_validation)
1050 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
1052 if (cl->backend != &uclient_backend_http)
1055 uclient_http_free_url_state(cl);
1057 uclient_http_free_ssl_ctx(uh);
1060 uh->ssl_require_validation = !!ctx && require_validation;
1065 const struct uclient_backend uclient_backend_http = {
1066 .prefix = uclient_http_prefix,
1068 .alloc = uclient_http_alloc,
1069 .free = uclient_http_free,
1070 .connect = uclient_http_connect,
1071 .disconnect = uclient_http_request_disconnect,
1072 .update_url = uclient_http_free_url_state,
1074 .read = uclient_http_read,
1075 .write = uclient_http_send_data,
1076 .request = uclient_http_request_done,