Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add IP filter to TCPStart command #12806

Merged
merged 1 commit into from
Aug 1, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 29 additions & 3 deletions tasmota/xdrv_41_tcp_bridge.ino
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ WiFiServer *server_tcp = nullptr;
WiFiClient client_tcp[TCP_BRIDGE_CONNECTIONS];
uint8_t client_next = 0;
uint8_t *tcp_buf = nullptr; // data transfer buffer
IPAddress ip_filter = 0;

#include <TasmotaSerial.h>
TasmotaSerial *TCPSerial = nullptr;
Expand All @@ -60,20 +61,33 @@ void TCPLoop(void)

// check for a new client connection
if ((server_tcp) && (server_tcp->hasClient())) {
WiFiClient new_client = server_tcp->available();

AddLog(LOG_LEVEL_INFO, PSTR(D_LOG_TCP "Got connection from %s"), new_client.remoteIP().toString().c_str());
// Check for IP filtering if it's enabled.
if (ip_filter) {
if (ip_filter != new_client.remoteIP()) {
AddLog(LOG_LEVEL_INFO, PSTR(D_LOG_TCP "Rejected due to filtering"));
new_client.stop();
} else {
AddLog(LOG_LEVEL_INFO, PSTR(D_LOG_TCP "Allowed through filter"));
}
}

// find an empty slot
uint32_t i;
for (i=0; i<nitems(client_tcp); i++) {
WiFiClient &client = client_tcp[i];
if (!client) {
client = server_tcp->available();
client = new_client;
break;
}
}
if (i >= nitems(client_tcp)) {
i = client_next++ % nitems(client_tcp);
WiFiClient &client = client_tcp[i];
client.stop();
client = server_tcp->available();
client = new_client;
}
}

Expand Down Expand Up @@ -139,12 +153,21 @@ void TCPInit(void) {
\*********************************************************************************************/

//
// Command `ZbConfig`
// Command `TCPStart`
// Params: port,<IPv4 allow>
//
void CmndTCPStart(void) {

if (!TCPSerial) { return; }

int32_t tcp_port = XdrvMailbox.payload;
if (ArgC() == 2) {
char sub_string[XdrvMailbox.data_len];
ip_filter.fromString(ArgV(sub_string, 2));
} else {
// Disable whitelist if previously set
ip_filter = (uint32_t)0;
}

if (server_tcp) {
AddLog(LOG_LEVEL_INFO, PSTR(D_LOG_TCP "Stopping TCP server"));
Expand All @@ -159,6 +182,9 @@ void CmndTCPStart(void) {
}
if (tcp_port > 0) {
AddLog(LOG_LEVEL_INFO, PSTR(D_LOG_TCP "Starting TCP server on port %d"), tcp_port);
if (ip_filter) {
AddLog(LOG_LEVEL_INFO, PSTR(D_LOG_TCP "Filtering %s"), ip_filter.toString().c_str());
}
server_tcp = new WiFiServer(tcp_port);
server_tcp->begin(); // start TCP server
server_tcp->setNoDelay(true);
Expand Down