UDPLink.cc 14.4 KB
Newer Older
1 2
/****************************************************************************
 *
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 69 70 71 72 73 74 75 76
UDPLink::UDPLink(SharedLinkConfigurationPtr& config)
    : LinkInterface     (config)
    , _running          (false)
    , _socket           (nullptr)
    , _udpConfig        (qobject_cast<UDPConfiguration*>(config.get()))
    , _connectState     (false)
#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 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
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.
131 132
    for (int i=0; i<_localAddresses.count(); i++) {
        QHostAddress &address = _localAddresses[i];
133 134 135 136 137 138 139 140
        if (address == add) {
            // This is a local address of the same host
            return true;
        }
    }
    return false;
}

141
void UDPLink::_writeBytes(const QByteArray data)
142
{
143
    if (!_socket) {
144
        return;
145
    }
146 147 148 149
    emit bytesSent(this, data);

    QMutexLocker locker(&_sessionTargetsMutex);

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

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

172
void UDPLink::readBytes()
pixhawk's avatar
pixhawk committed
173
{
174
    if (!_socket) {
DonLakeFlyer's avatar
DonLakeFlyer committed
175 176 177 178 179 180 181 182 183
        return;
    }
    QByteArray databuffer;
    while (_socket->hasPendingDatagrams())
    {
        QByteArray datagram;
        datagram.resize(_socket->pendingDatagramSize());
        QHostAddress sender;
        quint16 senderPort;
184 185 186 187 188 189
        // If the other end is reset then it will still report data available,
        // but will fail on the readDatagram call
        qint64 slen = _socket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
        if (slen == -1) {
            break;
        }
DonLakeFlyer's avatar
DonLakeFlyer committed
190 191
        databuffer.append(datagram);
        //-- Wait a bit before sending it over
192
        if (databuffer.size() > 10 * 1024) {
dogmaphobic's avatar
dogmaphobic committed
193
            emit bytesReceived(this, databuffer);
DonLakeFlyer's avatar
DonLakeFlyer committed
194
            databuffer.clear();
dogmaphobic's avatar
dogmaphobic committed
195
        }
Gus Grubba's avatar
Gus Grubba committed
196
        // TODO: This doesn't validade the sender. Anything sending UDP packets to this port gets
197 198 199
        // 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
200
        QHostAddress asender = sender;
201
        if(_isIpLocal(sender)) {
Gus Grubba's avatar
Gus Grubba committed
202 203
            asender = QHostAddress(QString("127.0.0.1"));
        }
204 205
        QMutexLocker locker(&_sessionTargetsMutex);
        if (!contains_target(_sessionTargets, asender, senderPort)) {
Gus Grubba's avatar
Gus Grubba committed
206 207 208 209
            qDebug() << "Adding target" << asender << senderPort;
            UDPCLient* target = new UDPCLient(asender, senderPort);
            _sessionTargets.append(target);
        }
210
        locker.unlock();
pixhawk's avatar
pixhawk committed
211
    }
dogmaphobic's avatar
dogmaphobic committed
212
    //-- Send whatever is left
213
    if (databuffer.size()) {
dogmaphobic's avatar
dogmaphobic committed
214 215
        emit bytesReceived(this, databuffer);
    }
pixhawk's avatar
pixhawk committed
216 217
}

218
void UDPLink::disconnect(void)
pixhawk's avatar
pixhawk committed
219
{
220
    _running = false;
221
    quit();
222
    wait();
223
    if (_socket) {
224 225
        // This prevents stale signal from calling the link after it has been deleted
        QObject::disconnect(_socket, &QUdpSocket::readyRead, this, &UDPLink::readBytes);
226 227
        // Make sure delete happen on correct thread
        _socket->deleteLater();
228
        _socket = nullptr;
229
        emit disconnected();
230 231
    }
    _connectState = false;
pixhawk's avatar
pixhawk committed
232 233
}

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

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

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

280 281 282 283
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
284 285 286 287 288 289 290 291
                                                    regType.c_str(),
                                                    NULL,
                                                    NULL,
                                                    htons(port),
                                                    0,
                                                    NULL,
                                                    NULL,
                                                    NULL);
292 293
    if (result != kDNSServiceErr_NoError)
    {
294
        emit communicationError(tr("UDP Link Error"), tr("Error registering Zeroconf"));
295 296 297 298 299 300 301 302 303 304 305 306
        _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
307 308 309 310
    {
        DNSServiceRefDeallocate(_dnssServiceRef);
        _dnssServiceRef = NULL;
    }
311 312 313
#endif
}

314 315
//--------------------------------------------------------------------------
//-- UDPConfiguration
316

317
UDPConfiguration::UDPConfiguration(const QString& name) : LinkConfiguration(name)
318
{
319 320 321 322
    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
323
        addHost(targetHostIP, settings->udpTargetHostPort()->rawValue().toUInt());
324
    }
325 326
}

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

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

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

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

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

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

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

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

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
425
    settings.setValue("hostCount", _targetHosts.size());
426
    for (int i=0; i<_targetHosts.size(); i++) {
Gus Grubba's avatar
Gus Grubba committed
427 428 429 430 431
        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);
432 433 434 435 436 437
    }
    settings.endGroup();
}

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

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