UDPLink.cc 15.2 KB
Newer Older
pixhawk's avatar
pixhawk committed
1 2
/*=====================================================================

lm's avatar
lm committed
3
QGroundControl Open Source Ground Control Station
pixhawk's avatar
pixhawk committed
4

5
(c) 2009 - 2015 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
pixhawk's avatar
pixhawk committed
6

lm's avatar
lm committed
7
This file is part of the QGROUNDCONTROL project
pixhawk's avatar
pixhawk committed
8

lm's avatar
lm committed
9
    QGROUNDCONTROL is free software: you can redistribute it and/or modify
pixhawk's avatar
pixhawk committed
10 11 12 13
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

lm's avatar
lm committed
14
    QGROUNDCONTROL is distributed in the hope that it will be useful,
pixhawk's avatar
pixhawk committed
15 16 17 18 19
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
lm's avatar
lm committed
20
    along with QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
pixhawk's avatar
pixhawk committed
21 22 23 24 25 26 27 28 29 30

======================================================================*/

/**
 * @file
 *   @brief Definition of UDP connection (server) for unmanned vehicles
 *   @author Lorenz Meier <mavteam@student.ethz.ch>
 *
 */

31
#include <QtGlobal>
pixhawk's avatar
pixhawk committed
32 33 34 35
#include <QTimer>
#include <QList>
#include <QDebug>
#include <QMutexLocker>
36
#include <QNetworkProxy>
37
#include <QNetworkInterface>
pixhawk's avatar
pixhawk committed
38
#include <iostream>
39

pixhawk's avatar
pixhawk committed
40
#include "UDPLink.h"
41
#include "QGC.h"
42
#include <QHostInfo>
pixhawk's avatar
pixhawk committed
43

44 45
#define REMOVE_GONE_HOSTS 0

46 47
static const char* kZeroconfRegistration = "_qgroundcontrol._udp";

48 49 50
static bool is_ip(const QString& address)
{
    int a,b,c,d;
51 52
    if (sscanf(address.toStdString().c_str(), "%d.%d.%d.%d", &a, &b, &c, &d) != 4
            && strcmp("::1", address.toStdString().c_str())) {
53
        return false;
54 55 56
    } else {
        return true;
    }
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
}

static QString get_ip_address(const QString& address)
{
    if(is_ip(address))
        return address;
    // Need to look it up
    QHostInfo info = QHostInfo::fromName(address);
    if (info.error() == QHostInfo::NoError)
    {
        QList<QHostAddress> hostAddresses = info.addresses();
        QHostAddress address;
        for (int i = 0; i < hostAddresses.size(); i++)
        {
            // Exclude all IPv6 addresses
            if (!hostAddresses.at(i).toString().contains(":"))
            {
                return hostAddresses.at(i).toString();
            }
        }
    }
    return QString("");
}

81 82 83
UDPLink::UDPLink(UDPConfiguration* config)
    : _socket(NULL)
    , _connectState(false)
Gus Grubba's avatar
Gus Grubba committed
84
    #if defined(QGC_ZEROCONF_ENABLED)
85
    , _dnssServiceRef(NULL)
Gus Grubba's avatar
Gus Grubba committed
86
    #endif
87
    , _running(false)
pixhawk's avatar
pixhawk committed
88
{
89 90 91 92
    Q_ASSERT(config != NULL);
    _config = config;
    _config->setLink(this);

93 94 95
    // We're doing it wrong - because the Qt folks got the API wrong:
    // http://blog.qt.digia.com/blog/2010/06/17/youre-doing-it-wrong/
    moveToThread(this);
pixhawk's avatar
pixhawk committed
96 97 98 99
}

UDPLink::~UDPLink()
{
100 101
    // Disconnect link from configuration
    _config->setLink(NULL);
102
    _disconnect();
Lorenz Meier's avatar
Lorenz Meier committed
103
    // Tell the thread to exit
104
    _running = false;
105
    quit();
Lorenz Meier's avatar
Lorenz Meier committed
106 107
    // Wait for it to exit
    wait();
108
    this->deleteLater();
pixhawk's avatar
pixhawk committed
109 110 111 112 113 114 115 116
}

/**
 * @brief Runs the thread
 *
 **/
void UDPLink::run()
{
117
    if(_hardwareConnect()) {
118
        exec();
119
    }
120
    if (_socket) {
121
        _deregisterZeroconf();
122 123
        _socket->close();
    }
pixhawk's avatar
pixhawk committed
124 125
}

126
void UDPLink::_restartConnection()
pixhawk's avatar
pixhawk committed
127
{
128 129 130 131 132
    if(this->isConnected())
    {
        _disconnect();
        _connect();
    }
pixhawk's avatar
pixhawk committed
133 134
}

135
QString UDPLink::getName() const
pixhawk's avatar
pixhawk committed
136
{
137
    return _config->name();
138 139 140 141
}

void UDPLink::addHost(const QString& host)
{
142
    _config->addHost(host);
143 144
}

145
void UDPLink::removeHost(const QString& host)
146
{
147
    _config->removeHost(host);
pixhawk's avatar
pixhawk committed
148 149
}

150
void UDPLink::_writeBytes(const QByteArray data)
151
{
152 153 154
    if (!_socket)
        return;

155 156 157 158 159 160 161
    QStringList goneHosts;
    // Send to all connected systems
    QString host;
    int port;
    if(_config->firstHost(host, port)) {
        do {
            QHostAddress currentHost(host);
162
            if(_socket->writeDatagram(data, currentHost, (quint16)port) < 0) {
163
                // This host is gone. Add to list to be removed
164 165 166 167 168 169 170 171 172 173 174 175
                // We should keep track of hosts that were manually added (static) and
                // hosts that were added because we heard from them (dynamic). Only
                // dynamic hosts should be removed and even then, after a few tries, not
                // the first failure. In the mean time, we don't remove anything.
                if(REMOVE_GONE_HOSTS) {
                    goneHosts.append(host);
                }
            } 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.
176
                _logOutputDataRate(data.size(), QDateTime::currentMSecsSinceEpoch());
177 178 179
            }
        } while (_config->nextHost(host, port));
        //-- Remove hosts that are no longer there
180
        foreach (const QString& ghost, goneHosts) {
181 182 183 184 185
            _config->removeHost(ghost);
        }
    }
}

pixhawk's avatar
pixhawk committed
186 187 188
/**
 * @brief Read a number of bytes from the interface.
 **/
189
void UDPLink::readBytes()
pixhawk's avatar
pixhawk committed
190
{
dogmaphobic's avatar
dogmaphobic committed
191
    QByteArray databuffer;
192
    while (_socket->hasPendingDatagrams())
193 194
    {
        QByteArray datagram;
195
        datagram.resize(_socket->pendingDatagramSize());
196 197
        QHostAddress sender;
        quint16 senderPort;
198
        _socket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
dogmaphobic's avatar
dogmaphobic committed
199 200 201 202 203 204
        databuffer.append(datagram);
        //-- Wait a bit before sending it over
        if(databuffer.size() > 10 * 1024) {
            emit bytesReceived(this, databuffer);
            databuffer.clear();
        }
205
        _logInputDataRate(datagram.length(), QDateTime::currentMSecsSinceEpoch());
206 207 208 209
        // TODO This doesn't validade the sender. Anything sending UDP packets to this port gets
        // 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
dogmaphobic's avatar
dogmaphobic committed
210
        _config->addHost(sender.toString(), (int)senderPort);
pixhawk's avatar
pixhawk committed
211
    }
dogmaphobic's avatar
dogmaphobic committed
212 213 214 215
    //-- Send whatever is left
    if(databuffer.size()) {
        emit bytesReceived(this, databuffer);
    }
pixhawk's avatar
pixhawk committed
216 217 218 219 220 221 222
}

/**
 * @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
223
void UDPLink::_disconnect(void)
pixhawk's avatar
pixhawk committed
224
{
225
    _running = false;
226
    quit();
227
    wait();
228 229 230 231
    if (_socket) {
        // Make sure delete happen on correct thread
        _socket->deleteLater();
        _socket = NULL;
232
        emit disconnected();
233 234
    }
    _connectState = false;
pixhawk's avatar
pixhawk committed
235 236 237 238 239 240 241
}

/**
 * @brief Connect the connection.
 *
 * @return True if connection has been established, false if connection couldn't be established.
 **/
242
bool UDPLink::_connect(void)
pixhawk's avatar
pixhawk committed
243
{
244
    if(this->isRunning() || _running)
245
    {
246
        _running = false;
247
        quit();
248
        wait();
249
    }
250
    _running = true;
251
    start(NormalPriority);
252
    return true;
oberion's avatar
oberion committed
253 254
}

255
bool UDPLink::_hardwareConnect()
oberion's avatar
oberion committed
256
{
257 258 259 260
    if (_socket) {
        delete _socket;
        _socket = NULL;
    }
261
    QHostAddress host = QHostAddress::AnyIPv4;
262
    _socket = new QUdpSocket();
263
    _socket->setProxy(QNetworkProxy::NoProxy);
264
    _connectState = _socket->bind(host, _config->localPort(), QAbstractSocket::ReuseAddressHint | QUdpSocket::ShareAddress);
265
    if (_connectState) {
dogmaphobic's avatar
dogmaphobic committed
266
        //-- Make sure we have a large enough IO buffers
Don Gagne's avatar
Don Gagne committed
267
#ifdef __mobile__
dogmaphobic's avatar
dogmaphobic committed
268 269 270 271 272 273
        _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
274
        _registerZeroconf(_config->localPort(), kZeroconfRegistration);
275
        QObject::connect(_socket, &QUdpSocket::readyRead, this, &UDPLink::readBytes);
276
        emit connected();
277 278
    } else {
        emit communicationError("UDP Link Error", "Error binding UDP port");
279
    }
280
    return _connectState;
pixhawk's avatar
pixhawk committed
281 282 283 284 285 286 287
}

/**
 * @brief Check if connection is active.
 *
 * @return True if link is connected, false otherwise.
 **/
288
bool UDPLink::isConnected() const
289
{
290
    return _connectState;
pixhawk's avatar
pixhawk committed
291 292
}

293
qint64 UDPLink::getConnectionSpeed() const
pixhawk's avatar
pixhawk committed
294
{
295 296 297 298 299 300
    return 54000000; // 54 Mbit
}

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

303
qint64 UDPLink::getCurrentOutDataRate() const
pixhawk's avatar
pixhawk committed
304
{
305
    return 0;
pixhawk's avatar
pixhawk committed
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
void UDPLink::_registerZeroconf(uint16_t port, const std::string &regType)
{
#if defined(QGC_ZEROCONF_ENABLED)
    DNSServiceErrorType result = DNSServiceRegister(&_dnssServiceRef, 0, 0, 0,
        regType.c_str(),
        NULL,
        NULL,
        htons(port),
        0,
        NULL,
        NULL,
        NULL);
    if (result != kDNSServiceErr_NoError)
    {
        emit communicationError("UDP Link Error", "Error registering Zeroconf");
        _dnssServiceRef = NULL;
    }
#else
    Q_UNUSED(port);
    Q_UNUSED(regType);
#endif
}

void UDPLink::_deregisterZeroconf()
{
#if defined(QGC_ZEROCONF_ENABLED)
    if (_dnssServiceRef)
     {
         DNSServiceRefDeallocate(_dnssServiceRef);
         _dnssServiceRef = NULL;
     }
#endif
}

342 343
//--------------------------------------------------------------------------
//-- UDPConfiguration
344

345
UDPConfiguration::UDPConfiguration(const QString& name) : LinkConfiguration(name)
346
{
347
    _localPort = QGC_UDP_LOCAL_PORT;
348 349
}

350
UDPConfiguration::UDPConfiguration(UDPConfiguration* source) : LinkConfiguration(source)
351
{
352 353 354
    _localPort = source->localPort();
    QString host;
    int port;
355
    _hostList.clear();
356 357 358 359 360
    if(source->firstHost(host, port)) {
        do {
            addHost(host, port);
        } while(source->nextHost(host, port));
    }
361 362
}

363
void UDPConfiguration::copyFrom(LinkConfiguration *source)
364
{
365
    LinkConfiguration::copyFrom(source);
366 367 368
    UDPConfiguration* usource = dynamic_cast<UDPConfiguration*>(source);
    Q_ASSERT(usource != NULL);
    _localPort = usource->localPort();
369
    _hosts.clear();
370 371 372 373 374 375 376 377 378 379 380 381
    QString host;
    int port;
    if(usource->firstHost(host, port)) {
        do {
            addHost(host, port);
        } while(usource->nextHost(host, port));
    }
}

/**
 * @param host Hostname in standard formatt, e.g. localhost:14551 or 192.168.1.1:14551
 */
382
void UDPConfiguration::addHost(const QString host)
383
{
384
    // Handle x.x.x.x:p
385 386
    if (host.contains(":"))
    {
387
        addHost(host.split(":").first(), host.split(":").last().toInt());
388
    }
389
    // If no port, use default
390 391
    else
    {
dogmaphobic's avatar
dogmaphobic committed
392
        addHost(host, (int)_localPort);
393 394 395 396 397
    }
}

void UDPConfiguration::addHost(const QString& host, int port)
{
dogmaphobic's avatar
dogmaphobic committed
398
    bool changed = false;
dogmaphobic's avatar
dogmaphobic committed
399 400 401 402
    QMutexLocker locker(&_confMutex);
    if(_hosts.contains(host)) {
        if(_hosts[host] != port) {
            _hosts[host] = port;
dogmaphobic's avatar
dogmaphobic committed
403
            changed = true;
dogmaphobic's avatar
dogmaphobic committed
404 405
        }
    } else {
406 407
        QString ipAdd = get_ip_address(host);
        if(ipAdd.isEmpty()) {
408
            qWarning() << "UDP:" << "Could not resolve host:" << host << "port:" << port;
409
        } else {
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
            // 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.
            bool not_local = true;
            // Run through all IPv4 interfaces and check if their canonical
            // IP address in string representation matches the source IP address
            foreach (const QHostAddress &address, QNetworkInterface::allAddresses()) {
                if (address.protocol() == QAbstractSocket::IPv4Protocol) {
                    if (ipAdd.endsWith(address.toString())) {
                        // This is a local address of the same host
                        not_local = false;
                    }
                }
            }
            if (not_local) {
                // This is a normal remote host, add it using its IPv4 address
                _hosts[ipAdd] = port;
                //qDebug() << "UDP:" << "Adding Host:" << ipAdd << ":" << port;
            } else {
                // It is localhost, so talk to it through the IPv4 loopback interface
                _hosts["127.0.0.1"] = port;
            }
dogmaphobic's avatar
dogmaphobic committed
437
            changed = true;
dogmaphobic's avatar
dogmaphobic committed
438 439
        }
    }
dogmaphobic's avatar
dogmaphobic committed
440 441 442
    if(changed) {
        _updateHostList();
    }
443 444
}

445
void UDPConfiguration::removeHost(const QString host)
446
{
dogmaphobic's avatar
dogmaphobic committed
447
    QMutexLocker locker(&_confMutex);
448 449 450 451 452 453 454
    QString tHost = host;
    if (tHost.contains(":")) {
        tHost = tHost.split(":").first();
    }
    tHost = tHost.trimmed();
    QMap<QString, int>::iterator i = _hosts.find(tHost);
    if(i != _hosts.end()) {
455
        //qDebug() << "UDP:" << "Removed host:" << host;
456
        _hosts.erase(i);
457 458
    } else {
        qWarning() << "UDP:" << "Could not remove unknown host:" << host;
459
    }
460
    _updateHostList();
461 462 463 464
}

bool UDPConfiguration::firstHost(QString& host, int& port)
{
dogmaphobic's avatar
dogmaphobic committed
465
    _confMutex.lock();
466 467
    _it = _hosts.begin();
    if(_it == _hosts.end()) {
dogmaphobic's avatar
dogmaphobic committed
468
        _confMutex.unlock();
469 470
        return false;
    }
dogmaphobic's avatar
dogmaphobic committed
471
    _confMutex.unlock();
472 473 474 475 476
    return nextHost(host, port);
}

bool UDPConfiguration::nextHost(QString& host, int& port)
{
dogmaphobic's avatar
dogmaphobic committed
477
    QMutexLocker locker(&_confMutex);
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
    if(_it != _hosts.end()) {
        host = _it.key();
        port = _it.value();
        _it++;
        return true;
    }
    return false;
}

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

void UDPConfiguration::saveSettings(QSettings& settings, const QString& root)
{
    _confMutex.lock();
    settings.beginGroup(root);
    settings.setValue("port", (int)_localPort);
    settings.setValue("hostCount", _hosts.count());
    int index = 0;
    QMap<QString, int>::const_iterator it = _hosts.begin();
    while(it != _hosts.end()) {
        QString hkey = QString("host%1").arg(index);
        settings.setValue(hkey, it.key());
        QString pkey = QString("port%1").arg(index);
        settings.setValue(pkey, it.value());
        it++;
        index++;
    }
    settings.endGroup();
    _confMutex.unlock();
}

void UDPConfiguration::loadSettings(QSettings& settings, const QString& root)
{
    _confMutex.lock();
    _hosts.clear();
dogmaphobic's avatar
dogmaphobic committed
516 517
    _confMutex.unlock();
    settings.beginGroup(root);
518
    _localPort = (quint16)settings.value("port", QGC_UDP_LOCAL_PORT).toUInt();
519 520 521 522 523 524 525 526 527
    int hostCount = settings.value("hostCount", 0).toInt();
    for(int i = 0; i < hostCount; i++) {
        QString hkey = QString("host%1").arg(i);
        QString pkey = QString("port%1").arg(i);
        if(settings.contains(hkey) && settings.contains(pkey)) {
            addHost(settings.value(hkey).toString(), settings.value(pkey).toInt());
        }
    }
    settings.endGroup();
528
    _updateHostList();
529 530 531 532 533 534 535 536 537 538
}

void UDPConfiguration::updateSettings()
{
    if(_link) {
        UDPLink* ulink = dynamic_cast<UDPLink*>(_link);
        if(ulink) {
            ulink->_restartConnection();
        }
    }
539
}
540 541 542 543 544 545 546 547 548 549 550 551

void UDPConfiguration::_updateHostList()
{
    _hostList.clear();
    QMap<QString, int>::const_iterator it = _hosts.begin();
    while(it != _hosts.end()) {
        QString host = QString("%1").arg(it.key()) + ":" + QString("%1").arg(it.value());
        _hostList += host;
        it++;
    }
    emit hostListChanged();
}