f290756dd089cb92ce7b17e132c5cf9a126f43b2
[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   _state = Disconnected;
103
104   setProgressMaximum(-1); // disable
105   emit connectionMsg(tr("Disconnected from core."));
106 }
107
108 void CoreConnection::socketStateChanged(QAbstractSocket::SocketState socketState) {
109   QString text;
110
111   switch(socketState) {
112   case QAbstractSocket::UnconnectedState:
113     text = tr("Disconnected.");
114     break;
115   case QAbstractSocket::HostLookupState:
116     text = tr("Looking up %1...").arg(currentAccount().hostName());
117     break;
118   case QAbstractSocket::ConnectingState:
119     text = tr("Connecting to %1...").arg(currentAccount().hostName());
120     break;
121   case QAbstractSocket::ConnectedState:
122     text = tr("Connected to %1.").arg(currentAccount().hostName());
123     break;
124   case QAbstractSocket::ClosingState:
125     text = tr("Disconnecting from %1...").arg(currentAccount().hostName());
126     break;
127   default:
128     break;
129   }
130
131   if(!text.isEmpty())
132     emit progressTextChanged(text);
133
134   setState(socketState);
135 }
136
137 void CoreConnection::setState(QAbstractSocket::SocketState socketState) {
138   ConnectionState state;
139
140   switch(socketState) {
141   case QAbstractSocket::UnconnectedState:
142     state = Disconnected;
143     break;
144   case QAbstractSocket::HostLookupState:
145   case QAbstractSocket::ConnectingState:
146     state = Connecting;
147     break;
148   case QAbstractSocket::ConnectedState:
149     state = Connected;
150     break;
151   default:
152     state = Disconnected;
153   }
154
155   setState(state);
156 }
157
158 void CoreConnection::setState(ConnectionState state) {
159   if(state != _state) {
160     _state = state;
161     emit stateChanged(state);
162   }
163 }
164
165 void CoreConnection::setWarningsHandler(const char *slot) {
166   resetWarningsHandler();
167   connect(this, SIGNAL(handleIgnoreWarnings(bool)), this, slot);
168 }
169
170 void CoreConnection::resetWarningsHandler() {
171   disconnect(this, SIGNAL(handleIgnoreWarnings(bool)), this, 0);
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   setState(Disconnected);
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 connectionError(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 connectionError(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       emit connectionError(tr("<b>Invalid data received from core!</b><br>Disconnecting."));
222       disconnectFromCore();
223       return;
224     }
225   }
226   if(_blockSize > 0) {
227     updateProgress(_socket->bytesAvailable(), _blockSize);
228   }
229 }
230
231 void CoreConnection::disconnectFromCore() {
232   Client::signalProxy()->removeAllPeers();
233   resetConnection();
234 }
235
236 void CoreConnection::reconnectToCore() {
237   if(currentAccount().isValid())
238     connectToCore(currentAccount().accountId());
239 }
240
241 bool CoreConnection::connectToCore(AccountId accId) {
242   if(isConnected())
243     return false;
244
245   CoreAccountSettings s;
246
247   if(!accId.isValid()) {
248     // check our settings and figure out what to do
249     if(!s.autoConnectOnStartup())
250       return false;
251     if(s.autoConnectToFixedAccount())
252       accId = s.autoConnectAccount();
253     else
254       accId = s.lastAccount();
255     if(!accId.isValid())
256       return false;
257   }
258   _account = accountModel()->account(accId);
259   if(!_account.accountId().isValid()) {
260     return false;
261   }
262
263   s.setLastAccount(accId);
264   connectToCurrentAccount();
265   return true;
266 }
267
268 void CoreConnection::connectToCurrentAccount() {
269   resetConnection();
270
271   Q_ASSERT(!_socket);
272 #ifdef HAVE_SSL
273   QSslSocket *sock = new QSslSocket(Client::instance());
274 #else
275   if(_account.useSsl()) {
276     emit connectionError(tr("<b>This client is built without SSL Support!</b><br />Disable the usage of SSL in the account settings."));
277     return;
278   }
279   QTcpSocket *sock = new QTcpSocket(Client::instance());
280 #endif
281
282 #ifndef QT_NO_NETWORKPROXY
283   if(_account.useProxy()) {
284     QNetworkProxy proxy(_account.proxyType(), _account.proxyHostName(), _account.proxyPort(), _account.proxyUser(), _account.proxyPassword());
285     sock->setProxy(proxy);
286   }
287 #endif
288
289   _socket = sock;
290   connect(sock, SIGNAL(readyRead()), SLOT(coreHasData()));
291   connect(sock, SIGNAL(connected()), SLOT(coreSocketConnected()));
292   connect(sock, SIGNAL(disconnected()), SLOT(coreSocketDisconnected()));
293   connect(sock, SIGNAL(error(QAbstractSocket::SocketError)), SLOT(coreSocketError(QAbstractSocket::SocketError)));
294   connect(sock, SIGNAL(stateChanged(QAbstractSocket::SocketState)), SLOT(socketStateChanged(QAbstractSocket::SocketState)));
295
296   emit connectionMsg(tr("Connecting to %1...").arg(currentAccount().accountName()));
297   sock->connectToHost(_account.hostName(), _account.port());
298 }
299
300 void CoreConnection::coreSocketConnected() {
301   // Phase One: Send client info and wait for core info
302
303   emit connectionMsg(tr("Synchronizing to core..."));
304
305   QVariantMap clientInit;
306   clientInit["MsgType"] = "ClientInit";
307   clientInit["ClientVersion"] = Quassel::buildInfo().fancyVersionString;
308   clientInit["ClientDate"] = Quassel::buildInfo().buildDate;
309   clientInit["ProtocolVersion"] = Quassel::buildInfo().protocolVersion;
310   clientInit["UseSsl"] = _account.useSsl();
311 #ifndef QT_NO_COMPRESS
312   clientInit["UseCompression"] = true;
313 #else
314   clientInit["UseCompression"] = false;
315 #endif
316
317   SignalProxy::writeDataToDevice(_socket, clientInit);
318 }
319
320 void CoreConnection::clientInitAck(const QVariantMap &msg) {
321   // Core has accepted our version info and sent its own. Let's see if we accept it as well...
322   uint ver = msg["ProtocolVersion"].toUInt();
323   if(ver < Quassel::buildInfo().clientNeedsProtocol) {
324     emit connectionError(tr("<b>The Quassel Core you are trying to connect to is too old!</b><br>"
325         "Need at least core/client protocol v%1 to connect.").arg(Quassel::buildInfo().clientNeedsProtocol));
326     disconnectFromCore();
327     return;
328   }
329
330 #ifndef QT_NO_COMPRESS
331   if(msg["SupportsCompression"].toBool()) {
332     _socket->setProperty("UseCompression", true);
333   }
334 #endif
335
336   _coreMsgBuffer = msg;
337 #ifdef HAVE_SSL
338   if(currentAccount().useSsl()) {
339     if(msg["SupportSsl"].toBool()) {
340       QSslSocket *sslSocket = qobject_cast<QSslSocket *>(_socket);
341       Q_ASSERT(sslSocket);
342       connect(sslSocket, SIGNAL(encrypted()), this, SLOT(sslSocketEncrypted()));
343       connect(sslSocket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
344
345       sslSocket->startClientEncryption();
346     } else {
347       emit connectionError(tr("<b>The Quassel Core you are trying to connect to does not support SSL!</b><br />If you want to connect anyways, disable the usage of SSL in the account settings."));
348       disconnectFromCore();
349     }
350     return;
351   }
352 #endif
353   // if we use SSL we wait for the next step until every SSL warning has been cleared
354   connectionReady();
355
356 }
357
358 void CoreConnection::connectionReady() {
359   if(!_coreMsgBuffer["Configured"].toBool()) {
360     // start wizard
361     emit startCoreSetup(_coreMsgBuffer["StorageBackends"].toList());
362   } else if(_coreMsgBuffer["LoginEnabled"].toBool()) {
363     loginToCore();
364   }
365   _coreMsgBuffer.clear();
366   resetWarningsHandler();
367 }
368
369 void CoreConnection::loginToCore(const QString &prevError) {
370   emit connectionMsg(tr("Logging in..."));
371   if(currentAccount().user().isEmpty() || currentAccount().password().isEmpty() || !prevError.isEmpty()) {
372     bool valid = false;
373     emit userAuthenticationRequired(&_account, &valid, prevError);  // *must* be a synchronous call
374     if(!valid || currentAccount().user().isEmpty() || currentAccount().password().isEmpty()) {
375       disconnectFromCore();
376       emit connectionError(tr("Login canceled"));
377       return;
378     }
379   }
380
381   QVariantMap clientLogin;
382   clientLogin["MsgType"] = "ClientLogin";
383   clientLogin["User"] = currentAccount().user();
384   clientLogin["Password"] = currentAccount().password();
385   SignalProxy::writeDataToDevice(_socket, clientLogin);
386 }
387
388 void CoreConnection::loginFailed(const QString &error) {
389   loginToCore(error);
390 }
391
392 void CoreConnection::loginSuccess() {
393   updateProgress(0, 0);
394
395   // save current account data
396   _model->createOrUpdateAccount(currentAccount());
397   _model->save();
398
399   setProgressText(tr("Receiving session state"));
400   setState(Synchronizing);
401   emit connectionMsg(tr("Synchronizing to %1...").arg(currentAccount().accountName()));
402 }
403
404 void CoreConnection::sessionStateReceived(const QVariantMap &state) {
405   updateProgress(100, 100);
406
407   // rest of communication happens through SignalProxy...
408   disconnect(_socket, SIGNAL(readyRead()), this, 0);
409   disconnect(_socket, SIGNAL(connected()), this, 0);
410
411   //Client::instance()->setConnectedToCore(currentAccount().accountId(), _socket);
412   syncToCore(state);
413 }
414
415 void CoreConnection::syncToCore(const QVariantMap &sessionState) {
416   setProgressText(tr("Receiving network states"));
417   updateProgress(0, 100);
418
419   // create identities
420   foreach(QVariant vid, sessionState["Identities"].toList()) {
421     Client::instance()->coreIdentityCreated(vid.value<Identity>());
422   }
423
424   // create buffers
425   // FIXME: get rid of this crap -- why?
426   QVariantList bufferinfos = sessionState["BufferInfos"].toList();
427   NetworkModel *networkModel = Client::networkModel();
428   Q_ASSERT(networkModel);
429   foreach(QVariant vinfo, bufferinfos)
430     networkModel->bufferUpdated(vinfo.value<BufferInfo>());  // create BufferItems
431
432   QVariantList networkids = sessionState["NetworkIds"].toList();
433
434   // prepare sync progress thingys...
435   // FIXME: Care about removal of networks
436   _numNetsToSync = networkids.count();
437   updateProgress(0, _numNetsToSync);
438
439   // create network objects
440   foreach(QVariant networkid, networkids) {
441     NetworkId netid = networkid.value<NetworkId>();
442     if(Client::network(netid))
443       continue;
444     Network *net = new Network(netid, Client::instance());
445     _netsToSync.insert(net);
446     connect(net, SIGNAL(initDone()), SLOT(networkInitDone()));
447     connect(net, SIGNAL(destroyed()), SLOT(networkInitDone()));
448     Client::addNetwork(net);
449   }
450   checkSyncState();
451 }
452
453 void CoreConnection::networkInitDone() {
454   Network *net = qobject_cast<Network *>(sender());
455   Q_ASSERT(net);
456   disconnect(net, 0, this, 0);
457   _netsToSync.remove(net);
458   updateProgress(_numNetsToSync - _netsToSync.count(), _numNetsToSync);
459   checkSyncState();
460 }
461
462 void CoreConnection::checkSyncState() {
463   if(_netsToSync.isEmpty()) {
464     setState(Synchronized);
465     setProgressText(QString());
466     setProgressMaximum(-1);
467     emit synchronized();
468   }
469 }