1 /***************************************************************************
2 * Copyright (C) 2009 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 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
19 ***************************************************************************/
21 #include "coreconnection.h"
23 #ifndef QT_NO_NETWORKPROXY
24 # include <QNetworkProxy>
28 #include "clientsettings.h"
29 #include "coreaccountmodel.h"
32 #include "networkmodel.h"
34 #include "signalproxy.h"
37 CoreConnection::CoreConnection(CoreAccountModel *model, QObject *parent)
42 _wantReconnect(false),
47 qRegisterMetaType<ConnectionState>("CoreConnection::ConnectionState");
49 _reconnectTimer.setSingleShot(true);
50 connect(&_reconnectTimer, SIGNAL(timeout()), SLOT(reconnectTimeout()));
53 connect(Solid::Networking::notifier(), SIGNAL(statusChanged(Solid::Networking::Status)),
54 SLOT(solidNetworkStatusChanged(Solid::Networking::Status)));
58 void CoreConnection::init() {
59 Client::signalProxy()->setHeartBeatInterval(30);
60 connect(Client::signalProxy(), SIGNAL(disconnected()), SLOT(coreSocketDisconnected()));
62 CoreConnectionSettings s;
63 s.initAndNotify("PingTimeoutInterval", this, SLOT(pingTimeoutIntervalChanged(QVariant)), 60);
64 s.initAndNotify("ReconnectInterval", this, SLOT(reconnectIntervalChanged(QVariant)), 60);
65 s.notify("NetworkDetectionMode", this, SLOT(networkDetectionModeChanged(QVariant)));
66 networkDetectionModeChanged(s.networkDetectionMode());
69 void CoreConnection::setProgressText(const QString &text) {
70 if(_progressText != text) {
72 emit progressTextChanged(text);
76 void CoreConnection::setProgressValue(int value) {
77 if(_progressValue != value) {
78 _progressValue = value;
79 emit progressValueChanged(value);
83 void CoreConnection::setProgressMinimum(int minimum) {
84 if(_progressMinimum != minimum) {
85 _progressMinimum = minimum;
86 emit progressRangeChanged(minimum, _progressMaximum);
90 void CoreConnection::setProgressMaximum(int maximum) {
91 if(_progressMaximum != maximum) {
92 _progressMaximum = maximum;
93 emit progressRangeChanged(_progressMinimum, maximum);
97 void CoreConnection::updateProgress(int value, int max) {
98 if(max != _progressMaximum) {
99 _progressMaximum = max;
100 emit progressRangeChanged(_progressMinimum, _progressMaximum);
102 setProgressValue(value);
105 void CoreConnection::reconnectTimeout() {
107 CoreConnectionSettings s;
108 if(_wantReconnect && s.autoReconnect()) {
111 // If using Solid, we don't want to reconnect if we're offline
112 if(s.networkDetectionMode() == CoreConnectionSettings::UseSolid) {
113 if(Solid::Networking::status() != Solid::Networking::Connected
114 && Solid::Networking::status() != Solid::Networking::Unknown) {
118 #endif /* HAVE_KDE */
125 void CoreConnection::networkDetectionModeChanged(const QVariant &vmode) {
126 CoreConnectionSettings s;
127 CoreConnectionSettings::NetworkDetectionMode mode = (CoreConnectionSettings::NetworkDetectionMode)vmode.toInt();
128 if(mode == CoreConnectionSettings::UsePingTimeout)
129 Client::signalProxy()->setMaxHeartBeatCount(s.pingTimeoutInterval() / 30);
131 Client::signalProxy()->setMaxHeartBeatCount(-1);
135 void CoreConnection::pingTimeoutIntervalChanged(const QVariant &interval) {
136 CoreConnectionSettings s;
137 if(s.networkDetectionMode() == CoreConnectionSettings::UsePingTimeout)
138 Client::signalProxy()->setMaxHeartBeatCount(interval.toInt() / 30); // interval is 30 seconds
141 void CoreConnection::reconnectIntervalChanged(const QVariant &interval) {
142 _reconnectTimer.setInterval(interval.toInt() * 1000);
147 void CoreConnection::solidNetworkStatusChanged(Solid::Networking::Status status) {
148 CoreConnectionSettings s;
149 if(s.networkDetectionMode() != CoreConnectionSettings::UseSolid)
153 case Solid::Networking::Unknown:
154 case Solid::Networking::Connected:
155 qDebug() << "Solid: Network status changed to connected or unknown";
156 if(state() == Disconnected) {
157 if(_wantReconnect && s.autoReconnect()) {
162 case Solid::Networking::Unconnected:
163 qDebug() << "Solid: Disconnected";
164 if(!isLocalConnection())
165 disconnectFromCore(tr("Network is down"), true);
174 bool CoreConnection::isEncrypted() const {
178 QSslSocket *sock = qobject_cast<QSslSocket *>(_socket);
179 return isConnected() && sock && sock->isEncrypted();
183 bool CoreConnection::isLocalConnection() const {
186 if(currentAccount().isInternal())
188 if(_socket->peerAddress().isInSubnet(QHostAddress::LocalHost, 0x00ffffff))
194 void CoreConnection::socketStateChanged(QAbstractSocket::SocketState socketState) {
197 switch(socketState) {
198 case QAbstractSocket::UnconnectedState:
199 text = tr("Disconnected");
201 case QAbstractSocket::HostLookupState:
202 text = tr("Looking up %1...").arg(currentAccount().hostName());
204 case QAbstractSocket::ConnectingState:
205 text = tr("Connecting to %1...").arg(currentAccount().hostName());
207 case QAbstractSocket::ConnectedState:
208 text = tr("Connected to %1").arg(currentAccount().hostName());
210 case QAbstractSocket::ClosingState:
211 text = tr("Disconnecting from %1...").arg(currentAccount().hostName());
218 emit progressTextChanged(text);
220 setState(socketState);
223 void CoreConnection::setState(QAbstractSocket::SocketState socketState) {
224 ConnectionState state;
226 switch(socketState) {
227 case QAbstractSocket::UnconnectedState:
228 state = Disconnected;
230 case QAbstractSocket::HostLookupState:
231 case QAbstractSocket::ConnectingState:
232 case QAbstractSocket::ConnectedState: // we'll set it to Connected in connectionReady()
236 state = Disconnected;
242 void CoreConnection::setState(ConnectionState state) {
243 if(state != _state) {
245 emit stateChanged(state);
246 if(state == Disconnected)
251 void CoreConnection::coreSocketError(QAbstractSocket::SocketError) {
252 qDebug() << "coreSocketError" << _socket << _socket->errorString();
253 disconnectFromCore(_socket->errorString(), true);
256 void CoreConnection::coreSocketDisconnected() {
257 qDebug() << Q_FUNC_INFO;
258 resetConnection(true);
259 // FIXME handle disconnects gracefully
262 void CoreConnection::coreHasData() {
264 while(SignalProxy::readDataFromDevice(_socket, _blockSize, item)) {
265 QVariantMap msg = item.toMap();
266 if(!msg.contains("MsgType")) {
267 // This core is way too old and does not even speak our init protocol...
268 emit connectionErrorPopup(tr("The Quassel Core you try to connect to is too old! Please consider upgrading."));
269 disconnectFromCore(QString(), false);
272 if(msg["MsgType"] == "ClientInitAck") {
274 } else if(msg["MsgType"] == "ClientInitReject") {
275 emit connectionErrorPopup(msg["Error"].toString());
276 disconnectFromCore(QString(), false);
278 } else if(msg["MsgType"] == "CoreSetupAck") {
279 emit coreSetupSuccess();
280 } else if(msg["MsgType"] == "CoreSetupReject") {
281 emit coreSetupFailed(msg["Error"].toString());
282 } else if(msg["MsgType"] == "ClientLoginReject") {
283 loginFailed(msg["Error"].toString());
284 } else if(msg["MsgType"] == "ClientLoginAck") {
286 } else if(msg["MsgType"] == "SessionInit") {
287 // that's it, let's hand over to the signal proxy
288 // if the socket is an orphan, the signalProxy adopts it.
289 // -> we don't need to care about it anymore
290 _socket->setParent(0);
291 Client::signalProxy()->addPeer(_socket);
293 sessionStateReceived(msg["SessionState"].toMap());
294 break; // this is definitively the last message we process here!
296 disconnectFromCore(tr("Invalid data received from core"), false);
301 updateProgress(_socket->bytesAvailable(), _blockSize);
305 void CoreConnection::disconnectFromCore() {
306 disconnectFromCore(QString(), false); // requested disconnect, so don't try to reconnect
309 void CoreConnection::disconnectFromCore(const QString &errorString, bool wantReconnect) {
311 _reconnectTimer.stop();
313 if(errorString.isEmpty())
314 emit connectionError(tr("Disconnected"));
316 emit connectionError(errorString);
318 Client::signalProxy()->removeAllPeers();
319 resetConnection(wantReconnect);
322 void CoreConnection::resetConnection(bool wantReconnect) {
323 _wantReconnect = wantReconnect;
326 disconnect(_socket, 0, this, 0);
327 _socket->deleteLater();
332 _coreMsgBuffer.clear();
337 setProgressMaximum(-1); // disable
338 setState(Disconnected);
340 emit connectionMsg(tr("Disconnected from core."));
341 emit encrypted(false);
343 // initiate if a reconnect if appropriate
344 CoreConnectionSettings s;
345 if(wantReconnect && s.autoReconnect()) {
346 _reconnectTimer.start();
350 void CoreConnection::reconnectToCore() {
351 if(currentAccount().isValid())
352 connectToCore(currentAccount().accountId());
355 bool CoreConnection::connectToCore(AccountId accId) {
359 CoreAccountSettings s;
361 // FIXME: Don't force connection to internal core in mono client
362 if(Quassel::runMode() == Quassel::Monolithic) {
363 _account = accountModel()->account(accountModel()->internalAccount());
364 Q_ASSERT(_account.isValid());
366 if(!accId.isValid()) {
367 // check our settings and figure out what to do
368 if(!s.autoConnectOnStartup())
370 if(s.autoConnectToFixedAccount())
371 accId = s.autoConnectAccount();
373 accId = s.lastAccount();
377 _account = accountModel()->account(accId);
378 if(!_account.accountId().isValid()) {
381 if(Quassel::runMode() != Quassel::Monolithic) {
382 if(_account.isInternal())
387 s.setLastAccount(accId);
388 connectToCurrentAccount();
392 void CoreConnection::connectToCurrentAccount() {
393 resetConnection(false);
395 if(currentAccount().isInternal()) {
396 if(Quassel::runMode() != Quassel::Monolithic) {
397 qWarning() << "Cannot connect to internal core in client-only mode!";
400 emit startInternalCore();
401 emit connectToInternalCore(Client::instance()->signalProxy());
405 CoreAccountSettings s;
409 QSslSocket *sock = new QSslSocket(Client::instance());
410 // make sure the warning is shown if we happen to connect without SSL support later
411 s.setAccountValue("ShowNoClientSslWarning", true);
413 if(_account.useSsl()) {
414 if(s.accountValue("ShowNoClientSslWarning", true).toBool()) {
415 bool accepted = false;
416 emit handleNoSslInClient(&accepted);
418 emit connectionError(tr("Unencrypted connection canceled"));
421 s.setAccountValue("ShowNoClientSslWarning", false);
424 QTcpSocket *sock = new QTcpSocket(Client::instance());
427 #ifndef QT_NO_NETWORKPROXY
428 if(_account.useProxy()) {
429 QNetworkProxy proxy(_account.proxyType(), _account.proxyHostName(), _account.proxyPort(), _account.proxyUser(), _account.proxyPassword());
430 sock->setProxy(proxy);
435 connect(sock, SIGNAL(readyRead()), SLOT(coreHasData()));
436 connect(sock, SIGNAL(connected()), SLOT(coreSocketConnected()));
437 connect(sock, SIGNAL(disconnected()), SLOT(coreSocketDisconnected()));
438 connect(sock, SIGNAL(error(QAbstractSocket::SocketError)), SLOT(coreSocketError(QAbstractSocket::SocketError)));
439 connect(sock, SIGNAL(stateChanged(QAbstractSocket::SocketState)), SLOT(socketStateChanged(QAbstractSocket::SocketState)));
441 emit connectionMsg(tr("Connecting to %1...").arg(currentAccount().accountName()));
442 sock->connectToHost(_account.hostName(), _account.port());
445 void CoreConnection::coreSocketConnected() {
446 // Phase One: Send client info and wait for core info
448 emit connectionMsg(tr("Synchronizing to core..."));
450 QVariantMap clientInit;
451 clientInit["MsgType"] = "ClientInit";
452 clientInit["ClientVersion"] = Quassel::buildInfo().fancyVersionString;
453 clientInit["ClientDate"] = Quassel::buildInfo().buildDate;
454 clientInit["ProtocolVersion"] = Quassel::buildInfo().protocolVersion;
455 clientInit["UseSsl"] = _account.useSsl();
456 #ifndef QT_NO_COMPRESS
457 clientInit["UseCompression"] = true;
459 clientInit["UseCompression"] = false;
462 SignalProxy::writeDataToDevice(_socket, clientInit);
465 void CoreConnection::clientInitAck(const QVariantMap &msg) {
466 // Core has accepted our version info and sent its own. Let's see if we accept it as well...
467 uint ver = msg["ProtocolVersion"].toUInt();
468 if(ver < Quassel::buildInfo().clientNeedsProtocol) {
469 emit connectionErrorPopup(tr("<b>The Quassel Core you are trying to connect to is too old!</b><br>"
470 "Need at least core/client protocol v%1 to connect.").arg(Quassel::buildInfo().clientNeedsProtocol));
471 disconnectFromCore(QString(), false);
475 #ifndef QT_NO_COMPRESS
476 if(msg["SupportsCompression"].toBool()) {
477 _socket->setProperty("UseCompression", true);
481 _coreMsgBuffer = msg;
484 CoreAccountSettings s;
485 if(currentAccount().useSsl()) {
486 if(msg["SupportSsl"].toBool()) {
487 // Make sure the warning is shown next time we don't have SSL in the core
488 s.setAccountValue("ShowNoCoreSslWarning", true);
490 QSslSocket *sslSocket = qobject_cast<QSslSocket *>(_socket);
492 connect(sslSocket, SIGNAL(encrypted()), SLOT(sslSocketEncrypted()));
493 connect(sslSocket, SIGNAL(sslErrors(const QList<QSslError> &)), SLOT(sslErrors()));
494 sslSocket->startClientEncryption();
496 if(s.accountValue("ShowNoCoreSslWarning", true).toBool()) {
497 bool accepted = false;
498 emit handleNoSslInCore(&accepted);
500 disconnectFromCore(tr("Unencrypted connection canceled"), false);
503 s.setAccountValue("ShowNoCoreSslWarning", false);
504 s.setAccountValue("SslCert", QString());
511 // if we use SSL we wait for the next step until every SSL warning has been cleared
517 void CoreConnection::sslSocketEncrypted() {
518 QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
521 if(!socket->sslErrors().count()) {
522 // Cert is valid, so we don't want to store it as known
523 // That way, a warning will appear in case it becomes invalid at some point
524 CoreAccountSettings s;
525 s.setAccountValue("SSLCert", QString());
528 emit encrypted(true);
532 void CoreConnection::sslErrors() {
533 QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
536 CoreAccountSettings s;
537 QByteArray knownDigest = s.accountValue("SslCert").toByteArray();
539 if(knownDigest != socket->peerCertificate().digest()) {
540 bool accepted = false;
541 bool permanently = false;
542 emit handleSslErrors(socket, &accepted, &permanently);
545 disconnectFromCore(tr("Unencrypted connection canceled"), false);
550 s.setAccountValue("SslCert", socket->peerCertificate().digest());
552 s.setAccountValue("SslCert", QString());
555 socket->ignoreSslErrors();
558 #endif /* HAVE_SSL */
560 void CoreConnection::connectionReady() {
562 emit connectionMsg(tr("Connected to %1").arg(currentAccount().accountName()));
564 if(!_coreMsgBuffer["Configured"].toBool()) {
566 emit startCoreSetup(_coreMsgBuffer["StorageBackends"].toList());
567 } else if(_coreMsgBuffer["LoginEnabled"].toBool()) {
570 _coreMsgBuffer.clear();
573 void CoreConnection::loginToCore(const QString &user, const QString &password, bool remember) {
574 _account.setUser(user);
575 _account.setPassword(password);
576 _account.setStorePassword(remember);
580 void CoreConnection::loginToCore(const QString &prevError) {
581 emit connectionMsg(tr("Logging in..."));
582 if(currentAccount().user().isEmpty() || currentAccount().password().isEmpty() || !prevError.isEmpty()) {
584 emit userAuthenticationRequired(&_account, &valid, prevError); // *must* be a synchronous call
585 if(!valid || currentAccount().user().isEmpty() || currentAccount().password().isEmpty()) {
586 disconnectFromCore(tr("Login canceled"), false);
591 QVariantMap clientLogin;
592 clientLogin["MsgType"] = "ClientLogin";
593 clientLogin["User"] = currentAccount().user();
594 clientLogin["Password"] = currentAccount().password();
595 SignalProxy::writeDataToDevice(_socket, clientLogin);
598 void CoreConnection::loginFailed(const QString &error) {
602 void CoreConnection::loginSuccess() {
603 updateProgress(0, 0);
605 // save current account data
606 _model->createOrUpdateAccount(currentAccount());
609 _reconnectTimer.stop();
611 setProgressText(tr("Receiving session state"));
612 setState(Synchronizing);
613 emit connectionMsg(tr("Synchronizing to %1...").arg(currentAccount().accountName()));
616 void CoreConnection::sessionStateReceived(const QVariantMap &state) {
617 updateProgress(100, 100);
619 // rest of communication happens through SignalProxy...
620 disconnect(_socket, SIGNAL(readyRead()), this, 0);
621 disconnect(_socket, SIGNAL(connected()), this, 0);
626 void CoreConnection::internalSessionStateReceived(const QVariant &packedState) {
627 updateProgress(100, 100);
629 setState(Synchronizing);
630 syncToCore(packedState.toMap());
633 void CoreConnection::syncToCore(const QVariantMap &sessionState) {
634 setProgressText(tr("Receiving network states"));
635 updateProgress(0, 100);
638 foreach(QVariant vid, sessionState["Identities"].toList()) {
639 Client::instance()->coreIdentityCreated(vid.value<Identity>());
643 // FIXME: get rid of this crap -- why?
644 QVariantList bufferinfos = sessionState["BufferInfos"].toList();
645 NetworkModel *networkModel = Client::networkModel();
646 Q_ASSERT(networkModel);
647 foreach(QVariant vinfo, bufferinfos)
648 networkModel->bufferUpdated(vinfo.value<BufferInfo>()); // create BufferItems
650 QVariantList networkids = sessionState["NetworkIds"].toList();
652 // prepare sync progress thingys...
653 // FIXME: Care about removal of networks
654 _numNetsToSync = networkids.count();
655 updateProgress(0, _numNetsToSync);
657 // create network objects
658 foreach(QVariant networkid, networkids) {
659 NetworkId netid = networkid.value<NetworkId>();
660 if(Client::network(netid))
662 Network *net = new Network(netid, Client::instance());
663 _netsToSync.insert(net);
664 connect(net, SIGNAL(initDone()), SLOT(networkInitDone()));
665 connect(net, SIGNAL(destroyed()), SLOT(networkInitDone()));
666 Client::addNetwork(net);
671 // this is also called for destroyed networks!
672 void CoreConnection::networkInitDone() {
673 QObject *net = sender();
675 disconnect(net, 0, this, 0);
676 _netsToSync.remove(net);
677 updateProgress(_numNetsToSync - _netsToSync.count(), _numNetsToSync);
681 void CoreConnection::checkSyncState() {
682 if(_netsToSync.isEmpty() && state() >= Synchronizing) {
683 setState(Synchronized);
684 setProgressText(tr("Synchronized to %1").arg(currentAccount().accountName()));
685 setProgressMaximum(-1);
690 void CoreConnection::doCoreSetup(const QVariant &setupData) {
692 setup["MsgType"] = "CoreSetupData";
693 setup["SetupData"] = setupData;
694 SignalProxy::writeDataToDevice(_socket, setup);