Skip to content

Commit 2fd5a48

Browse files
authored
Separate host:port before checking for private IP (x2) (#5643)
1 parent f4cff33 commit 2fd5a48

File tree

1 file changed

+22
-9
lines changed

1 file changed

+22
-9
lines changed

src/mqtt/MQTT.cpp

Lines changed: 22 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -231,6 +231,23 @@ bool isPrivateIpAddress(const IPAddress &ip)
231231
}
232232
return false;
233233
}
234+
235+
// Separate a <host>[:<port>] string. Returns a pair containing the parsed host and port. If the port is
236+
// not present in the input string, or is invalid, the value of the `port` argument will be returned.
237+
std::pair<String, uint16_t> parseHostAndPort(String server, uint16_t port = 0)
238+
{
239+
const int delimIndex = server.indexOf(':');
240+
if (delimIndex > 0) {
241+
const long parsedPort = server.substring(delimIndex + 1, server.length()).toInt();
242+
if (parsedPort < 1 || parsedPort > UINT16_MAX) {
243+
LOG_WARN("Invalid MQTT port %d: %s", parsedPort, server.c_str());
244+
} else {
245+
port = parsedPort;
246+
}
247+
server[delimIndex] = 0;
248+
}
249+
return std::make_pair(std::move(server), port);
250+
}
234251
} // namespace
235252

236253
void MQTT::mqttCallback(char *topic, byte *payload, unsigned int length)
@@ -308,7 +325,8 @@ MQTT::MQTT() : concurrency::OSThread("mqtt"), mqttQueue(MAX_MQTT_QUEUE)
308325
}
309326

310327
IPAddress ip;
311-
isMqttServerAddressPrivate = ip.fromString(moduleConfig.mqtt.address) && isPrivateIpAddress(ip);
328+
isMqttServerAddressPrivate =
329+
ip.fromString(parseHostAndPort(moduleConfig.mqtt.address).first.c_str()) && isPrivateIpAddress(ip);
312330

313331
#if HAS_NETWORKING
314332
if (!moduleConfig.mqtt.proxy_to_client_enabled)
@@ -424,14 +442,9 @@ void MQTT::reconnect()
424442
pubSub.setClient(mqttClient);
425443
#endif
426444

427-
String server = String(serverAddr);
428-
int delimIndex = server.indexOf(':');
429-
if (delimIndex > 0) {
430-
String port = server.substring(delimIndex + 1, server.length());
431-
server[delimIndex] = 0;
432-
serverPort = port.toInt();
433-
serverAddr = server.c_str();
434-
}
445+
std::pair<String, uint16_t> hostAndPort = parseHostAndPort(serverAddr, serverPort);
446+
serverAddr = hostAndPort.first.c_str();
447+
serverPort = hostAndPort.second;
435448
pubSub.setServer(serverAddr, serverPort);
436449
pubSub.setBufferSize(512);
437450

0 commit comments

Comments
 (0)