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 == Connected)
220 _wantReconnect = true;
221 if (state == Disconnected)
227 void CoreConnection::coreSocketError(QAbstractSocket::SocketError error, const QString &errorString)
231 disconnectFromCore(errorString, true);
235 void CoreConnection::coreSocketDisconnected()
237 setState(Disconnected);
238 _wasReconnect = false;
239 resetConnection(_wantReconnect);
243 void CoreConnection::disconnectFromCore()
245 disconnectFromCore(QString(), false); // requested disconnect, so don't try to reconnect
249 void CoreConnection::disconnectFromCore(const QString &errorString, bool wantReconnect)
252 _reconnectTimer.start();
254 _reconnectTimer.stop();
256 _wantReconnect = wantReconnect; // store if disconnect was requested
257 _wasReconnect = false;
260 _authHandler->close();
264 if (errorString.isEmpty())
265 emit connectionError(tr("Disconnected"));
267 emit connectionError(errorString);
271 void CoreConnection::resetConnection(bool wantReconnect)
277 _wantReconnect = wantReconnect;
280 disconnect(_authHandler, 0, this, 0);
281 _authHandler->close();
282 _authHandler->deleteLater();
287 disconnect(_peer, 0, this, 0);
288 // peer belongs to the sigproxy and thus gets deleted by it
296 setProgressMaximum(-1); // disable
297 setState(Disconnected);
300 emit connectionMsg(tr("Disconnected from core."));
301 emit encrypted(false);
302 setState(Disconnected);
304 // initiate if a reconnect if appropriate
305 CoreConnectionSettings s;
306 if (wantReconnect && s.autoReconnect()) {
307 _reconnectTimer.start();
314 void CoreConnection::reconnectToCore()
316 if (currentAccount().isValid()) {
317 _wasReconnect = true;
318 connectToCore(currentAccount().accountId());
323 bool CoreConnection::connectToCore(AccountId accId)
328 CoreAccountSettings s;
330 // FIXME: Don't force connection to internal core in mono client
331 if (Quassel::runMode() == Quassel::Monolithic) {
332 _account = accountModel()->account(accountModel()->internalAccount());
333 Q_ASSERT(_account.isValid());
336 if (!accId.isValid()) {
337 // check our settings and figure out what to do
338 if (!s.autoConnectOnStartup())
340 if (s.autoConnectToFixedAccount())
341 accId = s.autoConnectAccount();
343 accId = s.lastAccount();
344 if (!accId.isValid())
347 _account = accountModel()->account(accId);
348 if (!_account.accountId().isValid()) {
351 if (Quassel::runMode() != Quassel::Monolithic) {
352 if (_account.isInternal())
357 s.setLastAccount(accId);
358 connectToCurrentAccount();
363 void CoreConnection::connectToCurrentAccount()
366 qWarning() << Q_FUNC_INFO << "Already connected!";
370 if (currentAccount().isInternal()) {
371 if (Quassel::runMode() != Quassel::Monolithic) {
372 qWarning() << "Cannot connect to internal core in client-only mode!";
375 emit startInternalCore();
377 InternalPeer *peer = new InternalPeer();
379 Client::instance()->signalProxy()->addPeer(peer); // sigproxy will take ownership
380 emit connectToInternalCore(peer);
386 _authHandler = new ClientAuthHandler(currentAccount(), this);
388 connect(_authHandler, SIGNAL(disconnected()), SLOT(coreSocketDisconnected()));
389 connect(_authHandler, SIGNAL(connectionReady()), SLOT(onConnectionReady()));
390 connect(_authHandler, SIGNAL(socketError(QAbstractSocket::SocketError,QString)), SLOT(coreSocketError(QAbstractSocket::SocketError,QString)));
391 connect(_authHandler, SIGNAL(transferProgress(int,int)), SLOT(updateProgress(int,int)));
392 connect(_authHandler, SIGNAL(requestDisconnect(QString,bool)), SLOT(disconnectFromCore(QString,bool)));
394 connect(_authHandler, SIGNAL(errorMessage(QString)), SIGNAL(connectionError(QString)));
395 connect(_authHandler, SIGNAL(errorPopup(QString)), SIGNAL(connectionErrorPopup(QString)), Qt::QueuedConnection);
396 connect(_authHandler, SIGNAL(statusMessage(QString)), SIGNAL(connectionMsg(QString)));
397 connect(_authHandler, SIGNAL(encrypted(bool)), SIGNAL(encrypted(bool)));
398 connect(_authHandler, SIGNAL(startCoreSetup(QVariantList)), SIGNAL(startCoreSetup(QVariantList)));
399 connect(_authHandler, SIGNAL(coreSetupFailed(QString)), SIGNAL(coreSetupFailed(QString)));
400 connect(_authHandler, SIGNAL(coreSetupSuccessful()), SIGNAL(coreSetupSuccess()));
401 connect(_authHandler, SIGNAL(userAuthenticationRequired(CoreAccount*,bool*,QString)), SIGNAL(userAuthenticationRequired(CoreAccount*,bool*,QString)));
402 connect(_authHandler, SIGNAL(handleNoSslInClient(bool*)), SIGNAL(handleNoSslInClient(bool*)));
403 connect(_authHandler, SIGNAL(handleNoSslInCore(bool*)), SIGNAL(handleNoSslInCore(bool*)));
405 connect(_authHandler, SIGNAL(handleSslErrors(const QSslSocket*,bool*,bool*)), SIGNAL(handleSslErrors(const QSslSocket*,bool*,bool*)));
408 connect(_authHandler, SIGNAL(loginSuccessful(CoreAccount)), SLOT(onLoginSuccessful(CoreAccount)));
409 connect(_authHandler, SIGNAL(handshakeComplete(RemotePeer*,Protocol::SessionState)), SLOT(onHandshakeComplete(RemotePeer*,Protocol::SessionState)));
411 setState(Connecting);
412 _authHandler->connectToCore();
416 void CoreConnection::setupCore(const Protocol::SetupData &setupData)
418 _authHandler->setupCore(setupData);
422 void CoreConnection::loginToCore(const QString &user, const QString &password, bool remember)
424 _authHandler->login(user, password, remember);
428 void CoreConnection::onLoginSuccessful(const CoreAccount &account)
430 updateProgress(0, 0);
432 // save current account data
433 accountModel()->createOrUpdateAccount(account);
434 accountModel()->save();
436 _reconnectTimer.stop();
438 setProgressText(tr("Receiving session state"));
439 setState(Synchronizing);
440 emit connectionMsg(tr("Synchronizing to %1...").arg(account.accountName()));
444 void CoreConnection::onHandshakeComplete(RemotePeer *peer, const Protocol::SessionState &sessionState)
446 updateProgress(100, 100);
448 disconnect(_authHandler, 0, this, 0);
449 _authHandler->deleteLater();
453 connect(peer, SIGNAL(disconnected()), SLOT(coreSocketDisconnected()));
454 connect(peer, SIGNAL(statusMessage(QString)), SIGNAL(connectionMsg(QString)));
455 connect(peer, SIGNAL(socketError(QAbstractSocket::SocketError,QString)), SLOT(coreSocketError(QAbstractSocket::SocketError,QString)));
457 Client::signalProxy()->addPeer(_peer); // sigproxy takes ownership of the peer!
459 syncToCore(sessionState);
463 void CoreConnection::internalSessionStateReceived(const Protocol::SessionState &sessionState)
465 updateProgress(100, 100);
467 Client::setCoreFeatures(Quassel::features()); // mono connection...
469 setState(Synchronizing);
470 syncToCore(sessionState);
474 void CoreConnection::syncToCore(const Protocol::SessionState &sessionState)
476 setProgressText(tr("Receiving network states"));
477 updateProgress(0, 100);
480 foreach(const QVariant &vid, sessionState.identities) {
481 Client::instance()->coreIdentityCreated(vid.value<Identity>());
485 // FIXME: get rid of this crap -- why?
486 NetworkModel *networkModel = Client::networkModel();
487 Q_ASSERT(networkModel);
488 foreach(const QVariant &vinfo, sessionState.bufferInfos)
489 networkModel->bufferUpdated(vinfo.value<BufferInfo>()); // create BufferItems
491 // prepare sync progress thingys...
492 // FIXME: Care about removal of networks
493 _numNetsToSync = sessionState.networkIds.count();
494 updateProgress(0, _numNetsToSync);
496 // create network objects
497 foreach(const QVariant &networkid, sessionState.networkIds) {
498 NetworkId netid = networkid.value<NetworkId>();
499 if (Client::network(netid))
501 Network *net = new Network(netid, Client::instance());
502 _netsToSync.insert(net);
503 connect(net, SIGNAL(initDone()), SLOT(networkInitDone()));
504 connect(net, SIGNAL(destroyed()), SLOT(networkInitDone()));
505 Client::addNetwork(net);
511 // this is also called for destroyed networks!
512 void CoreConnection::networkInitDone()
514 QObject *net = sender();
516 disconnect(net, 0, this, 0);
517 _netsToSync.remove(net);
518 updateProgress(_numNetsToSync - _netsToSync.count(), _numNetsToSync);
523 void CoreConnection::checkSyncState()
525 if (_netsToSync.isEmpty() && state() >= Synchronizing) {
526 setState(Synchronized);
527 setProgressText(tr("Synchronized to %1").arg(currentAccount().accountName()));
528 setProgressMaximum(-1);