UDPLink.cc 15.5 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);
Gus Grubba's avatar
Gus Grubba committed
163
    // Send to all manually targeted systems
164
    for(UDPCLient* target: _udpConfig->targetHosts()) {
Gus Grubba's avatar
Gus Grubba committed
165
        // Skip it if it's part of the session clients below
166
        if(!contains_target(_sessionTargets, target->address, target->port)) {
Gus Grubba's avatar
Gus Grubba committed
167
            _writeDataGram(data, target);
168 169
        }
    }
Gus Grubba's avatar
Gus Grubba committed
170
    // Send to all connected systems
171
    for(UDPCLient* target: _sessionTargets) {
Gus Grubba's avatar
Gus Grubba committed
172 173 174 175 176 177
        _writeDataGram(data, target);
    }
}

void UDPLink::_writeDataGram(const QByteArray data, const UDPCLient* target)
{
178
    //qDebug() << "UDP Out" << target->address << target->port;
Gus Grubba's avatar
Gus Grubba committed
179 180 181 182 183 184 185 186 187
    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());
    }
188 189
}

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

/**
 * @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
239
void UDPLink::_disconnect(void)
pixhawk's avatar
pixhawk committed
240
{
241
    _running = false;
242
    quit();
243
    wait();
244 245 246
    if (_socket) {
        // Make sure delete happen on correct thread
        _socket->deleteLater();
247
        _socket = nullptr;
248
        emit disconnected();
249 250
    }
    _connectState = false;
pixhawk's avatar
pixhawk committed
251 252 253 254 255 256 257
}

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

270
bool UDPLink::_hardwareConnect()
oberion's avatar
oberion committed
271
{
272 273
    if (_socket) {
        delete _socket;
274
        _socket = nullptr;
275
    }
276
    QHostAddress host = QHostAddress::AnyIPv4;
277
    _socket = new QUdpSocket(this);
278
    _socket->setProxy(QNetworkProxy::NoProxy);
279
    _connectState = _socket->bind(host, _udpConfig->localPort(), QAbstractSocket::ReuseAddressHint | QUdpSocket::ShareAddress);
280
    if (_connectState) {
281
        _socket->joinMulticastGroup(QHostAddress("224.0.0.1"));
dogmaphobic's avatar
dogmaphobic committed
282
        //-- Make sure we have a large enough IO buffers
283

Don Gagne's avatar
Don Gagne committed
284
#ifdef __mobile__
285
        int bufferSizeMultiplier = 1;
dogmaphobic's avatar
dogmaphobic committed
286
#else
287
        int bufferSizeMultiplier = 4;
dogmaphobic's avatar
dogmaphobic committed
288
#endif
289 290 291 292
        int receiveBufferSize = _udpConfig->isTransmitOnly() ? 0 : 512 * 1024;
        _socket->setSocketOption(QAbstractSocket::SendBufferSizeSocketOption,     bufferSizeMultiplier * 64 * 1024);
        _socket->setSocketOption(QAbstractSocket::ReceiveBufferSizeSocketOption, bufferSizeMultiplier * receiveBufferSize);

293
        _registerZeroconf(_udpConfig->localPort(), kZeroconfRegistration);
294
        QObject::connect(_socket, &QUdpSocket::readyRead, this, &UDPLink::readBytes);
295
        emit connected();
296
    } else {
Don Gagne's avatar
Don Gagne committed
297
        emit communicationError(tr("UDP Link Error"), tr("Error binding UDP port: %1").arg(_socket->errorString()));
298
    }
299
    return _connectState;
pixhawk's avatar
pixhawk committed
300 301 302 303 304 305 306
}

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

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

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

322
qint64 UDPLink::getCurrentOutDataRate() const
pixhawk's avatar
pixhawk committed
323
{
324
    return 0;
pixhawk's avatar
pixhawk committed
325 326
}

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

361 362
//--------------------------------------------------------------------------
//-- UDPConfiguration
363

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

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

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

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

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

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

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

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

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

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

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

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

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