diff --git a/Sming/SmingCore/Network/FTPServer.cpp b/Sming/SmingCore/Network/FTPServer.cpp index 3699f2ef12..7865946130 100644 --- a/Sming/SmingCore/Network/FTPServer.cpp +++ b/Sming/SmingCore/Network/FTPServer.cpp @@ -11,7 +11,7 @@ #include "HttpResponse.h" #include "FTPServerConnection.h" #include "TcpClient.h" -#include "../Wiring/WString.h" +#include "WString.h" FTPServer::FTPServer() { @@ -28,13 +28,13 @@ TcpConnection* FTPServer::createClient(tcp_pcb* clientTcp) return con; } -void FTPServer::addUser(String login, String pass) +void FTPServer::addUser(const String& login, const String& pass) { debug_d("addUser: %s %s", login.c_str(), pass.c_str()); users[login] = pass; } -bool FTPServer::checkUser(String login, const String& pass) +bool FTPServer::checkUser(const String& login, const String& pass) { debug_d("checkUser: %s %s", login.c_str(), pass.c_str()); if(!users.contains(login)) @@ -47,7 +47,7 @@ bool FTPServer::onCommand(String cmd, String data, FTPServerConnection& connecti { if(cmd == "FSFORMAT") { spiffs_format(); - connection.response(200, "File system successfully formated"); + connection.response(200, F("File system successfully formatted")); return true; } return false; diff --git a/Sming/SmingCore/Network/FTPServer.h b/Sming/SmingCore/Network/FTPServer.h index fe9f315871..8432e4ba97 100644 --- a/Sming/SmingCore/Network/FTPServer.h +++ b/Sming/SmingCore/Network/FTPServer.h @@ -15,9 +15,9 @@ #define _SMING_CORE_FTPSERVER_H_ #include "TcpServer.h" -#include "../../Wiring/WHashMap.h" -#include "../../Wiring/WVector.h" -#include "../../Wiring/WString.h" +#include "WHashMap.h" +#include "WVector.h" +#include "WString.h" class FTPServerConnection; @@ -29,8 +29,8 @@ class FTPServer : public TcpServer FTPServer(); virtual ~FTPServer(); - void addUser(String login, String pass); - bool checkUser(String login, const String& pass); + void addUser(const String& login, const String& pass); + bool checkUser(const String& login, const String& pass); protected: virtual TcpConnection* createClient(tcp_pcb* clientTcp); diff --git a/Sming/SmingCore/Network/FTPServerConnection.cpp b/Sming/SmingCore/Network/FTPServerConnection.cpp index 135c73a7db..3c092f7900 100644 --- a/Sming/SmingCore/Network/FTPServerConnection.cpp +++ b/Sming/SmingCore/Network/FTPServerConnection.cpp @@ -2,60 +2,69 @@ #include "FTPServer.h" #include "NetUtils.h" #include "TcpConnection.h" -#include "../FileSystem.h" +#include "FileSystem.h" class FTPDataStream : public TcpConnection { public: - FTPDataStream(FTPServerConnection* connection) - : TcpConnection(true), parent(connection), completed(false), sent(0), written(0) + FTPDataStream(FTPServerConnection* connection) : TcpConnection(true), parent(connection) { } + virtual err_t onConnected(err_t err) { //response(125, "Connected"); setTimeOut(300); // Update timeout return TcpConnection::onConnected(err); } + virtual err_t onSent(uint16_t len) { sent += len; - if(written < sent || !completed) + if(written < sent || !completed) { return TcpConnection::onSent(len); + } finishTransfer(); return TcpConnection::onSent(len); } + void finishTransfer() { close(); parent->dataTransferFinished(this); } - void response(int code, String text = "") + + void response(int code, String text = nullptr) { parent->response(code, text); } + int write(const char* data, int len, uint8_t apiflags = 0) { written += len; return TcpConnection::write(data, len, apiflags); } + virtual void onReadyToSendData(TcpConnectionEvent sourceEvent) { - if(!parent->isCanTransfer()) + if(!parent->isCanTransfer()) { return; - if(completed && written == 0) + } + if(completed && written == 0) { finishTransfer(); + } transferData(sourceEvent); } + virtual void transferData(TcpConnectionEvent sourceEvent) { } protected: - FTPServerConnection* parent; - bool completed; - int written; - int sent; + FTPServerConnection* parent = nullptr; + bool completed = false; + unsigned written = 0; + unsigned sent = 0; }; class FTPDataFileList : public FTPDataStream @@ -64,14 +73,17 @@ class FTPDataFileList : public FTPDataStream FTPDataFileList(FTPServerConnection* connection) : FTPDataStream(connection) { } + virtual void transferData(TcpConnectionEvent sourceEvent) { - if(completed) + if(completed) { return; + } Vector list = fileList(); debug_d("send file list: %d", list.count()); - for(int i = 0; i < list.count(); i++) + for(unsigned i = 0; i < list.count(); i++) { writeString("01-01-15 01:00AM " + String(fileGetSize(list[i])) + " " + list[i] + "\r\n"); + } completed = true; finishTransfer(); } @@ -84,14 +96,17 @@ class FTPDataRetrieve : public FTPDataStream { file = fileOpen(fileName, eFO_ReadOnly); } + ~FTPDataRetrieve() { fileClose(file); } + virtual void transferData(TcpConnectionEvent sourceEvent) { - if(completed) + if(completed) { return; + } char buf[1024]; int len = fileRead(file, buf, 1024); write(buf, len, TCP_WRITE_FLAG_COPY); @@ -112,23 +127,26 @@ class FTPDataStore : public FTPDataStream { file = fileOpen(fileName, eFO_WriteOnly | eFO_CreateNewAlways); } + ~FTPDataStore() { fileClose(file); } + virtual err_t onReceive(pbuf* buf) { - if(completed) + if(completed) { return TcpConnection::onReceive(buf); + } - if(buf == NULL) { + if(buf == nullptr) { completed = true; response(226, "Transfer completed"); return TcpConnection::onReceive(buf); } pbuf* cur = buf; - while(cur != NULL && cur->len > 0) { + while(cur != nullptr && cur->len > 0) { fileWrite(file, (uint8_t*)cur->payload, cur->len); cur = cur->next; } @@ -142,47 +160,38 @@ class FTPDataStore : public FTPDataStream /////////////////////////////////////////////////////////////////////////////////////////////////////////// -FTPServerConnection::FTPServerConnection(FTPServer* parentServer, tcp_pcb* clientTcp) - : TcpConnection(clientTcp, true), server(parentServer), state(eFCS_Ready) -{ - dataConnection = NULL; - port = 0; - canTransfer = true; -} - -FTPServerConnection::~FTPServerConnection() -{ -} - err_t FTPServerConnection::onReceive(pbuf* buf) { - if(buf == NULL) + if(buf == nullptr) return ERR_OK; int p = 0, prev = 0; while(true) { p = NetUtils::pbufFindStr(buf, "\r\n", prev); - if(p == -1 || p - prev > MAX_FTP_CMD) + if(p < 0 || p - prev > MAX_FTP_CMD) { break; + } int split = NetUtils::pbufFindChar(buf, ' ', prev); String cmd, data; - if(split != -1 && split < p) { + if(split >= 0 && split < p) { cmd = NetUtils::pbufStrCopy(buf, prev, split - prev); split++; data = NetUtils::pbufStrCopy(buf, split, p - split); - } else + } else { cmd = NetUtils::pbufStrCopy(buf, prev, p - prev); + } debug_d("%s: '%s'", cmd.c_str(), data.c_str()); onCommand(cmd, data); prev = p + 1; - }; + } + return ERR_OK; } void FTPServerConnection::cmdPort(const String& data) { int last = getSplitterPos(data, ',', 4); - if(last == -1) { + if(last < 0) { response(550); // Invalid arguments //return; } @@ -297,13 +306,15 @@ err_t FTPServerConnection::onSent(uint16_t len) String FTPServerConnection::makeFileName(String name, bool shortIt) { - if(name.startsWith("/")) + if(name.startsWith("/")) { name = name.substring(1); + } if(shortIt && name.length() > 20) { String ext = ""; - if(name.lastIndexOf('.') != -1) + if(name.lastIndexOf('.') != -1) { ext = name.substring(name.lastIndexOf('.')); + } return name.substring(0, 16) + ext; } @@ -319,10 +330,11 @@ void FTPServerConnection::createDataConnection(TcpConnection* connection) void FTPServerConnection::dataTransferFinished(TcpConnection* connection) { - if(connection != dataConnection) + if(connection != dataConnection) { SYSTEM_ERROR("FTP Wrong state: connection != dataConnection"); + } - dataConnection = NULL; + dataConnection = nullptr; response(226, F("Transfer Complete.")); } @@ -330,7 +342,7 @@ int FTPServerConnection::getSplitterPos(String data, char splitter, uint8_t numb { uint8_t k = 0; - for(int i = 0; i < data.length(); i++) { + for(unsigned i = 0; i < data.length(); i++) { if(data[i] == splitter) { if(k == number) { return i; @@ -346,16 +358,18 @@ void FTPServerConnection::response(int code, String text /* = "" */) { String response = String(code, DEC); if(text.length() == 0) { - if(code >= 200 && code <= 399) // Just for simplify + if(code >= 200 && code <= 399) { // Just for simplify response += _F(" OK"); - else + } else { response += _F(" FAIL"); - } else + } + } else { response += ' ' + text; + } response += "\r\n"; debug_d("> %s", response.c_str()); - writeString(response.c_str(), TCP_WRITE_FLAG_COPY); // Dynamic memory, should copy + writeString(response, TCP_WRITE_FLAG_COPY); // Dynamic memory, should copy canTransfer = false; flush(); } diff --git a/Sming/SmingCore/Network/FTPServerConnection.h b/Sming/SmingCore/Network/FTPServerConnection.h index 9d7db65521..720393f687 100644 --- a/Sming/SmingCore/Network/FTPServerConnection.h +++ b/Sming/SmingCore/Network/FTPServerConnection.h @@ -2,8 +2,8 @@ #define SMINGCORE_NETWORK_FTPSERVERCONNECTION_H_ #include "TcpConnection.h" -#include "../../Wiring/IPAddress.h" -#include "../Wiring/WString.h" +#include "IPAddress.h" +#include "WString.h" #define MAX_FTP_CMD 255 @@ -17,8 +17,14 @@ class FTPServerConnection : public TcpConnection friend class FTPServer; public: - FTPServerConnection(FTPServer* parentServer, tcp_pcb* clientTcp); - virtual ~FTPServerConnection(); + FTPServerConnection(FTPServer* parentServer, tcp_pcb* clientTcp) + : TcpConnection(clientTcp, true), server(parentServer), state(eFCS_Ready) + { + } + + virtual ~FTPServerConnection() + { + } virtual err_t onReceive(pbuf* buf); virtual err_t onSent(uint16_t len); @@ -46,9 +52,9 @@ class FTPServerConnection : public TcpConnection String renameFrom; IPAddress ip; - int port; - TcpConnection* dataConnection; - bool canTransfer; + int port = 0; + TcpConnection* dataConnection = nullptr; + bool canTransfer = true; }; #endif /* SMINGCORE_NETWORK_FTPSERVERCONNECTION_H_ */ diff --git a/Sming/SmingCore/Network/MqttClient.cpp b/Sming/SmingCore/Network/MqttClient.cpp index ccc7550902..e8125c6882 100644 --- a/Sming/SmingCore/Network/MqttClient.cpp +++ b/Sming/SmingCore/Network/MqttClient.cpp @@ -13,22 +13,28 @@ #include "../Clock.h" #include -#define COPY_STRING(TO, FROM) \ - { \ - TO.length = FROM.length(); \ - TO.data = (uint8_t*)malloc(FROM.length()); \ - if(!TO.data) { \ - debug_e("Not enough memory"); \ - return false; \ - } \ - memcpy(TO.data, FROM.c_str(), FROM.length()); \ - } - #define MQTT_PUBLISH_STREAM 0 mqtt_serialiser_t MqttClient::serialiser; mqtt_parser_callbacks_t MqttClient::callbacks; +static bool copyString(mqtt_buffer_t& destBuffer, const String& sourceString) +{ + destBuffer.length = sourceString.length(); + destBuffer.data = (uint8_t*)malloc(sourceString.length()); + if(destBuffer.data == nullptr) { + debug_e("Not enough memory"); + return false; + } + memcpy(destBuffer.data, sourceString.c_str(), sourceString.length()); + return true; +} + +#define COPY_STRING(TO, FROM) \ + if(!copyString(TO, FROM)) { \ + return false; \ + } + MqttClient::MqttClient(bool withDefaultPayloadParser /* = true */, bool autoDestruct /* = false*/) : TcpClient(autoDestruct) { @@ -64,7 +70,7 @@ MqttClient::~MqttClient() } mqtt_message_clear(&connectMessage, 0); - if(outgoingMessage) { + if(outgoingMessage != nullptr) { mqtt_message_clear(outgoingMessage, 1); outgoingMessage = nullptr; } @@ -161,17 +167,7 @@ int MqttClient::staticOnMessageEnd(void* userData, mqtt_message_t* message) return 0; } -void MqttClient::setEventHandler(mqtt_type_t type, MqttDelegate handler) -{ - eventHandler[type] = handler; -} - -void MqttClient::setKeepAlive(uint16_t seconds) -{ - keepAlive = seconds; -} - -void MqttClient::setPingRepeatTime(int seconds) +void MqttClient::setPingRepeatTime(unsigned seconds) { if(pingRepeatTime > keepAlive) { pingRepeatTime = keepAlive; @@ -213,7 +209,7 @@ bool MqttClient::connect(const URL& url, const String& clientName, uint32_t sslO debug_d("MQTT start connection"); - String protocolName = "MQTT"; + String protocolName = F("MQTT"); COPY_STRING(connectMessage.connect.protocol_name, protocolName); connectMessage.connect.keep_alive = keepAlive; diff --git a/Sming/SmingCore/Network/MqttClient.h b/Sming/SmingCore/Network/MqttClient.h index 6941ce174b..ffa642965a 100644 --- a/Sming/SmingCore/Network/MqttClient.h +++ b/Sming/SmingCore/Network/MqttClient.h @@ -9,15 +9,14 @@ #define _SMING_CORE_NETWORK_MqttClient_H_ #include "TcpClient.h" -#include "../Network/URL.h" -#include "../../Wiring/WString.h" -#include "../../Wiring/WHashMap.h" +#include "URL.h" +#include "WString.h" +#include "WHashMap.h" #include "Data/ObjectQueue.h" #include "Mqtt/MqttPayloadParser.h" #include "../mqtt-codec/src/message.h" #include "../mqtt-codec/src/serialiser.h" #include "../mqtt-codec/src/parser.h" -#include /** @defgroup mqttclient MQTT client * @brief Provides MQTT client @@ -67,13 +66,16 @@ class MqttClient : protected TcpClient * Sets keep-alive time. That information is sent during connection to the server * @param uint16_t seconds */ - void setKeepAlive(uint16_t seconds); //send to broker + void setKeepAlive(uint16_t seconds) //send to broker + { + keepAlive = seconds; + } /** * Sets the interval in which to ping the remote server if there was no activity - * @param int seconds + * @param unsigned int seconds */ - void setPingRepeatTime(int seconds); + void setPingRepeatTime(unsigned seconds); /** * Sets last will and testament @@ -95,7 +97,10 @@ class MqttClient : protected TcpClient bool subscribe(const String& topic); bool unsubscribe(const String& topic); - void setEventHandler(mqtt_type_t type, MqttDelegate handler); + void setEventHandler(mqtt_type_t type, MqttDelegate handler) + { + eventHandler[type] = handler; + } /** * Sets or clears a payload parser (for PUBLISH messages from the server to us) @@ -259,7 +264,7 @@ class MqttClient : protected TcpClient /* @deprecated This method is only for compatibility with the previous release and will be removed soon. */ static int onPublish(MqttClient& client, mqtt_message_t* message) { - if(!message) { + if(message == nullptr) { return -1; } @@ -293,7 +298,7 @@ class MqttClient : protected TcpClient // keep-alives and pings uint16_t keepAlive = 60; - int pingRepeatTime = 20; + unsigned pingRepeatTime = 20; unsigned long lastMessage = 0; // messages @@ -316,9 +321,9 @@ class MqttClient : protected TcpClient #ifndef MQTT_NO_COMPAT // @deprecated - MqttMessageDeliveredCallback onDelivery = 0; + MqttMessageDeliveredCallback onDelivery = nullptr; // @deprecated - MqttStringSubscriptionCallback subscriptionCallback = 0; + MqttStringSubscriptionCallback subscriptionCallback = nullptr; #endif }; diff --git a/Sming/SmingCore/Network/NetUtils.h b/Sming/SmingCore/Network/NetUtils.h index ca063e9ff8..4681435154 100644 --- a/Sming/SmingCore/Network/NetUtils.h +++ b/Sming/SmingCore/Network/NetUtils.h @@ -14,12 +14,6 @@ struct pbuf; class String; -class TcpConnection; - -struct DnsLookup { - TcpConnection* con; - int port; -}; class NetUtils { diff --git a/Sming/SmingCore/Network/SmtpClient.cpp b/Sming/SmingCore/Network/SmtpClient.cpp index 4429337b0b..a945e59631 100644 --- a/Sming/SmingCore/Network/SmtpClient.cpp +++ b/Sming/SmingCore/Network/SmtpClient.cpp @@ -402,7 +402,7 @@ int SmtpClient::smtpParse(char* buffer, size_t len) if(!useSsl && (options & SMTP_OPT_STARTTLS)) { useSsl = true; - TcpConnection::staticOnConnected((void*)this, tcp, ERR_OK); + TcpConnection::internalOnConnected(ERR_OK); } sendString(F("EHLO ") + url.Host + "\r\n"); @@ -424,9 +424,6 @@ int SmtpClient::smtpParse(char* buffer, size_t len) // Process authentication methods // Ex: 250-AUTH CRAM-MD5 PLAIN LOGIN // See: https://tools.ietf.org/html/rfc4954 - int offset = 0; - int pos = -1; - String text(line + 5, lineLength - 5); splitString(text, ' ', authMethods); } diff --git a/Sming/SmingCore/Network/TcpClient.cpp b/Sming/SmingCore/Network/TcpClient.cpp index 06e7142367..3bb33e4b2f 100644 --- a/Sming/SmingCore/Network/TcpClient.cpp +++ b/Sming/SmingCore/Network/TcpClient.cpp @@ -8,48 +8,6 @@ #include "TcpClient.h" #include "Data/Stream/MemoryDataStream.h" -TcpClient::TcpClient(tcp_pcb* clientTcp, TcpClientDataDelegate clientReceive, TcpClientCompleteDelegate onCompleted) - : TcpConnection(clientTcp, true), state(eTCS_Connected) -{ - completed = onCompleted; - receive = clientReceive; - timeOut = TCP_CLIENT_TIMEOUT; -} - -TcpClient::TcpClient(bool autoDestruct) : TcpConnection(autoDestruct), state(eTCS_Ready) -{ - timeOut = TCP_CLIENT_TIMEOUT; -} - -TcpClient::TcpClient(TcpClientCompleteDelegate onCompleted, TcpClientEventDelegate onReadyToSend, - TcpClientDataDelegate onReceive) - : TcpConnection(false), state(eTCS_Ready) -{ - completed = onCompleted; - ready = onReadyToSend; - receive = onReceive; - timeOut = TCP_CLIENT_TIMEOUT; -} - -TcpClient::TcpClient(TcpClientCompleteDelegate onCompleted, TcpClientDataDelegate onReceive) - : TcpConnection(false), state(eTCS_Ready) -{ - completed = onCompleted; - receive = onReceive; - timeOut = TCP_CLIENT_TIMEOUT; -} - -TcpClient::TcpClient(TcpClientDataDelegate onReceive) : TcpConnection(false), state(eTCS_Ready) -{ - receive = onReceive; - timeOut = TCP_CLIENT_TIMEOUT; -} - -TcpClient::~TcpClient() -{ - freeStreams(); -} - void TcpClient::freeStreams() { if(buffer != nullptr) { @@ -71,33 +29,31 @@ void TcpClient::setBuffer(ReadWriteStream* stream) this->stream = buffer; } -bool TcpClient::connect(String server, int port, boolean useSsl /* = false */, uint32_t sslOptions /* = 0 */) +bool TcpClient::connect(const String& server, int port, boolean useSsl /* = false */, uint32_t sslOptions /* = 0 */) { - if(isProcessing()) + if(isProcessing()) { return false; + } state = eTCS_Connecting; return TcpConnection::connect(server.c_str(), port, useSsl, sslOptions); } -bool TcpClient::connect(IPAddress addr, uint16_t port, boolean useSsl /* = false */, uint32_t sslOptions /* = 0 */) +bool TcpClient::connect(IPAddress addr, uint16_t port, boolean useSsl, uint32_t sslOptions) { - if(isProcessing()) + if(isProcessing()) { return false; + } state = eTCS_Connecting; return TcpConnection::connect(addr, port, useSsl, sslOptions); } -bool TcpClient::sendString(const String& data, bool forceCloseAfterSent /* = false*/) -{ - return send(data.c_str(), data.length(), forceCloseAfterSent); -} - -bool TcpClient::send(const char* data, uint16_t len, bool forceCloseAfterSent /* = false*/) +bool TcpClient::send(const char* data, uint16_t len, bool forceCloseAfterSent) { - if(state != eTCS_Connecting && state != eTCS_Connected) + if(state != eTCS_Connecting && state != eTCS_Connected) { return false; + } if(buffer == nullptr) { setBuffer(new MemoryDataStream()); @@ -164,8 +120,9 @@ err_t TcpClient::onReceive(pbuf* buf) void TcpClient::onReadyToSendData(TcpConnectionEvent sourceEvent) { TcpConnection::onReadyToSendData(sourceEvent); - if(ready) + if(ready) { ready(*this, sourceEvent); + } pushAsyncPart(); } @@ -283,7 +240,7 @@ bool TcpClient::pinCertificate(const uint8_t* fingerprint, SslFingerprintType ty return true; } -bool TcpClient::pinCertificate(SSLFingerprints fingerprints) +bool TcpClient::pinCertificate(const SSLFingerprints& fingerprints) { bool success = false; if(fingerprints.certSha1 != nullptr) { @@ -297,13 +254,3 @@ bool TcpClient::pinCertificate(SSLFingerprints fingerprints) return success; } #endif - -void TcpClient::setReceiveDelegate(TcpClientDataDelegate receiveCb) -{ - receive = receiveCb; -} - -void TcpClient::setCompleteDelegate(TcpClientCompleteDelegate completeCb) -{ - completed = completeCb; -} diff --git a/Sming/SmingCore/Network/TcpClient.h b/Sming/SmingCore/Network/TcpClient.h index 11675a0419..0904d8e0c0 100644 --- a/Sming/SmingCore/Network/TcpClient.h +++ b/Sming/SmingCore/Network/TcpClient.h @@ -37,31 +37,75 @@ enum TcpClientState { eTCS_Ready, eTCS_Connecting, eTCS_Connected, eTCS_Successf class TcpClient : public TcpConnection { public: - TcpClient(bool autoDestruct); - TcpClient(tcp_pcb* clientTcp, TcpClientDataDelegate clientReceive, TcpClientCompleteDelegate onCompleted); + TcpClient(bool autoDestruct) : TcpConnection(autoDestruct) + { + TcpConnection::timeOut = TCP_CLIENT_TIMEOUT; + } + + TcpClient(tcp_pcb* clientTcp, TcpClientDataDelegate clientReceive, TcpClientCompleteDelegate onCompleted) + : TcpConnection(clientTcp, true), state(eTCS_Connected) + { + TcpConnection::timeOut = TCP_CLIENT_TIMEOUT; + completed = onCompleted; + receive = clientReceive; + } + TcpClient(TcpClientCompleteDelegate onCompleted, TcpClientEventDelegate onReadyToSend, - TcpClientDataDelegate onReceive = nullptr); - TcpClient(TcpClientCompleteDelegate onCompleted, TcpClientDataDelegate onReceive = nullptr); - TcpClient(TcpClientDataDelegate onReceive); - virtual ~TcpClient(); + TcpClientDataDelegate onReceive = nullptr) + : TcpConnection(false) + { + TcpConnection::timeOut = TCP_CLIENT_TIMEOUT; + completed = onCompleted; + ready = onReadyToSend; + receive = onReceive; + } + + TcpClient(TcpClientCompleteDelegate onCompleted, TcpClientDataDelegate onReceive = nullptr) : TcpConnection(false) + { + TcpConnection::timeOut = TCP_CLIENT_TIMEOUT; + completed = onCompleted; + receive = onReceive; + } + + TcpClient(TcpClientDataDelegate onReceive) : TcpConnection(false) + { + TcpConnection::timeOut = TCP_CLIENT_TIMEOUT; + receive = onReceive; + } + + virtual ~TcpClient() + { + freeStreams(); + } public: - virtual bool connect(String server, int port, boolean useSsl = false, uint32_t sslOptions = 0); + virtual bool connect(const String& server, int port, boolean useSsl = false, uint32_t sslOptions = 0); virtual bool connect(IPAddress addr, uint16_t port, boolean useSsl = false, uint32_t sslOptions = 0); virtual void close(); /** @brief Set or clear the callback for received data * @param receiveCb callback delegate or nullptr */ - void setReceiveDelegate(TcpClientDataDelegate receiveCb = nullptr); + void setReceiveDelegate(TcpClientDataDelegate receiveCb = nullptr) + { + receive = receiveCb; + } /** @brief Set or clear the callback for connection close * @param completeCb callback delegate or nullptr */ - void setCompleteDelegate(TcpClientCompleteDelegate completeCb = nullptr); + void setCompleteDelegate(TcpClientCompleteDelegate completeCb = nullptr) + { + completed = completeCb; + } bool send(const char* data, uint16_t len, bool forceCloseAfterSent = false); - bool sendString(const String& data, bool forceCloseAfterSent = false); + + bool sendString(const String& data, bool forceCloseAfterSent = false) + { + return send(data.c_str(), data.length(), forceCloseAfterSent); + } + __forceinline bool isProcessing() { return state == eTCS_Connected || state == eTCS_Connecting; @@ -118,7 +162,7 @@ class TcpClient : public TcpConnection * * @return bool true of success, false or failure */ - bool pinCertificate(SSLFingerprints fingerprints); + bool pinCertificate(const SSLFingerprints& fingerprints); #endif protected: @@ -143,14 +187,14 @@ class TcpClient : public TcpConnection IDataSourceStream* stream = nullptr; ///< The currently active stream being sent private: - TcpClientState state; + TcpClientState state = eTCS_Ready; TcpClientCompleteDelegate completed = nullptr; TcpClientDataDelegate receive = nullptr; TcpClientEventDelegate ready = nullptr; bool asyncCloseAfterSent = false; - int16_t asyncTotalSent = 0; - int16_t asyncTotalLen = 0; + uint16_t asyncTotalSent = 0; + uint16_t asyncTotalLen = 0; #ifdef ENABLE_SSL Vector sslValidators; Vector sslValidatorsData; diff --git a/Sming/SmingCore/Network/TcpConnection.cpp b/Sming/SmingCore/Network/TcpConnection.cpp index d360d83bad..b8407ada67 100644 --- a/Sming/SmingCore/Network/TcpConnection.cpp +++ b/Sming/SmingCore/Network/TcpConnection.cpp @@ -7,23 +7,17 @@ #include "TcpConnection.h" -#include "../Data/Stream/DataSourceStream.h" -#include "../../SmingCore/Platform/WDT.h" +#include "Data/Stream/DataSourceStream.h" +#include "Platform/WDT.h" #include "NetUtils.h" -#include "../Wiring/WString.h" -#include "../Wiring/IPAddress.h" +#include "WString.h" +#include "IPAddress.h" -#include - -TcpConnection::TcpConnection(bool autoDestruct) : autoSelfDestruct(autoDestruct), sleep(0), canSend(true) -{ -} - -TcpConnection::TcpConnection(tcp_pcb* connection, bool autoDestruct) - : autoSelfDestruct(autoDestruct), sleep(0), canSend(true) -{ - initialize(connection); -} +#ifdef DEBUG_TCP_EXTENDED +#define debug_tcp(fmt, ...) debug_d(fmt, ##__VA_ARGS__) +#else +#define debug_tcp(fmt, ...) debug_none(fmt, ##__VA_ARGS__) +#endif TcpConnection::~TcpConnection() { @@ -40,10 +34,11 @@ TcpConnection::~TcpConnection() } } -bool TcpConnection::connect(const String& server, int port, bool useSsl /* = false */, uint32_t sslOptions /* = 0 */) +bool TcpConnection::connect(const String& server, int port, bool useSsl, uint32_t sslOptions) { - if(tcp == NULL) + if(tcp == nullptr) { initialize(tcp_new()); + } ip_addr_t addr; @@ -52,7 +47,7 @@ bool TcpConnection::connect(const String& server, int port, bool useSsl /* = fal this->sslOptions |= sslOptions; if(useSsl) { - if(sslExtension != NULL) { + if(sslExtension != nullptr) { ssl_ext_free(sslExtension); } @@ -64,32 +59,42 @@ bool TcpConnection::connect(const String& server, int port, bool useSsl /* = fal debug_d("connect to: %s", server.c_str()); canSend = false; // Wait for connection + + struct DnsLookup { + TcpConnection* con; + int port; + }; DnsLookup* look = new DnsLookup{this, port}; - err_t dnslook = dns_gethostbyname(server.c_str(), &addr, staticDnsResponse, look); - if(dnslook != ERR_OK) { - if(dnslook == ERR_INPROGRESS) - return true; - else { - delete look; - return false; - } + err_t dnslook = dns_gethostbyname(server.c_str(), &addr, + [](const char* name, LWIP_IP_ADDR_T* ipaddr, void* arg) { + auto dlook = static_cast(arg); + if(dlook != nullptr) { + dlook->con->internalOnDnsResponse(name, ipaddr, dlook->port); + delete dlook; + } + }, + look); + if(dnslook == ERR_INPROGRESS) { + // Operation pending - see internalOnDnsResponse() + return true; } delete look; - return internalTcpConnect(addr, port); + return (dnslook == ERR_OK) ? internalConnect(addr, port) : false; } bool TcpConnection::connect(IPAddress addr, uint16_t port, bool useSsl /* = false */, uint32_t sslOptions /* = 0 */) { - if(tcp == NULL) + if(tcp == nullptr) { initialize(tcp_new()); + } this->useSsl = useSsl; #ifdef ENABLE_SSL this->sslOptions |= sslOptions; #endif - return internalTcpConnect(addr, port); + return internalConnect(addr, port); } void TcpConnection::setTimeOut(uint16_t waitTimeOut) @@ -100,13 +105,14 @@ void TcpConnection::setTimeOut(uint16_t waitTimeOut) err_t TcpConnection::onReceive(pbuf* buf) { - if(buf == NULL) + if(buf == nullptr) { debug_d("TCP received: (null)"); - else + } else { debug_d("TCP received: %d bytes", buf->tot_len); - - if(buf != NULL && getAvailableWriteSize() > 0) - onReadyToSendData(eTCE_Received); + if(getAvailableWriteSize() > 0) { + onReadyToSendData(eTCE_Received); + } + } return ERR_OK; } @@ -115,9 +121,10 @@ err_t TcpConnection::onSent(uint16_t len) { debug_d("TCP sent: %d", len); - //debug_d("%d %d", tcp->state, tcp->flags); // WRONG! - if(len >= 0 && tcp != NULL && getAvailableWriteSize() > 0) + debug_tcp("%d %d", tcp->state, tcp->flags); // WRONG! + if(tcp != nullptr && getAvailableWriteSize() > 0) { onReadyToSendData(eTCE_Sent); + } return ERR_OK; } @@ -131,24 +138,27 @@ err_t TcpConnection::onPoll() return ERR_TIMEOUT; } - if(tcp != NULL && getAvailableWriteSize() > 0) //(tcp->state >= SYN_SENT && tcp->state <= ESTABLISHED)) + if(tcp != nullptr && getAvailableWriteSize() > 0) { //(tcp->state >= SYN_SENT && tcp->state <= ESTABLISHED)) onReadyToSendData(eTCE_Poll); + } return ERR_OK; } err_t TcpConnection::onConnected(err_t err) { - if(err != ERR_OK) + if(err != ERR_OK) { debug_d("TCP connected error status: %d", err); - else + } else { debug_d("TCP connected"); + } canSend = true; - if(err == ERR_OK) + if(err == ERR_OK) { onReadyToSendData(eTCE_Connected); - else + } else { close(); + } return ERR_OK; } @@ -163,8 +173,9 @@ void TcpConnection::onError(err_t err) void TcpConnection::onReadyToSendData(TcpConnectionEvent sourceEvent) { - if(sourceEvent != eTCE_Poll) - debug_d("onReadyToSendData: %d", sourceEvent); + if(sourceEvent != eTCE_Poll) { + debug_d("TCP onReadyToSendData: %d", sourceEvent); + } } #ifdef ENABLE_SSL @@ -174,16 +185,6 @@ err_t TcpConnection::onSslConnected(SSL* ssl) } #endif -int TcpConnection::writeString(const String& data, uint8_t apiflags /* = TCP_WRITE_FLAG_COPY*/) -{ - return writeString(data.c_str(), apiflags); -} - -int TcpConnection::writeString(const char* data, uint8_t apiflags /* = TCP_WRITE_FLAG_COPY*/) -{ - return write(data, strlen(data), apiflags); -} - int TcpConnection::write(const char* data, int len, uint8_t apiflags /* = TCP_WRITE_FLAG_COPY*/) { WDT.alive(); @@ -194,13 +195,13 @@ int TcpConnection::write(const char* data, int len, uint8_t apiflags /* = TCP_WR if(ssl) { u16_t expected = ssl_calculate_write_length(ssl, len); u16_t available = tcp ? tcp_sndbuf(tcp) : 0; - // debug_d("SSL: Expected: %d, Available: %d", expected, available); + debug_tcp("SSL: Expected: %d, Available: %d", expected, available); if(expected < 0 || available < expected) { return -1; // No memory } int written = axl_ssl_write(ssl, (const uint8_t*)data, len); - // debug_d("SSL: Write len: %d, Written: %d", len, written); + debug_tcp("SSL: Write len: %d, Written: %d", len, written); if(written < ERR_OK) { err = written; debug_d("SSL: Write Error: %d", err); @@ -209,10 +210,11 @@ int TcpConnection::write(const char* data, int len, uint8_t apiflags /* = TCP_WR #endif u16_t available = getAvailableWriteSize(); if(available < len) { - if(available == 0) + if(available == 0) { return -1; // No memory - else + } else { len = available; + } } err = tcp_write(tcp, data, len, apiflags); @@ -221,10 +223,10 @@ int TcpConnection::write(const char* data, int len, uint8_t apiflags /* = TCP_WR #endif if(err == ERR_OK) { - //debug_d("TCP connection send: %d (%d)", len, original); + debug_tcp("TCP connection send: %d (%d)", len, original); return len; } else { - //debug_d("TCP connection failed with err %d (\"%s\")", err, lwip_strerr(err)); + debug_tcp("TCP connection failed with err %d (\"%s\")", err, lwip_strerr(err)); return -1; } } @@ -232,7 +234,7 @@ int TcpConnection::write(const char* data, int len, uint8_t apiflags /* = TCP_WR int TcpConnection::write(IDataSourceStream* stream) { #ifdef ENABLE_SSL - if(ssl && !sslConnected) { + if(ssl != nullptr && !sslConnected) { // wait until the SSL handshake is done. return 0; } @@ -258,20 +260,22 @@ int TcpConnection::write(IDataSourceStream* stream) do { pushCount++; int read = std::min((uint16_t)NETWORK_SEND_BUFFER_SIZE, getAvailableWriteSize()); - if(read > 0) + if(read > 0) { available = stream->readMemoryBlock(buffer, read); - else + } else { available = 0; + } if(available > 0) { int written = write(buffer, available, TCP_WRITE_FLAG_COPY | TCP_WRITE_FLAG_MORE); total += written; stream->seek(std::max(written, 0)); - debug_d("Written: %d, Available: %d, isFinished: %d, PushCount: %d [TcpBuf: %d]", written, available, - (stream->isFinished() ? 1 : 0), pushCount, tcp_sndbuf(tcp)); + debug_d("TCP Written: %d, Available: %d, isFinished: %d, PushCount: %d [TcpBuf: %d]", written, + available, (stream->isFinished() ? 1 : 0), pushCount, tcp_sndbuf(tcp)); repeat = written == available && !stream->isFinished() && pushCount < 25; - } else + } else { repeat = false; + } } while(repeat); space = (tcp_sndqueuelen(tcp) < TCP_SND_QUEUELEN); // && tcp_sndbuf(tcp) >= FILE_STREAM_BUFFER_SIZE; @@ -287,8 +291,9 @@ void TcpConnection::close() closeSsl(); #endif - if(tcp == NULL) + if(tcp == nullptr) { return; + } debug_d("TCP connection closing"); #ifdef ENABLE_SSL @@ -296,8 +301,8 @@ void TcpConnection::close() #endif tcp_poll(tcp, staticOnPoll, 1); - tcp_arg(tcp, NULL); // reset pointer to close connection on next callback - tcp = NULL; + tcp_arg(tcp, nullptr); // reset pointer to close connection on next callback + tcp = nullptr; checkSelfFree(); } @@ -313,9 +318,36 @@ void TcpConnection::initialize(tcp_pcb* pcb) tcp_nagle_disable(tcp); tcp_arg(tcp, (void*)this); - tcp_sent(tcp, staticOnSent); - tcp_recv(tcp, staticOnReceive); - tcp_err(tcp, staticOnError); + + tcp_sent(tcp, [](void* arg, tcp_pcb* tcp, uint16_t len) -> err_t { + auto con = static_cast(arg); + return (con == nullptr) ? ERR_OK : con->internalOnSent(len); + }); + + tcp_recv(tcp, [](void* arg, tcp_pcb* tcp, pbuf* p, err_t err) -> err_t { + auto con = static_cast(arg); + //Serial.println("echo_recv!"); + + if(con == nullptr) { + if(p != nullptr) { + /* Inform TCP that we have taken the data. */ + tcp_recved(tcp, p->tot_len); + pbuf_free(p); + } + closeTcpConnection(tcp); + return ERR_OK; + } else { + return con->internalOnReceive(p, err); + } + }); + + tcp_err(tcp, [](void* arg, err_t err) { + auto con = static_cast(arg); + if(con != nullptr) { + con->internalOnError(err); + } + }); + tcp_poll(tcp, staticOnPoll, 4); #ifdef NETWORK_DEBUG @@ -325,17 +357,18 @@ void TcpConnection::initialize(tcp_pcb* pcb) void TcpConnection::closeTcpConnection(tcp_pcb* tpcb) { - if(tpcb == NULL) + if(tpcb == nullptr) { return; + } debug_d("-TCP connection"); - tcp_arg(tpcb, NULL); - tcp_sent(tpcb, NULL); - tcp_recv(tpcb, NULL); - tcp_err(tpcb, NULL); - tcp_poll(tpcb, NULL, 0); - tcp_accept(tpcb, NULL); + tcp_arg(tpcb, nullptr); + tcp_sent(tpcb, nullptr); + tcp_recv(tpcb, nullptr); + tcp_err(tpcb, nullptr); + tcp_poll(tpcb, nullptr, 0); + tcp_accept(tpcb, nullptr); auto err = tcp_close(tpcb); if(err != ERR_OK) { @@ -348,46 +381,49 @@ void TcpConnection::closeTcpConnection(tcp_pcb* tpcb) void TcpConnection::flush() { if(tcp && tcp->state == ESTABLISHED) { - //debug_d("TCP flush()"); + debug_tcp("TCP flush()"); tcp_output(tcp); } } -bool TcpConnection::internalTcpConnect(IPAddress addr, uint16_t port) +bool TcpConnection::internalConnect(IPAddress addr, uint16_t port) { NetUtils::FixNetworkRouting(); - err_t res = tcp_connect(tcp, addr, port, staticOnConnected); - debug_d("TcpConnection::connect result:, %d", res); + err_t res = tcp_connect(tcp, addr, port, [](void* arg, tcp_pcb* tcp, err_t err) -> err_t { + auto con = static_cast(arg); + if(con == nullptr) { + debug_d("TCP connect ABORT"); + //closeTcpConnection(tcp); + tcp_abort(tcp); + return ERR_ABRT; + } else { + return con->internalOnConnected(err); + } + }); + debug_d("TCP connect result: %d", res); return res == ERR_OK; } -err_t TcpConnection::staticOnConnected(void* arg, tcp_pcb* tcp, err_t err) +err_t TcpConnection::internalOnConnected(err_t err) { - TcpConnection* con = (TcpConnection*)arg; - if(con == NULL) { - debug_d("OnConnected ABORT"); - //closeTcpConnection(tcp); - tcp_abort(tcp); - return ERR_ABRT; - } else - debug_d("OnConnected"); + debug_d("TCP connected"); #ifndef ENABLE_SSL - if(con->useSsl) { + if(useSsl) { debug_w("WARNING: SSL is not compiled. Make sure to compile Sming with 'make ENABLE_SSL=1' "); } #else - debug_d("staticOnConnected: useSSL: %d, Error: %d", con->useSsl, err); + debug_d("TCP connected: useSSL: %d, Error: %d", useSsl, err); - if(con->useSsl && err == ERR_OK) { + if(useSsl && err == ERR_OK) { int clientfd = axl_append(tcp); - if(clientfd == -1) { + if(clientfd < 0) { debug_d("SSL: Unable to add LWIP tcp -> clientfd mapping"); return ERR_OK; } else { - uint32_t sslOptions = con->sslOptions; + uint32_t localSslOptions = sslOptions; #ifdef SSL_DEBUG - sslOptions |= SSL_DISPLAY_STATES | SSL_DISPLAY_BYTES | SSL_DISPLAY_CERTS; + localSslOptions |= SSL_DISPLAY_STATES | SSL_DISPLAY_BYTES | SSL_DISPLAY_CERTS; debug_d("SSL: Show debug data ..."); #endif debug_d("SSL: Starting connection..."); @@ -397,41 +433,34 @@ err_t TcpConnection::staticOnConnected(void* arg, tcp_pcb* tcp, err_t err) #endif debug_d("SSL: handshake start (%d ms)", millis()); - if(con->sslContext != NULL) { - ssl_ctx_free(con->sslContext); - } - - con->sslContext = ssl_ctx_new(SSL_CONNECT_IN_PARTS | sslOptions, 1); + ssl_ctx_free(sslContext); + sslContext = ssl_ctx_new(SSL_CONNECT_IN_PARTS | localSslOptions, 1); - if(con->sslKeyCert.keyLength && con->sslKeyCert.certificateLength) { + if(sslKeyCert.keyLength != 0 && sslKeyCert.certificateLength != 0) { // if we have client certificate -> try to use it. - if(ssl_obj_memory_load(con->sslContext, SSL_OBJ_RSA_KEY, con->sslKeyCert.key, con->sslKeyCert.keyLength, - con->sslKeyCert.keyPassword) != SSL_OK) { + if(ssl_obj_memory_load(sslContext, SSL_OBJ_RSA_KEY, sslKeyCert.key, sslKeyCert.keyLength, + sslKeyCert.keyPassword) != SSL_OK) { debug_d("SSL: Unable to load client private key"); - } else if(ssl_obj_memory_load(con->sslContext, SSL_OBJ_X509_CERT, con->sslKeyCert.certificate, - con->sslKeyCert.certificateLength, NULL) != SSL_OK) { + } else if(ssl_obj_memory_load(sslContext, SSL_OBJ_X509_CERT, sslKeyCert.certificate, + sslKeyCert.certificateLength, nullptr) != SSL_OK) { debug_d("SSL: Unable to load client certificate"); } - if(con->freeKeyCert) { - con->freeSslKeyCert(); + if(freeKeyCert) { + freeSslKeyCert(); } } - debug_d("SSL: Session Id Length: %d", (con->sslSessionId != NULL ? con->sslSessionId->length : 0)); - if(con->sslSessionId != NULL && con->sslSessionId->length > 0) { + debug_d("SSL: Session Id Length: %d", sslSessionId != nullptr ? sslSessionId->length : 0); + if(sslSessionId != nullptr && sslSessionId->length > 0) { debug_d("-----BEGIN SSL SESSION PARAMETERS-----"); - for(int i = 0; i < con->sslSessionId->length; i++) { - m_printf("%02x", con->sslSessionId->value[i]); - } - + debug_hex(DBG, "Session", sslSessionId->value, sslSessionId->length); debug_d("\n-----END SSL SESSION PARAMETERS-----"); } - con->ssl = - ssl_client_new(con->sslContext, clientfd, (con->sslSessionId != NULL ? con->sslSessionId->value : NULL), - (con->sslSessionId != NULL ? con->sslSessionId->length : 0), con->sslExtension); - if(ssl_handshake_status(con->ssl) != SSL_OK) { + ssl = ssl_client_new(sslContext, clientfd, sslSessionId != nullptr ? sslSessionId->value : nullptr, + sslSessionId != nullptr ? sslSessionId->length : 0, sslExtension); + if(ssl_handshake_status(ssl) != SSL_OK) { debug_d("SSL: handshake is in progress..."); return SSL_OK; } @@ -440,72 +469,59 @@ err_t TcpConnection::staticOnConnected(void* arg, tcp_pcb* tcp, err_t err) debug_d("SSL: Switching back 80 MHz"); System.setCpuFrequency(eCF_80MHz); #endif - if(con->sslSessionId) { - if(con->sslSessionId->value == NULL) { - con->sslSessionId->value = new uint8_t[SSL_SESSION_ID_SIZE]; + if(sslSessionId != nullptr) { + if(sslSessionId->value == nullptr) { + sslSessionId->value = new uint8_t[SSL_SESSION_ID_SIZE]; } - memcpy((void*)con->sslSessionId->value, (void*)con->ssl->session_id, con->ssl->sess_id_size); - con->sslSessionId->length = con->ssl->sess_id_size; + memcpy(sslSessionId->value, ssl->session_id, ssl->sess_id_size); + sslSessionId->length = ssl->sess_id_size; } } } #endif - err_t res = con->onConnected(err); - con->checkSelfFree(); - //debug_d("tot_len); - pbuf_free(p); - } - closeTcpConnection(tcp); - return ERR_OK; - } else - con->sleep = 0; + sleep = 0; if(err != ERR_OK /*&& err != ERR_CLSD && err != ERR_RST*/) { - debug_d("Received ERROR %d", err); + debug_d("TCP receive ERROR %d", err); /* exit and free resources, for unknown reason */ - if(p != NULL) { + if(p != nullptr) { /* Inform TCP that we have taken the data. */ tcp_recved(tcp, p->tot_len); pbuf_free(p); } closeTcpConnection(tcp); // ?? - con->tcp = NULL; - con->onError(err); - //con->close(); + tcp = nullptr; + onError(err); + //close(); return err == ERR_ABRT ? ERR_ABRT : ERR_OK; } - //if (tcp != NULL && tcp->state == ESTABLISHED) // If active + //if (tcp != nullptr && tcp->state == ESTABLISHED) // If active /* We have taken the data. */ - if(p != NULL) { + if(p != nullptr) { tcp_recved(tcp, p->tot_len); } else { - debug_d("TcpConnection::staticOnReceive: pbuf is NULL"); + debug_d("TCP receive: pbuf is NULL"); } #ifdef ENABLE_SSL - if(con->ssl && p != NULL) { + if(ssl != nullptr && p != nullptr) { WDT.alive(); /* SSL handshake needs time. In theory we have max 8 seconds before the hardware watchdog resets the device */ - struct pbuf* pout; - int read_bytes = axl_ssl_read(con->ssl, tcp, p, &pout); + struct pbuf* pout; + int read_bytes = axl_ssl_read(ssl, tcp, p, &pout); // free the SSL pbuf and put the decrypted data in the brand new pout pbuf - if(p != NULL) { + if(p != nullptr) { pbuf_free(p); } @@ -515,36 +531,37 @@ err_t TcpConnection::staticOnReceive(void* arg, tcp_pcb* tcp, pbuf* p, err_t err return ERR_OK; } - con->close(); + close(); closeTcpConnection(tcp); return read_bytes; } if(read_bytes == 0) { - if(!con->sslConnected && ssl_handshake_status(con->ssl) == SSL_OK) { - con->sslConnected = true; + if(!sslConnected && ssl_handshake_status(ssl) == SSL_OK) { + sslConnected = true; debug_d("SSL: Handshake done (%d ms).", millis()); #ifndef SSL_SLOW_CONNECT debug_d("SSL: Switching back to 80 MHz"); System.setCpuFrequency(eCF_80MHz); // Preserve some CPU cycles #endif - if(con->onSslConnected(con->ssl) != ERR_OK) { - con->close(); + if(onSslConnected(ssl) != ERR_OK) { + close(); closeTcpConnection(tcp); return ERR_ABRT; } - if(con->sslSessionId) { - if(con->sslSessionId->value == NULL) { - con->sslSessionId->value = new uint8_t[SSL_SESSION_ID_SIZE]; + if(sslSessionId != nullptr) { + if(sslSessionId->value == nullptr) { + sslSessionId->value = new uint8_t[SSL_SESSION_ID_SIZE]; } - memcpy((void*)con->sslSessionId->value, (void*)con->ssl->session_id, con->ssl->sess_id_size); - con->sslSessionId->length = con->ssl->sess_id_size; + assert(ssl->sess_id_size <= SSL_SESSION_ID_SIZE); + memcpy(sslSessionId->value, ssl->session_id, ssl->sess_id_size); + sslSessionId->length = ssl->sess_id_size; } - err_t res = con->onConnected(err); - con->checkSelfFree(); + err_t res = onConnected(err); + checkSelfFree(); return res; } @@ -561,113 +578,93 @@ err_t TcpConnection::staticOnReceive(void* arg, tcp_pcb* tcp, pbuf* p, err_t err } #endif - err_t res = con->onReceive(p); + err_t res = onReceive(p); - if(p != NULL) + if(p != nullptr) { pbuf_free(p); - else { - con->close(); + } else { + close(); closeTcpConnection(tcp); } - con->checkSelfFree(); - //debug_d("sleep = 0; - - err_t res = con->onSent(len); - con->checkSelfFree(); - //debug_d("(arg); - if(con == NULL) { + if(con == nullptr) { closeTcpConnection(tcp); return ERR_OK; + } else { + return con->internalOnPoll(); } +} +err_t TcpConnection::internalOnPoll() +{ //if (tcp->state != ESTABLISHED) // return ERR_OK; - con->sleep++; - err_t res = con->onPoll(); - con->checkSelfFree(); - //debug_d("tcp = NULL; // IMPORTANT. No available connection after error! - con->onError(err); - con->checkSelfFree(); - //debug_d("con->internalTcpConnect(ip, dlook->port); + internalConnect(ip, port); } else { #ifdef NETWORK_DEBUG debug_d("DNS record _not_ found: %s", name); #endif - closeTcpConnection(dlook->con->tcp); - dlook->con->tcp = NULL; - dlook->con->close(); + closeTcpConnection(tcp); + tcp = nullptr; + close(); } - - delete dlook; -} - -void TcpConnection::setDestroyedDelegate(TcpConnectionDestroyedDelegate destroyedDelegate) -{ - this->destroyedDelegate = destroyedDelegate; } #ifdef ENABLE_SSL -void TcpConnection::addSslOptions(uint32_t sslOptions) -{ - this->sslOptions |= sslOptions; -} bool TcpConnection::setSslKeyCert(const uint8_t* key, int keyLength, const uint8_t* certificate, int certificateLength, - const char* keyPassword /* = NULL */, bool freeAfterHandshake /* = false */) + const char* keyPassword, bool freeAfterHandshake) { delete[] sslKeyCert.key; delete[] sslKeyCert.certificate; delete[] sslKeyCert.keyPassword; - sslKeyCert.keyPassword = NULL; + sslKeyCert.keyPassword = nullptr; sslKeyCert.key = new uint8_t[keyLength]; sslKeyCert.certificate = new uint8_t[certificateLength]; int passwordLength = 0; - if(keyPassword != NULL) { + if(keyPassword != nullptr) { passwordLength = strlen(keyPassword); sslKeyCert.keyPassword = new char[passwordLength + 1]; } @@ -678,7 +675,7 @@ bool TcpConnection::setSslKeyCert(const uint8_t* key, int keyLength, const uint8 memcpy(sslKeyCert.key, key, keyLength); memcpy(sslKeyCert.certificate, certificate, certificateLength); - if(keyPassword != NULL) { + if(keyPassword != nullptr) { memcpy(sslKeyCert.keyPassword, keyPassword, passwordLength); } freeKeyCert = freeAfterHandshake; @@ -693,7 +690,7 @@ bool TcpConnection::setSslKeyCert(const uint8_t* key, int keyLength, const uint8 bool TcpConnection::setSslKeyCert(const SSLKeyCertPair& keyCertPair, bool freeAfterHandshake /* = false */) { freeSslKeyCert(); - this->sslKeyCert = keyCertPair; + sslKeyCert = keyCertPair; freeKeyCert = freeAfterHandshake; return true; @@ -703,28 +700,23 @@ void TcpConnection::freeSslKeyCert() { if(sslKeyCert.key) { delete[] sslKeyCert.key; - sslKeyCert.key = NULL; + sslKeyCert.key = nullptr; } if(sslKeyCert.certificate) { delete[] sslKeyCert.certificate; - sslKeyCert.certificate = NULL; + sslKeyCert.certificate = nullptr; } if(sslKeyCert.keyPassword) { delete[] sslKeyCert.keyPassword; - sslKeyCert.keyPassword = NULL; + sslKeyCert.keyPassword = nullptr; } sslKeyCert.keyLength = 0; sslKeyCert.certificateLength = 0; } -SSL* TcpConnection::getSsl() -{ - return ssl; -} - void TcpConnection::closeSsl() { if(ssl == nullptr) { diff --git a/Sming/SmingCore/Network/TcpConnection.h b/Sming/SmingCore/Network/TcpConnection.h index 59e72f5d15..2d816c5797 100644 --- a/Sming/SmingCore/Network/TcpConnection.h +++ b/Sming/SmingCore/Network/TcpConnection.h @@ -14,13 +14,13 @@ #define _SMING_CORE_TCPCONNECTION_H_ #ifdef ENABLE_SSL -#include "../../axtls-8266/compat/lwipr_compat.h" -#include "../Clock.h" +#include "../axtls-8266/compat/lwipr_compat.h" +#include "Clock.h" #endif -#include "../Wiring/WiringFrameworkDependencies.h" +#include "WiringFrameworkDependencies.h" #include "IPAddress.h" -#include "../Delegate.h" +#include "Delegate.h" #define NETWORK_DEBUG @@ -46,20 +46,20 @@ enum SslFingerprintType { }; typedef struct { - uint8_t* certSha1 = NULL; // << certificate SHA1 fingerprint - uint8_t* pkSha256 = NULL; // << public key SHA256 fingerprint + uint8_t* certSha1 = nullptr; // << certificate SHA1 fingerprint + uint8_t* pkSha256 = nullptr; // << public key SHA256 fingerprint } SSLFingerprints; typedef struct { - uint8_t* key = NULL; + uint8_t* key = nullptr; int keyLength = 0; - char* keyPassword = NULL; - uint8_t* certificate = NULL; + char* keyPassword = nullptr; + uint8_t* certificate = nullptr; int certificateLength = 0; } SSLKeyCertPair; typedef struct { - uint8_t* value = NULL; + uint8_t* value = nullptr; int length = 0; } SSLSessionId; @@ -69,18 +69,22 @@ struct pbuf; class String; class IDataSourceStream; class IPAddress; -class TcpServer; class TcpConnection; typedef Delegate TcpConnectionDestroyedDelegate; class TcpConnection { - friend class TcpServer; - public: - TcpConnection(bool autoDestruct); - TcpConnection(tcp_pcb* connection, bool autoDestruct); + TcpConnection(bool autoDestruct) : autoSelfDestruct(autoDestruct) + { + } + + TcpConnection(tcp_pcb* connection, bool autoDestruct) : autoSelfDestruct(autoDestruct) + { + initialize(connection); + } + virtual ~TcpConnection(); public: @@ -89,36 +93,60 @@ class TcpConnection virtual void close(); // return -1 on error - int writeString(const char* data, uint8_t apiflags = TCP_WRITE_FLAG_COPY); - int writeString(const String& data, uint8_t apiflags = TCP_WRITE_FLAG_COPY); + int writeString(const char* data, uint8_t apiflags = TCP_WRITE_FLAG_COPY) + { + return write(data, strlen(data), apiflags); + } + // return -1 on error - virtual int write(const char* data, int len, - uint8_t apiflags = TCP_WRITE_FLAG_COPY); // flags: TCP_WRITE_FLAG_COPY, TCP_WRITE_FLAG_MORE + int writeString(const String& data, uint8_t apiflags = TCP_WRITE_FLAG_COPY) + { + return write(data.c_str(), data.length(), apiflags); + } + + /** @brief Base write operation + * @param data + * @param len + * @param apiflags TCP_WRITE_FLAG_COPY, TCP_WRITE_FLAG_MORE + * @retval int -1 on error + */ + virtual int write(const char* data, int len, uint8_t apiflags = TCP_WRITE_FLAG_COPY); + int write(IDataSourceStream* stream); + __forceinline uint16_t getAvailableWriteSize() { return (canSend && tcp) ? tcp_sndbuf(tcp) : 0; } + void flush(); void setTimeOut(uint16_t waitTimeOut); - IPAddress getRemoteIp() + + IPAddress getRemoteIp() const { - return (tcp == NULL) ? INADDR_NONE : IPAddress(tcp->remote_ip); - }; - uint16_t getRemotePort() + return (tcp == nullptr) ? INADDR_NONE : IPAddress(tcp->remote_ip); + } + + uint16_t getRemotePort() const { - return (tcp == NULL) ? 0 : tcp->remote_port; - }; + return (tcp == nullptr) ? 0 : tcp->remote_port; + } /** * @brief Sets a callback to be called when the object instance is destroyed * @param TcpServerConnectionDestroyedDelegate destroyedDelegate - callback */ - void setDestroyedDelegate(TcpConnectionDestroyedDelegate destroyedDelegate); + void setDestroyedDelegate(TcpConnectionDestroyedDelegate destroyedDelegate) + { + this->destroyedDelegate = destroyedDelegate; + } #ifdef ENABLE_SSL - void addSslOptions(uint32_t sslOptions); + void addSslOptions(uint32_t sslOptions) + { + this->sslOptions |= sslOptions; + } // start deprecated /** @@ -137,7 +165,7 @@ class TcpConnection * @return bool true of success, false or failure */ bool setSslClientKeyCert(const uint8_t* key, int keyLength, const uint8_t* certificate, int certificateLength, - const char* keyPassword = NULL, bool freeAfterHandshake = false) + const char* keyPassword = nullptr, bool freeAfterHandshake = false) { return setSslKeyCert(key, keyLength, certificate, certificateLength, keyPassword, freeAfterHandshake); } @@ -189,7 +217,7 @@ class TcpConnection * @return bool true of success, false or failure */ bool setSslKeyCert(const uint8_t* key, int keyLength, const uint8_t* certificate, int certificateLength, - const char* keyPassword = NULL, bool freeAfterHandshake = false); + const char* keyPassword = nullptr, bool freeAfterHandshake = false); /** * @brief Sets private key, certificate and password from memory for the SSL connection @@ -213,11 +241,24 @@ class TcpConnection */ void freeSslKeyCert(); - SSL* getSsl(); + // Called by TcpServer + void setSsl(SSL* ssl) + { + this->ssl = ssl; + useSsl = true; + } + + SSL* getSsl() + { + return ssl; + } + #endif protected: - bool internalTcpConnect(IPAddress addr, uint16_t port); + void initialize(tcp_pcb* pcb); + bool internalConnect(IPAddress addr, uint16_t port); + virtual err_t onConnected(err_t err); virtual err_t onReceive(pbuf* buf); virtual err_t onSent(uint16_t len); @@ -228,29 +269,31 @@ class TcpConnection virtual err_t onSslConnected(SSL* ssl); #endif - static err_t staticOnConnected(void* arg, tcp_pcb* tcp, err_t err); - static err_t staticOnReceive(void* arg, tcp_pcb* tcp, pbuf* p, err_t err); - static err_t staticOnSent(void* arg, tcp_pcb* tcp, uint16_t len); - static err_t staticOnPoll(void* arg, tcp_pcb* tcp); - static void staticOnError(void* arg, err_t err); - static void staticDnsResponse(const char* name, LWIP_IP_ADDR_T* ipaddr, void* arg); + // These methods are called via LWIP handlers + err_t internalOnConnected(err_t err); + err_t internalOnReceive(pbuf* p, err_t err); + err_t internalOnSent(uint16_t len); + err_t internalOnPoll(); + void internalOnError(err_t err); + void internalOnDnsResponse(const char* name, LWIP_IP_ADDR_T* ipaddr, int port); +private: + static err_t staticOnPoll(void* arg, tcp_pcb* tcp); static void closeTcpConnection(tcp_pcb* tpcb); - void initialize(tcp_pcb* pcb); -private: inline void checkSelfFree() { - if(tcp == NULL && autoSelfDestruct) + if(tcp == nullptr && autoSelfDestruct) { delete this; + } } protected: - tcp_pcb* tcp = NULL; - uint16_t sleep; + tcp_pcb* tcp = nullptr; + uint16_t sleep = 0; uint16_t timeOut = USHRT_MAX; // << By default a TCP connection does not have a time out - bool canSend; - bool autoSelfDestruct; + bool canSend = true; + bool autoSelfDestruct = true; #ifdef ENABLE_SSL SSL* ssl = nullptr; SSLCTX* sslContext = nullptr; @@ -259,12 +302,12 @@ class TcpConnection uint32_t sslOptions = 0; SSLKeyCertPair sslKeyCert; bool freeKeyCert = false; - SSLSessionId* sslSessionId = NULL; + SSLSessionId* sslSessionId = nullptr; #endif bool useSsl = false; private: - TcpConnectionDestroyedDelegate destroyedDelegate = 0; + TcpConnectionDestroyedDelegate destroyedDelegate = nullptr; #ifdef ENABLE_SSL void closeSsl(); diff --git a/Sming/SmingCore/Network/TcpServer.cpp b/Sming/SmingCore/Network/TcpServer.cpp index 39927f5aaa..668d2e9a66 100644 --- a/Sming/SmingCore/Network/TcpServer.cpp +++ b/Sming/SmingCore/Network/TcpServer.cpp @@ -6,55 +6,16 @@ ****/ #include "TcpServer.h" -#include "TcpClient.h" -#include "../../SmingCore/Digital.h" -#include "../../SmingCore/Timer.h" - -int16_t TcpServer::totalConnections = 0; - -TcpServer::TcpServer() : TcpConnection(false) -{ - timeOut = TCP_SERVER_TIMEOUT; -} - -TcpServer::TcpServer(TcpClientConnectDelegate onClientHandler, TcpClientDataDelegate clientReceiveDataHandler, - TcpClientCompleteDelegate clientCompleteHandler) - : TcpConnection(false), clientConnectDelegate(onClientHandler), clientReceiveDelegate(clientReceiveDataHandler), - clientCompleteDelegate(clientCompleteHandler) -{ - timeOut = TCP_SERVER_TIMEOUT; -} - -TcpServer::TcpServer(TcpClientDataDelegate clientReceiveDataHandler, TcpClientCompleteDelegate clientCompleteHandler) - : TcpConnection(false), clientReceiveDelegate(clientReceiveDataHandler), - clientCompleteDelegate(clientCompleteHandler) -{ - timeOut = TCP_SERVER_TIMEOUT; -} - -TcpServer::TcpServer(TcpClientDataDelegate clientReceiveDataHandler) - : TcpConnection(false), clientReceiveDelegate(clientReceiveDataHandler) -{ - timeOut = TCP_SERVER_TIMEOUT; -} - -TcpServer::~TcpServer() -{ - debug_i("Server is destroyed."); -} +uint16_t TcpServer::totalConnections = 0; TcpConnection* TcpServer::createClient(tcp_pcb* clientTcp) { - if(clientTcp == NULL) { - debug_d("TCP Server createClient NULL\r\n"); - } else { - debug_d("TCP Server createClient not NULL"); - } + debug_d("TCP Server createClient %sNULL\r\n", clientTcp ? "not" : ""); if(!active) { debug_w("Refusing new connections. The server is shutting down"); - return NULL; + return nullptr; } TcpConnection* con = new TcpClient(clientTcp, TcpClientDataDelegate(&TcpServer::onClientReceive, this), @@ -66,23 +27,25 @@ TcpConnection* TcpServer::createClient(tcp_pcb* clientTcp) //Timer stateTimer; void list_mem() { - debug_d("Free heap size=%d, K=%d", system_get_free_heap_size(), TcpServer::totalConnections); + debug_d("Free heap size=%u, K=%u", system_get_free_heap_size(), TcpServer::totalConnections); } void TcpServer::setKeepAlive(uint16_t seconds) { - debug_d("Server keep-alive updating: %d -> %d", keepAlive, seconds); + debug_d("Server keep-alive updating: %u -> %u", keepAlive, seconds); keepAlive = seconds; } -bool TcpServer::listen(int port, bool useSsl /*= false */) +bool TcpServer::listen(int port, bool useSsl) { - if(tcp == NULL) + if(tcp == nullptr) { initialize(tcp_new()); + } err_t res = tcp_bind(tcp, IP_ADDR_ANY, port); - if(res != ERR_OK) + if(res != ERR_OK) { return res; + } #ifdef ENABLE_SSL this->useSsl = useSsl; @@ -106,7 +69,7 @@ bool TcpServer::listen(int port, bool useSsl /*= false */) } if(ssl_obj_memory_load(sslContext, SSL_OBJ_X509_CERT, sslKeyCert.certificate, sslKeyCert.certificateLength, - NULL) != SSL_OK) { + nullptr) != SSL_OK) { debug_e("SSL: Unable to load server certificate"); return false; } @@ -137,13 +100,14 @@ err_t TcpServer::onAccept(tcp_pcb* clientTcp, err_t err) #endif if(err != ERR_OK) { - //closeTcpConnection(clientTcp, NULL); + //closeTcpConnection(clientTcp, nullptr); return err; } TcpConnection* client = createClient(clientTcp); - if(client == NULL) + if(client == nullptr) { return ERR_MEM; + } client->setTimeOut(keepAlive); #ifdef ENABLE_SSL @@ -156,8 +120,7 @@ err_t TcpServer::onAccept(tcp_pcb* clientTcp, err_t err) } debug_d("SSL: handshake start (%d ms)", millis()); - client->ssl = ssl_server_new(sslContext, clientfd); - client->useSsl = true; + client->setSsl(ssl_server_new(sslContext, clientfd)); } #endif @@ -180,12 +143,12 @@ void TcpServer::onClient(TcpClient* client) } } -void TcpServer::onClientComplete(TcpClient& client, bool succesfull) +void TcpServer::onClientComplete(TcpClient& client, bool successful) { activeClients--; debug_d("TcpSever onComplete: %s\r\n", client.getRemoteIp().toString().c_str()); if(clientCompleteDelegate) { - clientCompleteDelegate(client, succesfull); + clientCompleteDelegate(client, successful); } } @@ -201,15 +164,16 @@ bool TcpServer::onClientReceive(TcpClient& client, char* data, int size) err_t TcpServer::staticAccept(void* arg, tcp_pcb* new_tcp, err_t err) { - TcpServer* con = (TcpServer*)arg; + auto con = static_cast(arg); - if(con == NULL) { + if(con == nullptr) { debug_e("NO CONNECTION ON TCP"); //closeTcpConnection(new_tcp); tcp_abort(new_tcp); return ERR_ABRT; - } else + } else { con->sleep = 0; + } err_t res = con->onAccept(new_tcp, err); return res; @@ -222,21 +186,21 @@ void TcpServer::shutdown() debug_i("Shutting down the server ..."); if(tcp) { - tcp_arg(tcp, NULL); - tcp_accept(tcp, NULL); + tcp_arg(tcp, nullptr); + tcp_accept(tcp, nullptr); tcp_close(tcp); - tcp = NULL; + tcp = nullptr; } - if(!connections.count()) { + if(connections.count() == 0) { delete this; return; } - for(int i = 0; i < connections.count(); i++) { + for(unsigned i = 0; i < connections.count(); i++) { TcpConnection* connection = connections[i]; - if(connection == NULL) { + if(connection == nullptr) { continue; } diff --git a/Sming/SmingCore/Network/TcpServer.h b/Sming/SmingCore/Network/TcpServer.h index 0151f89e66..9f0bfc9c79 100644 --- a/Sming/SmingCore/Network/TcpServer.h +++ b/Sming/SmingCore/Network/TcpServer.h @@ -26,12 +26,36 @@ typedef Delegate TcpClientConnectDelegate; class TcpServer : public TcpConnection { public: - TcpServer(); + TcpServer() : TcpConnection(false) + { + TcpConnection::timeOut = TCP_SERVER_TIMEOUT; + } + TcpServer(TcpClientConnectDelegate onClientHandler, TcpClientDataDelegate clientReceiveDataHandler, - TcpClientCompleteDelegate clientCompleteHandler); - TcpServer(TcpClientDataDelegate clientReceiveDataHandler, TcpClientCompleteDelegate clientCompleteHandler); - TcpServer(TcpClientDataDelegate clientReceiveDataHandler); - virtual ~TcpServer(); + TcpClientCompleteDelegate clientCompleteHandler) + : TcpConnection(false), clientConnectDelegate(onClientHandler), clientReceiveDelegate(clientReceiveDataHandler), + clientCompleteDelegate(clientCompleteHandler) + { + TcpConnection::timeOut = TCP_SERVER_TIMEOUT; + } + + TcpServer(TcpClientDataDelegate clientReceiveDataHandler, TcpClientCompleteDelegate clientCompleteHandler) + : TcpConnection(false), clientReceiveDelegate(clientReceiveDataHandler), + clientCompleteDelegate(clientCompleteHandler) + { + TcpConnection::timeOut = TCP_SERVER_TIMEOUT; + } + + TcpServer(TcpClientDataDelegate clientReceiveDataHandler) + : TcpConnection(false), clientReceiveDelegate(clientReceiveDataHandler) + { + TcpConnection::timeOut = TCP_SERVER_TIMEOUT; + } + + virtual ~TcpServer() + { + debug_i("TcpServer destroyed"); + } public: virtual bool listen(int port, bool useSsl = false); @@ -62,17 +86,17 @@ class TcpServer : public TcpConnection virtual err_t onAccept(tcp_pcb* clientTcp, err_t err); virtual void onClient(TcpClient* client); virtual bool onClientReceive(TcpClient& client, char* data, int size); - virtual void onClientComplete(TcpClient& client, bool succesfull); + virtual void onClientComplete(TcpClient& client, bool successful); virtual void onClientDestroy(TcpConnection& connection); static err_t staticAccept(void* arg, tcp_pcb* new_tcp, err_t err); public: - static int16_t totalConnections; + static uint16_t totalConnections; ///< @deprecated not updated by framework uint16_t activeClients = 0; protected: - int minHeapSize = 3000; + size_t minHeapSize = 3000; #ifdef ENABLE_SSL int sslSessionCacheSize = 50; @@ -84,9 +108,9 @@ class TcpServer : public TcpConnection private: uint16_t keepAlive = 70; // << The time to wait after the connection is established. If there is no data // coming or going to the client within that period the client connection will be closed - TcpClientDataDelegate clientReceiveDelegate = NULL; - TcpClientCompleteDelegate clientCompleteDelegate = NULL; - TcpClientConnectDelegate clientConnectDelegate = NULL; + TcpClientConnectDelegate clientConnectDelegate = nullptr; + TcpClientDataDelegate clientReceiveDelegate = nullptr; + TcpClientCompleteDelegate clientCompleteDelegate = nullptr; }; /** @} */ diff --git a/Sming/SmingCore/Network/TelnetServer.cpp b/Sming/SmingCore/Network/TelnetServer.cpp index a91cc2b5cd..da9c2e802c 100644 --- a/Sming/SmingCore/Network/TelnetServer.cpp +++ b/Sming/SmingCore/Network/TelnetServer.cpp @@ -6,22 +6,12 @@ */ #include "TelnetServer.h" -#include "TcpServer.h" - -TelnetServer::TelnetServer() : TcpServer() -{ - // TODO Auto-generated constructor stub -} - -TelnetServer::~TelnetServer() -{ - // TODO Auto-generated destructor stub -} +#include "Debug.h" void TelnetServer::enableDebug(bool reqStatus) { telnetDebug = reqStatus; - if(telnetDebug && curClient) /* only setSetDebug when already connected */ + if(telnetDebug && curClient != nullptr) /* only setSetDebug when already connected */ { Debug.setDebug(DebugPrintCharDelegate(&TelnetServer::wrchar, this)); } else { @@ -32,23 +22,24 @@ void TelnetServer::enableDebug(bool reqStatus) void TelnetServer::enableCommand(bool reqStatus) { #if ENABLE_CMD_EXECUTOR - if(reqStatus && curClient && !commandExecutor) { + if(reqStatus && curClient != nullptr && commandExecutor == nullptr) { commandExecutor = new CommandExecutor(curClient); } - if(!reqStatus && commandExecutor) { + if(!reqStatus && commandExecutor != nullptr) { delete commandExecutor; commandExecutor = nullptr; } #endif telnetCommand = reqStatus; } + void TelnetServer::onClient(TcpClient* client) { debug_d("TelnetServer onClient %s", client->getRemoteIp().toString().c_str()); TcpServer::onClient(client); - if(curClient) { + if(curClient != nullptr) { debug_d("TCP Client already connected"); client->sendString("Telnet Client already connected\r\n"); client->close(); @@ -68,7 +59,7 @@ void TelnetServer::onClient(TcpClient* client) } } -void TelnetServer::onClientComplete(TcpClient& client, bool succesfull) +void TelnetServer::onClientComplete(TcpClient& client, bool successful) { if(&client == curClient) { #if ENABLE_CMD_EXECUTOR @@ -82,7 +73,7 @@ void TelnetServer::onClientComplete(TcpClient& client, bool succesfull) } debug_d("TelnetServer onClientComplete %s", client.getRemoteIp().toString().c_str()); - TcpServer::onClientComplete(client, succesfull); + TcpServer::onClientComplete(client, successful); Debug.setDebug(Serial); } @@ -98,7 +89,7 @@ bool TelnetServer::onClientReceive(TcpClient& client, char* data, int size) debug_d("TelnetServer onClientReceive : %s, %d bytes \r\n", client.getRemoteIp().toString().c_str(), size); debug_d("Data : %s", data); #if ENABLE_CMD_EXECUTOR - if(commandExecutor) { + if(commandExecutor != nullptr) { commandExecutor->executorReceive(data, size); } #endif diff --git a/Sming/SmingCore/Network/TelnetServer.h b/Sming/SmingCore/Network/TelnetServer.h index 9fa36b8dc3..e52b08089d 100644 --- a/Sming/SmingCore/Network/TelnetServer.h +++ b/Sming/SmingCore/Network/TelnetServer.h @@ -15,15 +15,12 @@ #define APP_TELNETSERVER_H_ #include -#include "../Delegate.h" -#include "../Debug.h" +#include "Delegate.h" #include "TcpClient.h" #include "TcpServer.h" #include "SystemClock.h" #include "../Services/CommandProcessing/CommandExecutor.h" -#include - #define TELNETSERVER_MAX_COMMANDSIZE 64 typedef Delegate TelnetServerCommandDelegate; @@ -31,8 +28,14 @@ typedef Delegate TelnetServerComm class TelnetServer : public TcpServer { public: - TelnetServer(); - virtual ~TelnetServer(); + TelnetServer() + { + } + + virtual ~TelnetServer() + { + } + // void setCommandDelegate(TelnetServerCommandDelegate reqDelegate); void enableDebug(bool reqStatus); void enableCommand(bool reqStatus); @@ -40,7 +43,7 @@ class TelnetServer : public TcpServer private: void onClient(TcpClient* client); bool onClientReceive(TcpClient& client, char* data, int size); - void onClientComplete(TcpClient& client, bool succesfull); + void onClientComplete(TcpClient& client, bool successful); void wrchar(char c); TcpClient* curClient = nullptr; CommandExecutor* commandExecutor = nullptr; diff --git a/samples/Arducam/app/application.cpp b/samples/Arducam/app/application.cpp index 7931b97477..211beea2df 100644 --- a/samples/Arducam/app/application.cpp +++ b/samples/Arducam/app/application.cpp @@ -2,7 +2,7 @@ #include //#include #include -//#include +#include //#include //#include