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)
46 qRegisterMetaType<ConnectionState>("CoreConnection::ConnectionState");
50 void CoreConnection::init() {
51 connect(Client::signalProxy(), SIGNAL(disconnected()), SLOT(coreSocketDisconnected()));
54 void CoreConnection::setProgressText(const QString &text) {
55 if(_progressText != text) {
57 emit progressTextChanged(text);
61 void CoreConnection::setProgressValue(int value) {
62 if(_progressValue != value) {
63 _progressValue = value;
64 emit progressValueChanged(value);
68 void CoreConnection::setProgressMinimum(int minimum) {
69 if(_progressMinimum != minimum) {
70 _progressMinimum = minimum;
71 emit progressRangeChanged(minimum, _progressMaximum);
75 void CoreConnection::setProgressMaximum(int maximum) {
76 if(_progressMaximum != maximum) {
77 _progressMaximum = maximum;
78 emit progressRangeChanged(_progressMinimum, maximum);
82 void CoreConnection::updateProgress(int value, int max) {
83 if(max != _progressMaximum) {
84 _progressMaximum = max;
85 emit progressRangeChanged(_progressMinimum, _progressMaximum);
87 setProgressValue(value);
90 void CoreConnection::resetConnection() {
92 disconnect(_socket, 0, this, 0);
93 _socket->deleteLater();
98 _coreMsgBuffer.clear();
103 setProgressMaximum(-1); // disable
104 setState(Disconnected);
105 emit connectionMsg(tr("Disconnected from core."));
106 emit encrypted(false);
109 bool CoreConnection::isEncrypted() const {
113 QSslSocket *sock = qobject_cast<QSslSocket *>(_socket);
114 return isConnected() && sock && sock->isEncrypted();
118 void CoreConnection::socketStateChanged(QAbstractSocket::SocketState socketState) {
121 switch(socketState) {
122 case QAbstractSocket::UnconnectedState:
123 text = tr("Disconnected");
125 case QAbstractSocket::HostLookupState:
126 text = tr("Looking up %1...").arg(currentAccount().hostName());
128 case QAbstractSocket::ConnectingState:
129 text = tr("Connecting to %1...").arg(currentAccount().hostName());
131 case QAbstractSocket::ConnectedState:
132 text = tr("Connected to %1").arg(currentAccount().hostName());
134 case QAbstractSocket::ClosingState:
135 text = tr("Disconnecting from %1...").arg(currentAccount().hostName());
142 emit progressTextChanged(text);
144 setState(socketState);
147 void CoreConnection::setState(QAbstractSocket::SocketState socketState) {
148 ConnectionState state;
150 switch(socketState) {
151 case QAbstractSocket::UnconnectedState:
152 state = Disconnected;
154 case QAbstractSocket::HostLookupState:
155 case QAbstractSocket::ConnectingState:
156 case QAbstractSocket::ConnectedState: // we'll set it to Connected in connectionReady()
160 state = Disconnected;
166 void CoreConnection::setState(ConnectionState state) {
167 if(state != _state) {
169 emit stateChanged(state);
170 if(state == Disconnected)
175 void CoreConnection::coreSocketError(QAbstractSocket::SocketError) {
176 qDebug() << "coreSocketError" << _socket << _socket->errorString();
177 emit connectionError(_socket->errorString());
181 void CoreConnection::coreSocketDisconnected() {
184 // FIXME handle disconnects gracefully
187 void CoreConnection::coreHasData() {
189 while(SignalProxy::readDataFromDevice(_socket, _blockSize, item)) {
190 QVariantMap msg = item.toMap();
191 if(!msg.contains("MsgType")) {
192 // This core is way too old and does not even speak our init protocol...
193 emit connectionErrorPopup(tr("The Quassel Core you try to connect to is too old! Please consider upgrading."));
194 disconnectFromCore();
197 if(msg["MsgType"] == "ClientInitAck") {
199 } else if(msg["MsgType"] == "ClientInitReject") {
200 emit connectionErrorPopup(msg["Error"].toString());
201 disconnectFromCore();
203 } else if(msg["MsgType"] == "CoreSetupAck") {
204 emit coreSetupSuccess();
205 } else if(msg["MsgType"] == "CoreSetupReject") {
206 emit coreSetupFailed(msg["Error"].toString());
207 } else if(msg["MsgType"] == "ClientLoginReject") {
208 loginFailed(msg["Error"].toString());
209 } else if(msg["MsgType"] == "ClientLoginAck") {
211 } else if(msg["MsgType"] == "SessionInit") {
212 // that's it, let's hand over to the signal proxy
213 // if the socket is an orphan, the signalProxy adopts it.
214 // -> we don't need to care about it anymore
215 _socket->setParent(0);
216 Client::signalProxy()->addPeer(_socket);
218 sessionStateReceived(msg["SessionState"].toMap());
219 break; // this is definitively the last message we process here!
221 disconnectFromCore(tr("Invalid data received from core"));
226 updateProgress(_socket->bytesAvailable(), _blockSize);
230 void CoreConnection::disconnectFromCore(const QString &errorString) {
231 if(errorString.isEmpty())
232 emit connectionError(tr("Disconnected"));
234 emit connectionError(errorString);
236 Client::signalProxy()->removeAllPeers();
240 void CoreConnection::reconnectToCore() {
241 if(currentAccount().isValid())
242 connectToCore(currentAccount().accountId());
245 bool CoreConnection::connectToCore(AccountId accId) {
249 CoreAccountSettings s;
251 // FIXME: Don't force connection to internal core in mono client
252 if(Quassel::runMode() == Quassel::Monolithic) {
253 _account = accountModel()->account(accountModel()->internalAccount());
254 Q_ASSERT(_account.isValid());
256 if(!accId.isValid()) {
257 // check our settings and figure out what to do
258 if(!s.autoConnectOnStartup())
260 if(s.autoConnectToFixedAccount())
261 accId = s.autoConnectAccount();
263 accId = s.lastAccount();
267 _account = accountModel()->account(accId);
268 if(!_account.accountId().isValid()) {
271 if(Quassel::runMode() != Quassel::Monolithic) {
272 if(_account.isInternal())
277 s.setLastAccount(accId);
278 connectToCurrentAccount();
282 void CoreConnection::connectToCurrentAccount() {
285 if(currentAccount().isInternal()) {
286 if(Quassel::runMode() != Quassel::Monolithic) {
287 qWarning() << "Cannot connect to internal core in client-only mode!";
290 emit startInternalCore();
291 emit connectToInternalCore(Client::instance()->signalProxy());
295 CoreAccountSettings s;
299 QSslSocket *sock = new QSslSocket(Client::instance());
300 // make sure the warning is shown if we happen to connect without SSL support later
301 s.setAccountValue("ShowNoClientSslWarning", true);
303 if(_account.useSsl()) {
304 if(s.accountValue("ShowNoClientSslWarning", true).toBool()) {
305 bool accepted = false;
306 emit handleNoSslInClient(&accepted);
308 emit connectionError(tr("Unencrypted connection canceled"));
311 s.setAccountValue("ShowNoClientSslWarning", false);
314 QTcpSocket *sock = new QTcpSocket(Client::instance());
317 #ifndef QT_NO_NETWORKPROXY
318 if(_account.useProxy()) {
319 QNetworkProxy proxy(_account.proxyType(), _account.proxyHostName(), _account.proxyPort(), _account.proxyUser(), _account.proxyPassword());
320 sock->setProxy(proxy);
325 connect(sock, SIGNAL(readyRead()), SLOT(coreHasData()));
326 connect(sock, SIGNAL(connected()), SLOT(coreSocketConnected()));
327 connect(sock, SIGNAL(disconnected()), SLOT(coreSocketDisconnected()));
328 connect(sock, SIGNAL(error(QAbstractSocket::SocketError)), SLOT(coreSocketError(QAbstractSocket::SocketError)));
329 connect(sock, SIGNAL(stateChanged(QAbstractSocket::SocketState)), SLOT(socketStateChanged(QAbstractSocket::SocketState)));
331 emit connectionMsg(tr("Connecting to %1...").arg(currentAccount().accountName()));
332 sock->connectToHost(_account.hostName(), _account.port());
335 void CoreConnection::coreSocketConnected() {
336 // Phase One: Send client info and wait for core info
338 emit connectionMsg(tr("Synchronizing to core..."));
340 QVariantMap clientInit;
341 clientInit["MsgType"] = "ClientInit";
342 clientInit["ClientVersion"] = Quassel::buildInfo().fancyVersionString;
343 clientInit["ClientDate"] = Quassel::buildInfo().buildDate;
344 clientInit["ProtocolVersion"] = Quassel::buildInfo().protocolVersion;
345 clientInit["UseSsl"] = _account.useSsl();
346 #ifndef QT_NO_COMPRESS
347 clientInit["UseCompression"] = true;
349 clientInit["UseCompression"] = false;
352 SignalProxy::writeDataToDevice(_socket, clientInit);
355 void CoreConnection::clientInitAck(const QVariantMap &msg) {
356 // Core has accepted our version info and sent its own. Let's see if we accept it as well...
357 uint ver = msg["ProtocolVersion"].toUInt();
358 if(ver < Quassel::buildInfo().clientNeedsProtocol) {
359 emit connectionErrorPopup(tr("<b>The Quassel Core you are trying to connect to is too old!</b><br>"
360 "Need at least core/client protocol v%1 to connect.").arg(Quassel::buildInfo().clientNeedsProtocol));
361 disconnectFromCore();
365 #ifndef QT_NO_COMPRESS
366 if(msg["SupportsCompression"].toBool()) {
367 _socket->setProperty("UseCompression", true);
371 _coreMsgBuffer = msg;
374 CoreAccountSettings s;
375 if(currentAccount().useSsl()) {
376 if(msg["SupportSsl"].toBool()) {
377 // Make sure the warning is shown next time we don't have SSL in the core
378 s.setAccountValue("ShowNoCoreSslWarning", true);
380 QSslSocket *sslSocket = qobject_cast<QSslSocket *>(_socket);
382 connect(sslSocket, SIGNAL(encrypted()), SLOT(sslSocketEncrypted()));
383 connect(sslSocket, SIGNAL(sslErrors(const QList<QSslError> &)), SLOT(sslErrors()));
384 sslSocket->startClientEncryption();
386 if(s.accountValue("ShowNoCoreSslWarning", true).toBool()) {
387 bool accepted = false;
388 emit handleNoSslInCore(&accepted);
390 disconnectFromCore(tr("Unencrypted connection canceled"));
393 s.setAccountValue("ShowNoCoreSslWarning", false);
394 s.setAccountValue("SslCert", QString());
401 // if we use SSL we wait for the next step until every SSL warning has been cleared
407 void CoreConnection::sslSocketEncrypted() {
408 QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
411 if(!socket->sslErrors().count()) {
412 // Cert is valid, so we don't want to store it as known
413 // That way, a warning will appear in case it becomes invalid at some point
414 CoreAccountSettings s;
415 s.setAccountValue("SSLCert", QString());
418 emit encrypted(true);
422 void CoreConnection::sslErrors() {
423 QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
426 CoreAccountSettings s;
427 QByteArray knownDigest = s.accountValue("SslCert").toByteArray();
429 if(knownDigest != socket->peerCertificate().digest()) {
430 bool accepted = false;
431 bool permanently = false;
432 emit handleSslErrors(socket, &accepted, &permanently);
435 disconnectFromCore(tr("Unencrypted connection canceled"));
440 s.setAccountValue("SslCert", socket->peerCertificate().digest());
442 s.setAccountValue("SslCert", QString());
445 socket->ignoreSslErrors();
448 #endif /* HAVE_SSL */
450 void CoreConnection::connectionReady() {
452 emit connectionMsg(tr("Connected to %1").arg(currentAccount().accountName()));
454 if(!_coreMsgBuffer["Configured"].toBool()) {
456 emit startCoreSetup(_coreMsgBuffer["StorageBackends"].toList());
457 } else if(_coreMsgBuffer["LoginEnabled"].toBool()) {
460 _coreMsgBuffer.clear();
463 void CoreConnection::loginToCore(const QString &user, const QString &password, bool remember) {
464 _account.setUser(user);
465 _account.setPassword(password);
466 _account.setStorePassword(remember);
470 void CoreConnection::loginToCore(const QString &prevError) {
471 emit connectionMsg(tr("Logging in..."));
472 if(currentAccount().user().isEmpty() || currentAccount().password().isEmpty() || !prevError.isEmpty()) {
474 emit userAuthenticationRequired(&_account, &valid, prevError); // *must* be a synchronous call
475 if(!valid || currentAccount().user().isEmpty() || currentAccount().password().isEmpty()) {
476 disconnectFromCore(tr("Login canceled"));
481 QVariantMap clientLogin;
482 clientLogin["MsgType"] = "ClientLogin";
483 clientLogin["User"] = currentAccount().user();
484 clientLogin["Password"] = currentAccount().password();
485 SignalProxy::writeDataToDevice(_socket, clientLogin);
488 void CoreConnection::loginFailed(const QString &error) {
492 void CoreConnection::loginSuccess() {
493 updateProgress(0, 0);
495 // save current account data
496 _model->createOrUpdateAccount(currentAccount());
499 setProgressText(tr("Receiving session state"));
500 setState(Synchronizing);
501 emit connectionMsg(tr("Synchronizing to %1...").arg(currentAccount().accountName()));
504 void CoreConnection::sessionStateReceived(const QVariantMap &state) {
505 updateProgress(100, 100);
507 // rest of communication happens through SignalProxy...
508 disconnect(_socket, SIGNAL(readyRead()), this, 0);
509 disconnect(_socket, SIGNAL(connected()), this, 0);
514 void CoreConnection::internalSessionStateReceived(const QVariant &packedState) {
515 updateProgress(100, 100);
517 setState(Synchronizing);
518 syncToCore(packedState.toMap());
521 void CoreConnection::syncToCore(const QVariantMap &sessionState) {
522 setProgressText(tr("Receiving network states"));
523 updateProgress(0, 100);
526 foreach(QVariant vid, sessionState["Identities"].toList()) {
527 Client::instance()->coreIdentityCreated(vid.value<Identity>());
531 // FIXME: get rid of this crap -- why?
532 QVariantList bufferinfos = sessionState["BufferInfos"].toList();
533 NetworkModel *networkModel = Client::networkModel();
534 Q_ASSERT(networkModel);
535 foreach(QVariant vinfo, bufferinfos)
536 networkModel->bufferUpdated(vinfo.value<BufferInfo>()); // create BufferItems
538 QVariantList networkids = sessionState["NetworkIds"].toList();
540 // prepare sync progress thingys...
541 // FIXME: Care about removal of networks
542 _numNetsToSync = networkids.count();
543 updateProgress(0, _numNetsToSync);
545 // create network objects
546 foreach(QVariant networkid, networkids) {
547 NetworkId netid = networkid.value<NetworkId>();
548 if(Client::network(netid))
550 Network *net = new Network(netid, Client::instance());
551 _netsToSync.insert(net);
552 connect(net, SIGNAL(initDone()), SLOT(networkInitDone()));
553 connect(net, SIGNAL(destroyed()), SLOT(networkInitDone()));
554 Client::addNetwork(net);
559 void CoreConnection::networkInitDone() {
560 Network *net = qobject_cast<Network *>(sender());
562 disconnect(net, 0, this, 0);
563 _netsToSync.remove(net);
564 updateProgress(_numNetsToSync - _netsToSync.count(), _numNetsToSync);
568 void CoreConnection::checkSyncState() {
569 if(_netsToSync.isEmpty()) {
570 setState(Synchronized);
571 setProgressText(tr("Synchronized to %1").arg(currentAccount().accountName()));
572 setProgressMaximum(-1);
577 void CoreConnection::doCoreSetup(const QVariant &setupData) {
579 setup["MsgType"] = "CoreSetupData";
580 setup["SetupData"] = setupData;
581 SignalProxy::writeDataToDevice(_socket, setup);