1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
|
#include "netproxysettings.h"
#include "ui_netproxysettings.h"
#include <QAbstractSocket>
#include <QCloseEvent>
#include <QMessageBox>
#include <QNetworkInterface>
#include <QPushButton>
#include <QTextCodec>
#define TRACE \
if (!debug) { \
} else \
qDebug()
static bool debug = false;
NetProxySettings::NetProxySettings(Settings *settings, QWidget *parent)
: QDialog(parent)
, m_settings(settings)
, ui(new Ui::NetProxySettings)
{
ui->setupUi(this);
ui->m_btn_udp->setText(tr("Listen"));
ui->m_btn_tcp->setText(tr("Listen"));
/* Set validators for the IP inputs */
QString ipRange = "(?:[0-1]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])";
// You may want to use QRegularExpression for new code with Qt 5 (not mandatory).
QRegExp ipRegex("^" + ipRange + "\\." + ipRange + "\\." + ipRange + "\\." + ipRange + "$");
QRegExpValidator *ipValidator = new QRegExpValidator(ipRegex, this);
ui->m_le_udp_remote_host->setValidator(ipValidator);
getLocalIp();
/* Initialize UDP socket */
m_udp = new QUdpSocket(this);
connect(ui->m_btn_udp, &QPushButton::clicked, this, [=]() {
TRACE << "UDP state: " << m_udp->state();
if (m_udp->state() != QAbstractSocket::BoundState) {
bindUdp();
} else {
unbindUdp();
}
});
connect(ui->m_bt_udp_help, &QPushButton::clicked, this, &NetProxySettings::helpMsgUdp);
connect(ui->m_bt_tcp_help, &QPushButton::clicked, this, &NetProxySettings::helpMsgTcp);
connect(m_udp, static_cast<void (QUdpSocket::*)(QAbstractSocket::SocketError)>(&QAbstractSocket::error), this,
&NetProxySettings::errorUdpSocket);
/* Initialise TCP socket */
m_tcp = new QTcpServer(this);
connect(ui->m_btn_tcp, &QPushButton::clicked, this, [=]() {
TRACE << "TCP state: " << m_udp->state();
if (m_tcp->isListening()) {
stopTcpServer();
} else {
startTcpServer();
}
});
connect(m_tcp, &QTcpServer::newConnection, this, &NetProxySettings::addTcpClient);
connect(m_tcp, &QTcpServer::acceptError, this, &NetProxySettings::errorTcpSocket);
/* update controls with the saved settings */
ui->m_sb_udp_port_local->setValue(m_settings->getCurrentSession().udpLocalPort);
ui->m_le_udp_remote_host->setText(m_settings->getCurrentSession().udpRemoteHost);
ui->m_sb_udp_port_remote->setValue(m_settings->getCurrentSession().udpRemotePort);
ui->m_sb_tcp_port_local->setValue(m_settings->getCurrentSession().tcpLocalPort);
connect(this, &NetProxySettings::rejected, this, &NetProxySettings::formClose);
}
NetProxySettings::~NetProxySettings() { delete ui; }
/**
* @brief When dialog closes then save settings
*/
void NetProxySettings::formClose()
{
/* update the settings with the current values */
m_settings->settingChanged(Settings::UdpLocalPort, ui->m_sb_udp_port_local->value());
m_settings->settingChanged(Settings::UdpRemoteHost, ui->m_le_udp_remote_host->text());
m_settings->settingChanged(Settings::UdpRemotePort, ui->m_sb_udp_port_remote->value());
m_settings->settingChanged(Settings::TcpLocalPort, ui->m_sb_tcp_port_local->value());
TRACE << "[NetProxySettings::formClose]";
}
/**
* @brief Check for valid IPv4 address
* @param addr The address to check
* @return true if IPv4 else false
*/
bool NetProxySettings::CheckIpAddress(QHostAddress *addr)
{
if (QAbstractSocket::IPv4Protocol != addr->protocol()) {
QMessageBox::critical(this, tr("Error"), tr("Invalid remote IP address: %1.").arg(addr->toString()));
return false;
}
return true;
}
/**
* @brief Check for valid TCP/UDP port
* @param port The port number. All port numbers are allowed
* @return true if valid port, else false
*/
bool NetProxySettings::CheckPort(quint16 port)
{
if (!port) {
QMessageBox::warning(this, tr("Error"), tr("Invalid remote port range!"));
return false;
}
return true;
}
/**
* @brief UDP socket errors
* @param err The error that occured
*/
void NetProxySettings::errorUdpSocket(QAbstractSocket::SocketError err)
{
unbindUdp();
if (err) {
QMessageBox::critical(this, tr("Error"), tr("UDP socket error: %1.").arg(m_udp->errorString()));
}
}
/**
* @brief TCP socket errors
* @param err The error that occured
*/
void NetProxySettings::errorTcpSocket(QAbstractSocket::SocketError err)
{
stopTcpServer();
if (err) {
QMessageBox::critical(this, tr("Error"), tr("TCP socket error: %1.").arg(m_tcp->errorString()));
}
}
/**
* @brief Bind UDP address and port and notify the interface
* elements.
*/
void NetProxySettings::bindUdp()
{
QHostAddress r_addr(ui->m_le_udp_remote_host->text());
QHostAddress l_addr(ui->m_cb_udp_local_ip->currentText());
/* Do some checks */
if (!CheckIpAddress(&r_addr) || !CheckIpAddress(&l_addr))
return;
int l_port = ui->m_sb_udp_port_local->text().toInt();
int r_port = ui->m_sb_udp_port_remote->text().toInt();
if (!CheckPort(l_port) || !CheckPort(r_port))
return;
if (l_port == r_port) {
QMessageBox::warning(this, tr("Error"),
tr("Remote and local port must be different, otherwise it will create a loop!"));
return;
}
if (m_udp->bind(l_addr, l_port)) {
connect(m_udp, &QUdpSocket::readyRead, this, &NetProxySettings::recvUDP);
ui->m_btn_udp->setText("Close");
/* store udp details */
m_udp_remote_addr = r_addr;
m_udp_remote_port = r_port;
emit ledSetValue(en_led::LED_UDP_EN, true);
QString status(QString("%1 : %2").arg(l_addr.toString()).arg(QString::number(l_port)));
emit udpStatus(true, status);
TRACE << "[NetProxySettings] UDP bind " << status;
} else {
QMessageBox::critical(this, tr("Error"), tr("Could not bind UDP socket!"));
m_udp_remote_addr.clear();
}
}
/**
* @brief In case of error or close request, then close the
* socket and notify the user interface elements
*/
void NetProxySettings::unbindUdp()
{
m_udp->close();
m_udp_remote_addr.clear();
m_udp_remote_port = 0;
ui->m_btn_udp->setText(tr("Listen"));
emit ledSetValue(en_led::LED_UDP_EN, false);
emit udpStatus(false, QString(tr("Not used")));
TRACE << "[NetProxySettings] UDP unbind";
}
/**
* @brief [SIGNAL] This receives the data from UDP and then
* emits the received data.
*/
void NetProxySettings::recvUDP()
{
while (m_udp->hasPendingDatagrams()) {
QByteArray datagram;
QHostAddress sender;
quint16 senderPort;
datagram.resize(m_udp->pendingDatagramSize());
m_udp->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
emit sendCmd(datagram);
emit ledSetValue(en_led::LED_UDP_RX, true);
}
}
/**
* @brief Start the local TCP server
*/
void NetProxySettings::startTcpServer()
{
int l_port = ui->m_sb_udp_port_local->text().toInt();
if (!CheckPort(l_port))
return;
if (!m_tcp->listen(QHostAddress::Any, l_port)) {
QMessageBox::critical(this, tr("Error"), tr("Could not start TCP server.\n%1.").arg(m_tcp->errorString()));
return;
}
ui->m_btn_tcp->setText(tr("Close"));
emit ledSetValue(en_led::LED_TCP_EN, true);
QString status(tr("Listening on: %1").arg(QString::number(l_port)));
emit tcpStatus(true, status);
}
/**
* @brief Stop local TCP server
*/
void NetProxySettings::stopTcpServer()
{
m_tcp->close();
ui->m_btn_tcp->setText(tr("Listen"));
emit ledSetValue(en_led::LED_TCP_EN, false);
emit tcpStatus(false, QString(tr("Not used")));
}
/**
* @brief On every new TCP connection add the client to the list
*/
void NetProxySettings::addTcpClient()
{
QTcpSocket *client = m_tcp->nextPendingConnection();
connect(client, &QTcpSocket::disconnected, this, &NetProxySettings::removeTcpClient);
connect(client, &QTcpSocket::readyRead, this, &NetProxySettings::recvTCP);
/* add client to the list */
m_tcpClients.append(client);
TRACE << "Connected: " << client->localAddress();
}
/**
* @brief Receive data from TCP clients and forward the data to the serial
*/
void NetProxySettings::recvTCP()
{
QTcpSocket *client = qobject_cast<QTcpSocket *>(sender());
while (client->bytesAvailable()) {
QByteArray recv_data = client->readAll();
emit sendCmd(recv_data);
emit ledSetValue(en_led::LED_TCP_RX, true);
TRACE << "TCP in: " << recv_data;
}
}
/**
* @brief Remove clients from the server's list
*/
void NetProxySettings::removeTcpClient()
{
QTcpSocket *client = qobject_cast<QTcpSocket *>(sender());
client->disconnectFromHost();
m_tcpClients.removeOne(client);
TRACE << "Disconnected: " << client->localAddress();
}
/**
* @brief Receive data from the plugin and send them to the
* UDP socket.
* @param cmd The data bytes
*/
void NetProxySettings::proxyCmd(QByteArray cmd)
{
if (m_udp->state() == QAbstractSocket::BoundState) {
m_udp->writeDatagram(cmd, m_udp_remote_addr, m_udp_remote_port);
emit ledSetValue(en_led::LED_UDP_TX, true);
}
if (m_tcp->isListening()) {
/* send the data to all clients */
QTcpSocket *client;
foreach (client, m_tcpClients) {
client->write(cmd);
emit ledSetValue(en_led::LED_TCP_TX, true);
}
}
TRACE << "[NetProxySettings::proxyCmd]: " << QString::fromUtf8(cmd.data());
}
/**
* @brief Retrieve the IP addresses of all the local interfaces
*/
void NetProxySettings::getLocalIp()
{
QList<QHostAddress> list = QNetworkInterface::allAddresses();
for (int i = 0; i < list.count(); i++) {
if (list[i].isLoopback())
continue;
if (list[i].protocol() == QAbstractSocket::IPv4Protocol) {
TRACE << "[NetProxySettings] found interface: " << list[i].toString();
ui->m_cb_udp_local_ip->addItem(list[i].toString());
}
}
}
/**
* @brief Help message for UDP settings
*/
void NetProxySettings::helpMsgUdp(void)
{
QString help_str = tr("This plugin provides a UDP socket that can be\n"
"used to forward the incoming serial data to the\n"
"bind socket or the opposite. Therefore, the UDP\n"
"communication is bi-directional.\n\n"
"The UDP socket will bind the local listen port\n"
"and forward the traffic of this port to the serial\n"
"port.\n\n"
"Also the UDP socket will forward all the incoming\n"
"data from the serial device to the remote UDP port\n"
"and IP which is set in the settings.\n\n"
"For obvious reasons, using the same UDP port for\n"
"listen and send is not allowed as it may lead to\n"
"an infinite tx/rx loop\n");
QMessageBox::information(this, tr("How to use UDP forwarding"), help_str);
}
/**
* @brief Help message for TCP settings
*/
void NetProxySettings::helpMsgTcp(void)
{
QString help_str = tr("This plugin provides a TCP server that can be\n"
"used to forward the incoming serial data to and from\n"
"connected clients.\n\n"
"Select the local port and run the server. Then use\n"
"any TCP client (e.g. telnet) to connect to the server\n"
"and receive or send data in the serial port.\n");
QMessageBox::information(this, tr("How to use TCP forwarding"), help_str);
}
|