1 /***************************************************************************
2 * Copyright (C) 2005-2015 by the Quassel Project *
3 * devel@quassel-irc.org *
5 * This program is free software; you can redistribute it and/or modify *
6 * it under the terms of the GNU General Public License as published by *
7 * the Free Software Foundation; either version 2 of the License, or *
8 * (at your option) version 3. *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
15 * You should have received a copy of the GNU General Public License *
16 * along with this program; if not, write to the *
17 * Free Software Foundation, Inc., *
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
19 ***************************************************************************/
21 #include "coreconnection.h"
24 #include "clientauthhandler.h"
25 #include "clientsettings.h"
26 #include "coreaccountmodel.h"
28 #include "internalpeer.h"
30 #include "networkmodel.h"
32 #include "signalproxy.h"
35 #include "protocols/legacy/legacypeer.h"
37 CoreConnection::CoreConnection(QObject *parent)
41 _wantReconnect(false),
48 qRegisterMetaType<ConnectionState>("CoreConnection::ConnectionState");
52 void CoreConnection::init()
54 Client::signalProxy()->setHeartBeatInterval(30);
55 connect(Client::signalProxy(), SIGNAL(lagUpdated(int)), SIGNAL(lagUpdated(int)));
57 _reconnectTimer.setSingleShot(true);
58 connect(&_reconnectTimer, SIGNAL(timeout()), SLOT(reconnectTimeout()));
60 _qNetworkConfigurationManager = new QNetworkConfigurationManager(this);
61 connect(_qNetworkConfigurationManager, SIGNAL(onlineStateChanged(bool)), SLOT(onlineStateChanged(bool)));
63 CoreConnectionSettings s;
64 s.initAndNotify("PingTimeoutInterval", this, SLOT(pingTimeoutIntervalChanged(QVariant)), 60);
65 s.initAndNotify("ReconnectInterval", this, SLOT(reconnectIntervalChanged(QVariant)), 60);
66 s.notify("NetworkDetectionMode", this, SLOT(networkDetectionModeChanged(QVariant)));
67 networkDetectionModeChanged(s.networkDetectionMode());
71 CoreAccountModel *CoreConnection::accountModel() const
73 return Client::coreAccountModel();
77 void CoreConnection::setProgressText(const QString &text)
79 if (_progressText != text) {
81 emit progressTextChanged(text);
86 void CoreConnection::setProgressValue(int value)
88 if (_progressValue != value) {
89 _progressValue = value;
90 emit progressValueChanged(value);
95 void CoreConnection::setProgressMinimum(int minimum)
97 if (_progressMinimum != minimum) {
98 _progressMinimum = minimum;
99 emit progressRangeChanged(minimum, _progressMaximum);
104 void CoreConnection::setProgressMaximum(int maximum)
106 if (_progressMaximum != maximum) {
107 _progressMaximum = maximum;
108 emit progressRangeChanged(_progressMinimum, maximum);
113 void CoreConnection::updateProgress(int value, int max)
115 if (max != _progressMaximum) {
116 _progressMaximum = max;
117 emit progressRangeChanged(_progressMinimum, _progressMaximum);
119 setProgressValue(value);
123 void CoreConnection::reconnectTimeout()
126 CoreConnectionSettings s;
127 if (_wantReconnect && s.autoReconnect()) {
128 // If using QNetworkConfigurationManager, we don't want to reconnect if we're offline
129 if (s.networkDetectionMode() == CoreConnectionSettings::UseQNetworkConfigurationManager) {
130 if (!_qNetworkConfigurationManager->isOnline()) {
140 void CoreConnection::networkDetectionModeChanged(const QVariant &vmode)
142 CoreConnectionSettings s;
143 CoreConnectionSettings::NetworkDetectionMode mode = (CoreConnectionSettings::NetworkDetectionMode)vmode.toInt();
144 if (mode == CoreConnectionSettings::UsePingTimeout)
145 Client::signalProxy()->setMaxHeartBeatCount(s.pingTimeoutInterval() / 30);
147 Client::signalProxy()->setMaxHeartBeatCount(-1);
152 void CoreConnection::pingTimeoutIntervalChanged(const QVariant &interval)
154 CoreConnectionSettings s;
155 if (s.networkDetectionMode() == CoreConnectionSettings::UsePingTimeout)
156 Client::signalProxy()->setMaxHeartBeatCount(interval.toInt() / 30); // interval is 30 seconds
160 void CoreConnection::reconnectIntervalChanged(const QVariant &interval)
162 _reconnectTimer.setInterval(interval.toInt() * 1000);
166 void CoreConnection::onlineStateChanged(bool isOnline)
168 CoreConnectionSettings s;
169 if (s.networkDetectionMode() != CoreConnectionSettings::UseQNetworkConfigurationManager)
173 // qDebug() << "QNetworkConfigurationManager reports Online";
174 if (state() == Disconnected) {
175 if (_wantReconnect && s.autoReconnect()) {
180 // qDebug() << "QNetworkConfigurationManager reports Offline";
181 if (state() != Disconnected && !isLocalConnection())
182 disconnectFromCore(tr("Network is down"), true);
187 bool CoreConnection::isEncrypted() const
189 return _peer && _peer->isSecure();
193 bool CoreConnection::isLocalConnection() const
197 if (currentAccount().isInternal())
200 return _authHandler->isLocal();
202 return _peer->isLocal();
208 void CoreConnection::onConnectionReady()
214 void CoreConnection::setState(ConnectionState state)
216 if (state != _state) {
218 emit stateChanged(state);
219 if (state == Disconnected)
225 void CoreConnection::coreSocketError(QAbstractSocket::SocketError error, const QString &errorString)
229 disconnectFromCore(errorString, true);
233 void CoreConnection::coreSocketDisconnected()
235 setState(Disconnected);
236 _wasReconnect = false;
237 resetConnection(_wantReconnect);
241 void CoreConnection::disconnectFromCore()
243 disconnectFromCore(QString(), false); // requested disconnect, so don't try to reconnect
247 void CoreConnection::disconnectFromCore(const QString &errorString, bool wantReconnect)
250 _reconnectTimer.start();
252 _reconnectTimer.stop();
254 _wantReconnect = wantReconnect; // store if disconnect was requested
255 _wasReconnect = false;
258 _authHandler->close();
262 if (errorString.isEmpty())
263 emit connectionError(tr("Disconnected"));
265 emit connectionError(errorString);
269 void CoreConnection::resetConnection(bool wantReconnect)
275 _wantReconnect = wantReconnect;
278 disconnect(_authHandler, 0, this, 0);
279 _authHandler->close();
280 _authHandler->deleteLater();
285 disconnect(_peer, 0, this, 0);
286 // peer belongs to the sigproxy and thus gets deleted by it
294 setProgressMaximum(-1); // disable
295 setState(Disconnected);
298 emit connectionMsg(tr("Disconnected from core."));
299 emit encrypted(false);
300 setState(Disconnected);
302 // initiate if a reconnect if appropriate
303 CoreConnectionSettings s;
304 if (wantReconnect && s.autoReconnect()) {
305 _reconnectTimer.start();
312 void CoreConnection::reconnectToCore()
314 if (currentAccount().isValid()) {
315 _wasReconnect = true;
316 connectToCore(currentAccount().accountId());
321 bool CoreConnection::connectToCore(AccountId accId)
326 CoreAccountSettings s;
328 // FIXME: Don't force connection to internal core in mono client
329 if (Quassel::runMode() == Quassel::Monolithic) {
330 _account = accountModel()->account(accountModel()->internalAccount());
331 Q_ASSERT(_account.isValid());
334 if (!accId.isValid()) {
335 // check our settings and figure out what to do
336 if (!s.autoConnectOnStartup())
338 if (s.autoConnectToFixedAccount())
339 accId = s.autoConnectAccount();
341 accId = s.lastAccount();
342 if (!accId.isValid())
345 _account = accountModel()->account(accId);
346 if (!_account.accountId().isValid()) {
349 if (Quassel::runMode() != Quassel::Monolithic) {
350 if (_account.isInternal())
355 s.setLastAccount(accId);
356 connectToCurrentAccount();
361 void CoreConnection::connectToCurrentAccount()
364 qWarning() << Q_FUNC_INFO << "Already connected!";
368 if (currentAccount().isInternal()) {
369 if (Quassel::runMode() != Quassel::Monolithic) {
370 qWarning() << "Cannot connect to internal core in client-only mode!";
373 emit startInternalCore();
375 InternalPeer *peer = new InternalPeer();
377 Client::instance()->signalProxy()->addPeer(peer); // sigproxy will take ownership
378 emit connectToInternalCore(peer);
384 _authHandler = new ClientAuthHandler(currentAccount(), this);
386 connect(_authHandler, SIGNAL(disconnected()), SLOT(coreSocketDisconnected()));
387 connect(_authHandler, SIGNAL(connectionReady()), SLOT(onConnectionReady()));
388 connect(_authHandler, SIGNAL(socketError(QAbstractSocket::SocketError,QString)), SLOT(coreSocketError(QAbstractSocket::SocketError,QString)));
389 connect(_authHandler, SIGNAL(transferProgress(int,int)), SLOT(updateProgress(int,int)));
390 connect(_authHandler, SIGNAL(requestDisconnect(QString,bool)), SLOT(disconnectFromCore(QString,bool)));
392 connect(_authHandler, SIGNAL(errorMessage(QString)), SIGNAL(connectionError(QString)));
393 connect(_authHandler, SIGNAL(errorPopup(QString)), SIGNAL(connectionErrorPopup(QString)), Qt::QueuedConnection);
394 connect(_authHandler, SIGNAL(statusMessage(QString)), SIGNAL(connectionMsg(QString)));
395 connect(_authHandler, SIGNAL(encrypted(bool)), SIGNAL(encrypted(bool)));
396 connect(_authHandler, SIGNAL(startCoreSetup(QVariantList)), SIGNAL(startCoreSetup(QVariantList)));
397 connect(_authHandler, SIGNAL(coreSetupFailed(QString)), SIGNAL(coreSetupFailed(QString)));
398 connect(_authHandler, SIGNAL(coreSetupSuccessful()), SIGNAL(coreSetupSuccess()));
399 connect(_authHandler, SIGNAL(userAuthenticationRequired(CoreAccount*,bool*,QString)), SIGNAL(userAuthenticationRequired(CoreAccount*,bool*,QString)));
400 connect(_authHandler, SIGNAL(handleNoSslInClient(bool*)), SIGNAL(handleNoSslInClient(bool*)));
401 connect(_authHandler, SIGNAL(handleNoSslInCore(bool*)), SIGNAL(handleNoSslInCore(bool*)));
403 connect(_authHandler, SIGNAL(handleSslErrors(const QSslSocket*,bool*,bool*)), SIGNAL(handleSslErrors(const QSslSocket*,bool*,bool*)));
406 connect(_authHandler, SIGNAL(loginSuccessful(CoreAccount)), SLOT(onLoginSuccessful(CoreAccount)));
407 connect(_authHandler, SIGNAL(handshakeComplete(RemotePeer*,Protocol::SessionState)), SLOT(onHandshakeComplete(RemotePeer*,Protocol::SessionState)));
409 setState(Connecting);
410 _authHandler->connectToCore();
414 void CoreConnection::setupCore(const Protocol::SetupData &setupData)
416 _authHandler->setupCore(setupData);
420 void CoreConnection::loginToCore(const QString &user, const QString &password, bool remember)
422 _authHandler->login(user, password, remember);
426 void CoreConnection::onLoginSuccessful(const CoreAccount &account)
428 updateProgress(0, 0);
430 // save current account data
431 accountModel()->createOrUpdateAccount(account);
432 accountModel()->save();
434 _reconnectTimer.stop();
436 setProgressText(tr("Receiving session state"));
437 setState(Synchronizing);
438 emit connectionMsg(tr("Synchronizing to %1...").arg(account.accountName()));
442 void CoreConnection::onHandshakeComplete(RemotePeer *peer, const Protocol::SessionState &sessionState)
444 updateProgress(100, 100);
446 disconnect(_authHandler, 0, this, 0);
447 _authHandler->deleteLater();
451 connect(peer, SIGNAL(disconnected()), SLOT(coreSocketDisconnected()));
452 connect(peer, SIGNAL(statusMessage(QString)), SIGNAL(connectionMsg(QString)));
453 connect(peer, SIGNAL(socketError(QAbstractSocket::SocketError,QString)), SLOT(coreSocketError(QAbstractSocket::SocketError,QString)));
455 Client::signalProxy()->addPeer(_peer); // sigproxy takes ownership of the peer!
457 syncToCore(sessionState);
461 void CoreConnection::internalSessionStateReceived(const Protocol::SessionState &sessionState)
463 updateProgress(100, 100);
465 Client::setCoreFeatures(Quassel::features()); // mono connection...
467 setState(Synchronizing);
468 syncToCore(sessionState);
472 void CoreConnection::syncToCore(const Protocol::SessionState &sessionState)
474 setProgressText(tr("Receiving network states"));
475 updateProgress(0, 100);
478 foreach(const QVariant &vid, sessionState.identities) {
479 Client::instance()->coreIdentityCreated(vid.value<Identity>());
483 // FIXME: get rid of this crap -- why?
484 NetworkModel *networkModel = Client::networkModel();
485 Q_ASSERT(networkModel);
486 foreach(const QVariant &vinfo, sessionState.bufferInfos)
487 networkModel->bufferUpdated(vinfo.value<BufferInfo>()); // create BufferItems
489 // prepare sync progress thingys...
490 // FIXME: Care about removal of networks
491 _numNetsToSync = sessionState.networkIds.count();
492 updateProgress(0, _numNetsToSync);
494 // create network objects
495 foreach(const QVariant &networkid, sessionState.networkIds) {
496 NetworkId netid = networkid.value<NetworkId>();
497 if (Client::network(netid))
499 Network *net = new Network(netid, Client::instance());
500 _netsToSync.insert(net);
501 connect(net, SIGNAL(initDone()), SLOT(networkInitDone()));
502 connect(net, SIGNAL(destroyed()), SLOT(networkInitDone()));
503 Client::addNetwork(net);
509 // this is also called for destroyed networks!
510 void CoreConnection::networkInitDone()
512 QObject *net = sender();
514 disconnect(net, 0, this, 0);
515 _netsToSync.remove(net);
516 updateProgress(_numNetsToSync - _netsToSync.count(), _numNetsToSync);
521 void CoreConnection::checkSyncState()
523 if (_netsToSync.isEmpty() && state() >= Synchronizing) {
524 setState(Synchronized);
525 setProgressText(tr("Synchronized to %1").arg(currentAccount().accountName()));
526 setProgressMaximum(-1);