Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Fetching contributors…

Cannot retrieve contributors at this time

file 729 lines (659 sloc) 21.161 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 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 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 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 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 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 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729
#include <QNetworkAddressEntry>
#include <QReadWriteLock>
#include <QWriteLocker>
#include <QReadLocker>

#include "mythcorecontext.h"
#include "mythlogging.h"
#include "serverpool.h"

#define PRETTYIP(x) x->protocol() == QAbstractSocket::IPv6Protocol ? \
"[" + x->toString().toLower() + "]" : \
x->toString().toLower()
#define PRETTYIP_(x) x.protocol() == QAbstractSocket::IPv6Protocol ? \
"[" + x.toString().toLower() + "]" : \
x.toString().toLower()

#define LOC QString("ServerPool: ")

static QList<QNetworkAddressEntry> naList_4;
static QList<QNetworkAddressEntry> naList_6;
static QReadWriteLock naLock;

class PrivUdpSocket : public QUdpSocket
{
public:
    PrivUdpSocket(QObject *parent, QNetworkAddressEntry host) :
        QUdpSocket(parent), m_host(host) { };
    ~PrivUdpSocket() { };
    QNetworkAddressEntry host()
    {
        return m_host;
    };
    bool contains(QHostAddress addr)
    {
        return contains(m_host, addr);
    };
    static bool contains(QNetworkAddressEntry host, QHostAddress addr)
    {
#if !defined(QT_NO_IPV6)
        if (addr.protocol() == QAbstractSocket::IPv6Protocol &&
            addr.isInSubnet(QHostAddress::parseSubnet("fe80::/10")) &&
            host.ip().scopeId() != addr.scopeId())
        {
            return false;
        }
#endif
        return addr.isInSubnet(host.ip(), host.prefixLength());
    }
private:
    QNetworkAddressEntry m_host;
};

PrivTcpServer::PrivTcpServer(QObject *parent) : QTcpServer(parent)
{
}

void PrivTcpServer::incomingConnection(int socket)
{
    emit newConnection(socket);
}

ServerPool::ServerPool(QObject *parent) : QObject(parent),
    m_listening(false), m_maxPendingConn(30), m_port(0),
    m_proxy(QNetworkProxy::DefaultProxy), m_lastUdpSocket(NULL)
{
}

ServerPool::~ServerPool()
{
    close();
}

void ServerPool::SelectDefaultListen(bool force)
{
    if (!force)
    {
        QReadLocker rlock(&naLock);
        if (!naList_4.isEmpty() || !naList_6.isEmpty())
            // lists are already populated, do nothing
            return;
    }

    QWriteLocker wlock(&naLock);
    naList_4.clear();
    naList_6.clear();

    // populate stored IPv4 and IPv6 addresses
    // if address is not defined, QHostAddress will be invalid and Null
    QHostAddress config_v4(gCoreContext->GetSetting("BackendServerIP"));
    bool v4IsSet = config_v4.isNull() ? true : false;
#if !defined(QT_NO_IPV6)
    QHostAddress config_v6(gCoreContext->GetSetting("BackendServerIP6"));
    bool v6IsSet = config_v6.isNull() ? true : false;
#endif

    // loop through all available interfaces
    QList<QNetworkInterface> IFs = QNetworkInterface::allInterfaces();
    QList<QNetworkInterface>::const_iterator qni;
    for (qni = IFs.begin(); qni != IFs.end(); ++qni)
    {
        if ((qni->flags() & QNetworkInterface::IsRunning) == 0)
            continue;

        QList<QNetworkAddressEntry> IPs = qni->addressEntries();
        QList<QNetworkAddressEntry>::const_iterator qnai;
        for (qnai = IPs.begin(); qnai != IPs.end(); ++qnai)
        {
            QHostAddress ip = qnai->ip();
            if (naList_4.contains(*qnai))
                // already defined, skip
                continue;
            else if (!config_v4.isNull() && (ip == config_v4))
            {
                // IPv4 address is defined, add it
                LOG(VB_GENERAL, LOG_DEBUG,
                        QString("Adding BackendServerIP to address list."));
                naList_4.append(*qnai);
                v4IsSet = true;
            }
            else if (ip == QHostAddress::LocalHost)
            {
                // always listen on LocalHost
                LOG(VB_GENERAL, LOG_DEBUG,
                        QString("Adding IPv4 loopback to address list."));
                naList_4.append(*qnai);
                if (!v4IsSet && (config_v4 == ip))
                    v4IsSet = true;
            }
            else if (config_v4.isNull() &&
                     (ip.protocol() == QAbstractSocket::IPv4Protocol))
            {
                // IPv4 address is not defined, populate one
                // restrict autoconfiguration to RFC1918 private networks
                if (ip.isInSubnet(QHostAddress::parseSubnet("10.0.0.0/8")) ||
                    ip.isInSubnet(QHostAddress::parseSubnet("172.16.0.0/12")) ||
                    ip.isInSubnet(QHostAddress::parseSubnet("192.168.0.0/16")))
                {
                    LOG(VB_GENERAL, LOG_DEBUG,
                            QString("Adding '%1' to address list.")
                                .arg(ip.toString()));
                    naList_4.append(*qnai);
                }
                else
                    LOG(VB_GENERAL, LOG_DEBUG, QString("Skipping non-private "
                            "address during IPv4 autoselection: %1")
                                .arg(ip.toString()));
            }
#if !defined(QT_NO_IPV6)
            else if (naList_6.contains(*qnai))
                // already defined, skip
                continue;
            else if (!config_v6.isNull() && (ip == config_v6))
            {
                // IPv6 address is defined, add it
                LOG(VB_GENERAL, LOG_DEBUG,
                        QString("Adding BackendServerIP6 to address list."));
                naList_6.append(*qnai);
                v6IsSet = true;
            }
            else if (ip == QHostAddress::LocalHostIPv6)
            {
                // always listen on LocalHost
                LOG(VB_GENERAL, LOG_DEBUG,
                        QString("Adding IPv6 loopback to address list."));
                naList_6.append(*qnai);
                if (!v6IsSet && (config_v6 == ip))
                    v6IsSet = true;
            }
            else if (config_v6.isNull() &&
                     (ip.protocol() == QAbstractSocket::IPv6Protocol))
            {
                bool linklocal = false;
                if (ip.isInSubnet(QHostAddress::parseSubnet("fe80::/10")))
                {
                    // Link-local address, find its scope ID (interface name)
                    QNetworkAddressEntry ae = *qnai;
                    QHostAddress ha = ip;
                    ha.setScopeId(qni->name());
                    ae.setIp(ha);
                    naList_6.append(ae);
                    linklocal = true;
                }
                else
                {
                    naList_6.append(*qnai);
                }
                LOG(VB_GENERAL, LOG_DEBUG,
                        QString("Adding%1 '%2' to address list.")
                    .arg(linklocal ? " link-local" : "")
                            .arg(PRETTYIP_(ip)));
            }
#endif
            else
                LOG(VB_GENERAL, LOG_DEBUG, QString("Skipping address: %1")
                    .arg(PRETTYIP_(ip)));
        }
    }

    if (!v4IsSet && (config_v4 != QHostAddress::LocalHost)
                 && !naList_4.isEmpty())
    {
        LOG(VB_GENERAL, LOG_CRIT, LOC + QString("Host is configured to listen "
                "on %1, but address is not used on any local network "
                "interfaces.").arg(config_v4.toString()));
    }

#if !defined(QT_NO_IPV6)
    if (!v6IsSet && (config_v6 != QHostAddress::LocalHostIPv6)
                 && !naList_6.isEmpty())
    {
        LOG(VB_GENERAL, LOG_CRIT, LOC + QString("Host is configured to listen "
                "on %1, but address is not used on any local network "
                "interfaces.").arg(PRETTYIP_(config_v6)));
    }
#endif

    // NOTE: there is no warning for the case where both defined addresses
    // are localhost, and neither are found. however this would also
    // mean there is no configured network at all, and should be
    // sufficiently rare a case as to not worry about it.
}

void ServerPool::RefreshDefaultListen(void)
{
    SelectDefaultListen(true);
    // TODO:
    // send signal for any running servers to cycle their addresses
    // will allow address configuration to be modified without a server
    // reset for use with the migration to the mythtv-setup replacement
}

QList<QHostAddress> ServerPool::DefaultListen(void)
{
    QList<QHostAddress> alist;
    alist << DefaultListenIPv4()
          << DefaultListenIPv6();
    return alist;
}

QList<QHostAddress> ServerPool::DefaultListenIPv4(void)
{
    SelectDefaultListen();
    QReadLocker rlock(&naLock);

    QList<QHostAddress> alist;
    QList<QNetworkAddressEntry>::const_iterator it;
    for (it = naList_4.begin(); it != naList_4.end(); ++it)
        if (!alist.contains(it->ip()))
            alist << it->ip();

    return alist;
}

QList<QHostAddress> ServerPool::DefaultListenIPv6(void)
{
    SelectDefaultListen();
    QReadLocker rlock(&naLock);

    QList<QHostAddress> alist;
    QList<QNetworkAddressEntry>::const_iterator it;
    for (it = naList_6.begin(); it != naList_6.end(); ++it)
        if (!alist.contains(it->ip()))
            alist << it->ip();

    return alist;
}

QList<QHostAddress> ServerPool::DefaultBroadcast(void)
{
    QList<QHostAddress> blist;
    blist << DefaultBroadcastIPv4();
    return blist;
}

QList<QHostAddress> ServerPool::DefaultBroadcastIPv4(void)
{
    SelectDefaultListen();
    QReadLocker rlock(&naLock);

    QList<QHostAddress> blist;
    QList<QNetworkAddressEntry>::const_iterator it;
    for (it = naList_4.begin(); it != naList_4.end(); ++it)
        if (!blist.contains(it->broadcast()) && (it->prefixLength() != 32) &&
                (it->ip() != QHostAddress::LocalHost))
            blist << it->broadcast();

    return blist;
}

//QList<QHostAddress> ServerPool::DefaultBroadcastIPv6(void)
//{
//
//}


void ServerPool::close(void)
{
    QTcpServer *server;
    while (!m_tcpServers.isEmpty())
    {
        server = m_tcpServers.takeLast();
        server->disconnect();
        server->close();
        server->deleteLater();
    }

    PrivUdpSocket *socket;
    while (!m_udpSockets.isEmpty())
    {
        socket = m_udpSockets.takeLast();
        socket->disconnect();
        socket->close();
        socket->deleteLater();
    }
    m_lastUdpSocket = NULL;
    m_listening = false;
}

bool ServerPool::listen(QList<QHostAddress> addrs, quint16 port,
                        bool requireall)
{
    m_port = port;
    QList<QHostAddress>::const_iterator it;

    for (it = addrs.begin(); it != addrs.end(); ++it)
    {
        PrivTcpServer *server = new PrivTcpServer(this);
        server->setProxy(m_proxy);
        server->setMaxPendingConnections(m_maxPendingConn);

        connect(server, SIGNAL(newConnection(int)),
                this, SLOT(newTcpConnection(int)));

        if (server->listen(*it, m_port))
        {
            LOG(VB_GENERAL, LOG_INFO, QString("Listening on TCP %1:%2")
                    .arg(PRETTYIP(it)).arg(port));
            m_tcpServers.append(server);
            if (m_port == 0)
                m_port = server->serverPort();
        }
        else
        {
            LOG(VB_GENERAL, LOG_ERR,
                    QString("Failed listening on TCP %1:%2 - Error %3: %4")
                        .arg(PRETTYIP(it))
                        .arg(port)
                        .arg(server->serverError())
                        .arg(server->errorString()));
            server->disconnect();
            server->deleteLater();

            if (requireall)
            {
                close();
                return false;
            }
        }
    }

    if (m_tcpServers.size() == 0)
        return false;

    m_listening = true;
    return true;
}

bool ServerPool::listen(QStringList addrstr, quint16 port, bool requireall)
{
    QList<QHostAddress> addrs;
    QStringList::const_iterator it;
    for (it = addrstr.begin(); it != addrstr.end(); ++it)
        addrs << QHostAddress(*it);
    return listen(addrs, port, requireall);
}

bool ServerPool::listen(quint16 port, bool requireall)
{
    return listen(DefaultListen(), port, requireall);
}

bool ServerPool::bind(QList<QHostAddress> addrs, quint16 port,
                      bool requireall)
{
    m_port = port;
    QList<QHostAddress>::const_iterator it;

    for (it = addrs.begin(); it != addrs.end(); ++it)
    {
        QNetworkAddressEntry host;

#if !defined(QT_NO_IPV6)
        if (it->protocol() == QAbstractSocket::IPv6Protocol)
        {
            QList<QNetworkAddressEntry>::iterator iae;
            for (iae = naList_6.begin(); iae != naList_6.end(); ++iae)
            {
                if (PrivUdpSocket::contains(*iae, *it))
                {
                    host = *iae;
                    break;
                }
            }
        }
        else
#endif
        {
            QList<QNetworkAddressEntry>::iterator iae;
            for (iae = naList_4.begin(); iae != naList_4.end(); ++iae)
            {
                if (PrivUdpSocket::contains(*iae, *it))
                {
                    host = *iae;
                    break;
                }
            }
        }

        PrivUdpSocket *socket = new PrivUdpSocket(this, host);

        if (socket->bind(*it, port))
        {
            LOG(VB_GENERAL, LOG_INFO, QString("Binding to UDP %1:%2")
                    .arg(PRETTYIP(it)).arg(port));
            m_udpSockets.append(socket);
            connect(socket, SIGNAL(readyRead()),
                    this, SLOT(newUdpDatagram()));
        }
        else
        {
            LOG(VB_GENERAL, LOG_ERR,
                    QString("Failed binding to UDP %1:%2 - Error %3: %4")
                        .arg(PRETTYIP(it))
                        .arg(port)
                        .arg(socket->error())
                        .arg(socket->errorString()));
            socket->disconnect();
            socket->deleteLater();

            if (requireall)
            {
                close();
                return false;
            }
        }
    }

    if (m_udpSockets.size() == 0)
        return false;

    m_listening = true;
    return true;
}

bool ServerPool::bind(QStringList addrstr, quint16 port, bool requireall)
{
    QList<QHostAddress> addrs;
    QStringList::const_iterator it;
    for (it = addrstr.begin(); it != addrstr.end(); ++it)
        addrs << QHostAddress(*it);
    return bind(addrs, port, requireall);
}

bool ServerPool::bind(quint16 port, bool requireall)
{
    return bind(DefaultListen(), port, requireall);
}

qint64 ServerPool::writeDatagram(const char * data, qint64 size,
                                 const QHostAddress &addr, quint16 port)
{
    if (!m_listening || m_udpSockets.size() == 0)
    {
        LOG(VB_GENERAL, LOG_ERR, "Trying to write datagram to disconnected "
                            "ServerPool instance.");
        return -1;
    }

    // check if can re-use the last one, so there's no need for a linear search
    if (!m_lastUdpSocket || !m_lastUdpSocket->contains(addr))
    {
        // find the right socket to use
        QList<PrivUdpSocket*>::iterator it;
        for (it = m_udpSockets.begin(); it != m_udpSockets.end(); ++it)
        {
            PrivUdpSocket *val = *it;
            if (val->contains(addr))
            {
                m_lastUdpSocket = val;
                break;
            }
        }
    }
    if (!m_lastUdpSocket)
        return -1;

    qint64 ret = m_lastUdpSocket->writeDatagram(data, size, addr, port);
    if (ret != size)
    {
        LOG(VB_GENERAL, LOG_DEBUG, QString("Error = %1 : %2")
                .arg(ret).arg(m_lastUdpSocket->error()));
    }
    return ret;
}

qint64 ServerPool::writeDatagram(const QByteArray &datagram,
                                 const QHostAddress &addr, quint16 port)
{
    return writeDatagram(datagram.data(), datagram.size(), addr, port);
}

void ServerPool::newTcpConnection(int socket)
{
    QTcpSocket *qsock = new QTcpSocket(this);
    qsock->setSocketDescriptor(socket);
    emit newConnection(qsock);
}

void ServerPool::newUdpDatagram(void)
{
    QUdpSocket *socket = dynamic_cast<QUdpSocket*>(sender());

    while (socket->state() == QAbstractSocket::BoundState &&
           socket->hasPendingDatagrams())
    {
        QByteArray buffer;
        buffer.resize(socket->pendingDatagramSize());
        QHostAddress sender;
        quint16 senderPort;

        socket->readDatagram(buffer.data(), buffer.size(),
                             &sender, &senderPort);
        emit newDatagram(buffer, sender, senderPort);
    }
}

/**
* tryListeningPort
*
* Description:
* Tells the server to listen for incoming connections on port port.
* The server will attempt to listen on all local interfaces.
*
* Usage:
* baseport: port to listen on.
* range: range of ports to try (default 1)
*
* Returns port used on success; otherwise returns -1.
*/
int ServerPool::tryListeningPort(int baseport, int range)
{
    // try a few ports in case the first is in use
    int port = baseport;
    while (port < baseport + range)
    {
        if (listen(port))
        {
            break;
        }
        port++;
    }

    if (port >= baseport + range)
    {
        return -1;
    }
    return port;
}

/**
* tryBindingPort
*
* Description:
* Binds this socket for incoming connections on port port.
* The socket will attempt to bind on all local interfaces.
*
* Usage:
* baseport: port to bind to.
* range: range of ports to try (default 1)
*
* Returns port used on success; otherwise returns -1.
*/
int ServerPool::tryBindingPort(int baseport, int range)
{
    // try a few ports in case the first is in use
    int port = baseport;
    while (port < baseport + range)
    {
        if (bind(port))
        {
            break;
        }
        port++;
    }

    if (port >= baseport + range)
    {
        return -1;
    }
    return port;
}

/**
* tryListeningPort
*
* Description:
* Tells the server to listen for incoming connections on port port.
* The server will attempt to listen on all IPv6 and IPv4 interfaces.
* If IPv6 isn't available, the server will listen on all IPv4 network interfaces.
*
* Usage:
* server: QTcpServer object to use
* baseport: port to listen on. If port is 0, a port is chosen automatically.
* range: range of ports to try (default 1)
* isipv6: is set to true if IPv6 was successful (default NULL)
*
* Returns port used on success; otherwise returns -1.
*/
int ServerPool::tryListeningPort(QTcpServer *server, int baseport,
                                 int range, bool *isipv6)
{
    bool ipv6 = true;
    // try a few ports in case the first is in use
    int port = baseport;
    while (port < baseport + range)
    {
        if (ipv6)
        {
            if (server->listen(QHostAddress::AnyIPv6, port))
            {
                break;
            }
            else
            {
                // did we fail because IPv6 isn't available?
                QAbstractSocket::SocketError err = server->serverError();
                if (err == QAbstractSocket::UnsupportedSocketOperationError)
                {
                    ipv6 = false;
                }
            }
        }
        if (!ipv6)
        {
            if (server->listen(QHostAddress::Any, port))
            {
                break;
            }
        }
        port++;
    }

    if (isipv6)
    {
        *isipv6 = ipv6;
    }

    if (port >= baseport + range)
    {
        return -1;
    }
    if (port == 0)
    {
        port = server->serverPort();
    }
    return port;
}

/**
* tryBindingPort
*
* Description:
* Binds this socket for incoming connections on port port.
* The socket will attempt to bind on all IPv6 and IPv4 interfaces.
* If IPv6 isn't available, the socket will be bound to all IPv4 network interfaces.
*
* Usage:
* socket: QUdpSocket object to use
* baseport: port to bind to.
* range: range of ports to try (default 1)
* isipv6: is set to true if IPv6 was successful (default NULL)
*
* Returns port used on success; otherwise returns -1.
*/
int ServerPool::tryBindingPort(QUdpSocket *socket, int baseport,
                               int range, bool *isipv6)
{
    bool ipv6 = true;
    // try a few ports in case the first is in use
    int port = baseport;
    while (port < baseport + range)
    {
        if (ipv6)
        {
            if (socket->bind(QHostAddress::AnyIPv6, port))
            {
                break;
            }
            else
            {
                // did we fail because IPv6 isn't available?
                QAbstractSocket::SocketError err = socket->error();
                if (err == QAbstractSocket::UnsupportedSocketOperationError)
                {
                    ipv6 = false;
                }
            }
        }
        if (!ipv6)
        {
            if (socket->bind(QHostAddress::Any, port))
            {
                break;
            }
        }
        port++;
    }

    if (isipv6)
    {
        *isipv6 = ipv6;
    }

    if (port >= baseport + range)
    {
        return -1;
    }
    return port;
}
Something went wrong with that request. Please try again.