Don't set Disconnected state on socket connection
[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   case QAbstractSocket::ConnectedState:  // we'll set it to Connected in connectionReady()
157     state = Connecting;
158     break;
159   default:
160     state = Disconnected;
161   }
162
163   setState(state);
164 }
165
166 void CoreConnection::setState(ConnectionState state) {
167   if(state != _state) {
168     _state = state;
169     emit stateChanged(state);
170     if(state == Disconnected)
171       emit disconnected();
172   }
173 }
174
175 void CoreConnection::coreSocketError(QAbstractSocket::SocketError) {
176   qDebug() << "coreSocketError" << _socket << _socket->errorString();
177   emit connectionError(_socket->errorString());
178   resetConnection();
179 }
180
181 void CoreConnection::coreSocketDisconnected() {
182   emit disconnected();
183   resetConnection();
184   // FIXME handle disconnects gracefully
185 }
186
187 void CoreConnection::coreHasData() {
188   QVariant item;
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();
195       return;
196     }
197     if(msg["MsgType"] == "ClientInitAck") {
198       clientInitAck(msg);
199     } else if(msg["MsgType"] == "ClientInitReject") {
200       emit connectionErrorPopup(msg["Error"].toString());
201       disconnectFromCore();
202       return;
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") {
210       loginSuccess();
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);
217
218       sessionStateReceived(msg["SessionState"].toMap());
219       break; // this is definitively the last message we process here!
220     } else {
221       disconnectFromCore(tr("Invalid data received from core"));
222       return;
223     }
224   }
225   if(_blockSize > 0) {
226     updateProgress(_socket->bytesAvailable(), _blockSize);
227   }
228 }
229
230 void CoreConnection::disconnectFromCore(const QString &errorString) {
231   if(errorString.isEmpty())
232     emit connectionError(tr("Disconnected"));
233   else
234     emit connectionError(errorString);
235
236   Client::signalProxy()->removeAllPeers();
237   resetConnection();
238 }
239
240 void CoreConnection::reconnectToCore() {
241   if(currentAccount().isValid())
242     connectToCore(currentAccount().accountId());
243 }
244
245 bool CoreConnection::connectToCore(AccountId accId) {
246   if(isConnected())
247     return false;
248
249   CoreAccountSettings s;
250
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());
255   } else {
256     if(!accId.isValid()) {
257       // check our settings and figure out what to do
258       if(!s.autoConnectOnStartup())
259         return false;
260       if(s.autoConnectToFixedAccount())
261         accId = s.autoConnectAccount();
262       else
263         accId = s.lastAccount();
264       if(!accId.isValid())
265         return false;
266     }
267     _account = accountModel()->account(accId);
268     if(!_account.accountId().isValid()) {
269       return false;
270     }
271     if(Quassel::runMode() != Quassel::Monolithic) {
272       if(_account.isInternal())
273         return false;
274     }
275   }
276
277   s.setLastAccount(accId);
278   connectToCurrentAccount();
279   return true;
280 }
281
282 void CoreConnection::connectToCurrentAccount() {
283   resetConnection();
284
285   if(currentAccount().isInternal()) {
286     if(Quassel::runMode() != Quassel::Monolithic) {
287       qWarning() << "Cannot connect to internal core in client-only mode!";
288       return;
289     }
290     emit startInternalCore();
291     emit connectToInternalCore(Client::instance()->signalProxy());
292     return;
293   }
294
295   CoreAccountSettings s;
296
297   Q_ASSERT(!_socket);
298 #ifdef HAVE_SSL
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);
302 #else
303   if(_account.useSsl()) {
304     if(s.accountValue("ShowNoClientSslWarning", true).toBool()) {
305       bool accepted = false;
306       emit handleNoSslInClient(&accepted);
307       if(!accepted) {
308         emit connectionError(tr("Unencrypted connection canceled"));
309         return;
310       }
311       s.setAccountValue("ShowNoClientSslWarning", false);
312     }
313   }
314   QTcpSocket *sock = new QTcpSocket(Client::instance());
315 #endif
316
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);
321   }
322 #endif
323
324   _socket = sock;
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)));
330
331   emit connectionMsg(tr("Connecting to %1...").arg(currentAccount().accountName()));
332   sock->connectToHost(_account.hostName(), _account.port());
333 }
334
335 void CoreConnection::coreSocketConnected() {
336   // Phase One: Send client info and wait for core info
337
338   emit connectionMsg(tr("Synchronizing to core..."));
339
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;
348 #else
349   clientInit["UseCompression"] = false;
350 #endif
351
352   SignalProxy::writeDataToDevice(_socket, clientInit);
353 }
354
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();
362     return;
363   }
364
365 #ifndef QT_NO_COMPRESS
366   if(msg["SupportsCompression"].toBool()) {
367     _socket->setProperty("UseCompression", true);
368   }
369 #endif
370
371   _coreMsgBuffer = msg;
372
373 #ifdef HAVE_SSL
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);
379
380       QSslSocket *sslSocket = qobject_cast<QSslSocket *>(_socket);
381       Q_ASSERT(sslSocket);
382       connect(sslSocket, SIGNAL(encrypted()), SLOT(sslSocketEncrypted()));
383       connect(sslSocket, SIGNAL(sslErrors(const QList<QSslError> &)), SLOT(sslErrors()));
384       sslSocket->startClientEncryption();
385     } else {
386       if(s.accountValue("ShowNoCoreSslWarning", true).toBool()) {
387         bool accepted = false;
388         emit handleNoSslInCore(&accepted);
389         if(!accepted) {
390           disconnectFromCore(tr("Unencrypted connection canceled"));
391           return;
392         }
393         s.setAccountValue("ShowNoCoreSslWarning", false);
394         s.setAccountValue("SslCert", QString());
395       }
396       connectionReady();
397     }
398     return;
399   }
400 #endif
401   // if we use SSL we wait for the next step until every SSL warning has been cleared
402   connectionReady();
403 }
404
405 #ifdef HAVE_SSL
406
407 void CoreConnection::sslSocketEncrypted() {
408   QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
409   Q_ASSERT(socket);
410
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());
416   }
417
418   emit encrypted(true);
419   connectionReady();
420 }
421
422 void CoreConnection::sslErrors() {
423   QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
424   Q_ASSERT(socket);
425
426   CoreAccountSettings s;
427   QByteArray knownDigest = s.accountValue("SslCert").toByteArray();
428
429   if(knownDigest != socket->peerCertificate().digest()) {
430     bool accepted = false;
431     bool permanently = false;
432     emit handleSslErrors(socket, &accepted, &permanently);
433
434     if(!accepted) {
435       disconnectFromCore(tr("Unencrypted connection canceled"));
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   setState(Connected);
452   emit connectionMsg(tr("Connected to %1").arg(currentAccount().accountName()));
453
454   if(!_coreMsgBuffer["Configured"].toBool()) {
455     // start wizard
456     emit startCoreSetup(_coreMsgBuffer["StorageBackends"].toList());
457   } else if(_coreMsgBuffer["LoginEnabled"].toBool()) {
458     loginToCore();
459   }
460   _coreMsgBuffer.clear();
461 }
462
463 void CoreConnection::loginToCore(const QString &user, const QString &password, bool remember) {
464   _account.setUser(user);
465   _account.setPassword(password);
466   _account.setStorePassword(remember);
467   loginToCore();
468 }
469
470 void CoreConnection::loginToCore(const QString &prevError) {
471   emit connectionMsg(tr("Logging in..."));
472   if(currentAccount().user().isEmpty() || currentAccount().password().isEmpty() || !prevError.isEmpty()) {
473     bool valid = false;
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"));
477       return;
478     }
479   }
480
481   QVariantMap clientLogin;
482   clientLogin["MsgType"] = "ClientLogin";
483   clientLogin["User"] = currentAccount().user();
484   clientLogin["Password"] = currentAccount().password();
485   SignalProxy::writeDataToDevice(_socket, clientLogin);
486 }
487
488 void CoreConnection::loginFailed(const QString &error) {
489   loginToCore(error);
490 }
491
492 void CoreConnection::loginSuccess() {
493   updateProgress(0, 0);
494
495   // save current account data
496   _model->createOrUpdateAccount(currentAccount());
497   _model->save();
498
499   setProgressText(tr("Receiving session state"));
500   setState(Synchronizing);
501   emit connectionMsg(tr("Synchronizing to %1...").arg(currentAccount().accountName()));
502 }
503
504 void CoreConnection::sessionStateReceived(const QVariantMap &state) {
505   updateProgress(100, 100);
506
507   // rest of communication happens through SignalProxy...
508   disconnect(_socket, SIGNAL(readyRead()), this, 0);
509   disconnect(_socket, SIGNAL(connected()), this, 0);
510
511   syncToCore(state);
512 }
513
514 void CoreConnection::internalSessionStateReceived(const QVariant &packedState) {
515   updateProgress(100, 100);
516
517   setState(Synchronizing);
518   syncToCore(packedState.toMap());
519 }
520
521 void CoreConnection::syncToCore(const QVariantMap &sessionState) {
522   setProgressText(tr("Receiving network states"));
523   updateProgress(0, 100);
524
525   // create identities
526   foreach(QVariant vid, sessionState["Identities"].toList()) {
527     Client::instance()->coreIdentityCreated(vid.value<Identity>());
528   }
529
530   // create buffers
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
537
538   QVariantList networkids = sessionState["NetworkIds"].toList();
539
540   // prepare sync progress thingys...
541   // FIXME: Care about removal of networks
542   _numNetsToSync = networkids.count();
543   updateProgress(0, _numNetsToSync);
544
545   // create network objects
546   foreach(QVariant networkid, networkids) {
547     NetworkId netid = networkid.value<NetworkId>();
548     if(Client::network(netid))
549       continue;
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);
555   }
556   checkSyncState();
557 }
558
559 void CoreConnection::networkInitDone() {
560   Network *net = qobject_cast<Network *>(sender());
561   Q_ASSERT(net);
562   disconnect(net, 0, this, 0);
563   _netsToSync.remove(net);
564   updateProgress(_numNetsToSync - _netsToSync.count(), _numNetsToSync);
565   checkSyncState();
566 }
567
568 void CoreConnection::checkSyncState() {
569   if(_netsToSync.isEmpty()) {
570     setState(Synchronized);
571     setProgressText(tr("Synchronized to %1").arg(currentAccount().accountName()));
572     setProgressMaximum(-1);
573     emit synchronized();
574   }
575 }
576
577 void CoreConnection::doCoreSetup(const QVariant &setupData) {
578   QVariantMap setup;
579   setup["MsgType"] = "CoreSetupData";
580   setup["SetupData"] = setupData;
581   SignalProxy::writeDataToDevice(_socket, setup);
582 }