UDPLink.cc 15.6 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(SharedLinkConfigurationPointer& config)
69 70 71 72 73 74 75 76
    : LinkInterface     (config)
#if defined(QGC_ZEROCONF_ENABLED)
    , _dnssServiceRef   (nullptr)
#endif
    , _running          (false)
    , _socket           (nullptr)
    , _udpConfig        (qobject_cast<UDPConfiguration*>(config.data()))
    , _connectState     (false)
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
    _disconnect();
Lorenz Meier's avatar
Lorenz Meier committed
92
    // Tell the thread to exit
93
    _running = false;
Gus Grubba's avatar
Gus Grubba committed
94
    // Clear client list
95 96
    qDeleteAll(_sessionTargets);
    _sessionTargets.clear();
97
    quit();
Lorenz Meier's avatar
Lorenz Meier committed
98 99
    // Wait for it to exit
    wait();
100
    this->deleteLater();
pixhawk's avatar
pixhawk committed
101 102 103 104 105 106 107 108
}

/**
 * @brief Runs the thread
 *
 **/
void UDPLink::run()
{
109
    if (_hardwareConnect()) {
110
        exec();
111
    }
112
    if (_socket) {
113
        _deregisterZeroconf();
114 115
        _socket->close();
    }
pixhawk's avatar
pixhawk committed
116 117
}

118
void UDPLink::_restartConnection()
pixhawk's avatar
pixhawk committed
119
{
120
    if (this->isConnected()) {
121 122 123
        _disconnect();
        _connect();
    }
pixhawk's avatar
pixhawk committed
124 125
}

126
QString UDPLink::getName() const
pixhawk's avatar
pixhawk committed
127
{
128
    return _udpConfig->name();
129 130
}

131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
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.
147 148
    for (int i=0; i<_localAddresses.count(); i++) {
        QHostAddress &address = _localAddresses[i];
149 150 151 152 153 154 155 156
        if (address == add) {
            // This is a local address of the same host
            return true;
        }
    }
    return false;
}

157
void UDPLink::_writeBytes(const QByteArray data)
158
{
159
    if (!_socket) {
160
        return;
161
    }
162
    emit bytesSent(this, data);
163 164 165

    QMutexLocker locker(&_sessionTargetsMutex);

Gus Grubba's avatar
Gus Grubba committed
166
    // Send to all manually targeted systems
167 168
    for (int i=0; i<_udpConfig->targetHosts().count(); i++) {
        UDPCLient* target = _udpConfig->targetHosts()[i];
Gus Grubba's avatar
Gus Grubba committed
169
        // Skip it if it's part of the session clients below
170
        if(!contains_target(_sessionTargets, target->address, target->port)) {
Gus Grubba's avatar
Gus Grubba committed
171
            _writeDataGram(data, target);
172 173
        }
    }
Gus Grubba's avatar
Gus Grubba committed
174
    // Send to all connected systems
175
    for(UDPCLient* target: _sessionTargets) {
Gus Grubba's avatar
Gus Grubba committed
176 177 178 179 180 181
        _writeDataGram(data, target);
    }
}

void UDPLink::_writeDataGram(const QByteArray data, const UDPCLient* target)
{
182
    //qDebug() << "UDP Out" << target->address << target->port;
Gus Grubba's avatar
Gus Grubba committed
183 184 185 186 187 188 189 190 191
    if(_socket->writeDatagram(data, target->address, target->port) < 0) {
        qWarning() << "Error writing to" << target->address << target->port;
    } else {
        // Only log rate if data actually got sent. Not sure about this as
        // "host not there" takes time too regardless of size of data. In fact,
        // 1 byte or "UDP frame size" bytes are the same as that's the data
        // unit sent by UDP.
        _logOutputDataRate(data.size(), QDateTime::currentMSecsSinceEpoch());
    }
192 193
}

pixhawk's avatar
pixhawk committed
194 195 196
/**
 * @brief Read a number of bytes from the interface.
 **/
197
void UDPLink::readBytes()
pixhawk's avatar
pixhawk committed
198
{
199
    if (!_socket) {
DonLakeFlyer's avatar
DonLakeFlyer committed
200 201 202 203 204 205 206 207 208
        return;
    }
    QByteArray databuffer;
    while (_socket->hasPendingDatagrams())
    {
        QByteArray datagram;
        datagram.resize(_socket->pendingDatagramSize());
        QHostAddress sender;
        quint16 senderPort;
209
        //-- 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
210 211 212
        _socket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
        databuffer.append(datagram);
        //-- Wait a bit before sending it over
213
        if (databuffer.size() > 10 * 1024) {
dogmaphobic's avatar
dogmaphobic committed
214
            emit bytesReceived(this, databuffer);
DonLakeFlyer's avatar
DonLakeFlyer committed
215
            databuffer.clear();
dogmaphobic's avatar
dogmaphobic committed
216
        }
217
        _logInputDataRate(datagram.length(), QDateTime::currentMSecsSinceEpoch());
Gus Grubba's avatar
Gus Grubba committed
218
        // TODO: This doesn't validade the sender. Anything sending UDP packets to this port gets
219 220 221
        // 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
222
        QHostAddress asender = sender;
223
        if(_isIpLocal(sender)) {
Gus Grubba's avatar
Gus Grubba committed
224 225
            asender = QHostAddress(QString("127.0.0.1"));
        }
226 227
        QMutexLocker locker(&_sessionTargetsMutex);
        if (!contains_target(_sessionTargets, asender, senderPort)) {
Gus Grubba's avatar
Gus Grubba committed
228 229 230 231
            qDebug() << "Adding target" << asender << senderPort;
            UDPCLient* target = new UDPCLient(asender, senderPort);
            _sessionTargets.append(target);
        }
232
        locker.unlock();
pixhawk's avatar
pixhawk committed
233
    }
dogmaphobic's avatar
dogmaphobic committed
234
    //-- Send whatever is left
235
    if (databuffer.size()) {
dogmaphobic's avatar
dogmaphobic committed
236 237
        emit bytesReceived(this, databuffer);
    }
pixhawk's avatar
pixhawk committed
238 239 240 241 242 243 244
}

/**
 * @brief Disconnect the connection.
 *
 * @return True if connection has been disconnected, false if connection couldn't be disconnected.
 **/
Don Gagne's avatar
Don Gagne committed
245
void UDPLink::_disconnect(void)
pixhawk's avatar
pixhawk committed
246
{
247
    _running = false;
248
    quit();
249
    wait();
250 251 252
    if (_socket) {
        // Make sure delete happen on correct thread
        _socket->deleteLater();
253
        _socket = nullptr;
254
        emit disconnected();
255 256
    }
    _connectState = false;
pixhawk's avatar
pixhawk committed
257 258 259 260 261 262 263
}

/**
 * @brief Connect the connection.
 *
 * @return True if connection has been established, false if connection couldn't be established.
 **/
264
bool UDPLink::_connect(void)
pixhawk's avatar
pixhawk committed
265
{
266
    if (this->isRunning() || _running) {
267
        _running = false;
268
        quit();
269
        wait();
270
    }
271
    _running = true;
272
    start(NormalPriority);
273
    return true;
oberion's avatar
oberion committed
274 275
}

276
bool UDPLink::_hardwareConnect()
oberion's avatar
oberion committed
277
{
278 279
    if (_socket) {
        delete _socket;
280
        _socket = nullptr;
281
    }
282
    QHostAddress host = QHostAddress::AnyIPv4;
283
    _socket = new QUdpSocket(this);
284
    _socket->setProxy(QNetworkProxy::NoProxy);
285
    _connectState = _socket->bind(host, _udpConfig->localPort(), QAbstractSocket::ReuseAddressHint | QUdpSocket::ShareAddress);
286
    if (_connectState) {
287
        _socket->joinMulticastGroup(QHostAddress("224.0.0.1"));
dogmaphobic's avatar
dogmaphobic committed
288
        //-- Make sure we have a large enough IO buffers
Don Gagne's avatar
Don Gagne committed
289
#ifdef __mobile__
290 291
        _socket->setSocketOption(QAbstractSocket::SendBufferSizeSocketOption,     64 * 1024);
        _socket->setSocketOption(QAbstractSocket::ReceiveBufferSizeSocketOption, 128 * 1024);
dogmaphobic's avatar
dogmaphobic committed
292
#else
293 294
        _socket->setSocketOption(QAbstractSocket::SendBufferSizeSocketOption,    256 * 1024);
        _socket->setSocketOption(QAbstractSocket::ReceiveBufferSizeSocketOption, 512 * 1024);
dogmaphobic's avatar
dogmaphobic committed
295
#endif
296
        _registerZeroconf(_udpConfig->localPort(), kZeroconfRegistration);
297
        QObject::connect(_socket, &QUdpSocket::readyRead, this, &UDPLink::readBytes);
298
        emit connected();
299
    } else {
Don Gagne's avatar
Don Gagne committed
300
        emit communicationError(tr("UDP Link Error"), tr("Error binding UDP port: %1").arg(_socket->errorString()));
301
    }
302
    return _connectState;
pixhawk's avatar
pixhawk committed
303 304 305 306 307 308 309
}

/**
 * @brief Check if connection is active.
 *
 * @return True if link is connected, false otherwise.
 **/
310
bool UDPLink::isConnected() const
311
{
312
    return _connectState;
pixhawk's avatar
pixhawk committed
313 314
}

315
qint64 UDPLink::getConnectionSpeed() const
pixhawk's avatar
pixhawk committed
316
{
317 318 319 320 321 322
    return 54000000; // 54 Mbit
}

qint64 UDPLink::getCurrentInDataRate() const
{
    return 0;
pixhawk's avatar
pixhawk committed
323 324
}

325
qint64 UDPLink::getCurrentOutDataRate() const
pixhawk's avatar
pixhawk committed
326
{
327
    return 0;
pixhawk's avatar
pixhawk committed
328 329
}

330 331 332 333
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
334 335 336 337 338 339 340 341
                                                    regType.c_str(),
                                                    NULL,
                                                    NULL,
                                                    htons(port),
                                                    0,
                                                    NULL,
                                                    NULL,
                                                    NULL);
342 343
    if (result != kDNSServiceErr_NoError)
    {
344
        emit communicationError(tr("UDP Link Error"), tr("Error registering Zeroconf"));
345 346 347 348 349 350 351 352 353 354 355 356
        _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
357 358 359 360
    {
        DNSServiceRefDeallocate(_dnssServiceRef);
        _dnssServiceRef = NULL;
    }
361 362 363
#endif
}

364 365
//--------------------------------------------------------------------------
//-- UDPConfiguration
366

367
UDPConfiguration::UDPConfiguration(const QString& name) : LinkConfiguration(name)
368
{
369 370 371 372
    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
373
        addHost(targetHostIP, settings->udpTargetHostPort()->rawValue().toUInt());
374
    }
375 376
}

377
UDPConfiguration::UDPConfiguration(UDPConfiguration* source) : LinkConfiguration(source)
378
{
Gus Grubba's avatar
Gus Grubba committed
379 380 381 382 383 384
    _copyFrom(source);
}

UDPConfiguration::~UDPConfiguration()
{
    _clearTargetHosts();
385 386
}

387
void UDPConfiguration::copyFrom(LinkConfiguration *source)
388
{
389
    LinkConfiguration::copyFrom(source);
Gus Grubba's avatar
Gus Grubba committed
390 391 392 393 394
    _copyFrom(source);
}

void UDPConfiguration::_copyFrom(LinkConfiguration *source)
{
395
    auto* usource = qobject_cast<UDPConfiguration*>(source);
DonLakeFlyer's avatar
DonLakeFlyer committed
396 397
    if (usource) {
        _localPort = usource->localPort();
Gus Grubba's avatar
Gus Grubba committed
398
        _clearTargetHosts();
399 400
        for (int i=0; i<usource->targetHosts().count(); i++) {
            UDPCLient* target = usource->targetHosts()[i];
401
            if(!contains_target(_targetHosts, target->address, target->port)) {
Gus Grubba's avatar
Gus Grubba committed
402 403
                UDPCLient* newTarget = new UDPCLient(target);
                _targetHosts.append(newTarget);
404
                _updateHostList();
Gus Grubba's avatar
Gus Grubba committed
405
            }
DonLakeFlyer's avatar
DonLakeFlyer committed
406 407 408
        }
    } else {
        qWarning() << "Internal error";
409 410 411
    }
}

Gus Grubba's avatar
Gus Grubba committed
412 413
void UDPConfiguration::_clearTargetHosts()
{
414 415
    qDeleteAll(_targetHosts);
    _targetHosts.clear();
Gus Grubba's avatar
Gus Grubba committed
416 417
}

418 419 420
/**
 * @param host Hostname in standard formatt, e.g. localhost:14551 or 192.168.1.1:14551
 */
421
void UDPConfiguration::addHost(const QString host)
422
{
423
    // Handle x.x.x.x:p
424
    if (host.contains(":")) {
Gus Grubba's avatar
Gus Grubba committed
425
        addHost(host.split(":").first(), host.split(":").last().toUInt());
426 427
    } else {
        // If no port, use default
Gus Grubba's avatar
Gus Grubba committed
428
        addHost(host, _localPort);
429 430 431
    }
}

Gus Grubba's avatar
Gus Grubba committed
432
void UDPConfiguration::addHost(const QString& host, quint16 port)
433
{
Gus Grubba's avatar
Gus Grubba committed
434
    QString ipAdd = get_ip_address(host);
435
    if (ipAdd.isEmpty()) {
Gus Grubba's avatar
Gus Grubba committed
436
        qWarning() << "UDP:" << "Could not resolve host:" << host << "port:" << port;
dogmaphobic's avatar
dogmaphobic committed
437
    } else {
Gus Grubba's avatar
Gus Grubba committed
438
        QHostAddress address(ipAdd);
439
        if(!contains_target(_targetHosts, address, port)) {
Gus Grubba's avatar
Gus Grubba committed
440 441 442
            UDPCLient* newTarget = new UDPCLient(address, port);
            _targetHosts.append(newTarget);
            _updateHostList();
dogmaphobic's avatar
dogmaphobic committed
443 444
        }
    }
445 446
}

447
void UDPConfiguration::removeHost(const QString host)
448
{
449
    if (host.contains(":")) {
Gus Grubba's avatar
Gus Grubba committed
450 451
        QHostAddress address = QHostAddress(get_ip_address(host.split(":").first()));
        quint16 port = host.split(":").last().toUInt();
452
        for (int i=0; i<_targetHosts.size(); i++) {
Gus Grubba's avatar
Gus Grubba committed
453 454 455 456 457 458 459 460
            UDPCLient* target = _targetHosts.at(i);
            if(target->address == address && target->port == port) {
                _targetHosts.removeAt(i);
                delete target;
                _updateHostList();
                return;
            }
        }
461
    }
Gus Grubba's avatar
Gus Grubba committed
462
    qWarning() << "UDP:" << "Could not remove unknown host:" << host;
463
    _updateHostList();
464 465 466 467 468 469 470 471 472 473 474
}

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
475
    settings.setValue("hostCount", _targetHosts.size());
476
    for (int i=0; i<_targetHosts.size(); i++) {
Gus Grubba's avatar
Gus Grubba committed
477 478 479 480 481
        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);
482 483 484 485 486 487
    }
    settings.endGroup();
}

void UDPConfiguration::loadSettings(QSettings& settings, const QString& root)
{
488
    AutoConnectSettings* acSettings = qgcApp()->toolbox()->settingsManager()->autoConnectSettings();
Gus Grubba's avatar
Gus Grubba committed
489
    _clearTargetHosts();
dogmaphobic's avatar
dogmaphobic committed
490
    settings.beginGroup(root);
491
    _localPort = (quint16)settings.value("port", acSettings->udpListenPort()->rawValue().toInt()).toUInt();
492
    int hostCount = settings.value("hostCount", 0).toInt();
493
    for (int i=0; i<hostCount; i++) {
494 495 496
        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
497
            addHost(settings.value(hkey).toString(), settings.value(pkey).toUInt());
498 499 500
        }
    }
    settings.endGroup();
501
    _updateHostList();
502 503 504 505
}

void UDPConfiguration::updateSettings()
{
506
    if (_link) {
507 508 509 510 511
        UDPLink* ulink = dynamic_cast<UDPLink*>(_link);
        if(ulink) {
            ulink->_restartConnection();
        }
    }
512
}
513 514 515 516

void UDPConfiguration::_updateHostList()
{
    _hostList.clear();
517
    for (int i=0; i<_targetHosts.size(); i++) {
Gus Grubba's avatar
Gus Grubba committed
518 519 520
        UDPCLient* target = _targetHosts.at(i);
        QString host = QString("%1").arg(target->address.toString()) + ":" + QString("%1").arg(target->port);
        _hostList << host;
521 522 523
    }
    emit hostListChanged();
}