Display lag and SSL status in CoreConnectionStatusWidget
[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   default:
159     state = Disconnected;
160   }
161
162   setState(state);
163 }
164
165 void CoreConnection::setState(ConnectionState state) {
166   if(state != _state) {
167     _state = state;
168     emit stateChanged(state);
169     if(state == Disconnected)
170       emit disconnected();
171   }
172 }
173
174 void CoreConnection::coreSocketError(QAbstractSocket::SocketError) {
175   qDebug() << "coreSocketError" << _socket << _socket->errorString();
176   emit connectionError(_socket->errorString());
177   resetConnection();
178 }
179
180 void CoreConnection::coreSocketDisconnected() {
181   emit disconnected();
182   resetConnection();
183   // FIXME handle disconnects gracefully
184 }
185
186 void CoreConnection::coreHasData() {
187   QVariant item;
188   while(SignalProxy::readDataFromDevice(_socket, _blockSize, item)) {
189     QVariantMap msg = item.toMap();
190     if(!msg.contains("MsgType")) {
191       // This core is way too old and does not even speak our init protocol...
192       emit connectionError(tr("The Quassel Core you try to connect to is too old! Please consider upgrading."));
193       disconnectFromCore();
194       return;
195     }
196     if(msg["MsgType"] == "ClientInitAck") {
197       clientInitAck(msg);
198     } else if(msg["MsgType"] == "ClientInitReject") {
199       emit connectionError(msg["Error"].toString());
200       disconnectFromCore();
201       return;
202     } else if(msg["MsgType"] == "CoreSetupAck") {
203       //emit coreSetupSuccess();
204     } else if(msg["MsgType"] == "CoreSetupReject") {
205       //emit coreSetupFailed(msg["Error"].toString());
206     } else if(msg["MsgType"] == "ClientLoginReject") {
207       loginFailed(msg["Error"].toString());
208     } else if(msg["MsgType"] == "ClientLoginAck") {
209       loginSuccess();
210     } else if(msg["MsgType"] == "SessionInit") {
211       // that's it, let's hand over to the signal proxy
212       // if the socket is an orphan, the signalProxy adopts it.
213       // -> we don't need to care about it anymore
214       _socket->setParent(0);
215       Client::signalProxy()->addPeer(_socket);
216
217       sessionStateReceived(msg["SessionState"].toMap());
218       break; // this is definitively the last message we process here!
219     } else {
220       emit connectionError(tr("Invalid data received from core, disconnecting."));
221       disconnectFromCore();
222       return;
223     }
224   }
225   if(_blockSize > 0) {
226     updateProgress(_socket->bytesAvailable(), _blockSize);
227   }
228 }
229
230 void CoreConnection::disconnectFromCore() {
231   Client::signalProxy()->removeAllPeers();
232   resetConnection();
233 }
234
235 void CoreConnection::reconnectToCore() {
236   if(currentAccount().isValid())
237     connectToCore(currentAccount().accountId());
238 }
239
240 bool CoreConnection::connectToCore(AccountId accId) {
241   if(isConnected())
242     return false;
243
244   CoreAccountSettings s;
245
246   // FIXME: Don't force connection to internal core in mono client
247   if(Quassel::runMode() == Quassel::Monolithic) {
248     _account = accountModel()->account(accountModel()->internalAccount());
249     Q_ASSERT(_account.isValid());
250   } else {
251     if(!accId.isValid()) {
252       // check our settings and figure out what to do
253       if(!s.autoConnectOnStartup())
254         return false;
255       if(s.autoConnectToFixedAccount())
256         accId = s.autoConnectAccount();
257       else
258         accId = s.lastAccount();
259       if(!accId.isValid())
260         return false;
261     }
262     _account = accountModel()->account(accId);
263     if(!_account.accountId().isValid()) {
264       return false;
265     }
266     if(Quassel::runMode() != Quassel::Monolithic) {
267       if(_account.isInternal())
268         return false;
269     }
270   }
271
272   s.setLastAccount(accId);
273   connectToCurrentAccount();
274   return true;
275 }
276
277 void CoreConnection::connectToCurrentAccount() {
278   resetConnection();
279
280   if(currentAccount().isInternal()) {
281     if(Quassel::runMode() != Quassel::Monolithic) {
282       qWarning() << "Cannot connect to internal core in client-only mode!";
283       return;
284     }
285     emit startInternalCore();
286     emit connectToInternalCore(Client::instance()->signalProxy());
287     return;
288   }
289
290   CoreAccountSettings s;
291
292   Q_ASSERT(!_socket);
293 #ifdef HAVE_SSL
294   QSslSocket *sock = new QSslSocket(Client::instance());
295   // make sure the warning is shown if we happen to connect without SSL support later
296   s.setAccountValue("ShowNoClientSslWarning", true);
297 #else
298   if(_account.useSsl()) {
299     if(s.accountValue("ShowNoClientSslWarning", true).toBool()) {
300       bool accepted = false;
301       emit handleNoSslInClient(&accepted);
302       if(!accepted) {
303         emit connectionError(tr("Unencrypted connection canceled"));
304         return;
305       }
306       s.setAccountValue("ShowNoClientSslWarning", false);
307     }
308   }
309   QTcpSocket *sock = new QTcpSocket(Client::instance());
310 #endif
311
312 #ifndef QT_NO_NETWORKPROXY
313   if(_account.useProxy()) {
314     QNetworkProxy proxy(_account.proxyType(), _account.proxyHostName(), _account.proxyPort(), _account.proxyUser(), _account.proxyPassword());
315     sock->setProxy(proxy);
316   }
317 #endif
318
319   _socket = sock;
320   connect(sock, SIGNAL(readyRead()), SLOT(coreHasData()));
321   connect(sock, SIGNAL(connected()), SLOT(coreSocketConnected()));
322   connect(sock, SIGNAL(disconnected()), SLOT(coreSocketDisconnected()));
323   connect(sock, SIGNAL(error(QAbstractSocket::SocketError)), SLOT(coreSocketError(QAbstractSocket::SocketError)));
324   connect(sock, SIGNAL(stateChanged(QAbstractSocket::SocketState)), SLOT(socketStateChanged(QAbstractSocket::SocketState)));
325
326   emit connectionMsg(tr("Connecting to %1...").arg(currentAccount().accountName()));
327   sock->connectToHost(_account.hostName(), _account.port());
328 }
329
330 void CoreConnection::coreSocketConnected() {
331   // Phase One: Send client info and wait for core info
332
333   emit connectionMsg(tr("Synchronizing to core..."));
334
335   QVariantMap clientInit;
336   clientInit["MsgType"] = "ClientInit";
337   clientInit["ClientVersion"] = Quassel::buildInfo().fancyVersionString;
338   clientInit["ClientDate"] = Quassel::buildInfo().buildDate;
339   clientInit["ProtocolVersion"] = Quassel::buildInfo().protocolVersion;
340   clientInit["UseSsl"] = _account.useSsl();
341 #ifndef QT_NO_COMPRESS
342   clientInit["UseCompression"] = true;
343 #else
344   clientInit["UseCompression"] = false;
345 #endif
346
347   SignalProxy::writeDataToDevice(_socket, clientInit);
348 }
349
350 void CoreConnection::clientInitAck(const QVariantMap &msg) {
351   // Core has accepted our version info and sent its own. Let's see if we accept it as well...
352   uint ver = msg["ProtocolVersion"].toUInt();
353   if(ver < Quassel::buildInfo().clientNeedsProtocol) {
354     emit connectionError(tr("<b>The Quassel Core you are trying to connect to is too old!</b><br>"
355         "Need at least core/client protocol v%1 to connect.").arg(Quassel::buildInfo().clientNeedsProtocol));
356     disconnectFromCore();
357     return;
358   }
359
360 #ifndef QT_NO_COMPRESS
361   if(msg["SupportsCompression"].toBool()) {
362     _socket->setProperty("UseCompression", true);
363   }
364 #endif
365
366   _coreMsgBuffer = msg;
367
368 #ifdef HAVE_SSL
369   CoreAccountSettings s;
370   if(currentAccount().useSsl()) {
371     if(msg["SupportSsl"].toBool()) {
372       // Make sure the warning is shown next time we don't have SSL in the core
373       s.setAccountValue("ShowNoCoreSslWarning", true);
374
375       QSslSocket *sslSocket = qobject_cast<QSslSocket *>(_socket);
376       Q_ASSERT(sslSocket);
377       connect(sslSocket, SIGNAL(encrypted()), SLOT(sslSocketEncrypted()));
378       connect(sslSocket, SIGNAL(sslErrors(const QList<QSslError> &)), SLOT(sslErrors()));
379       sslSocket->startClientEncryption();
380     } else {
381       if(s.accountValue("ShowNoCoreSslWarning", true).toBool()) {
382         bool accepted = false;
383         emit handleNoSslInCore(&accepted);
384         if(!accepted) {
385           emit connectionError(tr("Unencrypted connection canceled"));
386           disconnectFromCore();
387           return;
388         }
389         s.setAccountValue("ShowNoCoreSslWarning", false);
390         s.setAccountValue("SslCert", QString());
391       }
392       connectionReady();
393     }
394     return;
395   }
396 #endif
397   // if we use SSL we wait for the next step until every SSL warning has been cleared
398   connectionReady();
399 }
400
401 #ifdef HAVE_SSL
402
403 void CoreConnection::sslSocketEncrypted() {
404   QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
405   Q_ASSERT(socket);
406
407   if(!socket->sslErrors().count()) {
408     // Cert is valid, so we don't want to store it as known
409     // That way, a warning will appear in case it becomes invalid at some point
410     CoreAccountSettings s;
411     s.setAccountValue("SSLCert", QString());
412   }
413
414   emit encrypted(true);
415   connectionReady();
416 }
417
418 void CoreConnection::sslErrors() {
419   QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
420   Q_ASSERT(socket);
421
422   CoreAccountSettings s;
423   QByteArray knownDigest = s.accountValue("SslCert").toByteArray();
424
425   if(knownDigest != socket->peerCertificate().digest()) {
426     bool accepted = false;
427     bool permanently = false;
428     emit handleSslErrors(socket, &accepted, &permanently);
429
430     if(!accepted) {
431       emit connectionError(tr("Unencrypted connection canceled"));
432       disconnectFromCore();
433       return;
434     }
435
436     if(permanently)
437       s.setAccountValue("SslCert", socket->peerCertificate().digest());
438     else
439       s.setAccountValue("SslCert", QString());
440   }
441
442   socket->ignoreSslErrors();
443 }
444
445 #endif /* HAVE_SSL */
446
447 void CoreConnection::connectionReady() {
448   setState(Connected);
449   emit connectionMsg(tr("Connected to %1").arg(currentAccount().accountName()));
450
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(tr("Synchronized to %1").arg(currentAccount().accountName()));
563     setProgressMaximum(-1);
564     emit synchronized();
565   }
566 }