Experimental HTTP and HTTPS library for mbed OS 5

Dependents:   MQTTGateway2 MQTTGatewayK64 http-example-wnc GuardRoom ... more

For the example program, see: sandbox/http-example.

This library is used to make HTTP and HTTPS calls from Mbed OS 5 applications.

HTTP Request API

NetworkInterface* network = /* obtain a NetworkInterface object */

const char body[] = "{\"hello\":\"world\"}";

HttpRequest* request = new HttpRequest(network, HTTP_POST, "http://httpbin.org/post");
request->set_header("Content-Type", "application/json");
HttpResponse* response = request->send(body, strlen(body));
// if response is NULL, check response->get_error()

printf("status is %d - %s\n", response->get_status_code(), response->get_status_message());
printf("body is:\n%s\n", response->get_body_as_string().c_str());

delete request; // also clears out the response

HTTPS Request API

// pass in the root certificates that you trust, there is no central CA registry in Mbed OS
const char SSL_CA_PEM[] = "-----BEGIN CERTIFICATE-----\n"
    /* rest of the CA root certificates */;

NetworkInterface* network = /* obtain a NetworkInterface object */

const char body[] = "{\"hello\":\"world\"}";

HttpsRequest* request = new HttpsRequest(network, SSL_CA_PEM, HTTP_GET "https://httpbin.org/status/418");
HttpResponse* response = request->send();
// if response is NULL, check response->get_error()

printf("status is %d - %s\n", response->get_status_code(), response->get_status_message());
printf("body is:\n%s\n", response->get_body().c_str());

delete request;

Note: You can get the root CA for a domain easily from Firefox. Click on the green padlock, click More information > Security > View certificate > Details. Select the top entry in the 'Certificate Hierarchy' and click Export.... This gives you a PEM file. Add the content of the PEM file to your root CA list (here's an image).

Mbed TLS Entropy configuration

If your target does not have a built-in TRNG, or other entropy sources, add the following macros to your mbed_app.json file to disable entropy:

{
    "macros": [
        "MBEDTLS_TEST_NULL_ENTROPY",
        "MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES"
    ]
}

Note that this is not secure, and you should not deploy this device into production with this configuration.

Memory usage

Small requests where the body of the response is cached by the library (like the one found in main-http.cpp), require 4K of RAM. When the request is finished they require 1.5K of RAM, depending on the size of the response. This applies both to HTTP and HTTPS. If you need to handle requests that return a large response body, see 'Dealing with large body'.

HTTPS requires additional memory: on FRDM-K64F about 50K of heap space (at its peak). This means that you cannot use HTTPS on devices with less than 128K of memory, as you also need to reserve memory for the stack and network interface.

Dealing with large response body

By default the library will store the full request body on the heap. This works well for small responses, but you'll run out of memory when receiving a large response body. To mitigate this you can pass in a callback as the last argument to the request constructor. This callback will be called whenever a chunk of the body is received. You can set the request chunk size in the HTTP_RECEIVE_BUFFER_SIZE macro (see mbed_lib.json for the definition) although it also depends on the buffer size of the underlying network connection.

void body_callback(const char* data, uint32_t data_len) {
    // do something with the data
}

HttpRequest* req = new HttpRequest(network, HTTP_GET, "http://pathtolargefile.com", &body_callback);
req->send(NULL, 0);

Dealing with a large request body

If you cannot load the full request into memory, you can pass a callback into the send function. Through this callback you can feed in chunks of the request body. This is very useful if you want to send files from a file system.

const void * get_chunk(uint32_t* out_size) {
    // set the value of out_size (via *out_size = 10) to the size of the buffer
    // return the buffer

    // if you don't have any more data, set *out_size to 0
}

HttpRequest* req = new HttpRequest(network, HTTP_POST, "http://my_api.com/upload");
req->send(callback(&get_chunk));

Socket re-use

By default the library opens a new socket per request. This is wasteful, especially when dealing with TLS requests. You can re-use sockets like this:

HTTP

TCPSocket* socket = new TCPSocket();

nsapi_error_t open_result = socket->open(network);
// check open_result

nsapi_error_t connect_result = socket->connect("httpbin.org", 80);
// check connect_result

// Pass in `socket`, instead of `network` as first argument
HttpRequest* req = new HttpRequest(socket, HTTP_GET, "http://httpbin.org/status/418");

HTTPS

TLSSocket* socket = new TLSSocket();

nsapi_error_t r;
// make sure to check the return values for the calls below (should return NSAPI_ERROR_OK)
r = socket->open(network);
r = socket->set_root_ca_cert(SSL_CA_PEM);
r = 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.

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.

Files at this revision

API Documentation at this revision

Comitter:
Jan Jongboom
Date:
Tue Oct 30 11:02:12 2018 +0800
Parent:
30:3ad153a3fdfd
Parent:
31:b3730a2c4f39
Commit message:
Update to use TLSSocket from upstream Mbed OS

Changed in this revision

README.md Show annotated file Show diff for this revision Revisions of this file
http_parser/http_parser.h Show annotated file Show diff for this revision Revisions of this file
mbed_lib.json Show annotated file Show diff for this revision Revisions of this file
source/http_request.h Show annotated file Show diff for this revision Revisions of this file
source/http_request_builder.h Show annotated file Show diff for this revision Revisions of this file
source/http_response.h Show annotated file Show diff for this revision Revisions of this file
source/https_request.h Show annotated file Show diff for this revision Revisions of this file
source/tls_socket.h Show diff for this revision Revisions of this file
--- a/README.md	Thu Sep 06 14:01:09 2018 -0500
+++ b/README.md	Tue Oct 30 11:02:12 2018 +0800
@@ -43,16 +43,26 @@
 
 **Note:** You can get the root CA for a domain easily from Firefox. Click on the green padlock, click *More information > Security > View certificate > Details*. Select the top entry in the 'Certificate Hierarchy' and click *Export...*. This gives you a PEM file. Add the content of the PEM file to your root CA list ([here's an image](img/root-ca-selection.png)).
 
+### Mbed TLS Entropy configuration
+
+If your target does not have a built-in TRNG, or other entropy sources, add the following macros to your `mbed_app.json` file to disable entropy:
+
+```json
+{
+    "macros": [
+        "MBEDTLS_TEST_NULL_ENTROPY",
+        "MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES"
+    ]
+}
+```
+
+Note that this is **not** secure, and you should not deploy this device into production with this configuration.
+
 ## Memory usage
 
 Small requests where the body of the response is cached by the library (like the one found in main-http.cpp), require ~4K of RAM. When the request is finished they require ~1.5K of RAM, depending on the size of the response. This applies both to HTTP and HTTPS. If you need to handle requests that return a large response body, see 'Dealing with large body'.
 
-HTTPS requires additional memory. On FRDM-K64F:
-
-* TLS handshake requires 53K of heap space.
-* Keeping TLS socket open requires 43K of heap space.
-
-This means that you cannot use HTTPS on devices with less than 128K of memory, as you also need to reserve memory for the stack and network interface.
+HTTPS requires additional memory: on FRDM-K64F about 50K of heap space (at its peak). This means that you cannot use HTTPS on devices with less than 128K of memory, as you also need to reserve memory for the stack and network interface.
 
 ### Dealing with large response body
 
@@ -105,70 +115,32 @@
 ### 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();
+
+nsapi_error_t r;
+// make sure to check the return values for the calls below (should return NSAPI_ERROR_OK)
+r = socket->open(network);
+r = socket->set_root_ca_cert(SSL_CA_PEM);
+r = 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");
 ```
 
-**Note:** For HTTPS, if you are using a **K64F**, **K22F**, or **ODIN-W2** target, you will need to include the following `mbedtls_entropy_config.h` file to enable Mbed TLS entropy (placed in the root directory of your application):
+## 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
-/* Enable entropy for K64F, K22F, ODIN-W2. This means entropy is disabled for all other targets. */
-/* Do **NOT** deploy this code in production on other targets! */
-/* See https://tls.mbed.org/kb/how-to/add-entropy-sources-to-entropy-pool */
-#if defined(TARGET_K64F) || defined(TARGET_K22F) || defined(TARGET_UBLOX_EVK_ODIN_W2)
-#undef MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES
-#undef MBEDTLS_TEST_NULL_ENTROPY
-#endif
-
-#if !defined(MBEDTLS_ENTROPY_HARDWARE_ALT) && \
-    !defined(MBEDTLS_ENTROPY_NV_SEED) && !defined(MBEDTLS_TEST_NULL_ENTROPY)
-#error "This hardware does not have an entropy source."
-#endif /* !MBEDTLS_ENTROPY_HARDWARE_ALT && !MBEDTLS_ENTROPY_NV_SEED &&
-        * !MBEDTLS_TEST_NULL_ENTROPY */
-
-#if !defined(MBEDTLS_SHA1_C)
-#define MBEDTLS_SHA1_C
-#endif /* !MBEDTLS_SHA1_C */
-
-#if !defined(MBEDTLS_RSA_C)
-#define MBEDTLS_RSA_C
-#endif /* !MBEDTLS_RSA_C */
+uint8_t *request_buffer = (uint8_t*)calloc(2048, 1);
+req->set_request_log_buffer(request_buffer, 2048);
 
-/*
- *  This value is sufficient for handling 2048 bit RSA keys.
- *
- *  Set this value higher to enable handling larger keys, but be aware that this
- *  will increase the stack usage.
- */
-#define MBEDTLS_MPI_MAX_SIZE        1024
-
-#define MBEDTLS_MPI_WINDOW_SIZE     1
-```
-
-You will also need to enable a custom user config file macro in an `mbed_app.json` file (placed in the root of your application):
-
-```json
-{
-    "macros": ["MBEDTLS_USER_CONFIG_FILE=\"mbedtls_entropy_config.h\"",
-               "MBEDTLS_TEST_NULL_ENTROPY", "MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES" ]
+// 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]);
 }
-```
-
-You will also need to include an `mbedtls_config.h` file in the root directory of your application: [`mbedtls_config.h`](https://os.mbed.com/teams/sandbox/code/http-example/file/5ad8f931e4ff/mbedtls_config.h)
-
-For all other targets, you will need the following macro present in an `mbed_app.json` file (placed in the root of your application):
-
-```json
-{
-    "macros": ["MBEDTLS_TEST_NULL_ENTROPY", "MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES" ]
-}
+printf("\n");
 ```
 
 ## Tested on
@@ -177,5 +149,6 @@
 * NUCLEO_F411RE with ESP8266.
 * ODIN-W2 with WiFi.
 * K64F with Atmel 6LoWPAN shield.
+* [Mbed Simulator](https://github.com/janjongboom/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 11:02:12 2018 +0800
@@ -0,0 +1,1 @@
+https://github.com/ARMmbed/TLSSocket/#7118d69699e6779dc5de519c75669e722bd78ba0
--- a/http_parser/http_parser.h	Thu Sep 06 14:01:09 2018 -0500
+++ b/http_parser/http_parser.h	Tue Oct 30 11:02:12 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
 
-#include "stdlib.h"
-
 #if defined(_WIN32) && !defined(__MINGW32__) && \
   (!defined(_MSC_VER) || _MSC_VER<1600) && !defined(__WINE__)
 #include <BaseTsd.h>
--- a/mbed_lib.json	Thu Sep 06 14:01:09 2018 -0500
+++ b/mbed_lib.json	Tue Oct 30 11:02:12 2018 +0800
@@ -1,5 +1,8 @@
 {
     "name": "mbed-http",
+    "macros": [
+        "MBEDTLS_SHA1_C"
+    ],
     "config": {
         "http-buffer-size": {
             "help": "Size of the HTTP receive buffer in bytes",
--- a/source/http_request.h	Thu Sep 06 14:01:09 2018 -0500
+++ b/source/http_request.h	Tue Oct 30 11:02:12 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, uint32_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, uint32_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;
-        }
-
-        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();
+        _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*(uint32_t*)> body_cb) {
-
-        nsapi_error_t ret;
-
-        if ((ret = open_socket()) != NSAPI_ERROR_OK) {
-            error = ret;
-            return NULL;
-        }
-
-        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...
-            uint32_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, uint32_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
-            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;
+    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, uint32_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 11:02:12 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	Thu Sep 06 14:01:09 2018 -0500
+++ b/source/http_request_builder.h	Tue Oct 30 11:02:12 2018 +0800
@@ -58,14 +58,14 @@
         }
     }
 
-    char* build(const void* body, unsigned int body_size, uint32_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));
         }
 
--- a/source/https_request.h	Thu Sep 06 14:01:09 2018 -0500
+++ b/source/https_request.h	Tue Oct 30 11:02:12 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, 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;
     }
 
     /**
@@ -80,309 +77,22 @@
                  http_method method,
                  const char* url,
                  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;
-        }
-
-        uint32_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*(uint32_t*)> body_cb) {
-
-        nsapi_error_t ret;
-
-        if ((ret = open_socket()) != NSAPI_ERROR_OK) {
-            _error = ret;
-            return NULL;
-        }
-
-        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((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) {
-            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...
-            uint32_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, uint32_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
-            uint32_t _bpos = static_cast<uint32_t>(ret);
-            recv_buffer[_bpos] = 0;
-
-            uint32_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, uint32_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	Thu Sep 06 14:01:09 2018 -0500
+++ /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_