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, asyou 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 ofthe 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");

Integration tests

Integration tests are located in the TESTS folder and are ran through Greentea. Instructions on how to run the tests are in http-example.

Mbed OS 5.10 or lower

If you want to use this library on Mbed OS 5.10 or lower, you need to add the TLSSocket library to your project. This library is included in Mbed OS 5.11 and up.

Tested on

  • K64F with Ethernet.
  • NUCLEO_F411RE with ESP8266.
  • ODIN-W2 with WiFi.
  • K64F with Atmel 6LoWPAN shield.
  • DISCO-L475VG-IOT01A with WiFi.
  • Mbed Simulator.
Revision:
32:fa4d71265625
Parent:
29:383e9bfbfbed
Parent:
31:b3730a2c4f39
Child:
36:d46da03715db
--- 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_