X-Git-Url: https://git.quassel-irc.org/?p=quassel.git;a=blobdiff_plain;f=src%2Fclient%2Fcoreconnection.cpp;h=982d0c86a6b188095057c7e3ac9b0dc74db4b5f0;hp=3d769cc31ef4f9990264ce0840b25234f33dba40;hb=c1cf157116de7fc3da96203aa6f03c38c7ebb650;hpb=67a80c804797ba432378ad6b81fc82b1aa0d9a1d diff --git a/src/client/coreconnection.cpp b/src/client/coreconnection.cpp index 3d769cc3..982d0c86 100644 --- a/src/client/coreconnection.cpp +++ b/src/client/coreconnection.cpp @@ -1,5 +1,5 @@ /*************************************************************************** - * Copyright (C) 2009 by the Quassel Project * + * Copyright (C) 2005-2018 by the Quassel Project * * devel@quassel-irc.org * * * * This program is free software; you can redistribute it and/or modify * @@ -15,553 +15,485 @@ * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * - * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "coreconnection.h" -#ifndef QT_NO_NETWORKPROXY -# include -#endif - #include "client.h" +#include "clientauthhandler.h" #include "clientsettings.h" #include "coreaccountmodel.h" #include "identity.h" +#include "internalpeer.h" #include "network.h" #include "networkmodel.h" #include "quassel.h" #include "signalproxy.h" #include "util.h" -CoreConnection::CoreConnection(CoreAccountModel *model, QObject *parent) - : QObject(parent), - _model(model), - _blockSize(0), - _state(Disconnected), - _progressMinimum(0), - _progressMaximum(-1), - _progressValue(-1) -{ - qRegisterMetaType("CoreConnection::ConnectionState"); +#include "protocols/legacy/legacypeer.h" +CoreConnection::CoreConnection(QObject* parent) + : QObject(parent) + , _authHandler(nullptr) +{ + qRegisterMetaType("CoreConnection::ConnectionState"); } -void CoreConnection::init() { - connect(Client::signalProxy(), SIGNAL(disconnected()), SLOT(coreSocketDisconnected())); -} +void CoreConnection::init() +{ + Client::signalProxy()->setHeartBeatInterval(30); + connect(Client::signalProxy(), &SignalProxy::lagUpdated, this, &CoreConnection::lagUpdated); -void CoreConnection::setProgressText(const QString &text) { - if(_progressText != text) { - _progressText = text; - emit progressTextChanged(text); - } -} + _reconnectTimer.setSingleShot(true); + connect(&_reconnectTimer, &QTimer::timeout, this, &CoreConnection::reconnectTimeout); -void CoreConnection::setProgressValue(int value) { - if(_progressValue != value) { - _progressValue = value; - emit progressValueChanged(value); - } -} + _qNetworkConfigurationManager = new QNetworkConfigurationManager(this); + connect(_qNetworkConfigurationManager.data(), &QNetworkConfigurationManager::onlineStateChanged, this, &CoreConnection::onlineStateChanged); -void CoreConnection::setProgressMinimum(int minimum) { - if(_progressMinimum != minimum) { - _progressMinimum = minimum; - emit progressRangeChanged(minimum, _progressMaximum); - } + CoreConnectionSettings s; + s.initAndNotify("PingTimeoutInterval", this, &CoreConnection::pingTimeoutIntervalChanged, 60); + s.initAndNotify("ReconnectInterval", this, &CoreConnection::reconnectIntervalChanged, 60); + s.notify("NetworkDetectionMode", this, &CoreConnection::networkDetectionModeChanged); + networkDetectionModeChanged(s.networkDetectionMode()); } -void CoreConnection::setProgressMaximum(int maximum) { - if(_progressMaximum != maximum) { - _progressMaximum = maximum; - emit progressRangeChanged(_progressMinimum, maximum); - } +CoreAccountModel* CoreConnection::accountModel() const +{ + return Client::coreAccountModel(); } -void CoreConnection::updateProgress(int value, int max) { - if(max != _progressMaximum) { - _progressMaximum = max; - emit progressRangeChanged(_progressMinimum, _progressMaximum); - } - setProgressValue(value); +void CoreConnection::setProgressText(const QString& text) +{ + if (_progressText != text) { + _progressText = text; + emit progressTextChanged(text); + } } -void CoreConnection::resetConnection() { - if(_socket) { - disconnect(_socket, 0, this, 0); - _socket->deleteLater(); - _socket = 0; - } - _blockSize = 0; - - _coreMsgBuffer.clear(); - - _netsToSync.clear(); - _numNetsToSync = 0; - - setProgressMaximum(-1); // disable - setState(Disconnected); - emit connectionMsg(tr("Disconnected from core.")); - emit encrypted(false); +void CoreConnection::setProgressValue(int value) +{ + if (_progressValue != value) { + _progressValue = value; + emit progressValueChanged(value); + } } -bool CoreConnection::isEncrypted() const { -#ifndef HAVE_SSL - return false; -#else - QSslSocket *sock = qobject_cast(_socket); - return isConnected() && sock && sock->isEncrypted(); -#endif +void CoreConnection::setProgressMinimum(int minimum) +{ + if (_progressMinimum != minimum) { + _progressMinimum = minimum; + emit progressRangeChanged(minimum, _progressMaximum); + } } -void CoreConnection::socketStateChanged(QAbstractSocket::SocketState socketState) { - QString text; - - switch(socketState) { - case QAbstractSocket::UnconnectedState: - text = tr("Disconnected"); - break; - case QAbstractSocket::HostLookupState: - text = tr("Looking up %1...").arg(currentAccount().hostName()); - break; - case QAbstractSocket::ConnectingState: - text = tr("Connecting to %1...").arg(currentAccount().hostName()); - break; - case QAbstractSocket::ConnectedState: - text = tr("Connected to %1").arg(currentAccount().hostName()); - break; - case QAbstractSocket::ClosingState: - text = tr("Disconnecting from %1...").arg(currentAccount().hostName()); - break; - default: - break; - } - - if(!text.isEmpty()) - emit progressTextChanged(text); - - setState(socketState); -} - -void CoreConnection::setState(QAbstractSocket::SocketState socketState) { - ConnectionState state; - - switch(socketState) { - case QAbstractSocket::UnconnectedState: - state = Disconnected; - break; - case QAbstractSocket::HostLookupState: - case QAbstractSocket::ConnectingState: - state = Connecting; - break; - default: - state = Disconnected; - } - - setState(state); -} - -void CoreConnection::setState(ConnectionState state) { - if(state != _state) { - _state = state; - emit stateChanged(state); - if(state == Disconnected) - emit disconnected(); - } -} - -void CoreConnection::coreSocketError(QAbstractSocket::SocketError) { - qDebug() << "coreSocketError" << _socket << _socket->errorString(); - emit connectionError(_socket->errorString()); - resetConnection(); -} - -void CoreConnection::coreSocketDisconnected() { - emit disconnected(); - resetConnection(); - // FIXME handle disconnects gracefully -} - -void CoreConnection::coreHasData() { - QVariant item; - while(SignalProxy::readDataFromDevice(_socket, _blockSize, item)) { - QVariantMap msg = item.toMap(); - if(!msg.contains("MsgType")) { - // This core is way too old and does not even speak our init protocol... - emit connectionErrorPopup(tr("The Quassel Core you try to connect to is too old! Please consider upgrading.")); - disconnectFromCore(); - return; +void CoreConnection::setProgressMaximum(int maximum) +{ + if (_progressMaximum != maximum) { + _progressMaximum = maximum; + emit progressRangeChanged(_progressMinimum, maximum); } - if(msg["MsgType"] == "ClientInitAck") { - clientInitAck(msg); - } else if(msg["MsgType"] == "ClientInitReject") { - emit connectionErrorPopup(msg["Error"].toString()); - disconnectFromCore(); - return; - } else if(msg["MsgType"] == "CoreSetupAck") { - //emit coreSetupSuccess(); - } else if(msg["MsgType"] == "CoreSetupReject") { - //emit coreSetupFailed(msg["Error"].toString()); - } else if(msg["MsgType"] == "ClientLoginReject") { - loginFailed(msg["Error"].toString()); - } else if(msg["MsgType"] == "ClientLoginAck") { - loginSuccess(); - } else if(msg["MsgType"] == "SessionInit") { - // that's it, let's hand over to the signal proxy - // if the socket is an orphan, the signalProxy adopts it. - // -> we don't need to care about it anymore - _socket->setParent(0); - Client::signalProxy()->addPeer(_socket); - - sessionStateReceived(msg["SessionState"].toMap()); - break; // this is definitively the last message we process here! - } else { - disconnectFromCore(tr("Invalid data received from core")); - return; +} + +void CoreConnection::updateProgress(int value, int max) +{ + if (max != _progressMaximum) { + _progressMaximum = max; + emit progressRangeChanged(_progressMinimum, _progressMaximum); } - } - if(_blockSize > 0) { - updateProgress(_socket->bytesAvailable(), _blockSize); - } + setProgressValue(value); } -void CoreConnection::disconnectFromCore(const QString &errorString) { - if(errorString.isEmpty()) - emit connectionError(tr("Disconnected")); - else - emit connectionError(errorString); +void CoreConnection::reconnectTimeout() +{ + if (!_peer) { + CoreConnectionSettings s; + if (_wantReconnect && s.autoReconnect()) { + // If using QNetworkConfigurationManager, we don't want to reconnect if we're offline + if (s.networkDetectionMode() == CoreConnectionSettings::UseQNetworkConfigurationManager) { + if (!_qNetworkConfigurationManager->isOnline()) { + return; + } + } + reconnectToCore(); + } + } +} - Client::signalProxy()->removeAllPeers(); - resetConnection(); +void CoreConnection::networkDetectionModeChanged(const QVariant& vmode) +{ + CoreConnectionSettings s; + auto mode = (CoreConnectionSettings::NetworkDetectionMode)vmode.toInt(); + if (mode == CoreConnectionSettings::UsePingTimeout) + Client::signalProxy()->setMaxHeartBeatCount(s.pingTimeoutInterval() / 30); + else { + Client::signalProxy()->setMaxHeartBeatCount(-1); + } } -void CoreConnection::reconnectToCore() { - if(currentAccount().isValid()) - connectToCore(currentAccount().accountId()); +void CoreConnection::pingTimeoutIntervalChanged(const QVariant& interval) +{ + CoreConnectionSettings s; + if (s.networkDetectionMode() == CoreConnectionSettings::UsePingTimeout) + Client::signalProxy()->setMaxHeartBeatCount(interval.toInt() / 30); // interval is 30 seconds } -bool CoreConnection::connectToCore(AccountId accId) { - if(isConnected()) - return false; +void CoreConnection::reconnectIntervalChanged(const QVariant& interval) +{ + _reconnectTimer.setInterval(interval.toInt() * 1000); +} - CoreAccountSettings s; +void CoreConnection::onlineStateChanged(bool isOnline) +{ + CoreConnectionSettings s; + if (s.networkDetectionMode() != CoreConnectionSettings::UseQNetworkConfigurationManager) + return; - // FIXME: Don't force connection to internal core in mono client - if(Quassel::runMode() == Quassel::Monolithic) { - _account = accountModel()->account(accountModel()->internalAccount()); - Q_ASSERT(_account.isValid()); - } else { - if(!accId.isValid()) { - // check our settings and figure out what to do - if(!s.autoConnectOnStartup()) - return false; - if(s.autoConnectToFixedAccount()) - accId = s.autoConnectAccount(); - else - accId = s.lastAccount(); - if(!accId.isValid()) - return false; + if (isOnline) { + // qDebug() << "QNetworkConfigurationManager reports Online"; + if (state() == Disconnected) { + if (_wantReconnect && s.autoReconnect()) { + reconnectToCore(); + } + } } - _account = accountModel()->account(accId); - if(!_account.accountId().isValid()) { - return false; + else { + // qDebug() << "QNetworkConfigurationManager reports Offline"; + if (state() != Disconnected && !isLocalConnection()) + disconnectFromCore(tr("Network is down"), true); } - if(Quassel::runMode() != Quassel::Monolithic) { - if(_account.isInternal()) - return false; +} + +QPointer CoreConnection::peer() const +{ + if (_peer) { + return _peer; } - } + return _authHandler ? _authHandler->peer() : nullptr; +} - s.setLastAccount(accId); - connectToCurrentAccount(); - return true; +bool CoreConnection::isEncrypted() const +{ + return _peer && _peer->isSecure(); } -void CoreConnection::connectToCurrentAccount() { - resetConnection(); +bool CoreConnection::isLocalConnection() const +{ + if (!isConnected()) + return false; + if (currentAccount().isInternal()) + return true; + if (_authHandler) + return _authHandler->isLocal(); + if (_peer) + return _peer->isLocal(); - if(currentAccount().isInternal()) { - if(Quassel::runMode() != Quassel::Monolithic) { - qWarning() << "Cannot connect to internal core in client-only mode!"; - return; - } - emit startInternalCore(); - emit connectToInternalCore(Client::instance()->signalProxy()); - return; - } + return false; +} - CoreAccountSettings s; +void CoreConnection::onConnectionReady() +{ + setState(Connected); +} - Q_ASSERT(!_socket); -#ifdef HAVE_SSL - QSslSocket *sock = new QSslSocket(Client::instance()); - // make sure the warning is shown if we happen to connect without SSL support later - s.setAccountValue("ShowNoClientSslWarning", true); -#else - if(_account.useSsl()) { - if(s.accountValue("ShowNoClientSslWarning", true).toBool()) { - bool accepted = false; - emit handleNoSslInClient(&accepted); - if(!accepted) { - emit connectionError(tr("Unencrypted connection canceled")); - return; - } - s.setAccountValue("ShowNoClientSslWarning", false); +void CoreConnection::setState(ConnectionState state) +{ + if (state != _state) { + _state = state; + emit stateChanged(state); + if (state == Connected) + _wantReconnect = true; + if (state == Disconnected) + emit disconnected(); } - } - QTcpSocket *sock = new QTcpSocket(Client::instance()); -#endif +} -#ifndef QT_NO_NETWORKPROXY - if(_account.useProxy()) { - QNetworkProxy proxy(_account.proxyType(), _account.proxyHostName(), _account.proxyPort(), _account.proxyUser(), _account.proxyPassword()); - sock->setProxy(proxy); - } -#endif +void CoreConnection::coreSocketError(QAbstractSocket::SocketError error, const QString& errorString) +{ + Q_UNUSED(error) - _socket = sock; - connect(sock, SIGNAL(readyRead()), SLOT(coreHasData())); - connect(sock, SIGNAL(connected()), SLOT(coreSocketConnected())); - connect(sock, SIGNAL(disconnected()), SLOT(coreSocketDisconnected())); - connect(sock, SIGNAL(error(QAbstractSocket::SocketError)), SLOT(coreSocketError(QAbstractSocket::SocketError))); - connect(sock, SIGNAL(stateChanged(QAbstractSocket::SocketState)), SLOT(socketStateChanged(QAbstractSocket::SocketState))); + disconnectFromCore(errorString, true); +} - emit connectionMsg(tr("Connecting to %1...").arg(currentAccount().accountName())); - sock->connectToHost(_account.hostName(), _account.port()); +void CoreConnection::coreSocketDisconnected() +{ + setState(Disconnected); + _wasReconnect = false; + resetConnection(_wantReconnect); } -void CoreConnection::coreSocketConnected() { - // Phase One: Send client info and wait for core info +void CoreConnection::disconnectFromCore() +{ + disconnectFromCore(QString(), false); // requested disconnect, so don't try to reconnect +} + +void CoreConnection::disconnectFromCore(const QString& errorString, bool wantReconnect) +{ + if (wantReconnect) + _reconnectTimer.start(); + else + _reconnectTimer.stop(); - emit connectionMsg(tr("Synchronizing to core...")); + _wantReconnect = wantReconnect; // store if disconnect was requested + _wasReconnect = false; - QVariantMap clientInit; - clientInit["MsgType"] = "ClientInit"; - clientInit["ClientVersion"] = Quassel::buildInfo().fancyVersionString; - clientInit["ClientDate"] = Quassel::buildInfo().buildDate; - clientInit["ProtocolVersion"] = Quassel::buildInfo().protocolVersion; - clientInit["UseSsl"] = _account.useSsl(); -#ifndef QT_NO_COMPRESS - clientInit["UseCompression"] = true; -#else - clientInit["UseCompression"] = false; -#endif + if (_authHandler) + _authHandler->close(); + else if (_peer) + _peer->close(); - SignalProxy::writeDataToDevice(_socket, clientInit); + if (errorString.isEmpty()) + emit connectionError(tr("Disconnected")); + else + emit connectionError(errorString); } -void CoreConnection::clientInitAck(const QVariantMap &msg) { - // Core has accepted our version info and sent its own. Let's see if we accept it as well... - uint ver = msg["ProtocolVersion"].toUInt(); - if(ver < Quassel::buildInfo().clientNeedsProtocol) { - emit connectionErrorPopup(tr("The Quassel Core you are trying to connect to is too old!
" - "Need at least core/client protocol v%1 to connect.").arg(Quassel::buildInfo().clientNeedsProtocol)); - disconnectFromCore(); - return; - } +void CoreConnection::resetConnection(bool wantReconnect) +{ + if (_resetting) + return; + _resetting = true; -#ifndef QT_NO_COMPRESS - if(msg["SupportsCompression"].toBool()) { - _socket->setProperty("UseCompression", true); - } -#endif + _wantReconnect = wantReconnect; - _coreMsgBuffer = msg; + if (_authHandler) { + disconnect(_authHandler, nullptr, this, nullptr); + _authHandler->close(); + _authHandler->deleteLater(); + _authHandler = nullptr; + } -#ifdef HAVE_SSL - CoreAccountSettings s; - if(currentAccount().useSsl()) { - if(msg["SupportSsl"].toBool()) { - // Make sure the warning is shown next time we don't have SSL in the core - s.setAccountValue("ShowNoCoreSslWarning", true); - - QSslSocket *sslSocket = qobject_cast(_socket); - Q_ASSERT(sslSocket); - connect(sslSocket, SIGNAL(encrypted()), SLOT(sslSocketEncrypted())); - connect(sslSocket, SIGNAL(sslErrors(const QList &)), SLOT(sslErrors())); - sslSocket->startClientEncryption(); - } else { - if(s.accountValue("ShowNoCoreSslWarning", true).toBool()) { - bool accepted = false; - emit handleNoSslInCore(&accepted); - if(!accepted) { - disconnectFromCore(tr("Unencrypted connection canceled")); - return; - } - s.setAccountValue("ShowNoCoreSslWarning", false); - s.setAccountValue("SslCert", QString()); - } - connectionReady(); + if (_peer) { + disconnect(_peer, nullptr, this, nullptr); + // peer belongs to the sigproxy and thus gets deleted by it + _peer->close(); + _peer = nullptr; } - return; - } -#endif - // if we use SSL we wait for the next step until every SSL warning has been cleared - connectionReady(); -} -#ifdef HAVE_SSL + _netsToSync.clear(); + _numNetsToSync = 0; -void CoreConnection::sslSocketEncrypted() { - QSslSocket *socket = qobject_cast(sender()); - Q_ASSERT(socket); + setProgressMaximum(-1); // disable + setState(Disconnected); + emit lagUpdated(-1); - if(!socket->sslErrors().count()) { - // Cert is valid, so we don't want to store it as known - // That way, a warning will appear in case it becomes invalid at some point - CoreAccountSettings s; - s.setAccountValue("SSLCert", QString()); - } + emit connectionMsg(tr("Disconnected from core.")); + emit encrypted(false); + setState(Disconnected); + + // initiate if a reconnect if appropriate + CoreConnectionSettings s; + if (wantReconnect && s.autoReconnect()) { + _reconnectTimer.start(); + } - emit encrypted(true); - connectionReady(); + _resetting = false; } -void CoreConnection::sslErrors() { - QSslSocket *socket = qobject_cast(sender()); - Q_ASSERT(socket); +void CoreConnection::reconnectToCore() +{ + if (currentAccount().isValid()) { + _wasReconnect = true; + connectToCore(currentAccount().accountId()); + } +} - CoreAccountSettings s; - QByteArray knownDigest = s.accountValue("SslCert").toByteArray(); +bool CoreConnection::connectToCore(AccountId accId) +{ + if (isConnected()) + return false; - if(knownDigest != socket->peerCertificate().digest()) { - bool accepted = false; - bool permanently = false; - emit handleSslErrors(socket, &accepted, &permanently); + CoreAccountSettings s; - if(!accepted) { - disconnectFromCore(tr("Unencrypted connection canceled")); - return; + // FIXME: Don't force connection to internal core in mono client + if (Quassel::runMode() == Quassel::Monolithic) { + _account = accountModel()->account(accountModel()->internalAccount()); + Q_ASSERT(_account.isValid()); + } + else { + if (!accId.isValid()) { + // check our settings and figure out what to do + if (!s.autoConnectOnStartup()) + return false; + if (s.autoConnectToFixedAccount()) + accId = s.autoConnectAccount(); + else + accId = s.lastAccount(); + if (!accId.isValid()) + return false; + } + _account = accountModel()->account(accId); + if (!_account.accountId().isValid()) { + return false; + } + if (Quassel::runMode() != Quassel::Monolithic) { + if (_account.isInternal()) + return false; + } } - if(permanently) - s.setAccountValue("SslCert", socket->peerCertificate().digest()); - else - s.setAccountValue("SslCert", QString()); - } - - socket->ignoreSslErrors(); + s.setLastAccount(accId); + connectToCurrentAccount(); + return true; } -#endif /* HAVE_SSL */ - -void CoreConnection::connectionReady() { - setState(Connected); - emit connectionMsg(tr("Connected to %1").arg(currentAccount().accountName())); +void CoreConnection::connectToCurrentAccount() +{ + if (_authHandler) { + qWarning() << Q_FUNC_INFO << "Already connected!"; + return; + } - if(!_coreMsgBuffer["Configured"].toBool()) { - // start wizard - emit startCoreSetup(_coreMsgBuffer["StorageBackends"].toList()); - } else if(_coreMsgBuffer["LoginEnabled"].toBool()) { - loginToCore(); - } - _coreMsgBuffer.clear(); -} + if (currentAccount().isInternal()) { + if (Quassel::runMode() != Quassel::Monolithic) { + qWarning() << "Cannot connect to internal core in client-only mode!"; + return; + } -void CoreConnection::loginToCore(const QString &prevError) { - emit connectionMsg(tr("Logging in...")); - if(currentAccount().user().isEmpty() || currentAccount().password().isEmpty() || !prevError.isEmpty()) { - bool valid = false; - emit userAuthenticationRequired(&_account, &valid, prevError); // *must* be a synchronous call - if(!valid || currentAccount().user().isEmpty() || currentAccount().password().isEmpty()) { - disconnectFromCore(tr("Login canceled")); - return; + auto* peer = new InternalPeer(); + _peer = peer; + Client::instance()->signalProxy()->addPeer(peer); // sigproxy will take ownership + emit connectionMsg(tr("Initializing...")); + emit connectToInternalCore(peer); + setState(Connected); + return; } - } - QVariantMap clientLogin; - clientLogin["MsgType"] = "ClientLogin"; - clientLogin["User"] = currentAccount().user(); - clientLogin["Password"] = currentAccount().password(); - SignalProxy::writeDataToDevice(_socket, clientLogin); -} + _authHandler = new ClientAuthHandler(currentAccount(), this); + + connect(_authHandler, &ClientAuthHandler::disconnected, this, &CoreConnection::coreSocketDisconnected); + connect(_authHandler, &ClientAuthHandler::connectionReady, this, &CoreConnection::onConnectionReady); + connect(_authHandler, &ClientAuthHandler::socketError, this, &CoreConnection::coreSocketError); + connect(_authHandler, &ClientAuthHandler::transferProgress, this, &CoreConnection::updateProgress); + connect(_authHandler, + &ClientAuthHandler::requestDisconnect, + this, + selectOverload(&CoreConnection::disconnectFromCore)); + + connect(_authHandler, &ClientAuthHandler::errorMessage, this, &CoreConnection::connectionError); + connect(_authHandler, &ClientAuthHandler::errorPopup, this, &CoreConnection::connectionErrorPopup, Qt::QueuedConnection); + connect(_authHandler, &ClientAuthHandler::statusMessage, this, &CoreConnection::connectionMsg); + connect(_authHandler, &ClientAuthHandler::encrypted, this, &CoreConnection::encrypted); + connect(_authHandler, &ClientAuthHandler::startCoreSetup, this, &CoreConnection::startCoreSetup); + connect(_authHandler, &ClientAuthHandler::coreSetupFailed, this, &CoreConnection::coreSetupFailed); + connect(_authHandler, &ClientAuthHandler::coreSetupSuccessful, this, &CoreConnection::coreSetupSuccess); + connect(_authHandler, &ClientAuthHandler::userAuthenticationRequired, this, &CoreConnection::userAuthenticationRequired); + connect(_authHandler, &ClientAuthHandler::handleNoSslInClient, this, &CoreConnection::handleNoSslInClient); + connect(_authHandler, &ClientAuthHandler::handleNoSslInCore, this, &CoreConnection::handleNoSslInCore); +#ifdef HAVE_SSL + connect(_authHandler, &ClientAuthHandler::handleSslErrors, this, &CoreConnection::handleSslErrors); +#endif + connect(_authHandler, &ClientAuthHandler::loginSuccessful, this, &CoreConnection::onLoginSuccessful); + connect(_authHandler, &ClientAuthHandler::handshakeComplete, this, &CoreConnection::onHandshakeComplete); -void CoreConnection::loginFailed(const QString &error) { - loginToCore(error); + setState(Connecting); + _authHandler->connectToCore(); } -void CoreConnection::loginSuccess() { - updateProgress(0, 0); - - // save current account data - _model->createOrUpdateAccount(currentAccount()); - _model->save(); +void CoreConnection::setupCore(const Protocol::SetupData& setupData) +{ + _authHandler->setupCore(setupData); +} - setProgressText(tr("Receiving session state")); - setState(Synchronizing); - emit connectionMsg(tr("Synchronizing to %1...").arg(currentAccount().accountName())); +void CoreConnection::loginToCore(const QString& user, const QString& password, bool remember) +{ + _authHandler->login(user, password, remember); } -void CoreConnection::sessionStateReceived(const QVariantMap &state) { - updateProgress(100, 100); +void CoreConnection::onLoginSuccessful(const CoreAccount& account) +{ + updateProgress(0, 0); + + // save current account data + accountModel()->createOrUpdateAccount(account); + accountModel()->save(); - // rest of communication happens through SignalProxy... - disconnect(_socket, SIGNAL(readyRead()), this, 0); - disconnect(_socket, SIGNAL(connected()), this, 0); + _reconnectTimer.stop(); - syncToCore(state); + setProgressText(tr("Receiving session state")); + setState(Synchronizing); + emit connectionMsg(tr("Synchronizing to %1...").arg(account.accountName())); } -void CoreConnection::internalSessionStateReceived(const QVariant &packedState) { - updateProgress(100, 100); +void CoreConnection::onHandshakeComplete(RemotePeer* peer, const Protocol::SessionState& sessionState) +{ + updateProgress(100, 100); - setState(Synchronizing); - syncToCore(packedState.toMap()); -} + disconnect(_authHandler, nullptr, this, nullptr); + _authHandler->deleteLater(); + _authHandler = nullptr; -void CoreConnection::syncToCore(const QVariantMap &sessionState) { - setProgressText(tr("Receiving network states")); - updateProgress(0, 100); + _peer = peer; + connect(peer, &Peer::disconnected, this, &CoreConnection::coreSocketDisconnected); + connect(peer, &RemotePeer::statusMessage, this, &CoreConnection::connectionMsg); + connect(peer, &RemotePeer::socketError, this, &CoreConnection::coreSocketError); - // create identities - foreach(QVariant vid, sessionState["Identities"].toList()) { - Client::instance()->coreIdentityCreated(vid.value()); - } + Client::signalProxy()->addPeer(_peer); // sigproxy takes ownership of the peer! - // create buffers - // FIXME: get rid of this crap -- why? - QVariantList bufferinfos = sessionState["BufferInfos"].toList(); - NetworkModel *networkModel = Client::networkModel(); - Q_ASSERT(networkModel); - foreach(QVariant vinfo, bufferinfos) - networkModel->bufferUpdated(vinfo.value()); // create BufferItems + syncToCore(sessionState); +} + +void CoreConnection::internalSessionStateReceived(const Protocol::SessionState& sessionState) +{ + updateProgress(100, 100); + setState(Synchronizing); + syncToCore(sessionState); +} - QVariantList networkids = sessionState["NetworkIds"].toList(); +void CoreConnection::syncToCore(const Protocol::SessionState& sessionState) +{ + setProgressText(tr("Receiving network states")); + updateProgress(0, 100); - // prepare sync progress thingys... - // FIXME: Care about removal of networks - _numNetsToSync = networkids.count(); - updateProgress(0, _numNetsToSync); + // create identities + foreach (const QVariant& vid, sessionState.identities) { + Client::instance()->coreIdentityCreated(vid.value()); + } - // create network objects - foreach(QVariant networkid, networkids) { - NetworkId netid = networkid.value(); - if(Client::network(netid)) - continue; - Network *net = new Network(netid, Client::instance()); - _netsToSync.insert(net); - connect(net, SIGNAL(initDone()), SLOT(networkInitDone())); - connect(net, SIGNAL(destroyed()), SLOT(networkInitDone())); - Client::addNetwork(net); - } - checkSyncState(); + // create buffers + // FIXME: get rid of this crap -- why? + NetworkModel* networkModel = Client::networkModel(); + Q_ASSERT(networkModel); + foreach (const QVariant& vinfo, sessionState.bufferInfos) + networkModel->bufferUpdated(vinfo.value()); // create BufferItems + + // prepare sync progress thingys... + // FIXME: Care about removal of networks + _numNetsToSync = sessionState.networkIds.count(); + updateProgress(0, _numNetsToSync); + + // create network objects + foreach (const QVariant& networkid, sessionState.networkIds) { + NetworkId netid = networkid.value(); + if (Client::network(netid)) + continue; + auto* net = new Network(netid, Client::instance()); + _netsToSync.insert(net); + connect(net, &SyncableObject::initDone, this, &CoreConnection::networkInitDone); + connect(net, &QObject::destroyed, this, &CoreConnection::networkInitDone); + Client::addNetwork(net); + } + checkSyncState(); } -void CoreConnection::networkInitDone() { - Network *net = qobject_cast(sender()); - Q_ASSERT(net); - disconnect(net, 0, this, 0); - _netsToSync.remove(net); - updateProgress(_numNetsToSync - _netsToSync.count(), _numNetsToSync); - checkSyncState(); +// this is also called for destroyed networks! +void CoreConnection::networkInitDone() +{ + QObject* net = sender(); + Q_ASSERT(net); + disconnect(net, nullptr, this, nullptr); + _netsToSync.remove(net); + updateProgress(_numNetsToSync - _netsToSync.count(), _numNetsToSync); + checkSyncState(); } -void CoreConnection::checkSyncState() { - if(_netsToSync.isEmpty()) { - setState(Synchronized); - setProgressText(tr("Synchronized to %1").arg(currentAccount().accountName())); - setProgressMaximum(-1); - emit synchronized(); - } +void CoreConnection::checkSyncState() +{ + if (_netsToSync.isEmpty() && state() >= Synchronizing) { + setState(Synchronized); + setProgressText(tr("Synchronized to %1").arg(currentAccount().accountName())); + setProgressMaximum(-1); + emit synchronized(); + } }