From 3e8e815b372be26b5680b49be696fc5e13626274 Mon Sep 17 00:00:00 2001 From: "Uwe L. Korn" Date: Fri, 5 Apr 2013 13:19:57 +0200 Subject: [PATCH] Support multiple SipInfos per peer --- src/accounts/xmpp/sip/TomahawkXmppMessage.cpp | 57 +-- src/accounts/xmpp/sip/TomahawkXmppMessage.h | 21 +- .../xmpp/sip/TomahawkXmppMessageFactory.cpp | 142 ++++-- .../xmpp/sip/TomahawkXmppMessageFactory.h | 11 +- src/accounts/xmpp/sip/XmppSip.cpp | 34 +- src/accounts/xmpp/sip/XmppSip.h | 2 +- src/accounts/zeroconf/Zeroconf.cpp | 4 +- src/accounts/zeroconf/Zeroconf.h | 2 +- src/libtomahawk/CMakeLists.txt | 1 + src/libtomahawk/network/QTcpSocketExtra.cpp | 64 +++ src/libtomahawk/network/QTcpSocketExtra.h | 82 ++++ src/libtomahawk/network/Servent.cpp | 442 +++++++++++------- src/libtomahawk/network/Servent.h | 70 ++- src/libtomahawk/sip/PeerInfo.cpp | 31 +- src/libtomahawk/sip/PeerInfo.h | 14 +- src/libtomahawk/sip/SipPlugin.h | 3 +- src/tomahawk/DiagnosticsDialog.cpp | 77 +-- 17 files changed, 638 insertions(+), 419 deletions(-) create mode 100644 src/libtomahawk/network/QTcpSocketExtra.cpp create mode 100644 src/libtomahawk/network/QTcpSocketExtra.h diff --git a/src/accounts/xmpp/sip/TomahawkXmppMessage.cpp b/src/accounts/xmpp/sip/TomahawkXmppMessage.cpp index ef2951812..f7f5ca8e9 100644 --- a/src/accounts/xmpp/sip/TomahawkXmppMessage.cpp +++ b/src/accounts/xmpp/sip/TomahawkXmppMessage.cpp @@ -21,60 +21,39 @@ #include "utils/Logger.h" - -class TomahawkXmppMessagePrivate +TomahawkXmppMessage::TomahawkXmppMessage() : m_sipInfo() { -public: - QString ip; - int port; - QString uniqname; - QString key; - bool visible; -}; - -TomahawkXmppMessage::TomahawkXmppMessage(const QString &ip, unsigned int port, const QString &uniqname, const QString &key) : d_ptr(new TomahawkXmppMessagePrivate) -{ - Q_D(TomahawkXmppMessage); - d->ip = ip; - d->port = port; - d->uniqname = uniqname; - d->key = key; - d->visible = true; } -TomahawkXmppMessage::TomahawkXmppMessage() : d_ptr(new TomahawkXmppMessagePrivate) +TomahawkXmppMessage::TomahawkXmppMessage( const QList &sipInfo ) : m_sipInfo( sipInfo ) { - Q_D(TomahawkXmppMessage); - d->visible = false; - d->port = -1; } - TomahawkXmppMessage::~TomahawkXmppMessage() { } -const QString TomahawkXmppMessage::ip() const +const QList +TomahawkXmppMessage::sipInfo() const { - return d_func()->ip; + return m_sipInfo; } -unsigned int TomahawkXmppMessage::port() const + +const QString +TomahawkXmppMessage::key() const { - return d_func()->port; + if ( m_sipInfo.length() > 0 ) + return m_sipInfo.first().key(); + else + return QString(); } -const QString TomahawkXmppMessage::uniqname() const +const QString +TomahawkXmppMessage::uniqname() const { - return d_func()->uniqname; -} - -const QString TomahawkXmppMessage::key() const -{ - return d_func()->key; -} - -bool TomahawkXmppMessage::visible() const -{ - return d_func()->visible; + if ( m_sipInfo.length() > 0 ) + return m_sipInfo.first().nodeId(); + else + return QString(); } diff --git a/src/accounts/xmpp/sip/TomahawkXmppMessage.h b/src/accounts/xmpp/sip/TomahawkXmppMessage.h index d26ac30ae..9ea943b8b 100644 --- a/src/accounts/xmpp/sip/TomahawkXmppMessage.h +++ b/src/accounts/xmpp/sip/TomahawkXmppMessage.h @@ -22,30 +22,29 @@ #include +#include "sip/SipInfo.h" + #define TOMAHAWK_SIP_MESSAGE_NS QLatin1String("http://www.tomhawk-player.org/sip/transports") #include "accounts/AccountDllMacro.h" -class TomahawkXmppMessagePrivate; class ACCOUNTDLLEXPORT TomahawkXmppMessage : public Jreen::Payload { J_PAYLOAD(TomahawkXmppMessage) - Q_DECLARE_PRIVATE(TomahawkXmppMessage) public: - // sets visible to true - TomahawkXmppMessage(const QString &ip, unsigned int port, const QString &uniqname, const QString &key); - - // sets visible to false as we dont have any extra information TomahawkXmppMessage(); + TomahawkXmppMessage(const QList& sipInfo); ~TomahawkXmppMessage(); - const QString ip() const; - unsigned int port() const; - const QString uniqname() const; + //! The SipInfo objects that are wrapped in this XmppMessage + const QList sipInfo() const; + //! The name of the peer contained in this message const QString key() const; - bool visible() const; + //! The name of the peer contained in this message + const QString uniqname() const; + private: - QScopedPointer d_ptr; + QList m_sipInfo; }; #endif // ENTITYTIME_H diff --git a/src/accounts/xmpp/sip/TomahawkXmppMessageFactory.cpp b/src/accounts/xmpp/sip/TomahawkXmppMessageFactory.cpp index 5c6a3f81f..04cb9b9e3 100644 --- a/src/accounts/xmpp/sip/TomahawkXmppMessageFactory.cpp +++ b/src/accounts/xmpp/sip/TomahawkXmppMessageFactory.cpp @@ -19,6 +19,7 @@ #include "TomahawkXmppMessageFactory.h" +#include "network/Servent.h" #include "utils/Logger.h" #include @@ -28,7 +29,7 @@ using namespace Jreen; -TomahawkXmppMessageFactory::TomahawkXmppMessageFactory() +TomahawkXmppMessageFactory::TomahawkXmppMessageFactory() : m_sipInfo() { m_depth = 0; m_state = AtNowhere; @@ -54,31 +55,35 @@ void TomahawkXmppMessageFactory::handleStartElement(const QStringRef &name, cons const QXmlStreamAttributes &attributes) { m_depth++; - if (m_depth == 1) { + if ( m_depth == 1 ) + { m_state = AtNowhere; - m_ip = QString(); - m_port = -1; m_uniqname = QString(); m_key = QString(); - m_visible = false; - } else if (m_depth == 2) { - if (name == QLatin1String("transport")) + m_sipInfo = QList(); + } + else if ( m_depth == 2 ) + { + if ( name == QLatin1String( "transport" ) ) { -// qDebug() << "Found Transport"; m_state = AtTransport; - - m_uniqname = attributes.value(QLatin1String("uniqname")).toString(); - m_key = attributes.value(QLatin1String("pwd")).toString(); + m_uniqname = attributes.value( QLatin1String( "uniqname" ) ).toString(); + m_key = attributes.value( QLatin1String( "pwd" ) ).toString(); } - } else if(m_depth == 3) { - if (name == QLatin1String("candidate")) + } + else if(m_depth == 3) + { + if ( name == QLatin1String( "candidate" ) ) { m_state = AtCandidate; -// qDebug() << "Found candidate"; - m_ip = attributes.value(QLatin1String("ip")).toString(); - m_port = attributes.value(QLatin1String("port")).toString().toInt(); - - m_visible = true; + SipInfo info = SipInfo(); + info.setVisible( true ); + info.setHost( attributes.value( QLatin1String( "ip" ) ).toString() ); + info.setPort( attributes.value( QLatin1String( "port" ) ).toString().toInt() ); + info.setKey( m_key ); + info.setNodeId( m_uniqname ); + Q_ASSERT( info.isValid() ); + m_sipInfo.append( info ); } } Q_UNUSED(uri); @@ -87,8 +92,22 @@ void TomahawkXmppMessageFactory::handleStartElement(const QStringRef &name, cons void TomahawkXmppMessageFactory::handleEndElement(const QStringRef &name, const QStringRef &uri) { - if (m_depth == 3) + if ( m_depth == 3 ) + m_state = AtTransport; + else if ( m_depth == 2 ) + { m_state = AtNowhere; + // Check that we have at least one SipInfo so that we provide some information about invisible peers. + if ( m_sipInfo.length() == 0 ) + { + SipInfo info = SipInfo(); + info.setVisible( false ); + info.setKey( m_key ); + info.setNodeId( m_uniqname ); + Q_ASSERT( info.isValid() ); + m_sipInfo.append( info ); + } + } Q_UNUSED(name); Q_UNUSED(uri); m_depth--; @@ -111,38 +130,69 @@ void TomahawkXmppMessageFactory::serialize(Payload *extension, QXmlStreamWriter { TomahawkXmppMessage *sipMessage = se_cast(extension); - writer->writeStartElement(QLatin1String("tomahawk")); - writer->writeDefaultNamespace(TOMAHAWK_SIP_MESSAGE_NS); + writer->writeStartElement( QLatin1String( "tomahawk" ) ); + writer->writeDefaultNamespace( TOMAHAWK_SIP_MESSAGE_NS ); - if(sipMessage->visible()) + // Get a copy of the list, so that we can modify it here. + QList sipInfo = QList( sipMessage->sipInfo() ); + QSharedPointer lastInfo = QSharedPointer(); + foreach ( SipInfo info, sipInfo ) + { + if ( info.isVisible() ) { - // add transport tag - writer->writeStartElement(QLatin1String("transport")); - writer->writeAttribute(QLatin1String("pwd"), sipMessage->key()); - writer->writeAttribute(QLatin1String("uniqname"), sipMessage->uniqname()); + QHostAddress ha = QHostAddress( info.host() ); + if ( Servent::isValidExternalIP( ha ) && ha.protocol() == QAbstractSocket::IPv4Protocol ) + { + // For comapability reasons, this shall be put as the last candidate + lastInfo = QSharedPointer( new SipInfo( info ) ); + sipInfo.removeOne( info ); + break; + } + } + } - writer->writeEmptyElement(QLatin1String("candidate")); - writer->writeAttribute(QLatin1String("component"), "1"); - writer->writeAttribute(QLatin1String("id"), "el0747fg11"); // FIXME - writer->writeAttribute(QLatin1String("ip"), sipMessage->ip()); - writer->writeAttribute(QLatin1String("network"), "1"); - writer->writeAttribute(QLatin1String("port"), QVariant(sipMessage->port()).toString()); - writer->writeAttribute(QLatin1String("priority"), "1"); //TODO - writer->writeAttribute(QLatin1String("protocol"), "tcp"); - writer->writeAttribute(QLatin1String("type"), "host"); //FIXME: correct?! - writer->writeEndElement(); - } - else - { - writer->writeEmptyElement(QLatin1String("transport")); - } - writer->writeEndElement(); + writer->writeStartElement( QLatin1String( "transport" ) ); + writer->writeAttribute( QLatin1String( "pwd" ), sipMessage->key() ); + writer->writeAttribute( QLatin1String( "uniqname" ), sipMessage->uniqname() ); + + foreach ( SipInfo info, sipInfo ) + { + if ( info.isVisible() ) + serializeSipInfo( info, writer ); + } + + if ( !lastInfo.isNull() ) + { + Q_ASSERT( lastInfo->isVisible() ); + serializeSipInfo( *lastInfo, writer ); + } + + // + writer->writeEndElement(); } -Payload::Ptr TomahawkXmppMessageFactory::createPayload() +Payload::Ptr +TomahawkXmppMessageFactory::createPayload() { - if(m_visible) - return Payload::Ptr(new TomahawkXmppMessage(m_ip, m_port, m_uniqname, m_key)); + if ( ( ( m_sipInfo.length() == 1 ) && ( !m_sipInfo.first().isVisible() ) ) || ( m_sipInfo.length() < 1 ) ) + return Payload::Ptr( new TomahawkXmppMessage() ); else - return Payload::Ptr(new TomahawkXmppMessage()); + return Payload::Ptr( new TomahawkXmppMessage( m_sipInfo ) ); +} + +void +TomahawkXmppMessageFactory::serializeSipInfo(SipInfo &info, QXmlStreamWriter *writer) +{ + if ( info.isVisible() ) + { + writer->writeEmptyElement( QLatin1String( "candidate" ) ); + writer->writeAttribute( QLatin1String( "component" ), "1" ); + writer->writeAttribute( QLatin1String( "id" ), "el0747fg11" ); // FIXME + writer->writeAttribute( QLatin1String( "ip" ), info.host() ); + writer->writeAttribute( QLatin1String( "network" ), "1" ); + writer->writeAttribute( QLatin1String( "port" ), QVariant( info.port() ).toString() ); + writer->writeAttribute( QLatin1String( "priority" ), "1" ); //TODO + writer->writeAttribute( QLatin1String( "protocol" ), "tcp" ); + writer->writeAttribute( QLatin1String( "type" ), "host" ); //FIXME: correct?! + } } diff --git a/src/accounts/xmpp/sip/TomahawkXmppMessageFactory.h b/src/accounts/xmpp/sip/TomahawkXmppMessageFactory.h index f1910cb40..ba06f7a2c 100644 --- a/src/accounts/xmpp/sip/TomahawkXmppMessageFactory.h +++ b/src/accounts/xmpp/sip/TomahawkXmppMessageFactory.h @@ -39,13 +39,18 @@ public: void serialize(Jreen::Payload *extension, QXmlStreamWriter *writer); Jreen::Payload::Ptr createPayload(); private: + void serializeSipInfo(SipInfo& info, QXmlStreamWriter *writer); + enum State { AtNowhere, AtTransport, AtCandidate } m_state; + + //! All the provided Sip informations + QList m_sipInfo; + //! The current parsing depth int m_depth; - QString m_ip; - int m_port; + //! The unique name of the peer QString m_uniqname; + //! The authentication key of the peer QString m_key; - bool m_visible; }; #endif // ENTITYTIMEFACTORY_P_H diff --git a/src/accounts/xmpp/sip/XmppSip.cpp b/src/accounts/xmpp/sip/XmppSip.cpp index cd878d392..a2463ce5f 100644 --- a/src/accounts/xmpp/sip/XmppSip.cpp +++ b/src/accounts/xmpp/sip/XmppSip.cpp @@ -435,22 +435,15 @@ XmppSipPlugin::errorMessage( Jreen::Client::DisconnectReason reason ) void -XmppSipPlugin::sendSipInfo( const Tomahawk::peerinfo_ptr& receiver, const SipInfo& info ) +XmppSipPlugin::sendSipInfoList( const Tomahawk::peerinfo_ptr& receiver, const QList& info ) { tDebug( LOGVERBOSE ) << Q_FUNC_INFO << receiver << info; if ( !m_client ) return; - TomahawkXmppMessage *sipMessage; - if ( info.isVisible() ) - { - sipMessage = new TomahawkXmppMessage( info.host(), info.port(), info.nodeId(), info.key() ); - } - else - sipMessage = new TomahawkXmppMessage(); - - qDebug() << "Send sip messsage to" << receiver; + TomahawkXmppMessage* sipMessage = new TomahawkXmppMessage( info ); + tDebug( LOGVERBOSE ) << Q_FUNC_INFO << "Send sip messsage to" << receiver; Jreen::IQ iq( Jreen::IQ::Set, receiver->id() ); iq.addExtension( sipMessage ); Jreen::IQReply *reply = m_client->send( iq ); @@ -687,6 +680,7 @@ XmppSipPlugin::onNewMessage( const Jreen::Message& message ) return; } + // FIXME: We do not sent SipInfo in JSON via XMPP, why do we receive it here? SipInfo info = SipInfo::fromJson( msg ); if ( !info.isValid() ) { @@ -912,30 +906,22 @@ XmppSipPlugin::onNewIq( const Jreen::IQ& iq ) if ( sipMessage ) { iq.accept(); + tLog( LOGVERBOSE ) << Q_FUNC_INFO << "Received Sip Information from:" << iq.from().full(); - qDebug() << Q_FUNC_INFO << "Got SipMessage ..." - << "ip" << sipMessage->ip() << "port" << sipMessage->port() << "nodeId" << sipMessage->uniqname() << "key" << sipMessage->key() << "visible" << sipMessage->visible(); - - SipInfo info; - info.setVisible( sipMessage->visible() ); - if ( sipMessage->visible() ) + // Check that all received SipInfos are valid. + foreach ( SipInfo info, sipMessage->sipInfo() ) { - info.setHost( sipMessage->ip() ); - info.setPort( sipMessage->port() ); - info.setNodeId( sipMessage->uniqname() ); - info.setKey( sipMessage->key() ); + Q_ASSERT( info.isValid() ); } - Q_ASSERT( info.isValid() ); - - qDebug() << Q_FUNC_INFO << "From:" << iq.from().full() << ":" << info; + // Get the peer information for the sender. Tomahawk::peerinfo_ptr peerInfo = PeerInfo::get( this, iq.from().full() ); if ( peerInfo.isNull() ) { tDebug() << Q_FUNC_INFO << "no valid peerInfo for" << iq.from().full(); return; } - peerInfo->setSipInfo( info ); + peerInfo->setSipInfo( sipMessage->sipInfo() ); } } } diff --git a/src/accounts/xmpp/sip/XmppSip.h b/src/accounts/xmpp/sip/XmppSip.h index fabcbf438..43b43abb6 100644 --- a/src/accounts/xmpp/sip/XmppSip.h +++ b/src/accounts/xmpp/sip/XmppSip.h @@ -90,7 +90,7 @@ public slots: virtual void configurationChanged(); virtual void addContact( const QString& peerId, const QString& msg = QString() ); - virtual void sendSipInfo( const Tomahawk::peerinfo_ptr& receiver, const SipInfo& info ); + virtual void sendSipInfoList( const Tomahawk::peerinfo_ptr& receiver, const QList& info ); void showAddFriendDialog(); void publishTune( const QUrl& url, const Tomahawk::InfoSystem::InfoStringHash& trackInfo ); diff --git a/src/accounts/zeroconf/Zeroconf.cpp b/src/accounts/zeroconf/Zeroconf.cpp index 7a73d8d1c..1893b90b8 100644 --- a/src/accounts/zeroconf/Zeroconf.cpp +++ b/src/accounts/zeroconf/Zeroconf.cpp @@ -161,7 +161,9 @@ ZeroconfPlugin::lanHostFound( const QString& host, int port, const QString& name sipInfo.setVisible( true ); Tomahawk::peerinfo_ptr peerInfo = Tomahawk::PeerInfo::get( this, host, Tomahawk::PeerInfo::AutoCreate ); - peerInfo->setSipInfo( sipInfo ); + QList sipInfoList = QList(); + sipInfoList.append( sipInfo ); + peerInfo->setSipInfo( sipInfoList ); peerInfo->setContactId( host ); peerInfo->setFriendlyName( name ); peerInfo->setType( PeerInfo::Local ); diff --git a/src/accounts/zeroconf/Zeroconf.h b/src/accounts/zeroconf/Zeroconf.h index d6803f8f4..d1d660b8c 100644 --- a/src/accounts/zeroconf/Zeroconf.h +++ b/src/accounts/zeroconf/Zeroconf.h @@ -65,7 +65,7 @@ public slots: void advertise(); - void sendSipInfo( const Tomahawk::peerinfo_ptr&, const SipInfo& ) {} + virtual void sendSipInfoList( const Tomahawk::peerinfo_ptr& receiver, const QList& info ) {} void broadcastMsg( const QString & ) {} void addContact( const QString &, const QString& ) {} diff --git a/src/libtomahawk/CMakeLists.txt b/src/libtomahawk/CMakeLists.txt index d7f7daef7..f3f81a8b3 100644 --- a/src/libtomahawk/CMakeLists.txt +++ b/src/libtomahawk/CMakeLists.txt @@ -306,6 +306,7 @@ list(APPEND libSources network/Servent.cpp network/Connection.cpp network/ControlConnection.cpp + network/QTcpSocketExtra.cpp playlist/PlaylistUpdaterInterface.cpp playlist/dynamic/DynamicPlaylist.cpp diff --git a/src/libtomahawk/network/QTcpSocketExtra.cpp b/src/libtomahawk/network/QTcpSocketExtra.cpp new file mode 100644 index 000000000..25aa087ee --- /dev/null +++ b/src/libtomahawk/network/QTcpSocketExtra.cpp @@ -0,0 +1,64 @@ +/* === This file is part of Tomahawk Player - === + * + * Copyright 2010-2011, Christian Muehlhaeuser + * Copyright 2010-2012, Jeff Mitchell + * Copyright 2013, Teo Mrnjavac + * + * Tomahawk is free software: you can redistribute it and/or modify + * 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. + * + * Tomahawk is distributed in the hope that it will be useful, + * 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 + * along with Tomahawk. If not, see . + */ + +#include "QTcpSocketExtra.h" + +#include "utils/Logger.h" + +void +QTcpSocketExtra::connectToHost( const QHostAddress& host, quint16 port, OpenMode openMode ) +{ + if ( m_connectTimer->isActive() == true ) + { + tLog() << Q_FUNC_INFO << "Connection already establishing."; + return; + } + + QTcpSocket::connectToHost( host, port, openMode); + if ( m_connectTimeout > 0 ) + m_connectTimer->start( m_connectTimeout ); +} + +void +QTcpSocketExtra::connectToHost(const QString& host, quint16 port, OpenMode openMode) +{ + if ( m_connectTimer->isActive() == true ) + { + tLog() << Q_FUNC_INFO << "Connection already establishing."; + return; + } + + QTcpSocket::connectToHost( host, port, openMode); + if ( m_connectTimeout > 0 ) + m_connectTimer->start( m_connectTimeout ); +} + +void +QTcpSocketExtra::connectTimeout() +{ + m_connectTimer->stop(); + if ( state() != ConnectedState ) + { + // We did not manage to connect in the given timespan, so abort the attempt... + close(); + // .. and notify error handlers. + emit error( SocketTimeoutError ); + } +} diff --git a/src/libtomahawk/network/QTcpSocketExtra.h b/src/libtomahawk/network/QTcpSocketExtra.h new file mode 100644 index 000000000..d42e1a5e7 --- /dev/null +++ b/src/libtomahawk/network/QTcpSocketExtra.h @@ -0,0 +1,82 @@ +/* === This file is part of Tomahawk Player - === + * + * Copyright 2010-2011, Christian Muehlhaeuser + * Copyright 2010-2012, Jeff Mitchell + * Copyright 2013, Teo Mrnjavac + * + * Tomahawk is free software: you can redistribute it and/or modify + * 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. + * + * Tomahawk is distributed in the hope that it will be useful, + * 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 + * along with Tomahawk. If not, see . + */ + +#ifndef QTCPSOCKETEXTRA_H +#define QTCPSOCKETEXTRA_H + +// time before new connection terminates if no auth received +#define AUTH_TIMEOUT 180000 + +#include +#include +#include +#include + +#include "Msg.h" +#include "DllMacro.h" + +class Connection; + +// this is used to hold a bit of state, so when a connected signal is emitted +// from a socket, we can associate it with a Connection object etc. +// In addition, functionality to limit the connection timeout is implemented. +class DLLEXPORT QTcpSocketExtra : public QTcpSocket +{ +Q_OBJECT + +public: + QTcpSocketExtra() : QTcpSocket(), m_connectTimeout( -1 ) + { + QTimer::singleShot( AUTH_TIMEOUT, this, SLOT( authTimeout() ) ) ; + m_connectTimer = new QTimer( this ); + connect( m_connectTimer, SIGNAL( timeout() ), this, SLOT( connectTimeout() ) ); + } + + void connectToHost(const QString& host, quint16 port, OpenMode openMode = ReadWrite ); + void connectToHost( const QHostAddress& host, quint16 port, OpenMode openMode = ReadWrite ); + + QPointer _conn; + bool _outbound; + bool _disowned; + msg_ptr _msg; + + //! Set a time limit for establishing a connection. + void setConnectTimeout( qint32 timeout ) { m_connectTimeout = timeout; } + //! Get the current timeout for establishing a connection. + qint32 connectTimeout() const { return m_connectTimeout; } + +private slots: + void connectTimeout(); + void authTimeout() + { + if( _disowned ) + return; + + qDebug() << "Connection timed out before providing a valid offer-key"; + this->disconnectFromHost(); + } +private: + //! How long we will wait for a connection to establish + qint32 m_connectTimeout; + //! Timer to measure the connection initialisation + QTimer* m_connectTimer; +}; + +#endif // QTCPSOCKETEXTRA_H diff --git a/src/libtomahawk/network/Servent.cpp b/src/libtomahawk/network/Servent.cpp index e22263976..625c31c89 100644 --- a/src/libtomahawk/network/Servent.cpp +++ b/src/libtomahawk/network/Servent.cpp @@ -34,6 +34,7 @@ #include "sip/SipPlugin.h" #include "PortFwdThread.h" #include "TomahawkSettings.h" +#include "utils/Closure.h" #include "utils/TomahawkUtils.h" #include "utils/Logger.h" #include "accounts/AccountManager.h" @@ -50,6 +51,10 @@ #include + +typedef QPair< QList< SipInfo >, Connection* > sipConnectionPair; +Q_DECLARE_METATYPE( sipConnectionPair ) + using namespace Tomahawk; Servent* Servent::s_instance = 0; @@ -70,7 +75,6 @@ Servent::Servent( QObject* parent ) { s_instance = this; - m_lanHack = qApp->arguments().contains( "--lanhack" ); m_noAuth = qApp->arguments().contains( "--noauth" ); setProxy( QNetworkProxy::NoProxy ); @@ -113,6 +117,7 @@ Servent::~Servent() bool Servent::startListening( QHostAddress ha, bool upnp, int port ) { + m_externalAddresses = QList(); m_port = port; int defPort = TomahawkSettings::instance()->defaultPort(); @@ -125,8 +130,8 @@ Servent::startListening( QHostAddress ha, bool upnp, int port ) { if ( !listen( ha, defPort ) ) { - tLog() << "Failed to listen on both port" << m_port << "and port" << defPort; - tLog() << "Error string is:" << errorString(); + tLog() << Q_FUNC_INFO << "Failed to listen on both port" << m_port << "and port" << defPort; + tLog() << Q_FUNC_INFO << "Error string is:" << errorString(); return false; } else @@ -134,38 +139,63 @@ Servent::startListening( QHostAddress ha, bool upnp, int port ) } } - TomahawkSettings::ExternalAddressMode mode = TomahawkSettings::instance()->externalAddressMode(); + if ( ha == QHostAddress::AnyIPv6 ) + { + // We are listening on all available addresses, so we should send a SipInfo for all of them. + foreach ( QHostAddress addr, QNetworkInterface::allAddresses() ) + { + if ( addr.toString() == "127.0.0.1" ) + continue; // IPv4 localhost + if ( addr.toString() == "::1" ) + continue; // IPv6 localhost + tLog( LOGVERBOSE ) << Q_FUNC_INFO << "Listening to " << addr.toString(); + m_externalAddresses.append( addr ); + } - tLog() << "Servent listening on port" << m_port << "- servent thread:" << thread() + } + else if ( ( ha.toString() != "127.0.0.1" ) && ( ha.toString() != "::1" ) ) + { + // We listen only to one specific Address, only announce this. + m_externalAddresses.append( ha ); + } + // If we only accept connections via localhost, we'll announce nothing. + + TomahawkSettings::ExternalAddressMode mode = TomahawkSettings::instance()->externalAddressMode(); + tLog( LOGVERBOSE ) << Q_FUNC_INFO << "Servent listening on port" << m_port << "- servent thread:" << thread() << "- address mode:" << (int)( mode ); - // --lanhack means to advertise your LAN IP as if it were externally visible switch ( mode ) { case TomahawkSettings::Static: m_externalHostname = TomahawkSettings::instance()->externalHostname(); m_externalPort = TomahawkSettings::instance()->externalPort(); m_ready = true; + // All setup is made, were done. emit ready(); break; case TomahawkSettings::Lan: - setInternalAddress(); + // Nothing has to be done here. + m_ready = true; + emit ready(); break; case TomahawkSettings::Upnp: - if ( !upnp ) + if ( upnp ) { - setInternalAddress(); - break; + // upnp could be turned of on the cli with --noupnp + tLog( LOGVERBOSE ) << Q_FUNC_INFO << "External address mode set to upnp..."; + m_portfwd = QPointer< PortFwdThread >( new PortFwdThread( m_port ) ); + Q_ASSERT( m_portfwd ); + connect( m_portfwd.data(), SIGNAL( externalAddressDetected( QHostAddress, unsigned int ) ), + SLOT( setExternalAddress( QHostAddress, unsigned int ) ) ); + m_portfwd.data()->start(); + } + else + { + m_ready = true; + emit ready(); } - // TODO check if we have a public/internet IP on this machine directly - tLog() << "External address mode set to upnp..."; - m_portfwd = QPointer< PortFwdThread >( new PortFwdThread( m_port ) ); - Q_ASSERT( m_portfwd ); - connect( m_portfwd.data(), SIGNAL( externalAddressDetected( QHostAddress, unsigned int ) ), - SLOT( setExternalAddress( QHostAddress, unsigned int ) ) ); - m_portfwd.data()->start(); break; } @@ -173,6 +203,25 @@ Servent::startListening( QHostAddress ha, bool upnp, int port ) } +void +Servent::setExternalAddress( QHostAddress ha, unsigned int port ) +{ + if ( isValidExternalIP( ha ) ) + { + m_externalHostname = ha.toString(); + m_externalPort = port; + } + + if ( m_externalPort == 0 || !isValidExternalIP( ha ) ) + tLog() << Q_FUNC_INFO << "UPnP failed, no further external address could be acquired!"; + else + tLog( LOGVERBOSE ) << Q_FUNC_INFO << "UPnP setup successful"; + + m_ready = true; + emit ready(); +} + + QString Servent::createConnectionKey( const QString& name, const QString &nodeid, const QString &key, bool onceOnly ) { @@ -192,10 +241,55 @@ Servent::createConnectionKey( const QString& name, const QString &nodeid, const bool -Servent::isValidExternalIP( const QHostAddress& addr ) const +Servent::isValidExternalIP( const QHostAddress& addr ) { QString ip = addr.toString(); - if ( !m_lanHack && ( ip.startsWith( "10." ) || ip.startsWith( "172.16." ) || ip.startsWith( "192.168." ) ) ) + if (addr.protocol() == QAbstractSocket::IPv4Protocol) + { + // private network + if ( addr.isInSubnet(QHostAddress::parseSubnet("10.0.0.0/8")) ) + return false; + // localhost + if ( addr.isInSubnet(QHostAddress::parseSubnet("127.0.0.0/8")) ) + return false; + // private network + if ( addr.isInSubnet(QHostAddress::parseSubnet("169.254.0.0/16")) ) + return false; + // private network + if ( addr.isInSubnet(QHostAddress::parseSubnet("172.16.0.0/12")) ) + return false; + // private network + if ( addr.isInSubnet(QHostAddress::parseSubnet("192.168.0.0/16")) ) + return false; + // multicast + if ( addr.isInSubnet(QHostAddress::parseSubnet("224.0.0.0/4")) ) + return false; + } + else if (addr.protocol() == QAbstractSocket::IPv4Protocol) + { + // "unspecified address" + if ( addr.isInSubnet(QHostAddress::parseSubnet("::/128")) ) + return false; + // link-local + if ( addr.isInSubnet(QHostAddress::parseSubnet("fe80::/10")) ) + return false; + // unique local addresses + if ( addr.isInSubnet(QHostAddress::parseSubnet("fc00::/7")) ) + return false; + // benchmarking only + if ( addr.isInSubnet(QHostAddress::parseSubnet("2001:2::/48")) ) + return false; + // non-routed IPv6 addresses used for Cryptographic Hash Identifiers + if ( addr.isInSubnet(QHostAddress::parseSubnet("2001:10::/28")) ) + return false; + // documentation prefix + if ( addr.isInSubnet(QHostAddress::parseSubnet("2001:db8::/32")) ) + return false; + // multicast + if ( addr.isInSubnet(QHostAddress::parseSubnet("ff00::0/8 ")) ) + return false; + } + else { return false; } @@ -203,54 +297,6 @@ Servent::isValidExternalIP( const QHostAddress& addr ) const return !addr.isNull(); } - -void -Servent::setInternalAddress() -{ - foreach ( QHostAddress ha, QNetworkInterface::allAddresses() ) - { - if ( ha.toString() == "127.0.0.1" ) - continue; - if ( ha.toString().contains( ":" ) ) - continue; //ipv6 - - if ( m_lanHack && isValidExternalIP( ha ) ) - { - tLog() << "LANHACK: set external address to lan address" << ha.toString(); - setExternalAddress( ha, m_port ); - } - else - { - m_ready = true; - emit ready(); - } - break; - } -} - - -void -Servent::setExternalAddress( QHostAddress ha, unsigned int port ) -{ - if ( isValidExternalIP( ha ) ) - { - m_externalAddress = ha; - m_externalPort = port; - } - - if ( m_externalPort == 0 || !isValidExternalIP( ha ) ) - { - tLog() << "UPnP failed, LAN and outbound connections only!"; - setInternalAddress(); - return; - } - - tLog() << "UPnP setup successful"; - m_ready = true; - emit ready(); -} - - void Servent::registerOffer( const QString& key, Connection* conn ) { @@ -312,7 +358,7 @@ Servent::registerPeer( const Tomahawk::peerinfo_ptr& peerInfo ) if ( peerInfo->type() == Tomahawk::PeerInfo::Local ) { peerInfoDebug(peerInfo) << "we need to establish the connection now... thinking"; - if ( !connectedToSession( peerInfo->sipInfo().nodeId() ) ) + if ( !connectedToSession( peerInfo->sipInfo().first().nodeId() ) ) { connectToPeer( peerInfo ); } @@ -335,34 +381,47 @@ Servent::registerPeer( const Tomahawk::peerinfo_ptr& peerInfo ) } else { - SipInfo info; - QString peerId = peerInfo->id(); QString key = uuid(); - ControlConnection* conn = new ControlConnection( this ); - const QString& nodeid = Database::instance()->impl()->dbid(); + + ControlConnection* conn = new ControlConnection( this ); conn->setName( peerInfo->contactId() ); conn->setId( nodeid ); conn->addPeerInfo( peerInfo ); - if ( visibleExternally() ) + QList sipInfo = QList(); + foreach ( QHostAddress ha, m_externalAddresses ) { - registerOffer( key, conn ); + SipInfo info = SipInfo(); + info.setHost( ha.toString() ); + info.setPort( m_port ); + info.setKey( key ); info.setVisible( true ); - info.setHost( externalAddress() ); - info.setPort( externalPort() ); + info.setNodeId( nodeid ); + sipInfo.append( info ); + } + if ( m_externalHostname.length() > 0) + { + SipInfo info = SipInfo(); + info.setHost( m_externalHostname ); + info.setPort( m_externalPort ); + info.setKey( key ); + info.setVisible( true ); + info.setNodeId( nodeid ); + sipInfo.append( info ); + } + + if ( sipInfo.length() == 0 ) + { + // We are not visible via any IP, send a dummy SipInfo + SipInfo info = SipInfo(); + info.setVisible( false ); info.setKey( key ); info.setNodeId( nodeid ); - - tDebug() << "Asking them (" << peerInfo->id() << ") to connect to us:" << info; - } - else - { - info.setVisible( false ); - tDebug() << "We are not visible externally:" << info; + tDebug( LOGVERBOSE ) << Q_FUNC_INFO << "Only accepting connections, no usable IP to listen to found."; } - peerInfo->sendLocalSipInfo( info ); + peerInfo->sendLocalSipInfo( sipInfo ); handleSipInfo( peerInfo ); connect( peerInfo.data(), SIGNAL( sipInfoChanged() ), SLOT( onSipInfoChanged() ) ); @@ -384,43 +443,29 @@ Servent::onSipInfoChanged() void Servent::handleSipInfo( const Tomahawk::peerinfo_ptr& peerInfo ) { - tLog() << Q_FUNC_INFO << peerInfo->id() << peerInfo->sipInfo(); + // FIXME: Do we need this? + // SipInfo info = peerInfo->sipInfo(); + // if ( !info.isValid() ) + // return; - SipInfo info = peerInfo->sipInfo(); - if ( !info.isValid() ) - return; - - /* - If only one party is externally visible, connection is obvious - If both are, peer with lowest IP address initiates the connection. - - This avoids dupe connections. - */ - if ( info.isVisible() ) + foreach ( SipInfo info, peerInfo->sipInfo() ) { - if ( !visibleExternally() || - externalAddress() < info.host() || - ( externalAddress() == info.host() && externalPort() < info.port() ) ) + if (info.isVisible()) { - - tDebug() << "Initiate connection to" << peerInfo->id() << "at" << info.host() << "peer of:" << peerInfo->sipPlugin()->account()->accountFriendlyName(); + // There is at least one SipInfo that may be visible. Try connecting. + // Duplicate Connections are checked by connectToPeer, so we do not need to take care of this + tLog( LOGVERBOSE ) << Q_FUNC_INFO << "Initiate connection to" << peerInfo->id() << "at" << info.host() << "peer of:" << peerInfo->sipPlugin()->account()->accountFriendlyName(); connectToPeer( peerInfo ); - } - else - { - tDebug() << Q_FUNC_INFO << "They should be conecting to us..."; + // We connected to the peer, so we are done here. + return; } } - else - { - tDebug() << Q_FUNC_INFO << "They are not visible, doing nothing atm"; - if ( !visibleExternally() ) - { - if ( peerInfo->controlConnection() ) - delete peerInfo->controlConnection(); - } - } + // If we reach this point none of the previous SipInfos was visible. + if ( peerInfo->controlConnection() ) + delete peerInfo->controlConnection(); + + tDebug() << Q_FUNC_INFO << peerInfo->id() << "They are not visible, doing nothing atm"; } void @@ -616,10 +661,13 @@ Servent::createParallelConnection( Connection* orig_conn, Connection* new_conn, // if we can connect to them directly: if ( orig_conn && orig_conn->outbound() ) { - connectToPeer( orig_conn->socket()->peerAddress().toString(), - orig_conn->peerPort(), - key, - new_conn ); + QList sipInfo = QList(); + SipInfo info = SipInfo(); + info.setKey( key ); + info.setHost( orig_conn->socket()->peerAddress().toString() ); + info.setPort( orig_conn->peerPort() ); + sipInfo.append( info ); + connectToPeer( sipInfo, new_conn ); } else // ask them to connect to us: { @@ -631,7 +679,6 @@ Servent::createParallelConnection( Connection* orig_conn, Connection* new_conn, m.insert( "conntype", "request-offer" ); m.insert( "key", tmpkey ); m.insert( "offer", key ); - m.insert( "port", externalPort() ); m.insert( "controlid", Database::instance()->impl()->dbid() ); QJson::Serializer ser; @@ -680,45 +727,11 @@ void Servent::handoverSocket( Connection* conn, QTcpSocketExtra* sock ) conn->start( sock ); } - -void -Servent::socketError( QAbstractSocket::SocketError e ) -{ - QTcpSocketExtra* sock = (QTcpSocketExtra*)sender(); - if ( !sock ) - { - tLog() << "SocketError, sock is null"; - return; - } - - if ( !sock->_conn.isNull() ) - { - Connection* conn = sock->_conn.data(); - tLog() << "Servent::SocketError:" << e << conn->id() << conn->name(); - - if ( !sock->_disowned ) - { - // connection will delete if we already transferred ownership, otherwise: - sock->deleteLater(); - } - - conn->markAsFailed(); // will emit failed, then finished - } - else - { - tLog() << "SocketError, connection is null"; - sock->deleteLater(); - } -} - - void Servent::connectToPeer( const peerinfo_ptr& peerInfo ) { Q_ASSERT( this->thread() == QThread::currentThread() ); - SipInfo sipInfo = peerInfo->sipInfo(); - peerInfoDebug( peerInfo ) << "connectToPeer: search for already established connections to the same nodeid:" << m_controlconnections.count() << "connections"; if ( peerInfo->controlConnection() ) delete peerInfo->controlConnection(); @@ -731,7 +744,7 @@ Servent::connectToPeer( const peerinfo_ptr& peerInfo ) { Q_ASSERT( c ); - if ( c->id() == sipInfo.nodeId() ) + if ( c->id() == peerInfo->nodeId() ) { conn = c; @@ -773,8 +786,7 @@ Servent::connectToPeer( const peerinfo_ptr& peerInfo ) QVariantMap m; m["conntype"] = "accept-offer"; - m["key"] = sipInfo.key(); - m["port"] = externalPort(); + m["key"] = peerInfo->key(); m["nodeid"] = Database::instance()->impl()->dbid(); peerInfoDebug(peerInfo) << "No match found, creating a new ControlConnection..."; @@ -784,58 +796,132 @@ Servent::connectToPeer( const peerinfo_ptr& peerInfo ) if ( peerInfo->id().length() ) conn->setName( peerInfo->contactId() ); - if ( sipInfo.nodeId().length() ) - conn->setId( sipInfo.nodeId() ); + if ( peerInfo->nodeId().length() ) + conn->setId( peerInfo->nodeId() ); - conn->setProperty( "nodeid", sipInfo.nodeId() ); + conn->setProperty( "nodeid", peerInfo->nodeId() ); registerControlConnection( conn ); - connectToPeer( sipInfo.host(), sipInfo.port(), sipInfo.key(), conn ); + connectToPeer( peerInfo->sipInfo(), conn ); } void -Servent::connectToPeer( const QString& ha, int port, const QString& key, Connection* conn ) +Servent::connectToPeer(const QList& sipInfoList, Connection* conn ) { - tDebug( LOGVERBOSE ) << "Servent::connectToPeer:" << ha << ":" << port - << thread() << QThread::currentThread(); - - Q_ASSERT( port > 0 ); - Q_ASSERT( conn ); - - if ( ( ha == m_externalAddress.toString() || ha == m_externalHostname ) && - ( port == m_externalPort ) ) + if ( sipInfoList.isEmpty() ) { - tDebug() << "ERROR: Tomahawk won't try to connect to" << ha << ":" << port << ": identified as ourselves."; + tLog( LOGVERBOSE ) << Q_FUNC_INFO << "No more possible SIP endpoints for " << conn->name() << " skipping."; + return; + } + QList sipInfo = QList(sipInfoList); + // Use first available SIP endpoint and remove it from the list + SipInfo info = sipInfo.takeFirst(); + if ( !info.isVisible() ) + { + // Try next SipInfo, we can't connect to this one + connectToPeer( sipInfo, conn ); return; } - if ( key.length() && conn->firstMessage().isNull() ) + tDebug( LOGVERBOSE ) << "Servent::connectToPeer:" << info.host() << ":" << info.port() << thread() << QThread::currentThread(); + + Q_ASSERT( info.port() > 0 ); + Q_ASSERT( conn ); + + // Check that we are not connecting to ourselves + foreach( QHostAddress ha, m_externalAddresses ) + { + if ( QHostAddress( info.host() ) == ha) + { + tDebug() << "Tomahawk won't try to connect to" << info.host() << ":" << info.port() << ": same IP as ourselves."; + connectToPeer( sipInfo, conn ); + return; + } + } + if ( info.host() == m_externalHostname ) + { + tDebug() << "Tomahawk won't try to connect to" << info.host() << ":" << info.port() << ": same IP as ourselves."; + connectToPeer( sipInfo, conn ); + return; + } + + if ( info.key().length() && conn->firstMessage().isNull() ) { QVariantMap m; m["conntype"] = "accept-offer"; - m["key"] = key; - m["port"] = externalPort(); + m["key"] = info.key(); m["controlid"] = Database::instance()->impl()->dbid(); conn->setFirstMessage( m ); } QTcpSocketExtra* sock = new QTcpSocketExtra(); + sock->setConnectTimeout( CONNECT_TIMEOUT ); sock->_disowned = false; sock->_conn = conn; sock->_outbound = true; connect( sock, SIGNAL( connected() ), SLOT( socketConnected() ) ); - connect( sock, SIGNAL( error( QAbstractSocket::SocketError ) ), - SLOT( socketError( QAbstractSocket::SocketError ) ) ); + NewClosure( sock, SIGNAL( error( QAbstractSocket::SocketError ) ), + this, SLOT( connectToPeerFailed( QAbstractSocket::SocketError, QPair, Connection*> ) ), + QPair, Connection*>(sipInfo, conn) ); if ( !conn->peerIpAddress().isNull() ) - sock->connectToHost( conn->peerIpAddress(), port, QTcpSocket::ReadWrite ); + sock->connectToHost( conn->peerIpAddress(), info.port(), QTcpSocket::ReadWrite ); else - sock->connectToHost( ha, port, QTcpSocket::ReadWrite ); + sock->connectToHost( info.host(), info.port(), QTcpSocket::ReadWrite ); sock->moveToThread( thread() ); } +void +Servent::connectToPeerFailed( QAbstractSocket::SocketError e, QPair, Connection*> pair ) +{ + QList sipInfo = pair.first; + Connection* conn = pair.second; + + // Call default handler + socketError( e ); + + if ( e != QAbstractSocket::SocketResourceError ) + { + // If we do not have run out of resource, try next SipInfo + connectToPeer( sipInfo, conn ); + } +} + +void +Servent::socketError( QAbstractSocket::SocketError e ) +{ + QTcpSocketExtra* sock = (QTcpSocketExtra*)sender(); + if ( !sock ) + { + tLog() << "SocketError, sock is null"; + return; + } + + if ( !sock->_conn.isNull() ) + { + Connection* conn = sock->_conn.data(); + tLog() << "Servent::SocketError:" << e << conn->id() << conn->name(); + + if ( !sock->_disowned ) + { + // connection will delete if we already transferred ownership, otherwise: + sock->deleteLater(); + } + + conn->markAsFailed(); // will emit failed, then finished + } + else + { + tLog() << "SocketError, connection is null"; + sock->deleteLater(); + } +} + + + + void Servent::reverseOfferRequest( ControlConnection* orig_conn, const QString& theirdbid, const QString& key, const QString& theirkey ) @@ -854,13 +940,11 @@ Servent::reverseOfferRequest( ControlConnection* orig_conn, const QString& their QVariantMap m; m["conntype"] = "push-offer"; m["key"] = theirkey; - m["port"] = externalPort(); m["controlid"] = Database::instance()->impl()->dbid(); new_conn->setFirstMessage( m ); createParallelConnection( orig_conn, new_conn, QString() ); } - // return the appropriate connection for a given offer key, or NULL if invalid Connection* Servent::claimOffer( ControlConnection* cc, const QString &nodeid, const QString &key, const QHostAddress peer ) diff --git a/src/libtomahawk/network/Servent.h b/src/libtomahawk/network/Servent.h index 622c3f84d..44ac55cce 100644 --- a/src/libtomahawk/network/Servent.h +++ b/src/libtomahawk/network/Servent.h @@ -21,8 +21,8 @@ #ifndef SERVENT_H #define SERVENT_H -// time before new connection terminates if no auth received -#define AUTH_TIMEOUT 180000 +// time before new connection terminate if it could not be established +#define CONNECT_TIMEOUT 10000 #include #include @@ -40,6 +40,7 @@ #include "Typedefs.h" #include "Msg.h" +#include "network/QTcpSocketExtra.h" #include @@ -58,48 +59,19 @@ class SipInfo; typedef boost::function< void( const Tomahawk::result_ptr&, boost::function< void( QSharedPointer< QIODevice >& ) > )> IODeviceFactoryFunc; -// this is used to hold a bit of state, so when a connected signal is emitted -// from a socket, we can associate it with a Connection object etc. -class DLLEXPORT QTcpSocketExtra : public QTcpSocket -{ -Q_OBJECT - -public: - QTcpSocketExtra() : QTcpSocket() - { - QTimer::singleShot( AUTH_TIMEOUT, this, SLOT( authTimeout() ) ) ; - } - - QPointer _conn; - bool _outbound; - bool _disowned; - msg_ptr _msg; - -private slots: - void authTimeout() - { - if( _disowned ) - return; - - qDebug() << "Connection timed out before providing a valid offer-key"; - this->disconnectFromHost(); - } -}; - class DLLEXPORT Servent : public QTcpServer { Q_OBJECT public: static Servent* instance(); + static bool isValidExternalIP( const QHostAddress& addr ); explicit Servent( QObject* parent = 0 ); virtual ~Servent(); bool startListening( QHostAddress ha, bool upnp, int port ); - int port() const { return m_port; } - // creates new token that allows a controlconnection to be set up QString createConnectionKey( const QString& name = "", const QString &nodeid = "", const QString &key = "", bool onceOnly = true ); @@ -118,12 +90,18 @@ public slots: public: void connectToPeer( const Tomahawk::peerinfo_ptr& ha ); - void connectToPeer( const QString& ha, int port, const QString& key, Connection* conn ); - void reverseOfferRequest( ControlConnection* orig_conn, const QString& theirdbid, const QString& key, const QString& theirkey ); + void connectToPeer( const QList& sipInfoList, Connection* conn ); + void reverseOfferRequest( ControlConnection* orig_conn, const QString &theirdbid, const QString& key, const QString& theirkey ); - bool visibleExternally() const { return !m_externalHostname.isNull() || (m_externalPort > 0 && !m_externalAddress.isNull()); } - QString externalAddress() const { return !m_externalHostname.isNull() ? m_externalHostname : m_externalAddress.toString(); } - int externalPort() const { return m_externalPort; } + bool visibleExternally() const { return (!m_externalHostname.isNull()) || (m_externalAddresses.length() > 0); } + //! The port this Peer listens directly (per default) + int port() const { return m_port; } + //! The IP addresses this Peer listens directly (per default) + QList< QHostAddress > addresses() const { return m_externalAddresses; } + //! An additional address this peer listens to, e.g. via UPnP. + QString additionalAddress() const { return m_externalHostname; } + //! An additional port this peer listens to, e.g. via UPnP (only in combination with additionalAddress. + int additionalPort() const { return m_externalPort; } static bool isIPWhitelisted( QHostAddress ip ); @@ -138,7 +116,7 @@ public: void localFileIODeviceFactory( const Tomahawk::result_ptr& result, boost::function< void ( QSharedPointer< QIODevice >& ) > callback ); void httpIODeviceFactory( const Tomahawk::result_ptr& result, boost::function< void ( QSharedPointer< QIODevice >& ) > callback ); - bool isReady() const { return m_ready; }; + bool isReady() const { return m_ready; } signals: void dbSyncTriggered(); @@ -150,10 +128,10 @@ protected: void incomingConnection( int sd ); public slots: - void setInternalAddress(); void setExternalAddress( QHostAddress ha, unsigned int port ); - void socketError( QAbstractSocket::SocketError ); + void connectToPeerFailed( QAbstractSocket::SocketError e, QPair, Connection*> pair ); + void socketError( QAbstractSocket::SocketError e ); void createParallelConnection( Connection* orig_conn, Connection* new_conn, const QString& key ); void registerStreamConnection( StreamConnection* ); @@ -168,7 +146,6 @@ private slots: Connection* claimOffer( ControlConnection* cc, const QString &nodeid, const QString &key, const QHostAddress peer = QHostAddress::Any ); private: - bool isValidExternalIP( const QHostAddress& addr ) const; void handoverSocket( Connection* conn, QTcpSocketExtra* sock ); void printCurrentTransfers(); @@ -177,11 +154,16 @@ private: QMap< QString, QPointer< Connection > > m_offers; QStringList m_connectedNodes; - int m_port, m_externalPort; - QHostAddress m_externalAddress; + //! The external port used by all address except those obtained via UPnP or the static configuration option + int m_port; + //! Either the static set or the UPnP set external port + int m_externalPort; + //! All available external IPs + QList m_externalAddresses; + //! Either the static set or the UPnP set external host QString m_externalHostname; + bool m_ready; - bool m_lanHack; bool m_noAuth; // currently active file transfers: diff --git a/src/libtomahawk/sip/PeerInfo.cpp b/src/libtomahawk/sip/PeerInfo.cpp index 6630f2501..7ca33ac42 100644 --- a/src/libtomahawk/sip/PeerInfo.cpp +++ b/src/libtomahawk/sip/PeerInfo.cpp @@ -202,9 +202,9 @@ PeerInfo::sipPlugin() const void -PeerInfo::sendLocalSipInfo( const SipInfo& sipInfo ) +PeerInfo::sendLocalSipInfo( const QList& sipInfoList ) { - sipPlugin()->sendSipInfo( weakRef().toStrongRef(), sipInfo ); + sipPlugin()->sendSipInfoList( weakRef().toStrongRef(), sipInfoList ); } @@ -228,6 +228,23 @@ PeerInfo::contactId() const return m_contactId; } +const QString +PeerInfo::nodeId() const +{ + Q_ASSERT( m_sipInfo.length() > 0 ); + // All sip infos share the same nodeId + return m_sipInfo.first().nodeId(); +} + +const QString +PeerInfo::key() const +{ + Q_ASSERT( m_sipInfo.length() > 0 ); + // All sip infos share the same key + return m_sipInfo.first().key(); +} + + void PeerInfo::setStatus( PeerInfo::Status status ) @@ -259,19 +276,16 @@ PeerInfo::status() const void -PeerInfo::setSipInfo( const SipInfo& sipInfo ) +PeerInfo::setSipInfo( const QList& sipInfo ) { - if ( sipInfo == m_sipInfo ) - return; - - m_sipInfo = sipInfo; + m_sipInfo = QList(sipInfo); tLog() << "id:" << id() << "info changed" << sipInfo; emit sipInfoChanged(); } -const SipInfo +const QList PeerInfo::sipInfo() const { return m_sipInfo; @@ -389,7 +403,6 @@ PeerInfo::setData( const QVariant& data ) m_data = data; } - const QVariant PeerInfo::data() const { diff --git a/src/libtomahawk/sip/PeerInfo.h b/src/libtomahawk/sip/PeerInfo.h index 2b49548b3..0f11cf070 100644 --- a/src/libtomahawk/sip/PeerInfo.h +++ b/src/libtomahawk/sip/PeerInfo.h @@ -74,7 +74,7 @@ public: const QString id() const; SipPlugin* sipPlugin() const; const QString debugName() const; - void sendLocalSipInfo( const SipInfo& sipInfo ); + void sendLocalSipInfo( const QList& sipInfoList ); QWeakPointer< Tomahawk::PeerInfo > weakRef(); void setWeakRef( QWeakPointer< Tomahawk::PeerInfo > weakRef ); @@ -96,8 +96,8 @@ public: void setStatus( Status status ); Status status() const; - void setSipInfo( const SipInfo& sipInfo ); - const SipInfo sipInfo() const; + void setSipInfo( const QList& sipInfo ); + const QList sipInfo() const; void setFriendlyName( const QString& friendlyName ); const QString friendlyName() const; @@ -112,6 +112,12 @@ public: void setData( const QVariant& data ); const QVariant data() const; + //! Get the node id of this peer + const QString nodeId() const; + + //! Get the authentication key for this host + const QString key() const; + signals: void sipInfoChanged(); @@ -131,7 +137,7 @@ private: QString m_id; QString m_contactId; Status m_status; - SipInfo m_sipInfo; + QList m_sipInfo; QString m_friendlyName; QString m_versionString; QVariant m_data; diff --git a/src/libtomahawk/sip/SipPlugin.h b/src/libtomahawk/sip/SipPlugin.h index 6503c282e..10d27c565 100644 --- a/src/libtomahawk/sip/SipPlugin.h +++ b/src/libtomahawk/sip/SipPlugin.h @@ -70,7 +70,8 @@ public slots: virtual void configurationChanged() = 0; virtual void addContact( const QString& peerId, const QString& msg = QString() ) = 0; - virtual void sendSipInfo( const Tomahawk::peerinfo_ptr& receiver, const SipInfo& info ) = 0; + //! Send a list of SipInfos to all contacts. + virtual void sendSipInfoList( const Tomahawk::peerinfo_ptr& receiver, const QList& info ) = 0; signals: void peerStatusChanged( const Tomahawk::peerinfo_ptr& ); diff --git a/src/tomahawk/DiagnosticsDialog.cpp b/src/tomahawk/DiagnosticsDialog.cpp index 77efc0a72..18d515391 100644 --- a/src/tomahawk/DiagnosticsDialog.cpp +++ b/src/tomahawk/DiagnosticsDialog.cpp @@ -64,24 +64,26 @@ DiagnosticsDialog::updateLogView() log.append( QString( "TOMAHAWK DIAGNOSTICS LOG -%1 \n\n" ).arg( QDateTime::currentDateTime().toString() ) ); log.append( "TOMAHAWK-VERSION: " TOMAHAWK_VERSION "\n" ); log.append( "PLATFORM: " TOMAHAWK_SYSTEM "\n\n"); - log.append( "NETWORK:\n General:\n" ); + log.append( "NETWORK:\n Listening to:\n" ); if ( Servent::instance()->visibleExternally() ) { - log.append( - QString( - " visible: true\n" - " host: %1\n" - " port: %2\n" - "\n" - ).arg( Servent::instance()->externalAddress() ) - .arg( Servent::instance()->externalPort() ) + foreach ( QHostAddress ha, Servent::instance()->addresses() ) + { + if ( ha.protocol() == QAbstractSocket::IPv6Protocol ) + log.append( QString( " [%1]:%2\n" ).arg( ha.toString() ).arg( Servent::instance()->port() ) ); + else + log.append( QString( " %1:%2\n" ).arg( ha.toString() ).arg( Servent::instance()->port() ) ); + } + if ( !Servent::instance()->additionalAddress().isNull() ) + { + log.append( QString( " [%1]:%2\n" ).arg( Servent::instance()->additionalAddress() ).arg( Servent::instance()->additionalPort() ) ); + } - ); } else { - log.append( " visible: false\n" ); + log.append( " not listening to any interface, outgoing connections only\n" ); } log.append( "\n\nINFOPLUGINS:\n" ); @@ -162,54 +164,17 @@ DiagnosticsDialog::accountLog( Tomahawk::Accounts::Account* account ) foreach( const Tomahawk::peerinfo_ptr& peerInfo, account->sipPlugin()->peersOnline() ) { - QString peerId = peerInfo->id(); - QString versionString = peerInfo->versionString(); - SipInfo sipInfo = peerInfo->sipInfo(); - if ( !sipInfo.isValid() ) + accountInfo.append( QString( " %1: " ).arg( peerInfo->id() ) ); + foreach ( SipInfo info, peerInfo->sipInfo() ) { - accountInfo.append( - QString(" %1: %2 %3" /*"(%4)"*/) - .arg( peerInfo->id() ) - .arg( "sipinfo invalid" ) - .arg( versionString ) - // .arg( connected ? "connected" : "not connected") - ); - } - else if ( sipInfo.isVisible() ) - { - accountInfo.append( - QString(" %1: %2:%3 %4" /*" (%5)"*/) - .arg( peerId ) - .arg( sipInfo.host() ) - .arg( sipInfo.port() ) - .arg( versionString ) - // .arg( connected ? "connected" : "not connected") - ); - } - else - { - accountInfo.append( - QString(" %1: visible: false %2" /*" (%3)"*/) - .arg( peerId ) - .arg( versionString ) - // .arg( connected ? "connected" : "not connected") - ); - } - - if( sipInfo.isValid() ) - { - if( !Servent::instance()->visibleExternally() || - Servent::instance()->externalAddress() < sipInfo.host() || - ( Servent::instance()->externalAddress() == sipInfo.host() && Servent::instance()->externalPort() < sipInfo.port() ) ) - { - accountInfo.append(" (outbound)"); - } + if ( info.isValid() ) + accountInfo.append( QString( "[%1]:%2; " ).arg( info.host() ).arg( info.port() ) ); else - { - accountInfo.append(" (inbound)"); - } + accountInfo.append( "SipInfo invalid; " ); } - accountInfo.append("\n"); + if ( ( peerInfo->sipInfo().length() == 1 ) && ( !peerInfo->sipInfo().first().isVisible() ) || ( peerInfo->sipInfo().length() == 0 ) ) + accountInfo.append( "(outbound connections only) "); + accountInfo.append( QString( " (%1)\n" ).arg( peerInfo->versionString() ) ); } accountInfo.append( "\n" );