UDPLink.cc 14.2 KB
Newer Older
1 2
/****************************************************************************
 *
Gus Grubba's avatar
Gus Grubba committed
3
 * (c) 2009-2020 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
4 5 6 7 8
 *
 * QGroundControl is licensed according to the terms in the file
 * COPYING.md in the root of the source code directory.
 *
 ****************************************************************************/
pixhawk's avatar
pixhawk committed
9

10
#include <QtGlobal>
pixhawk's avatar
pixhawk committed
11 12 13 14
#include <QTimer>
#include <QList>
#include <QDebug>
#include <QMutexLocker>
15
#include <QNetworkProxy>
16
#include <QNetworkInterface>
pixhawk's avatar
pixhawk committed
17
#include <iostream>
18
#include <QHostInfo>
19

pixhawk's avatar
pixhawk committed
20
#include "UDPLink.h"
21
#include "QGC.h"
22 23 24
#include "QGCApplication.h"
#include "SettingsManager.h"
#include "AutoConnectSettings.h"
pixhawk's avatar
pixhawk committed
25

26 27
static const char* kZeroconfRegistration = "_qgroundcontrol._udp";

28 29 30
static bool is_ip(const QString& address)
{
    int a,b,c,d;
31
    if (sscanf(address.toStdString().c_str(), "%d.%d.%d.%d", &a, &b, &c, &d) != 4 && strcmp("::1", address.toStdString().c_str())) {
32
        return false;
33 34 35
    } else {
        return true;
    }
36 37 38 39
}

static QString get_ip_address(const QString& address)
{
40
    if (is_ip(address)) {
41
        return address;
42
    }
43 44
    // Need to look it up
    QHostInfo info = QHostInfo::fromName(address);
45
    if (info.error() == QHostInfo::NoError) {
46
        QList<QHostAddress> hostAddresses = info.addresses();
47
        for (int i=0; i<hostAddresses.size(); i++) {
48
            // Exclude all IPv6 addresses
49
            if (!hostAddresses.at(i).toString().contains(":")) {
50 51 52 53
                return hostAddresses.at(i).toString();
            }
        }
    }
54
    return QString();
55 56
}

57
static bool contains_target(const QList<UDPCLient*> list, const QHostAddress& address, quint16 port)
Gus Grubba's avatar
Gus Grubba committed
58
{
59 60 61
    for (int i=0; i<list.count(); i++) {
        UDPCLient* target = list[i];
        if (target->address == address && target->port == port) {
Gus Grubba's avatar
Gus Grubba committed
62 63 64 65 66 67
            return true;
        }
    }
    return false;
}

68
UDPLink::UDPLink(SharedLinkConfigurationPtr& config)
69 70 71
    : LinkInterface     (config)
    , _running          (false)
    , _socket           (nullptr)
72
    , _udpConfig        (qobject_cast<UDPConfiguration*>(config.get()))
73
    , _connectState     (false)
74 75 76
#if defined(QGC_ZEROCONF_ENABLED)
    , _dnssServiceRef   (nullptr)
#endif
pixhawk's avatar
pixhawk committed
77
{
DonLakeFlyer's avatar
DonLakeFlyer committed
78 79 80
    if (!_udpConfig) {
        qWarning() << "Internal error";
    }
81 82 83 84
    auto allAddresses = QNetworkInterface::allAddresses();
    for (int i=0; i<allAddresses.count(); i++) {
        QHostAddress &address = allAddresses[i];
        _localAddresses.append(QHostAddress(address));
85
    }
86
    moveToThread(this);
pixhawk's avatar
pixhawk committed
87 88 89 90
}

UDPLink::~UDPLink()
{
91 92
    qDebug() << "~UDPLink";
    disconnect();
Lorenz Meier's avatar
Lorenz Meier committed
93
    // Tell the thread to exit
94
    _running = false;
Gus Grubba's avatar
Gus Grubba committed
95
    // Clear client list
96 97
    qDeleteAll(_sessionTargets);
    _sessionTargets.clear();
98
    quit();
Lorenz Meier's avatar
Lorenz Meier committed
99 100
    // Wait for it to exit
    wait();
101
    this->deleteLater();
pixhawk's avatar
pixhawk committed
102 103 104 105
}

void UDPLink::run()
{
106
    if (_hardwareConnect()) {
107
        exec();
108
    }
109
    if (_socket) {
110
        _deregisterZeroconf();
111 112
        _socket->close();
    }
pixhawk's avatar
pixhawk committed
113 114
}

115
QString UDPLink::getName() const
pixhawk's avatar
pixhawk committed
116
{
117
    return _udpConfig->name();
118 119
}

120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
bool UDPLink::_isIpLocal(const QHostAddress& add)
{
    // In simulation and testing setups the vehicle and the GCS can be
    // running on the same host. This leads to packets arriving through
    // the local network or the loopback adapter, which makes it look
    // like the vehicle is connected through two different links,
    // complicating routing.
    //
    // We detect this case and force all traffic to a simulated instance
    // onto the local loopback interface.
    // Run through all IPv4 interfaces and check if their canonical
    // IP address in string representation matches the source IP address
    //
    // On Windows, this is a very expensive call only Redmond would know
    // why. As such, we make it once and keep the list locally. If a new
    // interface shows up after we start, it won't be on this list.
136 137
    for (int i=0; i<_localAddresses.count(); i++) {
        QHostAddress &address = _localAddresses[i];
138 139 140 141 142 143 144 145
        if (address == add) {
            // This is a local address of the same host
            return true;
        }
    }
    return false;
}

146
void UDPLink::_writeBytes(const QByteArray data)
147
{
148
    if (!_socket) {
149
        return;
150
    }
151
    emit bytesSent(this, data);
152 153 154

    QMutexLocker locker(&_sessionTargetsMutex);

Gus Grubba's avatar
Gus Grubba committed
155
    // Send to all manually targeted systems
156 157
    for (int i=0; i<_udpConfig->targetHosts().count(); i++) {
        UDPCLient* target = _udpConfig->targetHosts()[i];
Gus Grubba's avatar
Gus Grubba committed
158
        // Skip it if it's part of the session clients below
159
        if(!contains_target(_sessionTargets, target->address, target->port)) {
Gus Grubba's avatar
Gus Grubba committed
160
            _writeDataGram(data, target);
161 162
        }
    }
Gus Grubba's avatar
Gus Grubba committed
163
    // Send to all connected systems
164
    for(UDPCLient* target: _sessionTargets) {
Gus Grubba's avatar
Gus Grubba committed
165 166 167 168 169 170
        _writeDataGram(data, target);
    }
}

void UDPLink::_writeDataGram(const QByteArray data, const UDPCLient* target)
{
171
    //qDebug() << "UDP Out" << target->address << target->port;
Gus Grubba's avatar
Gus Grubba committed
172 173 174
    if(_socket->writeDatagram(data, target->address, target->port) < 0) {
        qWarning() << "Error writing to" << target->address << target->port;
    }
175 176
}

177
void UDPLink::readBytes()
pixhawk's avatar
pixhawk committed
178
{
179
    if (!_socket) {
DonLakeFlyer's avatar
DonLakeFlyer committed
180 181 182 183 184 185 186 187 188
        return;
    }
    QByteArray databuffer;
    while (_socket->hasPendingDatagrams())
    {
        QByteArray datagram;
        datagram.resize(_socket->pendingDatagramSize());
        QHostAddress sender;
        quint16 senderPort;
189
        //-- Note: This call is broken in Qt 5.9.3 on Windows. It always returns a blank sender and 0 for the port.
DonLakeFlyer's avatar
DonLakeFlyer committed
190 191 192
        _socket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
        databuffer.append(datagram);
        //-- Wait a bit before sending it over
193
        if (databuffer.size() > 10 * 1024) {
dogmaphobic's avatar
dogmaphobic committed
194
            emit bytesReceived(this, databuffer);
DonLakeFlyer's avatar
DonLakeFlyer committed
195
            databuffer.clear();
dogmaphobic's avatar
dogmaphobic committed
196
        }
Gus Grubba's avatar
Gus Grubba committed
197
        // TODO: This doesn't validade the sender. Anything sending UDP packets to this port gets
198 199 200
        // added to the list and will start receiving datagrams from here. Even a port scanner
        // would trigger this.
        // Add host to broadcast list if not yet present, or update its port
Gus Grubba's avatar
Gus Grubba committed
201
        QHostAddress asender = sender;
202
        if(_isIpLocal(sender)) {
Gus Grubba's avatar
Gus Grubba committed
203 204
            asender = QHostAddress(QString("127.0.0.1"));
        }
205 206
        QMutexLocker locker(&_sessionTargetsMutex);
        if (!contains_target(_sessionTargets, asender, senderPort)) {
Gus Grubba's avatar
Gus Grubba committed
207 208 209 210
            qDebug() << "Adding target" << asender << senderPort;
            UDPCLient* target = new UDPCLient(asender, senderPort);
            _sessionTargets.append(target);
        }
211
        locker.unlock();
pixhawk's avatar
pixhawk committed
212
    }
dogmaphobic's avatar
dogmaphobic committed
213
    //-- Send whatever is left
214
    if (databuffer.size()) {
dogmaphobic's avatar
dogmaphobic committed
215 216
        emit bytesReceived(this, databuffer);
    }
pixhawk's avatar
pixhawk committed
217 218
}

219
void UDPLink::disconnect(void)
pixhawk's avatar
pixhawk committed
220
{
221
    _running = false;
222
    quit();
223
    wait();
224 225 226
    if (_socket) {
        // Make sure delete happen on correct thread
        _socket->deleteLater();
227
        _socket = nullptr;
228
        emit disconnected();
229 230
    }
    _connectState = false;
pixhawk's avatar
pixhawk committed
231 232
}

233
bool UDPLink::_connect(void)
pixhawk's avatar
pixhawk committed
234
{
235
    if (this->isRunning() || _running) {
236
        _running = false;
237
        quit();
238
        wait();
239
    }
240
    _running = true;
241
    start(NormalPriority);
242
    return true;
oberion's avatar
oberion committed
243 244
}

245
bool UDPLink::_hardwareConnect()
oberion's avatar
oberion committed
246
{
247 248
    if (_socket) {
        delete _socket;
249
        _socket = nullptr;
250
    }
251
    QHostAddress host = QHostAddress::AnyIPv4;
252
    _socket = new QUdpSocket(this);
253
    _socket->setProxy(QNetworkProxy::NoProxy);
254
    _connectState = _socket->bind(host, _udpConfig->localPort(), QAbstractSocket::ReuseAddressHint | QUdpSocket::ShareAddress);
255
    if (_connectState) {
256
        _socket->joinMulticastGroup(QHostAddress("224.0.0.1"));
dogmaphobic's avatar
dogmaphobic committed
257
        //-- Make sure we have a large enough IO buffers
Don Gagne's avatar
Don Gagne committed
258
#ifdef __mobile__
259 260
        _socket->setSocketOption(QAbstractSocket::SendBufferSizeSocketOption,     64 * 1024);
        _socket->setSocketOption(QAbstractSocket::ReceiveBufferSizeSocketOption, 128 * 1024);
dogmaphobic's avatar
dogmaphobic committed
261
#else
262 263
        _socket->setSocketOption(QAbstractSocket::SendBufferSizeSocketOption,    256 * 1024);
        _socket->setSocketOption(QAbstractSocket::ReceiveBufferSizeSocketOption, 512 * 1024);
dogmaphobic's avatar
dogmaphobic committed
264
#endif
265
        _registerZeroconf(_udpConfig->localPort(), kZeroconfRegistration);
266
        QObject::connect(_socket, &QUdpSocket::readyRead, this, &UDPLink::readBytes);
267
        emit connected();
268
    } else {
Don Gagne's avatar
Don Gagne committed
269
        emit communicationError(tr("UDP Link Error"), tr("Error binding UDP port: %1").arg(_socket->errorString()));
270
    }
271
    return _connectState;
pixhawk's avatar
pixhawk committed
272 273
}

274
bool UDPLink::isConnected() const
275
{
276
    return _connectState;
pixhawk's avatar
pixhawk committed
277 278
}

279 280 281 282
void UDPLink::_registerZeroconf(uint16_t port, const std::string &regType)
{
#if defined(QGC_ZEROCONF_ENABLED)
    DNSServiceErrorType result = DNSServiceRegister(&_dnssServiceRef, 0, 0, 0,
DonLakeFlyer's avatar
DonLakeFlyer committed
283 284 285 286 287 288 289 290
                                                    regType.c_str(),
                                                    NULL,
                                                    NULL,
                                                    htons(port),
                                                    0,
                                                    NULL,
                                                    NULL,
                                                    NULL);
291 292
    if (result != kDNSServiceErr_NoError)
    {
293
        emit communicationError(tr("UDP Link Error"), tr("Error registering Zeroconf"));
294 295 296 297 298 299 300 301 302 303 304 305
        _dnssServiceRef = NULL;
    }
#else
    Q_UNUSED(port);
    Q_UNUSED(regType);
#endif
}

void UDPLink::_deregisterZeroconf()
{
#if defined(QGC_ZEROCONF_ENABLED)
    if (_dnssServiceRef)
DonLakeFlyer's avatar
DonLakeFlyer committed
306 307 308 309
    {
        DNSServiceRefDeallocate(_dnssServiceRef);
        _dnssServiceRef = NULL;
    }
310 311 312
#endif
}

313 314
//--------------------------------------------------------------------------
//-- UDPConfiguration
315

316
UDPConfiguration::UDPConfiguration(const QString& name) : LinkConfiguration(name)
317
{
318 319 320 321
    AutoConnectSettings* settings = qgcApp()->toolbox()->settingsManager()->autoConnectSettings();
    _localPort = settings->udpListenPort()->rawValue().toInt();
    QString targetHostIP = settings->udpTargetHostIP()->rawValue().toString();
    if (!targetHostIP.isEmpty()) {
Gus Grubba's avatar
Gus Grubba committed
322
        addHost(targetHostIP, settings->udpTargetHostPort()->rawValue().toUInt());
323
    }
324 325
}

326
UDPConfiguration::UDPConfiguration(UDPConfiguration* source) : LinkConfiguration(source)
327
{
Gus Grubba's avatar
Gus Grubba committed
328 329 330 331 332 333
    _copyFrom(source);
}

UDPConfiguration::~UDPConfiguration()
{
    _clearTargetHosts();
334 335
}

336
void UDPConfiguration::copyFrom(LinkConfiguration *source)
337
{
338
    LinkConfiguration::copyFrom(source);
Gus Grubba's avatar
Gus Grubba committed
339 340 341 342 343
    _copyFrom(source);
}

void UDPConfiguration::_copyFrom(LinkConfiguration *source)
{
344
    auto* usource = qobject_cast<UDPConfiguration*>(source);
DonLakeFlyer's avatar
DonLakeFlyer committed
345 346
    if (usource) {
        _localPort = usource->localPort();
Gus Grubba's avatar
Gus Grubba committed
347
        _clearTargetHosts();
348 349
        for (int i=0; i<usource->targetHosts().count(); i++) {
            UDPCLient* target = usource->targetHosts()[i];
350
            if(!contains_target(_targetHosts, target->address, target->port)) {
Gus Grubba's avatar
Gus Grubba committed
351 352
                UDPCLient* newTarget = new UDPCLient(target);
                _targetHosts.append(newTarget);
353
                _updateHostList();
Gus Grubba's avatar
Gus Grubba committed
354
            }
DonLakeFlyer's avatar
DonLakeFlyer committed
355 356 357
        }
    } else {
        qWarning() << "Internal error";
358 359 360
    }
}

Gus Grubba's avatar
Gus Grubba committed
361 362
void UDPConfiguration::_clearTargetHosts()
{
363 364
    qDeleteAll(_targetHosts);
    _targetHosts.clear();
Gus Grubba's avatar
Gus Grubba committed
365 366
}

367 368 369
/**
 * @param host Hostname in standard formatt, e.g. localhost:14551 or 192.168.1.1:14551
 */
370
void UDPConfiguration::addHost(const QString host)
371
{
372
    // Handle x.x.x.x:p
373
    if (host.contains(":")) {
Gus Grubba's avatar
Gus Grubba committed
374
        addHost(host.split(":").first(), host.split(":").last().toUInt());
375 376
    } else {
        // If no port, use default
Gus Grubba's avatar
Gus Grubba committed
377
        addHost(host, _localPort);
378 379 380
    }
}

Gus Grubba's avatar
Gus Grubba committed
381
void UDPConfiguration::addHost(const QString& host, quint16 port)
382
{
Gus Grubba's avatar
Gus Grubba committed
383
    QString ipAdd = get_ip_address(host);
384
    if (ipAdd.isEmpty()) {
Gus Grubba's avatar
Gus Grubba committed
385
        qWarning() << "UDP:" << "Could not resolve host:" << host << "port:" << port;
dogmaphobic's avatar
dogmaphobic committed
386
    } else {
Gus Grubba's avatar
Gus Grubba committed
387
        QHostAddress address(ipAdd);
388
        if(!contains_target(_targetHosts, address, port)) {
Gus Grubba's avatar
Gus Grubba committed
389 390 391
            UDPCLient* newTarget = new UDPCLient(address, port);
            _targetHosts.append(newTarget);
            _updateHostList();
dogmaphobic's avatar
dogmaphobic committed
392 393
        }
    }
394 395
}

396
void UDPConfiguration::removeHost(const QString host)
397
{
398
    if (host.contains(":")) {
Gus Grubba's avatar
Gus Grubba committed
399 400
        QHostAddress address = QHostAddress(get_ip_address(host.split(":").first()));
        quint16 port = host.split(":").last().toUInt();
401
        for (int i=0; i<_targetHosts.size(); i++) {
Gus Grubba's avatar
Gus Grubba committed
402 403 404 405 406 407 408 409
            UDPCLient* target = _targetHosts.at(i);
            if(target->address == address && target->port == port) {
                _targetHosts.removeAt(i);
                delete target;
                _updateHostList();
                return;
            }
        }
410
    }
Gus Grubba's avatar
Gus Grubba committed
411
    qWarning() << "UDP:" << "Could not remove unknown host:" << host;
412
    _updateHostList();
413 414 415 416 417 418 419 420 421 422 423
}

void UDPConfiguration::setLocalPort(quint16 port)
{
    _localPort = port;
}

void UDPConfiguration::saveSettings(QSettings& settings, const QString& root)
{
    settings.beginGroup(root);
    settings.setValue("port", (int)_localPort);
Gus Grubba's avatar
Gus Grubba committed
424
    settings.setValue("hostCount", _targetHosts.size());
425
    for (int i=0; i<_targetHosts.size(); i++) {
Gus Grubba's avatar
Gus Grubba committed
426 427 428 429 430
        UDPCLient* target = _targetHosts.at(i);
        QString hkey = QString("host%1").arg(i);
        settings.setValue(hkey, target->address.toString());
        QString pkey = QString("port%1").arg(i);
        settings.setValue(pkey, target->port);
431 432 433 434 435 436
    }
    settings.endGroup();
}

void UDPConfiguration::loadSettings(QSettings& settings, const QString& root)
{
437
    AutoConnectSettings* acSettings = qgcApp()->toolbox()->settingsManager()->autoConnectSettings();
Gus Grubba's avatar
Gus Grubba committed
438
    _clearTargetHosts();
dogmaphobic's avatar
dogmaphobic committed
439
    settings.beginGroup(root);
440
    _localPort = (quint16)settings.value("port", acSettings->udpListenPort()->rawValue().toInt()).toUInt();
441
    int hostCount = settings.value("hostCount", 0).toInt();
442
    for (int i=0; i<hostCount; i++) {
443 444 445
        QString hkey = QString("host%1").arg(i);
        QString pkey = QString("port%1").arg(i);
        if(settings.contains(hkey) && settings.contains(pkey)) {
Gus Grubba's avatar
Gus Grubba committed
446
            addHost(settings.value(hkey).toString(), settings.value(pkey).toUInt());
447 448 449
        }
    }
    settings.endGroup();
450
    _updateHostList();
451 452
}

453 454 455
void UDPConfiguration::_updateHostList()
{
    _hostList.clear();
456
    for (int i=0; i<_targetHosts.size(); i++) {
Gus Grubba's avatar
Gus Grubba committed
457 458 459
        UDPCLient* target = _targetHosts.at(i);
        QString host = QString("%1").arg(target->address.toString()) + ":" + QString("%1").arg(target->port);
        _hostList << host;
460 461 462
    }
    emit hostListChanged();
}