Experimental HTTP and HTTPS library for mbed OS 5
Revision 31:b3730a2c4f39, committed 2018-10-30
- Comitter:
- Jan Jongboom
- Date:
- Tue Oct 30 10:18:51 2018 +0800
- Branch:
- tlssocket
- Parent:
- 28:9a04ed79d67e
- Child:
- 32:fa4d71265625
- Commit message:
- Switch to TLSSocket library
Changed in this revision
--- a/README.md Tue Mar 27 11:07:02 2018 +0200
+++ b/README.md Tue Oct 30 10:18:51 2018 +0800
@@ -105,22 +105,38 @@
### HTTPS
```cpp
-TLSSocket* socket = new TLSSocket(network, "httpbin.org", 443, SSL_CA_PEM);
-socket->set_debug(true);
-if (socket->connect() != 0) {
- printf("TLS Connect failed %d\n", socket->error());
- return 1;
-}
+TLSSocket* socket = new TLSSocket();
+// make sure to check the return values for the calls below (should return NSAPI_ERROR_OK)
+socket->open(network);
+socket->set_root_ca_cert(SSL_CA_PEM);
+socket->connect("httpbin.org", 443);
// Pass in `socket`, instead of `network` as first argument, and omit the `SSL_CA_PEM` argument
HttpsRequest* get_req = new HttpsRequest(socket, HTTP_GET, "https://httpbin.org/status/418");
```
+## Request logging
+
+To make debugging easier you can log the raw request body that goes over the line. This also works with chunked encoding.
+
+```cpp
+uint8_t *request_buffer = (uint8_t*)calloc(2048, 1);
+req->set_request_log_buffer(request_buffer, 2048);
+
+// after the request is done:
+printf("\n----- Request buffer -----\n");
+for (size_t ix = 0; ix < req->get_request_log_buffer_length(); ix++) {
+ printf("%02x ", request_buffer[ix]);
+}
+printf("\n");
+```
+
## Tested on
* K64F with Ethernet.
* NUCLEO_F411RE with ESP8266.
* ODIN-W2 with WiFi.
* K64F with Atmel 6LoWPAN shield.
+* Mbed Simulator.
But this should work with any Mbed OS 5 device that implements the `NetworkInterface` API.
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/TLSSocket.lib Tue Oct 30 10:18:51 2018 +0800 @@ -0,0 +1,1 @@ +https://github.com/ARMmbed/TLSSocket/#7118d69699e6779dc5de519c75669e722bd78ba0
--- a/http_parser/http_parser.c Tue Mar 27 11:07:02 2018 +0200
+++ b/http_parser/http_parser.c Tue Oct 30 10:18:51 2018 +0800
@@ -631,10 +631,10 @@
return s_dead;
}
-size_t http_parser_execute (http_parser *parser,
+uint32_t http_parser_execute (http_parser *parser,
const http_parser_settings *settings,
const char *data,
- size_t len)
+ uint32_t len)
{
char c, ch;
int8_t unhex_val;
@@ -1536,7 +1536,7 @@
{
const char* p_cr;
const char* p_lf;
- size_t limit = data + len - p;
+ uint32_t limit = data + len - p;
limit = MIN(limit, HTTP_MAX_HEADER_SIZE);
@@ -2160,13 +2160,13 @@
const char *
http_errno_name(enum http_errno err) {
- assert(((size_t) err) < ARRAY_SIZE(http_strerror_tab));
+ assert(((uint32_t) err) < ARRAY_SIZE(http_strerror_tab));
return http_strerror_tab[err].name;
}
const char *
http_errno_description(enum http_errno err) {
- assert(((size_t) err) < ARRAY_SIZE(http_strerror_tab));
+ assert(((uint32_t) err) < ARRAY_SIZE(http_strerror_tab));
return http_strerror_tab[err].description;
}
@@ -2257,7 +2257,7 @@
enum http_host_state s;
const char *p;
- size_t buflen = u->field_data[UF_HOST].off + u->field_data[UF_HOST].len;
+ uint32_t buflen = u->field_data[UF_HOST].off + u->field_data[UF_HOST].len;
assert(u->field_set & (1 << UF_HOST));
@@ -2340,7 +2340,7 @@
}
int
-http_parser_parse_url(const char *buf, size_t buflen, int is_connect,
+http_parser_parse_url(const char *buf, uint32_t buflen, int is_connect,
struct http_parser_url *u)
{
enum state s;
--- a/http_parser/http_parser.h Tue Mar 27 11:07:02 2018 +0200
+++ b/http_parser/http_parser.h Tue Oct 30 10:18:51 2018 +0800
@@ -20,6 +20,7 @@
*/
#ifndef http_parser_h
#define http_parser_h
+
#ifdef __cplusplus
extern "C" {
#endif
@@ -29,8 +30,6 @@
#define HTTP_PARSER_VERSION_MINOR 7
#define HTTP_PARSER_VERSION_PATCH 1
-typedef unsigned int size_t;
-
#if defined(_WIN32) && !defined(__MINGW32__) && \
(!defined(_MSC_VER) || _MSC_VER<1600) && !defined(__WINE__)
#include <BaseTsd.h>
@@ -87,7 +86,7 @@
* many times for each string. E.G. you might get 10 callbacks for "on_url"
* each providing just a few characters more data.
*/
-typedef int (*http_data_cb) (http_parser*, const char *at, size_t length);
+typedef int (*http_data_cb) (http_parser*, const char *at, uint32_t length);
typedef int (*http_cb) (http_parser*);
@@ -390,10 +389,10 @@
/* Executes the parser. Returns number of parsed bytes. Sets
* `parser->http_errno` on error. */
-size_t http_parser_execute(http_parser *parser,
+uint32_t http_parser_execute(http_parser *parser,
const http_parser_settings *settings,
const char *data,
- size_t len);
+ uint32_t len);
/* If http_should_keep_alive() in the on_headers_complete or
@@ -417,7 +416,7 @@
void http_parser_url_init(struct http_parser_url *u);
/* Parse a URL; return nonzero on failure */
-int http_parser_parse_url(const char *buf, size_t buflen,
+int http_parser_parse_url(const char *buf, uint32_t buflen,
int is_connect,
struct http_parser_url *u);
--- a/source/http_request.h Tue Mar 27 11:07:02 2018 +0200
+++ b/source/http_request.h Tue Oct 30 10:18:51 2018 +0800
@@ -21,11 +21,9 @@
#include <string>
#include <vector>
#include <map>
-#include "http_parser.h"
-#include "http_response.h"
-#include "http_request_builder.h"
-#include "http_request_parser.h"
+#include "http_request_base.h"
#include "http_parsed_url.h"
+#include "TCPSocket.h"
/**
* @todo:
@@ -39,310 +37,64 @@
/**
* \brief HttpRequest implements the logic for interacting with HTTP servers.
*/
-class HttpRequest {
+class HttpRequest : public HttpRequestBase {
public:
+ friend class HttpRequestBase;
+
/**
* HttpRequest Constructor
*
- * @param[in] aNetwork The network interface
- * @param[in] aMethod HTTP method to use
+ * @param[in] network The network interface
+ * @param[in] method HTTP method to use
* @param[in] url URL to the resource
- * @param[in] aBodyCallback Callback on which to retrieve chunks of the response body.
- If not set, the complete body will be allocated on the HttpResponse object,
- which might use lots of memory.
+ * @param[in] bodyCallback Callback on which to retrieve chunks of the response body.
+ If not set, the complete body will be allocated on the HttpResponse object,
+ which might use lots of memory.
*/
- HttpRequest(NetworkInterface* aNetwork, http_method aMethod, const char* url, Callback<void(const char *at, size_t length)> aBodyCallback = 0)
- : network(aNetwork), method(aMethod), body_callback(aBodyCallback)
+ HttpRequest(NetworkInterface* network, http_method method, const char* url, Callback<void(const char *at, uint32_t length)> bodyCallback = 0)
+ : HttpRequestBase(NULL, bodyCallback)
{
- error = 0;
- response = NULL;
+ _error = 0;
+ _response = NULL;
- parsed_url = new ParsedUrl(url);
- request_builder = new HttpRequestBuilder(method, parsed_url);
+ _parsed_url = new ParsedUrl(url);
+ _request_builder = new HttpRequestBuilder(method, _parsed_url);
- socket = new TCPSocket();
- we_created_socket = true;
+ _socket = new TCPSocket();
+ ((TCPSocket*)_socket)->open(network);
+ _we_created_socket = true;
}
/**
* HttpRequest Constructor
*
- * @param[in] aSocket An open TCPSocket
- * @param[in] aMethod HTTP method to use
+ * @param[in] socket An open TCPSocket
+ * @param[in] method HTTP method to use
* @param[in] url URL to the resource
- * @param[in] aBodyCallback Callback on which to retrieve chunks of the response body.
+ * @param[in] bodyCallback Callback on which to retrieve chunks of the response body.
If not set, the complete body will be allocated on the HttpResponse object,
which might use lots of memory.
*/
- HttpRequest(TCPSocket* aSocket, http_method aMethod, const char* url, Callback<void(const char *at, size_t length)> aBodyCallback = 0)
- : socket(aSocket), method(aMethod), body_callback(aBodyCallback)
+ HttpRequest(TCPSocket* socket, http_method method, const char* url, Callback<void(const char *at, uint32_t length)> bodyCallback = 0)
+ : HttpRequestBase(socket, bodyCallback)
{
- error = 0;
- response = NULL;
- network = NULL;
-
- parsed_url = new ParsedUrl(url);
- request_builder = new HttpRequestBuilder(method, parsed_url);
-
- we_created_socket = false;
- }
-
- /**
- * HttpRequest Constructor
- */
- ~HttpRequest() {
- // should response be owned by us? Or should user free it?
- // maybe implement copy constructor on response...
- if (response) {
- delete response;
- }
-
- if (parsed_url) {
- delete parsed_url;
- }
-
- if (request_builder) {
- delete request_builder;
- }
+ _error = 0;
+ _response = NULL;
- if (socket && we_created_socket) {
- delete socket;
- }
- }
-
- /**
- * Execute the request and receive the response.
- * This adds a Content-Length header to the request (when body_size is set), and sends the data to the server.
- * @param body Pointer to the body to be sent
- * @param body_size Size of the body to be sent
- * @return An HttpResponse pointer on success, or NULL on failure.
- * See get_error() for the error code.
- */
- HttpResponse* send(const void* body = NULL, nsapi_size_t body_size = 0) {
- nsapi_size_or_error_t ret = open_socket();
+ _parsed_url = new ParsedUrl(url);
+ _request_builder = new HttpRequestBuilder(method, _parsed_url);
- if (ret != NSAPI_ERROR_OK) {
- error = ret;
- return NULL;
- }
-
- size_t request_size = 0;
- char* request = request_builder->build(body, body_size, request_size);
-
- ret = send_buffer(request, request_size);
-
- free(request);
-
- if (ret < 0) {
- error = ret;
- return NULL;
- }
-
- return create_http_response();
+ _we_created_socket = false;
}
- /**
- * Execute the request and receive the response.
- * This sends the request through chunked-encoding.
- * @param body_cb Callback which generates the next chunk of the request
- * @return An HttpResponse pointer on success, or NULL on failure.
- * See get_error() for the error code.
- */
- HttpResponse* send(Callback<const void*(size_t*)> body_cb) {
-
- nsapi_error_t ret;
-
- if ((ret = open_socket()) != NSAPI_ERROR_OK) {
- error = ret;
- return NULL;
- }
-
- set_header("Transfer-Encoding", "chunked");
-
- size_t request_size = 0;
- char* request = request_builder->build(NULL, 0, request_size);
-
- // first... send this request headers without the body
- nsapi_size_or_error_t total_send_count = send_buffer(request, request_size);
-
- if (total_send_count < 0) {
- free(request);
- error = total_send_count;
- return NULL;
- }
-
- // ok... now it's time to start sending chunks...
- while (1) {
- size_t size;
- const void *buffer = body_cb(&size);
-
- if (size == 0) break;
-
- // so... size in HEX, \r\n, data, \r\n again
- char size_buff[10]; // if sending length of more than 8 digits, you have another problem on a microcontroller...
- size_t size_buff_size = sprintf(size_buff, "%X\r\n", size);
- if ((total_send_count = send_buffer(size_buff, size_buff_size)) < 0) {
- free(request);
- error = total_send_count;
- return NULL;
- }
-
- // now send the normal buffer... and then \r\n at the end
- total_send_count = send_buffer((char*)buffer, size);
- if (total_send_count < 0) {
- free(request);
- error = total_send_count;
- return NULL;
- }
-
- // and... \r\n
- const char* rn = "\r\n";
- if ((total_send_count = send_buffer((char*)rn, 2)) < 0) {
- free(request);
- error = total_send_count;
- return NULL;
- }
- }
-
- // finalize...?
- const char* fin = "0\r\n\r\n";
- if ((total_send_count = send_buffer((char*)fin, strlen(fin))) < 0) {
- free(request);
- error = total_send_count;
- return NULL;
- }
-
- free(request);
-
- return create_http_response();
- }
-
- /**
- * Set a header for the request.
- *
- * The 'Host' and 'Content-Length' headers are set automatically.
- * Setting the same header twice will overwrite the previous entry.
- *
- * @param[in] key Header key
- * @param[in] value Header value
- */
- void set_header(string key, string value) {
- request_builder->set_header(key, value);
- }
-
- /**
- * Get the error code.
- *
- * When send() fails, this error is set.
- */
- nsapi_error_t get_error() {
- return error;
+ virtual ~HttpRequest() {
}
-private:
- nsapi_error_t open_socket() {
- if (response != NULL) {
- // already executed this response
- return -2100; // @todo, make a lookup table with errors
- }
-
-
- if (we_created_socket) {
- nsapi_error_t open_result = socket->open(network);
- if (open_result != NSAPI_ERROR_OK) {
- return open_result;
- }
-
- nsapi_error_t connection_result = socket->connect(parsed_url->host(), parsed_url->port());
- if (connection_result != NSAPI_ERROR_OK) {
- return connection_result;
- }
- }
-
- return NSAPI_ERROR_OK;
- }
-
- nsapi_size_or_error_t send_buffer(char* buffer, size_t buffer_size) {
- nsapi_size_or_error_t total_send_count = 0;
- while (total_send_count < buffer_size) {
- nsapi_size_or_error_t send_result = socket->send(buffer + total_send_count, buffer_size - total_send_count);
-
- if (send_result < 0) {
- total_send_count = send_result;
- break;
- }
-
- if (send_result == 0) {
- break;
- }
-
- total_send_count += send_result;
- }
-
- return total_send_count;
- }
-
- HttpResponse* create_http_response() {
- // Create a response object
- response = new HttpResponse();
- // And a response parser
- HttpParser parser(response, HTTP_RESPONSE, body_callback);
-
- // Set up a receive buffer (on the heap)
- uint8_t* recv_buffer = (uint8_t*)malloc(HTTP_RECEIVE_BUFFER_SIZE);
+protected:
- // TCPSocket::recv is called until we don't have any data anymore
- nsapi_size_or_error_t recv_ret;
- while ((recv_ret = socket->recv(recv_buffer, HTTP_RECEIVE_BUFFER_SIZE)) > 0) {
-
- // Pass the chunk into the http_parser
- size_t nparsed = parser.execute((const char*)recv_buffer, recv_ret);
- if (nparsed != recv_ret) {
- // printf("Parsing failed... parsed %d bytes, received %d bytes\n", nparsed, recv_ret);
- error = -2101;
- free(recv_buffer);
- return NULL;
- }
-
- if (response->is_message_complete()) {
- break;
- }
- }
- // error?
- if (recv_ret < 0) {
- error = recv_ret;
- free(recv_buffer);
- return NULL;
- }
-
- // When done, call parser.finish()
- parser.finish();
-
- // Free the receive buffer
- free(recv_buffer);
-
- if (we_created_socket) {
- // Close the socket
- socket->close();
- }
-
- return response;
+ virtual nsapi_error_t connect_socket(char *host, uint16_t port) {
+ return ((TCPSocket*)_socket)->connect(host, port);
}
-
-
- NetworkInterface* network;
- TCPSocket* socket;
- http_method method;
- Callback<void(const char *at, size_t length)> body_callback;
-
- ParsedUrl* parsed_url;
-
- HttpRequestBuilder* request_builder;
- HttpResponse* response;
-
- bool we_created_socket;
-
- nsapi_error_t error;
};
#endif // _HTTP_REQUEST_
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/source/http_request_base.h Tue Oct 30 10:18:51 2018 +0800
@@ -0,0 +1,352 @@
+/*
+ * PackageLicenseDeclared: Apache-2.0
+ * Copyright (c) 2017 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _HTTP_REQUEST_BASE_H_
+#define _HTTP_REQUEST_BASE_H_
+
+#include <map>
+#include <string>
+#include <vector>
+#include "mbed.h"
+#include "http_parser.h"
+#include "http_parsed_url.h"
+#include "http_request_builder.h"
+#include "http_request_parser.h"
+#include "http_response.h"
+#include "NetworkInterface.h"
+#include "netsocket/Socket.h"
+
+/**
+ * @todo:
+ * - Userinfo parameter is not handled
+ */
+
+#ifndef HTTP_RECEIVE_BUFFER_SIZE
+#define HTTP_RECEIVE_BUFFER_SIZE 8 * 1024
+#endif
+
+class HttpRequest;
+class HttpsRequest;
+
+/**
+ * \brief HttpRequest implements the logic for interacting with HTTP servers.
+ */
+class HttpRequestBase {
+ friend class HttpRequest;
+ friend class HttpsRequest;
+
+public:
+ HttpRequestBase(Socket *socket, Callback<void(const char *at, uint32_t length)> bodyCallback)
+ : _socket(socket), _body_callback(bodyCallback), _request_buffer(NULL), _request_buffer_ix(0)
+ {}
+
+ /**
+ * HttpRequest Constructor
+ */
+ virtual ~HttpRequestBase() {
+ // should response be owned by us? Or should user free it?
+ // maybe implement copy constructor on response...
+ if (_response) {
+ delete _response;
+ }
+
+ if (_parsed_url) {
+ delete _parsed_url;
+ }
+
+ if (_request_builder) {
+ delete _request_builder;
+ }
+
+ if (_socket && _we_created_socket) {
+ delete _socket;
+ }
+ }
+
+ /**
+ * Execute the request and receive the response.
+ * This adds a Content-Length header to the request (when body_size is set), and sends the data to the server.
+ * @param body Pointer to the body to be sent
+ * @param body_size Size of the body to be sent
+ * @return An HttpResponse pointer on success, or NULL on failure.
+ * See get_error() for the error code.
+ */
+ HttpResponse* send(const void* body = NULL, nsapi_size_t body_size = 0) {
+ nsapi_size_or_error_t ret = connect_socket();
+
+ if (ret != NSAPI_ERROR_OK) {
+ _error = ret;
+ return NULL;
+ }
+
+ _request_buffer_ix = 0;
+
+ uint32_t request_size = 0;
+ char* request = _request_builder->build(body, body_size, request_size);
+
+ ret = send_buffer(request, request_size);
+
+ free(request);
+
+ if (ret < 0) {
+ _error = ret;
+ return NULL;
+ }
+
+ return create_http_response();
+ }
+
+ /**
+ * Execute the request and receive the response.
+ * This sends the request through chunked-encoding.
+ * @param body_cb Callback which generates the next chunk of the request
+ * @return An HttpResponse pointer on success, or NULL on failure.
+ * See get_error() for the error code.
+ */
+ HttpResponse* send(Callback<const void*(uint32_t*)> body_cb) {
+
+ nsapi_error_t ret;
+
+ if ((ret = connect_socket()) != NSAPI_ERROR_OK) {
+ _error = ret;
+ return NULL;
+ }
+
+ _request_buffer_ix = 0;
+
+ set_header("Transfer-Encoding", "chunked");
+
+ uint32_t request_size = 0;
+ char* request = _request_builder->build(NULL, 0, request_size);
+
+ // first... send this request headers without the body
+ nsapi_size_or_error_t total_send_count = send_buffer(request, request_size);
+
+ if (total_send_count < 0) {
+ free(request);
+ _error = total_send_count;
+ return NULL;
+ }
+
+ // ok... now it's time to start sending chunks...
+ while (1) {
+ uint32_t size;
+ const void *buffer = body_cb(&size);
+
+ if (size == 0) break;
+
+ // so... size in HEX, \r\n, data, \r\n again
+ char size_buff[10]; // if sending length of more than 8 digits, you have another problem on a microcontroller...
+ int size_buff_size = sprintf(size_buff, "%X\r\n", static_cast<size_t>(size));
+ if ((total_send_count = send_buffer(size_buff, static_cast<uint32_t>(size_buff_size))) < 0) {
+ free(request);
+ _error = total_send_count;
+ return NULL;
+ }
+
+ // now send the normal buffer... and then \r\n at the end
+ total_send_count = send_buffer((char*)buffer, size);
+ if (total_send_count < 0) {
+ free(request);
+ _error = total_send_count;
+ return NULL;
+ }
+
+ // and... \r\n
+ const char* rn = "\r\n";
+ if ((total_send_count = send_buffer((char*)rn, 2)) < 0) {
+ free(request);
+ _error = total_send_count;
+ return NULL;
+ }
+ }
+
+ // finalize...?
+ const char* fin = "0\r\n\r\n";
+ if ((total_send_count = send_buffer((char*)fin, strlen(fin))) < 0) {
+ free(request);
+ _error = total_send_count;
+ return NULL;
+ }
+
+ free(request);
+
+ return create_http_response();
+ }
+
+ /**
+ * Set a header for the request.
+ *
+ * The 'Host', 'Content-Length', and (optionally) 'Transfer-Encoding: chunked'
+ * headers are set automatically.
+ * Setting the same header twice will overwrite the previous entry.
+ *
+ * @param key Header key
+ * @param value Header value
+ */
+ void set_header(string key, string value) {
+ _request_builder->set_header(key, value);
+ }
+
+ /**
+ * Get the error code.
+ *
+ * When send() fails, this error is set.
+ */
+ nsapi_error_t get_error() {
+ return _error;
+ }
+
+ /**
+ * Set the request log buffer, all bytes that are sent for this request are logged here.
+ * If the buffer would overflow logging is stopped.
+ *
+ * @param buffer Pointer to a buffer to store the data in
+ * @param buffer_size Size of the buffer
+ */
+ void set_request_log_buffer(uint8_t *buffer, size_t buffer_size) {
+ _request_buffer = buffer;
+ _request_buffer_size = buffer_size;
+ _request_buffer_ix = 0;
+ }
+
+ /**
+ * Get the number of bytes written to the request log buffer, since the last request.
+ * If no request was sent, or if the request log buffer is NULL, then this returns 0.
+ */
+ size_t get_request_log_buffer_length() {
+ return _request_buffer_ix;
+ }
+
+protected:
+ virtual nsapi_error_t connect_socket(char *host, uint16_t port) = 0;
+
+private:
+ nsapi_error_t connect_socket( ) {
+ if (_response != NULL) {
+ // already executed this response
+ return -2100; // @todo, make a lookup table with errors
+ }
+
+
+ if (_we_created_socket) {
+ nsapi_error_t connection_result = connect_socket(_parsed_url->host(), _parsed_url->port());
+ if (connection_result != NSAPI_ERROR_OK) {
+ return connection_result;
+ }
+ }
+
+ return NSAPI_ERROR_OK;
+ }
+
+ nsapi_size_or_error_t send_buffer(char* buffer, uint32_t buffer_size) {
+ nsapi_size_or_error_t total_send_count = 0;
+ while (total_send_count < buffer_size) {
+
+ // get a slice of the buffer
+ char *buffer_slice = buffer + total_send_count;
+ uint32_t buffer_slice_size = buffer_size - total_send_count;
+
+ // if request buffer was set, copy it there
+ if (_request_buffer != NULL && _request_buffer_ix + buffer_slice_size < _request_buffer_size) {
+ memcpy(_request_buffer + _request_buffer_ix, buffer_slice, buffer_slice_size);
+ _request_buffer_ix += buffer_slice_size;
+ }
+
+ nsapi_size_or_error_t send_result = _socket->send(buffer_slice, buffer_slice_size);
+
+ if (send_result < 0) {
+ total_send_count = send_result;
+ break;
+ }
+
+ if (send_result == 0) {
+ break;
+ }
+
+ total_send_count += send_result;
+ }
+
+ return total_send_count;
+ }
+
+ HttpResponse* create_http_response() {
+ // Create a response object
+ _response = new HttpResponse();
+ // And a response parser
+ HttpParser parser(_response, HTTP_RESPONSE, _body_callback);
+
+ // Set up a receive buffer (on the heap)
+ uint8_t* recv_buffer = (uint8_t*)malloc(HTTP_RECEIVE_BUFFER_SIZE);
+
+ // Socket::recv is called until we don't have any data anymore
+ nsapi_size_or_error_t recv_ret;
+ while ((recv_ret = _socket->recv(recv_buffer, HTTP_RECEIVE_BUFFER_SIZE)) > 0) {
+
+ // Pass the chunk into the http_parser
+ uint32_t nparsed = parser.execute((const char*)recv_buffer, recv_ret);
+ if (nparsed != recv_ret) {
+ // printf("Parsing failed... parsed %d bytes, received %d bytes\n", nparsed, recv_ret);
+ _error = -2101;
+ free(recv_buffer);
+ return NULL;
+ }
+
+ if (_response->is_message_complete()) {
+ break;
+ }
+ }
+ // error?
+ if (recv_ret < 0) {
+ _error = recv_ret;
+ free(recv_buffer);
+ return NULL;
+ }
+
+ // When done, call parser.finish()
+ parser.finish();
+
+ // Free the receive buffer
+ free(recv_buffer);
+
+ if (_we_created_socket) {
+ // Close the socket
+ _socket->close();
+ }
+
+ return _response;
+ }
+
+private:
+ Socket* _socket;
+ Callback<void(const char *at, uint32_t length)> _body_callback;
+
+ ParsedUrl* _parsed_url;
+
+ HttpRequestBuilder* _request_builder;
+ HttpResponse* _response;
+
+ bool _we_created_socket;
+
+ nsapi_error_t _error;
+
+ uint8_t *_request_buffer;
+ size_t _request_buffer_size;
+ size_t _request_buffer_ix;
+};
+
+#endif // _HTTP_REQUEST_BASE_H_
--- a/source/http_request_builder.h Tue Mar 27 11:07:02 2018 +0200
+++ b/source/http_request_builder.h Tue Oct 30 10:18:51 2018 +0800
@@ -58,15 +58,16 @@
}
}
- char* build(const void* body, size_t body_size, size_t &size, bool skip_content_length = false) {
+ char* build(const void* body, uint32_t body_size, uint32_t &size, bool skip_content_length = false) {
const char* method_str = http_method_str(method);
bool is_chunked = has_header("Transfer-Encoding", "chunked");
if (!is_chunked && (method == HTTP_POST || method == HTTP_PUT || method == HTTP_DELETE || body_size > 0)) {
char buffer[10];
- snprintf(buffer, 10, "%d", body_size);
+ snprintf(buffer, 10, "%lu", body_size);
set_header("Content-Length", string(buffer));
+ printf("header Content-Length: %s\n", buffer);
}
size = 0;
--- a/source/http_request_parser.h Tue Mar 27 11:07:02 2018 +0200
+++ b/source/http_request_parser.h Tue Oct 30 10:18:51 2018 +0800
@@ -24,7 +24,7 @@
class HttpParser {
public:
- HttpParser(HttpResponse* a_response, http_parser_type parser_type, Callback<void(const char *at, size_t length)> a_body_callback = 0)
+ HttpParser(HttpResponse* a_response, http_parser_type parser_type, Callback<void(const char *at, uint32_t length)> a_body_callback = 0)
: response(a_response), body_callback(a_body_callback)
{
settings = new http_parser_settings();
@@ -55,7 +55,7 @@
}
}
- size_t execute(const char* buffer, size_t buffer_size) {
+ uint32_t execute(const char* buffer, uint32_t buffer_size) {
return http_parser_execute(parser, settings, buffer, buffer_size);
}
@@ -69,25 +69,25 @@
return 0;
}
- int on_url(http_parser* parser, const char *at, size_t length) {
+ int on_url(http_parser* parser, const char *at, uint32_t length) {
string s(at, length);
response->set_url(s);
return 0;
}
- int on_status(http_parser* parser, const char *at, size_t length) {
+ int on_status(http_parser* parser, const char *at, uint32_t length) {
string s(at, length);
response->set_status(parser->status_code, s);
return 0;
}
- int on_header_field(http_parser* parser, const char *at, size_t length) {
+ int on_header_field(http_parser* parser, const char *at, uint32_t length) {
string s(at, length);
response->set_header_field(s);
return 0;
}
- int on_header_value(http_parser* parser, const char *at, size_t length) {
+ int on_header_value(http_parser* parser, const char *at, uint32_t length) {
string s(at, length);
response->set_header_value(s);
return 0;
@@ -99,7 +99,7 @@
return 0;
}
- int on_body(http_parser* parser, const char *at, size_t length) {
+ int on_body(http_parser* parser, const char *at, uint32_t length) {
response->increase_body_length(length);
if (body_callback) {
@@ -132,19 +132,19 @@
return ((HttpParser*)parser->data)->on_message_begin(parser);
}
- static int on_url_callback(http_parser* parser, const char *at, size_t length) {
+ static int on_url_callback(http_parser* parser, const char *at, uint32_t length) {
return ((HttpParser*)parser->data)->on_url(parser, at, length);
}
- static int on_status_callback(http_parser* parser, const char *at, size_t length) {
+ static int on_status_callback(http_parser* parser, const char *at, uint32_t length) {
return ((HttpParser*)parser->data)->on_status(parser, at, length);
}
- static int on_header_field_callback(http_parser* parser, const char *at, size_t length) {
+ static int on_header_field_callback(http_parser* parser, const char *at, uint32_t length) {
return ((HttpParser*)parser->data)->on_header_field(parser, at, length);
}
- static int on_header_value_callback(http_parser* parser, const char *at, size_t length) {
+ static int on_header_value_callback(http_parser* parser, const char *at, uint32_t length) {
return ((HttpParser*)parser->data)->on_header_value(parser, at, length);
}
@@ -152,7 +152,7 @@
return ((HttpParser*)parser->data)->on_headers_complete(parser);
}
- static int on_body_callback(http_parser* parser, const char *at, size_t length) {
+ static int on_body_callback(http_parser* parser, const char *at, uint32_t length) {
return ((HttpParser*)parser->data)->on_body(parser, at, length);
}
@@ -169,7 +169,7 @@
}
HttpResponse* response;
- Callback<void(const char *at, size_t length)> body_callback;
+ Callback<void(const char *at, uint32_t length)> body_callback;
http_parser* parser;
http_parser_settings* settings;
};
--- a/source/http_response.h Tue Mar 27 11:07:02 2018 +0200
+++ b/source/http_response.h Tue Oct 30 10:18:51 2018 +0800
@@ -114,7 +114,7 @@
}
}
- size_t get_headers_length() {
+ uint32_t get_headers_length() {
return header_fields.size();
}
@@ -126,7 +126,7 @@
return header_values;
}
- void set_body(const char *at, size_t length) {
+ void set_body(const char *at, uint32_t length) {
// Connection: close, could not specify Content-Length, nor chunked... So do it like this:
if (expected_content_length == 0 && length > 0) {
is_chunked = true;
@@ -166,11 +166,11 @@
return s;
}
- void increase_body_length(size_t length) {
+ void increase_body_length(uint32_t length) {
body_length += length;
}
- size_t get_body_length() {
+ uint32_t get_body_length() {
return body_offset;
}
@@ -216,15 +216,15 @@
bool concat_header_field;
bool concat_header_value;
- size_t expected_content_length;
+ uint32_t expected_content_length;
bool is_chunked;
bool is_message_completed;
char * body;
- size_t body_length;
- size_t body_offset;
+ uint32_t body_length;
+ uint32_t body_offset;
};
#endif
--- a/source/https_request.h Tue Mar 27 11:07:02 2018 +0200
+++ b/source/https_request.h Tue Oct 30 10:18:51 2018 +0800
@@ -21,12 +21,8 @@
#include <string>
#include <vector>
#include <map>
-#include "http_parser.h"
-#include "http_response.h"
-#include "http_request_builder.h"
-#include "http_request_parser.h"
-#include "http_parsed_url.h"
-#include "tls_socket.h"
+#include "http_request_base.h"
+#include "TLSSocket.h"
#ifndef HTTP_RECEIVE_BUFFER_SIZE
#define HTTP_RECEIVE_BUFFER_SIZE 8 * 1024
@@ -35,13 +31,13 @@
/**
* \brief HttpsRequest implements the logic for interacting with HTTPS servers.
*/
-class HttpsRequest {
+class HttpsRequest : public HttpRequestBase {
public:
/**
* HttpsRequest Constructor
* Initializes the TCP socket, sets up event handlers and flags.
*
- * @param[in] net_iface The network interface
+ * @param[in] network The network interface
* @param[in] ssl_ca_pem String containing the trusted CAs
* @param[in] method HTTP method to use
* @param[in] url URL to the resource
@@ -49,20 +45,21 @@
If not set, the complete body will be allocated on the HttpResponse object,
which might use lots of memory.
*/
- HttpsRequest(NetworkInterface* net_iface,
+ HttpsRequest(NetworkInterface* network,
const char* ssl_ca_pem,
http_method method,
const char* url,
- Callback<void(const char *at, size_t length)> body_callback = 0)
+ Callback<void(const char *at, uint32_t length)> body_callback = 0)
+ : HttpRequestBase(NULL, body_callback)
{
_parsed_url = new ParsedUrl(url);
- _body_callback = body_callback;
_request_builder = new HttpRequestBuilder(method, _parsed_url);
_response = NULL;
- _debug = false;
- _tlssocket = new TLSSocket(net_iface, _parsed_url->host(), _parsed_url->port(), ssl_ca_pem);
- _we_created_the_socket = true;
+ _socket = new TLSSocket();
+ ((TLSSocket*)_socket)->open(network);
+ ((TLSSocket*)_socket)->set_root_ca_cert(ssl_ca_pem);
+ _we_created_socket = true;
}
/**
@@ -79,310 +76,23 @@
HttpsRequest(TLSSocket* socket,
http_method method,
const char* url,
- Callback<void(const char *at, size_t length)> body_callback = 0)
+ Callback<void(const char *at, uint32_t length)> body_callback = 0)
+ : HttpRequestBase(socket, body_callback)
{
_parsed_url = new ParsedUrl(url);
_body_callback = body_callback;
_request_builder = new HttpRequestBuilder(method, _parsed_url);
_response = NULL;
- _debug = false;
- _tlssocket = socket;
- _we_created_the_socket = false;
- }
-
- /**
- * HttpsRequest Destructor
- */
- ~HttpsRequest() {
- if (_request_builder) {
- delete _request_builder;
- }
-
- if (_tlssocket && _we_created_the_socket) {
- delete _tlssocket;
- }
-
- if (_parsed_url) {
- delete _parsed_url;
- }
-
- if (_response) {
- delete _response;
- }
- }
-
- /**
- * Execute the HTTPS request.
- *
- * @param[in] body Pointer to the request body
- * @param[in] body_size Size of the request body
- * @return An HttpResponse pointer on success, or NULL on failure.
- * See get_error() for the error code.
- */
- HttpResponse* send(const void* body = NULL, nsapi_size_t body_size = 0) {
- nsapi_size_or_error_t ret = open_socket();
-
- if (ret != NSAPI_ERROR_OK) {
- _error = ret;
- return NULL;
- }
-
- size_t request_size = 0;
- char* request = _request_builder->build(body, body_size, request_size);
-
- ret = send_buffer((const unsigned char*)request, request_size);
-
- free(request);
-
- if (ret < 0) {
- _error = ret;
- return NULL;
- }
-
- return create_http_response();
- }
-
- /**
- * Execute the HTTPS request.
- * This sends the request through chunked-encoding.
- * @param body_cb Callback which generates the next chunk of the request
- * @return An HttpResponse pointer on success, or NULL on failure.
- * See get_error() for the error code.
- */
- HttpResponse* send(Callback<const void*(size_t*)> body_cb) {
-
- nsapi_error_t ret;
-
- if ((ret = open_socket()) != NSAPI_ERROR_OK) {
- _error = ret;
- return NULL;
- }
-
- set_header("Transfer-Encoding", "chunked");
-
- size_t request_size = 0;
- char* request = _request_builder->build(NULL, 0, request_size);
-
- // first... send this request headers without the body
- nsapi_size_or_error_t total_send_count = send_buffer((unsigned char*)request, request_size);
-
- if (total_send_count < 0) {
- free(request);
- _error = total_send_count;
- return NULL;
- }
-
- // ok... now it's time to start sending chunks...
- while (1) {
- size_t size;
- const void *buffer = body_cb(&size);
-
- if (size == 0) break;
-
- // so... size in HEX, \r\n, data, \r\n again
- char size_buff[10]; // if sending length of more than 8 digits, you have another problem on a microcontroller...
- size_t size_buff_size = sprintf(size_buff, "%X\r\n", size);
- if ((total_send_count = send_buffer((const unsigned char*)size_buff, size_buff_size)) < 0) {
- free(request);
- _error = total_send_count;
- return NULL;
- }
-
- // now send the normal buffer... and then \r\n at the end
- total_send_count = send_buffer((const unsigned char*)buffer, size);
- if (total_send_count < 0) {
- free(request);
- _error = total_send_count;
- return NULL;
- }
-
- // and... \r\n
- const char* rn = "\r\n";
- if ((total_send_count = send_buffer((const unsigned char*)rn, 2)) < 0) {
- free(request);
- _error = total_send_count;
- return NULL;
- }
- }
-
- // finalize...?
- const char* fin = "0\r\n\r\n";
- if ((total_send_count = send_buffer((const unsigned char*)fin, strlen(fin))) < 0) {
- free(request);
- _error = total_send_count;
- return NULL;
- }
-
- free(request);
-
- return create_http_response();
- }
-
- /**
- * Closes the underlying TCP socket
- */
- void close() {
- _tlssocket->get_tcp_socket()->close();
+ _we_created_socket = false;
}
- /**
- * Set a header for the request.
- *
- * The 'Host' and 'Content-Length' headers are set automatically.
- * Setting the same header twice will overwrite the previous entry.
- *
- * @param[in] key Header key
- * @param[in] value Header value
- */
- void set_header(string key, string value) {
- _request_builder->set_header(key, value);
- }
-
- /**
- * Get the error code.
- *
- * When send() fails, this error is set.
- */
- nsapi_error_t get_error() {
- return _error;
- }
-
- /**
- * Set the debug flag.
- *
- * If this flag is set, debug information from mbed TLS will be logged to stdout.
- */
- void set_debug(bool debug) {
- _debug = debug;
-
- _tlssocket->set_debug(debug);
- }
-
+ virtual ~HttpsRequest() {}
protected:
- /**
- * Helper for pretty-printing mbed TLS error codes
- */
- static void print_mbedtls_error(const char *name, int err) {
- char buf[128];
- mbedtls_strerror(err, buf, sizeof (buf));
- mbedtls_printf("%s() failed: -0x%04x (%d): %s\r\n", name, -err, err, buf);
- }
-
- void onError(TCPSocket *s, int error) {
- s->close();
- _error = error;
- }
-
- nsapi_error_t onErrorAndReturn(TCPSocket *s, int error) {
- s->close();
- return error;
- }
-
-private:
- nsapi_error_t open_socket() {
- // not tried to connect before?
- if (_tlssocket->error() != 0) {
- return _tlssocket->error();
- }
-
- _socket_was_open = _tlssocket->connected();
-
- if (!_socket_was_open) {
- nsapi_error_t r = _tlssocket->connect();
- if (r != NSAPI_ERROR_OK) {
- return r;
- }
- }
-
- return NSAPI_ERROR_OK;
- }
-
- nsapi_size_or_error_t send_buffer(const unsigned char *buffer, size_t buffer_size) {
- nsapi_size_or_error_t ret = mbedtls_ssl_write(_tlssocket->get_ssl_context(), (const unsigned char *) buffer, buffer_size);
-
- if (ret < 0) {
- if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
- ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
- print_mbedtls_error("mbedtls_ssl_write", ret);
- return onErrorAndReturn(_tlssocket->get_tcp_socket(), -1 );
- }
- else {
- return ret;
- }
- }
-
- return NSAPI_ERROR_OK;
+ virtual nsapi_error_t connect_socket(char *host, uint16_t port) {
+ return ((TLSSocket*)_socket)->connect(host, port);
}
-
- HttpResponse* create_http_response() {
- nsapi_size_or_error_t ret;
-
- // Create a response object
- _response = new HttpResponse();
- // And a response parser
- HttpParser parser(_response, HTTP_RESPONSE, _body_callback);
-
- // Set up a receive buffer (on the heap)
- uint8_t* recv_buffer = (uint8_t*)malloc(HTTP_RECEIVE_BUFFER_SIZE);
-
- /* Read data out of the socket */
- while ((ret = mbedtls_ssl_read(_tlssocket->get_ssl_context(), (unsigned char *) recv_buffer, HTTP_RECEIVE_BUFFER_SIZE)) > 0) {
- // Don't know if this is actually needed, but OK
- size_t _bpos = static_cast<size_t>(ret);
- recv_buffer[_bpos] = 0;
-
- size_t nparsed = parser.execute((const char*)recv_buffer, _bpos);
- if (nparsed != _bpos) {
- print_mbedtls_error("parser_error", nparsed);
- // parser error...
- _error = -2101;
- free(recv_buffer);
- return NULL;
- }
-
- if (_response->is_message_complete()) {
- break;
- }
- }
- if (ret < 0) {
- if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
- print_mbedtls_error("mbedtls_ssl_read", ret);
- onError(_tlssocket->get_tcp_socket(), -1 );
- }
- else {
- _error = ret;
- }
- free(recv_buffer);
- return NULL;
- }
-
- parser.finish();
-
- if (!_socket_was_open) {
- _tlssocket->get_tcp_socket()->close();
- }
-
- free(recv_buffer);
-
- return _response;
- }
-
-protected:
- TLSSocket* _tlssocket;
- bool _we_created_the_socket;
-
- Callback<void(const char *at, size_t length)> _body_callback;
- ParsedUrl* _parsed_url;
- HttpRequestBuilder* _request_builder;
- HttpResponse* _response;
-
- bool _socket_was_open;
-
- nsapi_error_t _error;
- bool _debug;
-
};
#endif // _MBED_HTTPS_REQUEST_H_
--- a/source/tls_socket.h Tue Mar 27 11:07:02 2018 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,333 +0,0 @@
-/*
- * PackageLicenseDeclared: Apache-2.0
- * Copyright (c) 2017 ARM Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _MBED_HTTPS_TLS_SOCKET_H_
-#define _MBED_HTTPS_TLS_SOCKET_H_
-
-/* Change to a number between 1 and 4 to debug the TLS connection */
-#define DEBUG_LEVEL 0
-
-#include <string>
-#include <vector>
-#include <map>
-#include "TCPSocket.h"
-#include "http_parser.h"
-#include "http_response.h"
-#include "http_request_builder.h"
-#include "http_request_parser.h"
-#include "http_parsed_url.h"
-
-#include "mbedtls/platform.h"
-#include "mbedtls/ssl.h"
-#include "mbedtls/entropy.h"
-#include "mbedtls/ctr_drbg.h"
-#include "mbedtls/error.h"
-
-#if DEBUG_LEVEL > 0
-#include "mbedtls/debug.h"
-#endif
-
-/**
- * \brief TLSSocket a wrapper around TCPSocket for interacting with TLS servers
- */
-class TLSSocket {
-public:
- TLSSocket(NetworkInterface* net_iface, const char* hostname, uint16_t port, const char* ssl_ca_pem) {
- _tcpsocket = new TCPSocket(net_iface);
- _ssl_ca_pem = ssl_ca_pem;
- _is_connected = false;
- _debug = false;
- _hostname = hostname;
- _port = port;
- _error = 0;
-
- DRBG_PERS = "mbed TLS helloword client";
-
- mbedtls_entropy_init(&_entropy);
- mbedtls_ctr_drbg_init(&_ctr_drbg);
- mbedtls_x509_crt_init(&_cacert);
- mbedtls_ssl_init(&_ssl);
- mbedtls_ssl_config_init(&_ssl_conf);
- }
-
- ~TLSSocket() {
- mbedtls_entropy_free(&_entropy);
- mbedtls_ctr_drbg_free(&_ctr_drbg);
- mbedtls_x509_crt_free(&_cacert);
- mbedtls_ssl_free(&_ssl);
- mbedtls_ssl_config_free(&_ssl_conf);
-
- if (_tcpsocket) {
- _tcpsocket->close();
- delete _tcpsocket;
- }
-
- // @todo: free DRBG_PERS ?
- }
-
- nsapi_error_t connect() {
- /* Initialize the flags */
- /*
- * Initialize TLS-related stuf.
- */
- int ret;
- if ((ret = mbedtls_ctr_drbg_seed(&_ctr_drbg, mbedtls_entropy_func, &_entropy,
- (const unsigned char *) DRBG_PERS,
- sizeof (DRBG_PERS))) != 0) {
- print_mbedtls_error("mbedtls_crt_drbg_init", ret);
- _error = ret;
- return _error;
- }
-
- if ((ret = mbedtls_x509_crt_parse(&_cacert, (const unsigned char *)_ssl_ca_pem,
- strlen(_ssl_ca_pem) + 1)) != 0) {
- print_mbedtls_error("mbedtls_x509_crt_parse", ret);
- _error = ret;
- return _error;
- }
-
- if ((ret = mbedtls_ssl_config_defaults(&_ssl_conf,
- MBEDTLS_SSL_IS_CLIENT,
- MBEDTLS_SSL_TRANSPORT_STREAM,
- MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
- print_mbedtls_error("mbedtls_ssl_config_defaults", ret);
- _error = ret;
- return _error;
- }
-
- mbedtls_ssl_conf_ca_chain(&_ssl_conf, &_cacert, NULL);
- mbedtls_ssl_conf_rng(&_ssl_conf, mbedtls_ctr_drbg_random, &_ctr_drbg);
-
- /* It is possible to disable authentication by passing
- * MBEDTLS_SSL_VERIFY_NONE in the call to mbedtls_ssl_conf_authmode()
- */
- mbedtls_ssl_conf_authmode(&_ssl_conf, MBEDTLS_SSL_VERIFY_REQUIRED);
-
-#if DEBUG_LEVEL > 0
- mbedtls_ssl_conf_verify(&_ssl_conf, my_verify, NULL);
- mbedtls_ssl_conf_dbg(&_ssl_conf, my_debug, NULL);
- mbedtls_debug_set_threshold(DEBUG_LEVEL);
-#endif
-
- if ((ret = mbedtls_ssl_setup(&_ssl, &_ssl_conf)) != 0) {
- print_mbedtls_error("mbedtls_ssl_setup", ret);
- _error = ret;
- return _error;
- }
-
- mbedtls_ssl_set_hostname(&_ssl, _hostname);
-
- mbedtls_ssl_set_bio(&_ssl, static_cast<void *>(_tcpsocket),
- ssl_send, ssl_recv, NULL );
-
- /* Connect to the server */
- if (_debug) mbedtls_printf("Connecting to %s:%d\r\n", _hostname, _port);
- ret = _tcpsocket->connect(_hostname, _port);
- if (ret != NSAPI_ERROR_OK) {
- if (_debug) mbedtls_printf("Failed to connect\r\n");
- onError(_tcpsocket, -1);
- return _error;
- }
-
- /* Start the handshake, the rest will be done in onReceive() */
- if (_debug) mbedtls_printf("Starting the TLS handshake...\r\n");
- ret = mbedtls_ssl_handshake(&_ssl);
- if (ret < 0) {
- if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
- ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
- print_mbedtls_error("mbedtls_ssl_handshake", ret);
- onError(_tcpsocket, -1);
- }
- else {
- _error = ret;
- }
- return _error;
- }
-
- /* It also means the handshake is done, time to print info */
- if (_debug) mbedtls_printf("TLS connection to %s:%d established\r\n", _hostname, _port);
-
- const uint32_t buf_size = 1024;
- char buf[buf_size] = { 0 };
- mbedtls_x509_crt_info(buf, buf_size, "\r ",
- mbedtls_ssl_get_peer_cert(&_ssl));
- if (_debug) mbedtls_printf("Server certificate:\r\n%s\r", buf);
-
- uint32_t flags = mbedtls_ssl_get_verify_result(&_ssl);
- if( flags != 0 )
- {
- mbedtls_x509_crt_verify_info(buf, buf_size, "\r ! ", flags);
- if (_debug) mbedtls_printf("Certificate verification failed:\r\n%s\r\r\n", buf);
- }
- else {
- if (_debug) mbedtls_printf("Certificate verification passed\r\n\r\n");
- }
-
- _is_connected = true;
-
- return 0;
- }
-
- bool connected() {
- return _is_connected;
- }
-
- nsapi_error_t error() {
- return _error;
- }
-
- TCPSocket* get_tcp_socket() {
- return _tcpsocket;
- }
-
- mbedtls_ssl_context* get_ssl_context() {
- return &_ssl;
- }
-
- /**
- * Set the debug flag.
- *
- * If this flag is set, debug information from mbed TLS will be logged to stdout.
- */
- void set_debug(bool debug) {
- _debug = debug;
- }
-
-protected:
- /**
- * Helper for pretty-printing mbed TLS error codes
- */
- static void print_mbedtls_error(const char *name, int err) {
- char buf[128];
- mbedtls_strerror(err, buf, sizeof (buf));
- mbedtls_printf("%s() failed: -0x%04x (%d): %s\r\n", name, -err, err, buf);
- }
-
-#if DEBUG_LEVEL > 0
- /**
- * Debug callback for mbed TLS
- * Just prints on the USB serial port
- */
- static void my_debug(void *ctx, int level, const char *file, int line,
- const char *str)
- {
- const char *p, *basename;
- (void) ctx;
-
- /* Extract basename from file */
- for(p = basename = file; *p != '\0'; p++) {
- if(*p == '/' || *p == '\\') {
- basename = p + 1;
- }
- }
-
- if (_debug) {
- mbedtls_printf("%s:%04d: |%d| %s", basename, line, level, str);
- }
- }
-
- /**
- * Certificate verification callback for mbed TLS
- * Here we only use it to display information on each cert in the chain
- */
- static int my_verify(void *data, mbedtls_x509_crt *crt, int depth, uint32_t *flags)
- {
- const uint32_t buf_size = 1024;
- char *buf = new char[buf_size];
- (void) data;
-
- if (_debug) mbedtls_printf("\nVerifying certificate at depth %d:\n", depth);
- mbedtls_x509_crt_info(buf, buf_size - 1, " ", crt);
- if (_debug) mbedtls_printf("%s", buf);
-
- if (*flags == 0)
- if (_debug) mbedtls_printf("No verification issue for this certificate\n");
- else
- {
- mbedtls_x509_crt_verify_info(buf, buf_size, " ! ", *flags);
- if (_debug) mbedtls_printf("%s\n", buf);
- }
-
- delete[] buf;
- return 0;
- }
-#endif
-
- /**
- * Receive callback for mbed TLS
- */
- static int ssl_recv(void *ctx, unsigned char *buf, size_t len) {
- int recv = -1;
- TCPSocket *socket = static_cast<TCPSocket *>(ctx);
- recv = socket->recv(buf, len);
-
- if (NSAPI_ERROR_WOULD_BLOCK == recv) {
- return MBEDTLS_ERR_SSL_WANT_READ;
- }
- else if (recv < 0) {
- return -1;
- }
- else {
- return recv;
- }
- }
-
- /**
- * Send callback for mbed TLS
- */
- static int ssl_send(void *ctx, const unsigned char *buf, size_t len) {
- int size = -1;
- TCPSocket *socket = static_cast<TCPSocket *>(ctx);
- size = socket->send(buf, len);
-
- if(NSAPI_ERROR_WOULD_BLOCK == size) {
- return len;
- }
- else if (size < 0){
- return -1;
- }
- else {
- return size;
- }
- }
-
-private:
- void onError(TCPSocket *s, int error) {
- s->close();
- _error = error;
- }
-
- TCPSocket* _tcpsocket;
-
- const char* DRBG_PERS;
- const char* _ssl_ca_pem;
- const char* _hostname;
- uint16_t _port;
-
- bool _debug;
- bool _is_connected;
-
- nsapi_error_t _error;
-
- mbedtls_entropy_context _entropy;
- mbedtls_ctr_drbg_context _ctr_drbg;
- mbedtls_x509_crt _cacert;
- mbedtls_ssl_context _ssl;
- mbedtls_ssl_config _ssl_conf;
-};
-
-#endif // _MBED_HTTPS_TLS_SOCKET_H_