Skip to content

Commit

Permalink
Merged from tinywebsockets: Added missing delete[] after memory alloc…
Browse files Browse the repository at this point in the history
…ation for masking in send. Also masking key is now 0 by default so sending messages that are masked costs almost no extra computation. This should act as a fix to memory over-use in issue #16
  • Loading branch information
gilmaimon committed Jun 14, 2019
1 parent 2852934 commit f4505a1
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 7 deletions.
8 changes: 5 additions & 3 deletions src/tiny_websockets/internals/websockets_endpoint.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@
#include <tiny_websockets/message.hpp>
#include <memory>

namespace websockets {
#define __TINY_WS_INTERNAL_DEFAULT_MASK "\00\00\00\00"

namespace websockets {
enum FragmentsPolicy {
FragmentsPolicy_Aggregate,
FragmentsPolicy_Notify
Expand Down Expand Up @@ -42,8 +44,8 @@ namespace websockets {

bool poll();
WebsocketsMessage recv();
bool send(const char* data, const size_t len, const uint8_t opcode, const bool fin, const bool mask, const char* maskingKey = "\01\20\03\40");
bool send(const WSString& data, const uint8_t opcode, const bool fin, const bool mask, const char* maskingKey = "\01\20\03\40");
bool send(const char* data, const size_t len, const uint8_t opcode, const bool fin, const bool mask, const char* maskingKey = __TINY_WS_INTERNAL_DEFAULT_MASK);
bool send(const WSString& data, const uint8_t opcode, const bool fin, const bool mask, const char* maskingKey = __TINY_WS_INTERNAL_DEFAULT_MASK);

bool send(const char* data, const size_t len, const uint8_t opcode, const bool fin);
bool send(const WSString& data, const uint8_t opcode, const bool fin);
Expand Down
18 changes: 14 additions & 4 deletions src/websockets_endpoint.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -364,18 +364,28 @@ namespace internals {
// send the header
sendHeader(len, opcode, fin, mask);

char* finalData = new char[len];
memcpy(finalData, data, len);
char* finalData = const_cast<char*>(data);
bool shouldFreeBuffer = false;

// if masking is set, send the masking key
if(mask) {
remaskData(finalData, len, maskingKey);
if(memcmp(maskingKey, __TINY_WS_INTERNAL_DEFAULT_MASK, 4) != 0) {
finalData = new char[len];
shouldFreeBuffer = true;

memcpy(finalData, data, len);
remaskData(finalData, len, maskingKey);
}

this->_client->send(reinterpret_cast<const uint8_t*>(maskingKey), 4);
}

if(len > 0) {
this->_client->send(reinterpret_cast<uint8_t*>(finalData), len);
}

if(shouldFreeBuffer) {
delete[] finalData;
}
return true; // TODO dont assume success
}

Expand Down

0 comments on commit f4505a1

Please sign in to comment.