Make SSL work again for CoreConnection
[quassel.git] / src / client / coreconnection.cpp
1 /***************************************************************************
2  *   Copyright (C) 2009 by the Quassel Project                             *
3  *   devel@quassel-irc.org                                                 *
4  *                                                                         *
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.                                           *
9  *                                                                         *
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.                          *
14  *                                                                         *
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  ***************************************************************************/
20
21 #include "coreconnection.h"
22
23 #ifndef QT_NO_NETWORKPROXY
24 #  include <QNetworkProxy>
25 #endif
26
27 #include "client.h"
28 #include "clientsettings.h"
29 #include "coreaccountmodel.h"
30 #include "identity.h"
31 #include "network.h"
32 #include "networkmodel.h"
33 #include "quassel.h"
34 #include "signalproxy.h"
35 #include "util.h"
36
37 CoreConnection::CoreConnection(CoreAccountModel *model, QObject *parent)
38   : QObject(parent),
39   _model(model),
40   _blockSize(0),
41   _state(Disconnected),
42   _progressMinimum(0),
43   _progressMaximum(-1),
44   _progressValue(-1)
45 {
46   qRegisterMetaType<ConnectionState>("CoreConnection::ConnectionState");
47
48 }
49
50 void CoreConnection::init() {
51   connect(Client::signalProxy(), SIGNAL(disconnected()), SLOT(coreSocketDisconnected()));
52 }
53
54 void CoreConnection::setProgressText(const QString &text) {
55   if(_progressText != text) {
56     _progressText = text;
57     emit progressTextChanged(text);
58   }
59 }
60
61 void CoreConnection::setProgressValue(int value) {
62   if(_progressValue != value) {
63     _progressValue = value;
64     emit progressValueChanged(value);
65   }
66 }
67
68 void CoreConnection::setProgressMinimum(int minimum) {
69   if(_progressMinimum != minimum) {
70     _progressMinimum = minimum;
71     emit progressRangeChanged(minimum, _progressMaximum);
72   }
73 }
74
75 void CoreConnection::setProgressMaximum(int maximum) {
76   if(_progressMaximum != maximum) {
77     _progressMaximum = maximum;
78     emit progressRangeChanged(_progressMinimum, maximum);
79   }
80 }
81
82 void CoreConnection::updateProgress(int value, int max) {
83   if(max != _progressMaximum) {
84     _progressMaximum = max;
85     emit progressRangeChanged(_progressMinimum, _progressMaximum);
86   }
87   setProgressValue(value);
88 }
89
90 void CoreConnection::resetConnection() {
91   if(_socket) {
92     disconnect(_socket, 0, this, 0);
93     _socket->deleteLater();
94     _socket = 0;
95   }
96   _blockSize = 0;
97
98   _coreMsgBuffer.clear();
99
100   _netsToSync.clear();
101   _numNetsToSync = 0;
102
103   setProgressMaximum(-1); // disable
104   setState(Disconnected);
105   emit connectionMsg(tr("Disconnected from core."));
106   emit encrypted(false);
107 }
108
109 bool CoreConnection::isEncrypted() const {
110 #ifndef HAVE_SSL
111   return false;
112 #else
113   QSslSocket *sock = qobject_cast<QSslSocket *>(_socket);
114   return isConnected() && sock && sock->isEncrypted();
115 #endif
116 }
117
118 void CoreConnection::socketStateChanged(QAbstractSocket::SocketState socketState) {
119   QString text;
120
121   switch(socketState) {
122   case QAbstractSocket::UnconnectedState:
123     text = tr("Disconnected.");
124     break;
125   case QAbstractSocket::HostLookupState:
126     text = tr("Looking up %1...").arg(currentAccount().hostName());
127     break;
128   case QAbstractSocket::ConnectingState:
129     text = tr("Connecting to %1...").arg(currentAccount().hostName());
130     break;
131   case QAbstractSocket::ConnectedState:
132     text = tr("Connected to %1.").arg(currentAccount().hostName());
133     break;
134   case QAbstractSocket::ClosingState:
135     text = tr("Disconnecting from %1...").arg(currentAccount().hostName());
136     break;
137   default:
138     break;
139   }
140
141   if(!text.isEmpty())
142     emit progressTextChanged(text);
143
144   setState(socketState);
145 }
146
147 void CoreConnection::setState(QAbstractSocket::SocketState socketState) {
148   ConnectionState state;
149
150   switch(socketState) {
151   case QAbstractSocket::UnconnectedState:
152     state = Disconnected;
153     break;
154   case QAbstractSocket::HostLookupState:
155   case QAbstractSocket::ConnectingState:
156     state = Connecting;
157     break;
158   case QAbstractSocket::ConnectedState:
159     state = Connected;
160     break;
161   default:
162     state = Disconnected;
163   }
164
165   setState(state);
166 }
167
168 void CoreConnection::setState(ConnectionState state) {
169   if(state != _state) {
170     _state = state;
171     emit stateChanged(state);
172     if(state == Disconnected)
173       emit disconnected();
174   }
175 }
176
177 void CoreConnection::coreSocketError(QAbstractSocket::SocketError) {
178   qDebug() << "coreSocketError" << _socket << _socket->errorString();
179   emit connectionError(_socket->errorString());
180   resetConnection();
181 }
182
183 void CoreConnection::coreSocketDisconnected() {
184   emit disconnected();
185   resetConnection();
186   // FIXME handle disconnects gracefully
187 }
188
189 void CoreConnection::coreHasData() {
190   QVariant item;
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();
197       return;
198     }
199     if(msg["MsgType"] == "ClientInitAck") {
200       clientInitAck(msg);
201     } else if(msg["MsgType"] == "ClientInitReject") {
202       emit connectionError(msg["Error"].toString());
203       disconnectFromCore();
204       return;
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") {
212       loginSuccess();
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);
219
220       sessionStateReceived(msg["SessionState"].toMap());
221       break; // this is definitively the last message we process here!
222     } else {
223       emit connectionError(tr("<b>Invalid data received from core!</b><br>Disconnecting."));
224       disconnectFromCore();
225       return;
226     }
227   }
228   if(_blockSize > 0) {
229     updateProgress(_socket->bytesAvailable(), _blockSize);
230   }
231 }
232
233 void CoreConnection::disconnectFromCore() {
234   Client::signalProxy()->removeAllPeers();
235   resetConnection();
236 }
237
238 void CoreConnection::reconnectToCore() {
239   if(currentAccount().isValid())
240     connectToCore(currentAccount().accountId());
241 }
242
243 bool CoreConnection::connectToCore(AccountId accId) {
244   if(isConnected())
245     return false;
246
247   CoreAccountSettings s;
248
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());
253   } else {
254     if(!accId.isValid()) {
255       // check our settings and figure out what to do
256       if(!s.autoConnectOnStartup())
257         return false;
258       if(s.autoConnectToFixedAccount())
259         accId = s.autoConnectAccount();
260       else
261         accId = s.lastAccount();
262       if(!accId.isValid())
263         return false;
264     }
265     _account = accountModel()->account(accId);
266     if(!_account.accountId().isValid()) {
267       return false;
268     }
269     if(Quassel::runMode() != Quassel::Monolithic) {
270       if(_account.isInternal())
271         return false;
272     }
273   }
274
275   s.setLastAccount(accId);
276   connectToCurrentAccount();
277   return true;
278 }
279
280 void CoreConnection::connectToCurrentAccount() {
281   resetConnection();
282
283   if(currentAccount().isInternal()) {
284     if(Quassel::runMode() != Quassel::Monolithic) {
285       qWarning() << "Cannot connect to internal core in client-only mode!";
286       return;
287     }
288     emit startInternalCore();
289     emit connectToInternalCore(Client::instance()->signalProxy());
290     return;
291   }
292
293   CoreAccountSettings s;
294
295   Q_ASSERT(!_socket);
296 #ifdef HAVE_SSL
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);
300 #else
301   if(_account.useSsl()) {
302     if(s.accountValue("ShowNoClientSslWarning", true).toBool()) {
303       bool accepted = false;
304       emit handleNoSslInClient(&accepted);
305       if(!accepted) {
306         emit connectionError(tr("Unencrypted connection canceled"));
307         return;
308       }
309       s.setAccountValue("ShowNoClientSslWarning", false);
310     }
311   }
312   QTcpSocket *sock = new QTcpSocket(Client::instance());
313 #endif
314
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);
319   }
320 #endif
321
322   _socket = sock;
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)));
328
329   emit connectionMsg(tr("Connecting to %1...").arg(currentAccount().accountName()));
330   sock->connectToHost(_account.hostName(), _account.port());
331 }
332
333 void CoreConnection::coreSocketConnected() {
334   // Phase One: Send client info and wait for core info
335
336   emit connectionMsg(tr("Synchronizing to core..."));
337
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;
346 #else
347   clientInit["UseCompression"] = false;
348 #endif
349
350   SignalProxy::writeDataToDevice(_socket, clientInit);
351 }
352
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();
360     return;
361   }
362
363 #ifndef QT_NO_COMPRESS
364   if(msg["SupportsCompression"].toBool()) {
365     _socket->setProperty("UseCompression", true);
366   }
367 #endif
368
369   _coreMsgBuffer = msg;
370
371 #ifdef HAVE_SSL
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);
377
378       QSslSocket *sslSocket = qobject_cast<QSslSocket *>(_socket);
379       Q_ASSERT(sslSocket);
380       connect(sslSocket, SIGNAL(encrypted()), SLOT(sslSocketEncrypted()));
381       connect(sslSocket, SIGNAL(sslErrors(const QList<QSslError> &)), SLOT(sslErrors()));
382       sslSocket->startClientEncryption();
383     } else {
384       if(s.accountValue("ShowNoCoreSslWarning", true).toBool()) {
385         bool accepted = false;
386         emit handleNoSslInCore(&accepted);
387         if(!accepted) {
388           emit connectionError(tr("Unencrypted connection canceled"));
389           disconnectFromCore();
390           return;
391         }
392         s.setAccountValue("ShowNoCoreSslWarning", false);
393         s.setAccountValue("SslCert", QString());
394       }
395       connectionReady();
396     }
397     return;
398   }
399 #endif
400   // if we use SSL we wait for the next step until every SSL warning has been cleared
401   connectionReady();
402 }
403
404 #ifdef HAVE_SSL
405
406 void CoreConnection::sslSocketEncrypted() {
407   QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
408   Q_ASSERT(socket);
409
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());
415   }
416
417   emit encrypted(true);
418   connectionReady();
419 }
420
421 void CoreConnection::sslErrors() {
422   QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
423   Q_ASSERT(socket);
424
425   CoreAccountSettings s;
426   QByteArray knownDigest = s.accountValue("SslCert").toByteArray();
427
428   if(knownDigest != socket->peerCertificate().digest()) {
429     bool accepted = false;
430     bool permanently = false;
431     emit handleSslErrors(socket, &accepted, &permanently);
432
433     if(!accepted) {
434       emit connectionError(tr("Unencrypted connection canceled"));
435       disconnectFromCore();
436       return;
437     }
438
439     if(permanently)
440       s.setAccountValue("SslCert", socket->peerCertificate().digest());
441     else
442       s.setAccountValue("SslCert", QString());
443   }
444
445   socket->ignoreSslErrors();
446 }
447
448 #endif /* HAVE_SSL */
449
450 void CoreConnection::connectionReady() {
451   if(!_coreMsgBuffer["Configured"].toBool()) {
452     // start wizard
453     emit startCoreSetup(_coreMsgBuffer["StorageBackends"].toList());
454   } else if(_coreMsgBuffer["LoginEnabled"].toBool()) {
455     loginToCore();
456   }
457   _coreMsgBuffer.clear();
458 }
459
460 void CoreConnection::loginToCore(const QString &prevError) {
461   emit connectionMsg(tr("Logging in..."));
462   if(currentAccount().user().isEmpty() || currentAccount().password().isEmpty() || !prevError.isEmpty()) {
463     bool valid = false;
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"));
468       return;
469     }
470   }
471
472   QVariantMap clientLogin;
473   clientLogin["MsgType"] = "ClientLogin";
474   clientLogin["User"] = currentAccount().user();
475   clientLogin["Password"] = currentAccount().password();
476   SignalProxy::writeDataToDevice(_socket, clientLogin);
477 }
478
479 void CoreConnection::loginFailed(const QString &error) {
480   loginToCore(error);
481 }
482
483 void CoreConnection::loginSuccess() {
484   updateProgress(0, 0);
485
486   // save current account data
487   _model->createOrUpdateAccount(currentAccount());
488   _model->save();
489
490   setProgressText(tr("Receiving session state"));
491   setState(Synchronizing);
492   emit connectionMsg(tr("Synchronizing to %1...").arg(currentAccount().accountName()));
493 }
494
495 void CoreConnection::sessionStateReceived(const QVariantMap &state) {
496   updateProgress(100, 100);
497
498   // rest of communication happens through SignalProxy...
499   disconnect(_socket, SIGNAL(readyRead()), this, 0);
500   disconnect(_socket, SIGNAL(connected()), this, 0);
501
502   syncToCore(state);
503 }
504
505 void CoreConnection::internalSessionStateReceived(const QVariant &packedState) {
506   updateProgress(100, 100);
507
508   setState(Synchronizing);
509   syncToCore(packedState.toMap());
510 }
511
512 void CoreConnection::syncToCore(const QVariantMap &sessionState) {
513   setProgressText(tr("Receiving network states"));
514   updateProgress(0, 100);
515
516   // create identities
517   foreach(QVariant vid, sessionState["Identities"].toList()) {
518     Client::instance()->coreIdentityCreated(vid.value<Identity>());
519   }
520
521   // create buffers
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
528
529   QVariantList networkids = sessionState["NetworkIds"].toList();
530
531   // prepare sync progress thingys...
532   // FIXME: Care about removal of networks
533   _numNetsToSync = networkids.count();
534   updateProgress(0, _numNetsToSync);
535
536   // create network objects
537   foreach(QVariant networkid, networkids) {
538     NetworkId netid = networkid.value<NetworkId>();
539     if(Client::network(netid))
540       continue;
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);
546   }
547   checkSyncState();
548 }
549
550 void CoreConnection::networkInitDone() {
551   Network *net = qobject_cast<Network *>(sender());
552   Q_ASSERT(net);
553   disconnect(net, 0, this, 0);
554   _netsToSync.remove(net);
555   updateProgress(_numNetsToSync - _netsToSync.count(), _numNetsToSync);
556   checkSyncState();
557 }
558
559 void CoreConnection::checkSyncState() {
560   if(_netsToSync.isEmpty()) {
561     setState(Synchronized);
562     setProgressText(QString());
563     setProgressMaximum(-1);
564     emit synchronized();
565   }
566 }