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;
77 bool ssl_require_validation;
80 bool connection_close;
82 enum request_type req_type;
83 enum http_state state;
85 enum auth_type auth_type;
93 struct blob_buf headers;
103 static const char * const uclient_http_prefix[] = {
104 [PREFIX_HTTP] = "http://",
105 [PREFIX_HTTPS] = "https://",
106 [__PREFIX_MAX] = NULL
109 static int uclient_do_connect(struct uclient_http *uh, const char *port)
114 if (uh->uc.url->port)
115 port = uh->uc.url->port;
117 fd = usock(USOCK_TCP | USOCK_NONBLOCK, uh->uc.url->host, port);
121 ustream_fd_init(&uh->ufd, fd);
123 memset(&uh->uc.local_addr, 0, sizeof(uh->uc.local_addr));
124 memset(&uh->uc.remote_addr, 0, sizeof(uh->uc.remote_addr));
126 sl = sizeof(uh->uc.local_addr);
127 getsockname(fd, &uh->uc.local_addr.sa, &sl);
128 getpeername(fd, &uh->uc.remote_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)
199 uclient_backend_reset_state(&uh->uc);
200 uh->read_chunked = -1;
201 uh->content_length = -1;
203 uh->disconnect = false;
204 uh->connection_close = false;
205 uh->state = HTTP_STATE_INIT;
207 if (uh->auth_type == AUTH_TYPE_UNKNOWN && !uh->uc.url->auth)
208 uh->auth_type = AUTH_TYPE_NONE;
211 static void uclient_http_init_request(struct uclient_http *uh)
213 uclient_http_reset_state(uh);
214 blob_buf_init(&uh->meta, 0);
217 static enum auth_type
218 uclient_http_update_auth_type(struct uclient_http *uh)
221 return AUTH_TYPE_NONE;
223 if (!strncasecmp(uh->auth_str, "basic", 5))
224 return AUTH_TYPE_BASIC;
226 if (!strncasecmp(uh->auth_str, "digest", 6))
227 return AUTH_TYPE_DIGEST;
229 return AUTH_TYPE_NONE;
232 static void uclient_http_process_headers(struct uclient_http *uh)
235 HTTP_HDR_TRANSFER_ENCODING,
237 HTTP_HDR_CONTENT_LENGTH,
241 static const struct blobmsg_policy hdr_policy[__HTTP_HDR_MAX] = {
242 #define hdr(_name) { .name = _name, .type = BLOBMSG_TYPE_STRING }
243 [HTTP_HDR_TRANSFER_ENCODING] = hdr("transfer-encoding"),
244 [HTTP_HDR_CONNECTION] = hdr("connection"),
245 [HTTP_HDR_CONTENT_LENGTH] = hdr("content-length"),
246 [HTTP_HDR_AUTH] = hdr("www-authenticate"),
249 struct blob_attr *tb[__HTTP_HDR_MAX];
250 struct blob_attr *cur;
252 blobmsg_parse(hdr_policy, __HTTP_HDR_MAX, tb, blob_data(uh->meta.head), blob_len(uh->meta.head));
254 cur = tb[HTTP_HDR_TRANSFER_ENCODING];
255 if (cur && strstr(blobmsg_data(cur), "chunked"))
256 uh->read_chunked = 0;
258 cur = tb[HTTP_HDR_CONNECTION];
259 if (cur && strstr(blobmsg_data(cur), "close"))
260 uh->connection_close = true;
262 cur = tb[HTTP_HDR_CONTENT_LENGTH];
264 uh->content_length = strtoul(blobmsg_data(cur), NULL, 10);
266 cur = tb[HTTP_HDR_AUTH];
269 uh->auth_str = strdup(blobmsg_data(cur));
272 uh->auth_type = uclient_http_update_auth_type(uh);
276 uclient_http_add_auth_basic(struct uclient_http *uh)
278 struct uclient_url *url = uh->uc.url;
279 int auth_len = strlen(url->auth);
285 auth_buf = alloca(base64_len(auth_len) + 1);
286 base64_encode(url->auth, auth_len, auth_buf);
287 ustream_printf(uh->us, "Authorization: Basic %s\r\n", auth_buf);
290 static char *digest_unquote_sep(char **str)
292 char *cur = *str + 1;
324 static char *digest_sep(char **str)
329 next = strchr(*str, ',');
334 *str += strlen(*str);
340 static bool strmatch(char **str, const char *prefix)
342 int len = strlen(prefix);
344 if (strncmp(*str, prefix, len) != 0 || (*str)[len] != '=')
352 get_cnonce(char *dest)
357 f = fopen("/dev/urandom", "r");
359 fread(&val, sizeof(val), 1, f);
363 bin_to_hex(dest, &val, sizeof(val));
366 static void add_field(char **buf, int *ofs, int *len, const char *name, const char *val)
368 int available = *len - *ofs;
376 required = strlen(name) + 4 + strlen(val) * 2;
377 if (required > available)
378 *len += required - available + 64;
380 *buf = realloc(*buf, *len);
385 cur += sprintf(cur, ", %s=\"", name);
387 while ((next = strchr(val, '"'))) {
389 memcpy(cur, val, next - val);
393 cur += sprintf(cur, "\\\"");
397 cur += sprintf(cur, "%s\"", val);
402 uclient_http_add_auth_digest(struct uclient_http *uh)
404 struct uclient_url *url = uh->uc.url;
405 const char *realm = NULL, *opaque = NULL;
406 const char *user, *password;
415 struct http_digest_data data = {
417 .cnonce = cnonce_str,
421 len = strlen(uh->auth_str) + 1;
426 strcpy(buf, uh->auth_str);
433 const char **dest = NULL;
436 while (*next && isspace(*next))
439 if (strmatch(&next, "realm"))
441 else if (strmatch(&next, "qop"))
443 else if (strmatch(&next, "nonce"))
445 else if (strmatch(&next, "opaque"))
447 else if (strmatch(&next, "stale") ||
448 strmatch(&next, "algorithm") ||
449 strmatch(&next, "auth-param")) {
452 } else if (strmatch(&next, "domain") ||
453 strmatch(&next, "qop-options"))
460 *dest = digest_unquote_sep(&next);
463 if (!realm || !data.qop || !data.nonce)
466 sprintf(nc_str, "%08x", uh->nc++);
467 get_cnonce(cnonce_str);
470 data.uri = url->location;
471 data.method = request_types[uh->req_type];
473 password = strchr(url->auth, ':');
477 len = password - url->auth;
481 user_buf = alloca(len + 1);
482 strncpy(user_buf, url->auth, len);
491 http_digest_calculate_auth_hash(ahash, user, realm, password);
492 http_digest_calculate_response(hash, &data);
498 add_field(&buf, &ofs, &len, "username", user);
499 add_field(&buf, &ofs, &len, "realm", realm);
500 add_field(&buf, &ofs, &len, "nonce", data.nonce);
501 add_field(&buf, &ofs, &len, "uri", data.uri);
502 add_field(&buf, &ofs, &len, "cnonce", data.cnonce);
503 add_field(&buf, &ofs, &len, "response", hash);
505 add_field(&buf, &ofs, &len, "opaque", opaque);
507 ustream_printf(uh->us, "Authorization: Digest nc=%s, qop=%s%s\r\n", data.nc, data.qop, buf);
512 uclient_http_add_auth_header(struct uclient_http *uh)
514 if (!uh->uc.url->auth)
517 switch (uh->auth_type) {
518 case AUTH_TYPE_UNKNOWN:
521 case AUTH_TYPE_BASIC:
522 uclient_http_add_auth_basic(uh);
524 case AUTH_TYPE_DIGEST:
525 uclient_http_add_auth_digest(uh);
531 uclient_http_send_headers(struct uclient_http *uh)
533 struct uclient_url *url = uh->uc.url;
534 struct blob_attr *cur;
535 enum request_type req_type = uh->req_type;
538 if (uh->state >= HTTP_STATE_HEADERS_SENT)
541 ustream_printf(uh->us,
544 request_types[req_type],
545 url->location, url->host);
547 blobmsg_for_each_attr(cur, uh->headers.head, rem)
548 ustream_printf(uh->us, "%s: %s\n", blobmsg_name(cur), (char *) blobmsg_data(cur));
550 if (uh->req_type == REQ_POST || uh->req_type == REQ_PUT)
551 ustream_printf(uh->us, "Transfer-Encoding: chunked\r\n");
553 uclient_http_add_auth_header(uh);
555 ustream_printf(uh->us, "\r\n");
557 uh->state = HTTP_STATE_HEADERS_SENT;
560 static void uclient_http_headers_complete(struct uclient_http *uh)
562 enum auth_type auth_type = uh->auth_type;
564 uh->state = HTTP_STATE_RECV_DATA;
565 uh->uc.meta = uh->meta.head;
566 uclient_http_process_headers(uh);
568 if (auth_type == AUTH_TYPE_UNKNOWN && uh->uc.status_code == 401 &&
569 (uh->req_type == REQ_HEAD || uh->req_type == REQ_GET)) {
570 uclient_http_init_request(uh);
571 uclient_http_send_headers(uh);
572 uh->state = HTTP_STATE_REQUEST_DONE;
576 if (uh->uc.cb->header_done)
577 uh->uc.cb->header_done(&uh->uc);
582 if (uh->req_type == REQ_HEAD || uh->uc.status_code == 204) {
584 uclient_notify_eof(uh);
588 static void uclient_parse_http_line(struct uclient_http *uh, char *data)
593 if (uh->state == HTTP_STATE_REQUEST_DONE) {
602 code = strsep(&data, " ");
606 uh->uc.status_code = strtoul(code, &sep, 10);
610 uh->state = HTTP_STATE_RECV_HEADERS;
615 uclient_http_headers_complete(uh);
619 sep = strchr(data, ':');
625 for (name = data; *name; name++)
626 *name = tolower(*name);
629 while (isspace(*sep))
632 blobmsg_add_string(&uh->meta, name, sep);
636 uh->uc.status_code = 400;
638 uclient_notify_eof(uh);
641 static void __uclient_notify_read(struct uclient_http *uh)
643 struct uclient *uc = &uh->uc;
647 if (uh->state < HTTP_STATE_REQUEST_DONE || uh->state == HTTP_STATE_ERROR)
650 data = ustream_get_read_buf(uh->us, &len);
654 if (uh->state < HTTP_STATE_RECV_DATA) {
659 sep = strstr(data, "\r\n");
663 /* Check for multi-line HTTP headers */
668 if (isspace(sep[2]) && sep[2] != '\r') {
676 cur_len = sep + 2 - data;
677 uclient_parse_http_line(uh, data);
678 ustream_consume(uh->us, cur_len);
684 data = ustream_get_read_buf(uh->us, &len);
685 } while (data && uh->state < HTTP_STATE_RECV_DATA);
694 if (uh->state == HTTP_STATE_RECV_DATA) {
695 /* Now it's uclient user turn to read some data */
696 uloop_timeout_cancel(&uc->connection_timeout);
698 if (uc->cb->data_read)
699 uc->cb->data_read(uc);
703 static void __uclient_notify_write(struct uclient_http *uh)
705 struct uclient *uc = &uh->uc;
707 if (uc->cb->data_sent)
708 uc->cb->data_sent(uc);
711 static void uclient_notify_read(struct ustream *us, int bytes)
713 struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
715 __uclient_notify_read(uh);
718 static void uclient_notify_write(struct ustream *us, int bytes)
720 struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
722 __uclient_notify_write(uh);
725 static void uclient_notify_state(struct ustream *us)
727 struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
729 uclient_notify_eof(uh);
732 static int uclient_setup_http(struct uclient_http *uh)
734 struct ustream *us = &uh->ufd.stream;
740 us->string_data = true;
741 us->notify_state = uclient_notify_state;
742 us->notify_read = uclient_notify_read;
743 us->notify_write = uclient_notify_write;
745 ret = uclient_do_connect(uh, "80");
747 return UCLIENT_ERROR_CONNECT;
752 static void uclient_ssl_notify_read(struct ustream *us, int bytes)
754 struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
756 __uclient_notify_read(uh);
759 static void uclient_ssl_notify_write(struct ustream *us, int bytes)
761 struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
763 __uclient_notify_write(uh);
766 static void uclient_ssl_notify_state(struct ustream *us)
768 struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
770 uclient_notify_eof(uh);
773 static void uclient_ssl_notify_error(struct ustream_ssl *ssl, int error, const char *str)
775 struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
777 uclient_http_error(uh, UCLIENT_ERROR_CONNECT);
780 static void uclient_ssl_notify_verify_error(struct ustream_ssl *ssl, int error, const char *str)
782 struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
784 if (!uh->ssl_require_validation)
787 uclient_http_error(uh, UCLIENT_ERROR_SSL_INVALID_CERT);
790 static void uclient_ssl_notify_connected(struct ustream_ssl *ssl)
792 struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
794 if (!uh->ssl_require_validation)
797 if (!uh->ussl.valid_cn)
798 uclient_http_error(uh, UCLIENT_ERROR_SSL_CN_MISMATCH);
801 static int uclient_setup_https(struct uclient_http *uh)
803 struct ustream *us = &uh->ussl.stream;
810 return UCLIENT_ERROR_MISSING_SSL_CONTEXT;
812 ret = uclient_do_connect(uh, "443");
814 return UCLIENT_ERROR_CONNECT;
816 us->string_data = true;
817 us->notify_state = uclient_ssl_notify_state;
818 us->notify_read = uclient_ssl_notify_read;
819 us->notify_write = uclient_ssl_notify_write;
820 uh->ussl.notify_error = uclient_ssl_notify_error;
821 uh->ussl.notify_verify_error = uclient_ssl_notify_verify_error;
822 uh->ussl.notify_connected = uclient_ssl_notify_connected;
823 uh->ssl_ops->init(&uh->ussl, &uh->ufd.stream, uh->ssl_ctx, false);
824 uh->ssl_ops->set_peer_cn(&uh->ussl, uh->uc.url->host);
829 static int uclient_http_connect(struct uclient *cl)
831 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
834 if (!cl->eof || uh->disconnect)
835 uclient_http_disconnect(uh);
837 uclient_http_init_request(uh);
842 uh->ssl = cl->url->prefix == PREFIX_HTTPS;
845 ret = uclient_setup_https(uh);
847 ret = uclient_setup_http(uh);
852 static void uclient_http_disconnect_cb(struct uloop_timeout *timeout)
854 struct uclient_http *uh = container_of(timeout, struct uclient_http, disconnect_t);
856 uclient_http_disconnect(uh);
859 static struct uclient *uclient_http_alloc(void)
861 struct uclient_http *uh;
863 uh = calloc_a(sizeof(*uh));
864 uh->disconnect_t.cb = uclient_http_disconnect_cb;
865 blob_buf_init(&uh->headers, 0);
870 static void uclient_http_free_ssl_ctx(struct uclient_http *uh)
876 static void uclient_http_free(struct uclient *cl)
878 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
880 uclient_http_free_url_state(cl);
881 uclient_http_free_ssl_ctx(uh);
882 blob_buf_free(&uh->headers);
883 blob_buf_free(&uh->meta);
888 uclient_http_set_request_type(struct uclient *cl, const char *type)
890 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
893 if (cl->backend != &uclient_backend_http)
896 if (uh->state > HTTP_STATE_INIT)
899 for (i = 0; i < ARRAY_SIZE(request_types); i++) {
900 if (strcmp(request_types[i], type) != 0)
911 uclient_http_reset_headers(struct uclient *cl)
913 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
915 blob_buf_init(&uh->headers, 0);
921 uclient_http_set_header(struct uclient *cl, const char *name, const char *value)
923 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
925 if (cl->backend != &uclient_backend_http)
928 if (uh->state > HTTP_STATE_INIT)
931 blobmsg_add_string(&uh->headers, name, value);
936 uclient_http_send_data(struct uclient *cl, const char *buf, unsigned int len)
938 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
940 if (uh->state >= HTTP_STATE_REQUEST_DONE)
943 uclient_http_send_headers(uh);
946 ustream_printf(uh->us, "%X\r\n", len);
947 ustream_write(uh->us, buf, len, false);
948 ustream_printf(uh->us, "\r\n");
955 uclient_http_request_done(struct uclient *cl)
957 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
959 if (uh->state >= HTTP_STATE_REQUEST_DONE)
962 uclient_http_send_headers(uh);
963 if (uh->req_type == REQ_POST || uh->req_type == REQ_PUT)
964 ustream_printf(uh->us, "0\r\n\r\n");
965 uh->state = HTTP_STATE_REQUEST_DONE;
971 uclient_http_read(struct uclient *cl, char *buf, unsigned int len)
973 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
975 char *data, *data_end;
977 if (uh->state < HTTP_STATE_RECV_DATA || !uh->us)
980 data = ustream_get_read_buf(uh->us, &read_len);
981 if (!data || !read_len)
984 data_end = data + read_len;
987 if (uh->read_chunked == 0) {
990 if (data[0] == '\r' && data[1] == '\n') {
995 sep = strstr(data, "\r\n");
1000 uh->read_chunked = strtoul(data, NULL, 16);
1002 read_len += sep + 2 - data;
1005 if (!uh->read_chunked) {
1007 uh->uc.data_eof = true;
1011 if (len > data_end - data)
1012 len = data_end - data;
1014 if (uh->read_chunked >= 0) {
1015 if (len > uh->read_chunked)
1016 len = uh->read_chunked;
1018 uh->read_chunked -= len;
1019 } else if (uh->content_length >= 0) {
1020 if (len > uh->content_length)
1021 len = uh->content_length;
1023 uh->content_length -= len;
1024 if (!uh->content_length) {
1026 uh->uc.data_eof = true;
1032 memcpy(buf, data, len);
1036 ustream_consume(uh->us, read_len);
1038 uclient_notify_eof(uh);
1040 /* Now that we consumed something and if this isn't EOF, start timer again */
1041 if (!uh->uc.eof && !cl->connection_timeout.pending)
1042 uloop_timeout_set(&cl->connection_timeout, cl->timeout_msecs);
1047 bool uclient_http_redirect(struct uclient *cl)
1049 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
1050 struct blobmsg_policy location = {
1052 .type = BLOBMSG_TYPE_STRING,
1054 struct uclient_url *url = cl->url;
1055 struct blob_attr *tb;
1057 if (cl->backend != &uclient_backend_http)
1060 switch (cl->status_code) {
1069 blobmsg_parse(&location, 1, &tb, blob_data(uh->meta.head), blob_len(uh->meta.head));
1073 url = uclient_get_url(blobmsg_data(tb), url->auth);
1079 uclient_http_connect(cl);
1080 uclient_http_request_done(cl);
1085 int uclient_http_set_ssl_ctx(struct uclient *cl, const struct ustream_ssl_ops *ops,
1086 struct ustream_ssl_ctx *ctx, bool require_validation)
1088 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
1090 if (cl->backend != &uclient_backend_http)
1093 uclient_http_free_url_state(cl);
1095 uclient_http_free_ssl_ctx(uh);
1098 uh->ssl_require_validation = !!ctx && require_validation;
1103 const struct uclient_backend uclient_backend_http = {
1104 .prefix = uclient_http_prefix,
1106 .alloc = uclient_http_alloc,
1107 .free = uclient_http_free,
1108 .connect = uclient_http_connect,
1109 .disconnect = uclient_http_request_disconnect,
1110 .update_url = uclient_http_free_url_state,
1112 .read = uclient_http_read,
1113 .write = uclient_http_send_data,
1114 .request = uclient_http_request_done,