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:
158 case QAbstractSocket::ConnectedState:
162 state = Disconnected;
168 void CoreConnection::setState(ConnectionState state) {
169 if(state != _state) {
171 emit stateChanged(state);
172 if(state == Disconnected)
177 void CoreConnection::coreSocketError(QAbstractSocket::SocketError) {
178 qDebug() << "coreSocketError" << _socket << _socket->errorString();
179 emit connectionError(_socket->errorString());
183 void CoreConnection::coreSocketDisconnected() {
186 // FIXME handle disconnects gracefully
189 void CoreConnection::coreHasData() {
191 while(SignalProxy::readDataFromDevice(_socket, _blockSize, item)) {
192 QVariantMap msg = item.toMap();
193 if(!msg.contains("MsgType")) {
194 // This core is way too old and does not even speak our init protocol...
195 emit connectionError(tr("The Quassel Core you try to connect to is too old! Please consider upgrading."));
196 disconnectFromCore();
199 if(msg["MsgType"] == "ClientInitAck") {
201 } else if(msg["MsgType"] == "ClientInitReject") {
202 emit connectionError(msg["Error"].toString());
203 disconnectFromCore();
205 } else if(msg["MsgType"] == "CoreSetupAck") {
206 //emit coreSetupSuccess();
207 } else if(msg["MsgType"] == "CoreSetupReject") {
208 //emit coreSetupFailed(msg["Error"].toString());
209 } else if(msg["MsgType"] == "ClientLoginReject") {
210 loginFailed(msg["Error"].toString());
211 } else if(msg["MsgType"] == "ClientLoginAck") {
213 } else if(msg["MsgType"] == "SessionInit") {
214 // that's it, let's hand over to the signal proxy
215 // if the socket is an orphan, the signalProxy adopts it.
216 // -> we don't need to care about it anymore
217 _socket->setParent(0);
218 Client::signalProxy()->addPeer(_socket);
220 sessionStateReceived(msg["SessionState"].toMap());
221 break; // this is definitively the last message we process here!
223 emit connectionError(tr("<b>Invalid data received from core!</b><br>Disconnecting."));
224 disconnectFromCore();
229 updateProgress(_socket->bytesAvailable(), _blockSize);
233 void CoreConnection::disconnectFromCore() {
234 Client::signalProxy()->removeAllPeers();
238 void CoreConnection::reconnectToCore() {
239 if(currentAccount().isValid())
240 connectToCore(currentAccount().accountId());
243 bool CoreConnection::connectToCore(AccountId accId) {
247 CoreAccountSettings s;
249 // FIXME: Don't force connection to internal core in mono client
250 if(Quassel::runMode() == Quassel::Monolithic) {
251 _account = accountModel()->account(accountModel()->internalAccount());
252 Q_ASSERT(_account.isValid());
254 if(!accId.isValid()) {
255 // check our settings and figure out what to do
256 if(!s.autoConnectOnStartup())
258 if(s.autoConnectToFixedAccount())
259 accId = s.autoConnectAccount();
261 accId = s.lastAccount();
265 _account = accountModel()->account(accId);
266 if(!_account.accountId().isValid()) {
269 if(Quassel::runMode() != Quassel::Monolithic) {
270 if(_account.isInternal())
275 s.setLastAccount(accId);
276 connectToCurrentAccount();
280 void CoreConnection::connectToCurrentAccount() {
283 if(currentAccount().isInternal()) {
284 if(Quassel::runMode() != Quassel::Monolithic) {
285 qWarning() << "Cannot connect to internal core in client-only mode!";
288 emit startInternalCore();
289 emit connectToInternalCore(Client::instance()->signalProxy());
293 CoreAccountSettings s;
297 QSslSocket *sock = new QSslSocket(Client::instance());
298 // make sure the warning is shown if we happen to connect without SSL support later
299 s.setAccountValue("ShowNoClientSslWarning", true);
301 if(_account.useSsl()) {
302 if(s.accountValue("ShowNoClientSslWarning", true).toBool()) {
303 bool accepted = false;
304 emit handleNoSslInClient(&accepted);
306 emit connectionError(tr("Unencrypted connection canceled"));
309 s.setAccountValue("ShowNoClientSslWarning", false);
312 QTcpSocket *sock = new QTcpSocket(Client::instance());
315 #ifndef QT_NO_NETWORKPROXY
316 if(_account.useProxy()) {
317 QNetworkProxy proxy(_account.proxyType(), _account.proxyHostName(), _account.proxyPort(), _account.proxyUser(), _account.proxyPassword());
318 sock->setProxy(proxy);
323 connect(sock, SIGNAL(readyRead()), SLOT(coreHasData()));
324 connect(sock, SIGNAL(connected()), SLOT(coreSocketConnected()));
325 connect(sock, SIGNAL(disconnected()), SLOT(coreSocketDisconnected()));
326 connect(sock, SIGNAL(error(QAbstractSocket::SocketError)), SLOT(coreSocketError(QAbstractSocket::SocketError)));
327 connect(sock, SIGNAL(stateChanged(QAbstractSocket::SocketState)), SLOT(socketStateChanged(QAbstractSocket::SocketState)));
329 emit connectionMsg(tr("Connecting to %1...").arg(currentAccount().accountName()));
330 sock->connectToHost(_account.hostName(), _account.port());
333 void CoreConnection::coreSocketConnected() {
334 // Phase One: Send client info and wait for core info
336 emit connectionMsg(tr("Synchronizing to core..."));
338 QVariantMap clientInit;
339 clientInit["MsgType"] = "ClientInit";
340 clientInit["ClientVersion"] = Quassel::buildInfo().fancyVersionString;
341 clientInit["ClientDate"] = Quassel::buildInfo().buildDate;
342 clientInit["ProtocolVersion"] = Quassel::buildInfo().protocolVersion;
343 clientInit["UseSsl"] = _account.useSsl();
344 #ifndef QT_NO_COMPRESS
345 clientInit["UseCompression"] = true;
347 clientInit["UseCompression"] = false;
350 SignalProxy::writeDataToDevice(_socket, clientInit);
353 void CoreConnection::clientInitAck(const QVariantMap &msg) {
354 // Core has accepted our version info and sent its own. Let's see if we accept it as well...
355 uint ver = msg["ProtocolVersion"].toUInt();
356 if(ver < Quassel::buildInfo().clientNeedsProtocol) {
357 emit connectionError(tr("<b>The Quassel Core you are trying to connect to is too old!</b><br>"
358 "Need at least core/client protocol v%1 to connect.").arg(Quassel::buildInfo().clientNeedsProtocol));
359 disconnectFromCore();
363 #ifndef QT_NO_COMPRESS
364 if(msg["SupportsCompression"].toBool()) {
365 _socket->setProperty("UseCompression", true);
369 _coreMsgBuffer = msg;
372 CoreAccountSettings s;
373 if(currentAccount().useSsl()) {
374 if(msg["SupportSsl"].toBool()) {
375 // Make sure the warning is shown next time we don't have SSL in the core
376 s.setAccountValue("ShowNoCoreSslWarning", true);
378 QSslSocket *sslSocket = qobject_cast<QSslSocket *>(_socket);
380 connect(sslSocket, SIGNAL(encrypted()), SLOT(sslSocketEncrypted()));
381 connect(sslSocket, SIGNAL(sslErrors(const QList<QSslError> &)), SLOT(sslErrors()));
382 sslSocket->startClientEncryption();
384 if(s.accountValue("ShowNoCoreSslWarning", true).toBool()) {
385 bool accepted = false;
386 emit handleNoSslInCore(&accepted);
388 emit connectionError(tr("Unencrypted connection canceled"));
389 disconnectFromCore();
392 s.setAccountValue("ShowNoCoreSslWarning", false);
393 s.setAccountValue("SslCert", QString());
400 // if we use SSL we wait for the next step until every SSL warning has been cleared
406 void CoreConnection::sslSocketEncrypted() {
407 QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
410 if(!socket->sslErrors().count()) {
411 // Cert is valid, so we don't want to store it as known
412 // That way, a warning will appear in case it becomes invalid at some point
413 CoreAccountSettings s;
414 s.setAccountValue("SSLCert", QString());
417 emit encrypted(true);
421 void CoreConnection::sslErrors() {
422 QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
425 CoreAccountSettings s;
426 QByteArray knownDigest = s.accountValue("SslCert").toByteArray();
428 if(knownDigest != socket->peerCertificate().digest()) {
429 bool accepted = false;
430 bool permanently = false;
431 emit handleSslErrors(socket, &accepted, &permanently);
434 emit connectionError(tr("Unencrypted connection canceled"));
435 disconnectFromCore();
440 s.setAccountValue("SslCert", socket->peerCertificate().digest());
442 s.setAccountValue("SslCert", QString());
445 socket->ignoreSslErrors();
448 #endif /* HAVE_SSL */
450 void CoreConnection::connectionReady() {
451 if(!_coreMsgBuffer["Configured"].toBool()) {
453 emit startCoreSetup(_coreMsgBuffer["StorageBackends"].toList());
454 } else if(_coreMsgBuffer["LoginEnabled"].toBool()) {
457 _coreMsgBuffer.clear();
460 void CoreConnection::loginToCore(const QString &prevError) {
461 emit connectionMsg(tr("Logging in..."));
462 if(currentAccount().user().isEmpty() || currentAccount().password().isEmpty() || !prevError.isEmpty()) {
464 emit userAuthenticationRequired(&_account, &valid, prevError); // *must* be a synchronous call
465 if(!valid || currentAccount().user().isEmpty() || currentAccount().password().isEmpty()) {
466 disconnectFromCore();
467 emit connectionError(tr("Login canceled"));
472 QVariantMap clientLogin;
473 clientLogin["MsgType"] = "ClientLogin";
474 clientLogin["User"] = currentAccount().user();
475 clientLogin["Password"] = currentAccount().password();
476 SignalProxy::writeDataToDevice(_socket, clientLogin);
479 void CoreConnection::loginFailed(const QString &error) {
483 void CoreConnection::loginSuccess() {
484 updateProgress(0, 0);
486 // save current account data
487 _model->createOrUpdateAccount(currentAccount());
490 setProgressText(tr("Receiving session state"));
491 setState(Synchronizing);
492 emit connectionMsg(tr("Synchronizing to %1...").arg(currentAccount().accountName()));
495 void CoreConnection::sessionStateReceived(const QVariantMap &state) {
496 updateProgress(100, 100);
498 // rest of communication happens through SignalProxy...
499 disconnect(_socket, SIGNAL(readyRead()), this, 0);
500 disconnect(_socket, SIGNAL(connected()), this, 0);
505 void CoreConnection::internalSessionStateReceived(const QVariant &packedState) {
506 updateProgress(100, 100);
508 setState(Synchronizing);
509 syncToCore(packedState.toMap());
512 void CoreConnection::syncToCore(const QVariantMap &sessionState) {
513 setProgressText(tr("Receiving network states"));
514 updateProgress(0, 100);
517 foreach(QVariant vid, sessionState["Identities"].toList()) {
518 Client::instance()->coreIdentityCreated(vid.value<Identity>());
522 // FIXME: get rid of this crap -- why?
523 QVariantList bufferinfos = sessionState["BufferInfos"].toList();
524 NetworkModel *networkModel = Client::networkModel();
525 Q_ASSERT(networkModel);
526 foreach(QVariant vinfo, bufferinfos)
527 networkModel->bufferUpdated(vinfo.value<BufferInfo>()); // create BufferItems
529 QVariantList networkids = sessionState["NetworkIds"].toList();
531 // prepare sync progress thingys...
532 // FIXME: Care about removal of networks
533 _numNetsToSync = networkids.count();
534 updateProgress(0, _numNetsToSync);
536 // create network objects
537 foreach(QVariant networkid, networkids) {
538 NetworkId netid = networkid.value<NetworkId>();
539 if(Client::network(netid))
541 Network *net = new Network(netid, Client::instance());
542 _netsToSync.insert(net);
543 connect(net, SIGNAL(initDone()), SLOT(networkInitDone()));
544 connect(net, SIGNAL(destroyed()), SLOT(networkInitDone()));
545 Client::addNetwork(net);
550 void CoreConnection::networkInitDone() {
551 Network *net = qobject_cast<Network *>(sender());
553 disconnect(net, 0, this, 0);
554 _netsToSync.remove(net);
555 updateProgress(_numNetsToSync - _netsToSync.count(), _numNetsToSync);
559 void CoreConnection::checkSyncState() {
560 if(_netsToSync.isEmpty()) {
561 setState(Synchronized);
562 setProgressText(QString());
563 setProgressMaximum(-1);