![](/media/cache/profiles/profile2.jpg.50x50_q85.jpg)
This software setup a central node of a star topology network
Dependencies: MQTT target_st_bluenrg
Fork of ble-star-mbed by
Diff: MQTTNetwork.h
- Revision:
- 4:4af40af2530e
diff -r 3f35e80ed848 -r 4af40af2530e MQTTNetwork.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/MQTTNetwork.h Sat Mar 31 15:10:54 2018 +0000 @@ -0,0 +1,349 @@ +#ifndef _MQTTNETWORK_H_ +#define _MQTTNETWORK_H_ + +#include "NetworkInterface.h" +#include "mbedtls/platform.h" +#include "mbedtls/ssl.h" +#include "mbedtls/entropy.h" +#include "mbedtls/ctr_drbg.h" +#include "mbedtls/error.h" + +/* Change to a number between 1 and 4 to debug the TLS connection */ +#define DEBUG_LEVEL 0 + +#if DEBUG_LEVEL > 0 +#include "mbedtls/debug.h" +#endif + +#define TLS_OFF 0 +#define TLS_ON 1 + +/* personalization string for the drbg */ +const char *DRBG_PERS = "mbed TLS Publisher for IBM Watson IoT"; + +/* List of trusted root CA certificates + * currently only GlobalSign, the CA for os.mbed.com + * + * To add more than one root, just concatenate them. + */ + mbedtls_entropy_context _entropy; + mbedtls_ctr_drbg_context _ctr_drbg; + mbedtls_x509_crt _cacert; + mbedtls_ssl_context _ssl; + mbedtls_ssl_config _ssl_conf; + +class MQTTNetwork { +public: + MQTTNetwork(NetworkInterface *net_iface) : _network(net_iface) { + _tcpsocket = new TCPSocket(); + _tcpsocket->set_blocking(false); + _is_tcpsocket_connected = 0; + } + + ~MQTTNetwork() { + if (_is_tcpsocket_connected && _tls) { + mbedtls_ssl_session_reset( &_ssl ); + 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); + } + _tcpsocket->close(); + delete _tcpsocket; + } + + int read(unsigned char* buffer, int len, int timeout) { + size_t _bpos = 0; int offset = 0; int ret = 0; + if (_tls) { +//_tcpsocket->set_timeout(timeout); + /* Read data out of the socket */ + offset = 0; + Countdown timer; + timer.countdown_ms(timeout); + + do { + ret = mbedtls_ssl_read(&_ssl, buffer + offset, + len - offset ); + if (ret > 0) offset += ret; + if (offset == len) return offset; + if (timer.expired()) return 0; + } while (ret == MBEDTLS_ERR_SSL_WANT_READ || + ret == MBEDTLS_ERR_SSL_WANT_WRITE || ret == 0 ); + if (ret == MBEDTLS_ERR_SSL_CLIENT_RECONNECT) { + print_mbedtls_error("MBEDTLS_ERR_SSL_CLIENT_RECONNECT\n\r", ret); + // int mbedtls_ssl_session_reset( mbedtls_ssl_context *ssl ); + _tcpsocket->close(); + _is_tcpsocket_connected = 0; + return ret; + } + + if (ret < 0) { + print_mbedtls_error("mbedtls_ssl_read", ret); + _tcpsocket->close(); + _is_tcpsocket_connected = 0; + return ret; + } + return ret; + } else { + _tcpsocket->set_blocking(true); + _tcpsocket->set_timeout(timeout); + return _tcpsocket->recv(buffer, len); + } + } + + + int write(unsigned char* buffer, int len, int timeout) { + + size_t _bpos = len; + int offset = 0; int ret = 0; + if (_tls) { + do { + ret = mbedtls_ssl_write(&_ssl, + (const unsigned char *) buffer + offset, + _bpos - offset); + if (ret > 0) + offset += ret; + } while (offset < _bpos && (ret > 0 || ret == MBEDTLS_ERR_SSL_WANT_READ || + ret == MBEDTLS_ERR_SSL_WANT_WRITE)); + if (ret < 0) { + print_mbedtls_error("mbedtls_ssl_write", ret); + _tcpsocket->close(); + _is_tcpsocket_connected = 0; + return ret; + } + return ret; + } else { + _tcpsocket->set_blocking(true); + _tcpsocket->set_timeout(timeout); + return _tcpsocket->send(buffer, len); + } + } + + int connect(const char* hostname, int port, unsigned int tls=TLS_OFF, const char * cert=NULL, unsigned int sizeof_cert=0) { + _tls = tls; + if (tls == TLS_ON) { printf ("--->TLS is ON\n\r");}; + if (tls == TLS_ON) { + 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); + /* + * Initialize TLS-related stuf. + */ + int ret = 0; + 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); + return ret; + } + if ((ret = mbedtls_x509_crt_parse(&_cacert, (const unsigned char *) cert, + sizeof_cert)) != 0) { + print_mbedtls_error("mbedtls_x509_crt_parse", ret); + return ret; + } + 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); + return ret; + } + 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); + return ret; + } + mbedtls_ssl_set_hostname(&_ssl, hostname); + + mbedtls_ssl_set_bio(&_ssl, static_cast<void *>(_tcpsocket), ssl_send, ssl_recv, NULL ); + /* Connect to the server */ + _tcpsocket->open(_network); + mbedtls_printf("Connecting with %s port: %d\n", hostname, port); + ret = _tcpsocket->connect(hostname, port); + if (ret != NSAPI_ERROR_OK) { + mbedtls_printf("Failed to connect\n"); + printf("MBED: Socket Error: %d\n", ret); + _tcpsocket->close(); + return ret; + } + printf ("--->TCP Connected\n\r"); + _is_tcpsocket_connected = 1; + + /* Start the handshake, the rest will be done in onReceive() */ + mbedtls_printf("Starting the TLS handshake...\n"); + do { + ret = mbedtls_ssl_handshake(&_ssl); + } while (ret != 0 && (ret == MBEDTLS_ERR_SSL_WANT_READ || + ret == MBEDTLS_ERR_SSL_WANT_WRITE)); + if (ret < 0) { + print_mbedtls_error("mbedtls_ssl_handshake", ret); + _tcpsocket->close(); + return ret; + } +/* const uint32_t buf_size = 1024; + char *buf = new char[buf_size]; + mbedtls_x509_crt_info(buf, buf_size, "\r ", + mbedtls_ssl_get_peer_cert(&_ssl)); + mbedtls_printf("Server certificate:\n%s", buf); + + uint32_t flags = mbedtls_ssl_get_verify_result(&_ssl); + if( flags != 0 ) + { + mbedtls_x509_crt_verify_info(buf, buf_size, "\r ! ", flags); + printf("Certificate verification failed:\n%s\n", buf); + } + else + printf("Certificate verification passed\n\n"); +*/ + _is_tcpsocket_connected = 1; + return ret; + + } else { // tls off + printf ("\r\n--->TLS is OFF\n"); + _tcpsocket->open(_network); + int ret = _tcpsocket->connect(hostname, port); + if (ret != NSAPI_ERROR_OK) { + mbedtls_printf("\r\nFailed to connect\n"); + printf("\r\nMBED: Socket Error: %d\n", ret); + _tcpsocket->close(); + return ret; + } + printf ("\r\n--->TCP Connected\n"); + _is_tcpsocket_connected = 1; + return ret; + } + } + + int disconnect() { + if (_is_tcpsocket_connected && _tls == TLS_ON) { + mbedtls_ssl_session_reset( &_ssl ); + 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); + } + _is_tcpsocket_connected = 0; + return _tcpsocket->close(); + } + + bool isConnected () { return _is_tcpsocket_connected; } + +private: + NetworkInterface* _network; + unsigned int _is_tcpsocket_connected; + +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\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; + } + } + + 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; + + mbedtls_printf("\nVerifying certificate at depth %d:\n", depth); + mbedtls_x509_crt_info(buf, buf_size - 1, " ", crt); + mbedtls_printf("%s", buf); + + if (*flags == 0) + mbedtls_printf("No verification issue for this certificate\n"); + else + { + mbedtls_x509_crt_verify_info(buf, buf_size, " ! ", *flags); + 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){ + mbedtls_printf("Socket recv error %d\n", recv); + 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 MBEDTLS_ERR_SSL_WANT_WRITE; + }else if(size < 0){ + mbedtls_printf("Socket send error %d\n", size); + return -1; + }else{ + return size; + } + } + + TCPSocket* _tcpsocket; + volatile bool _disconnected; + unsigned int _tls; +}; + + +#endif // _MQTTNETWORK_H_