b2c040ebd15ef3902128b144d7a505cbe4d89003
[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 "coreaccountmodel.h"
29 #include "identity.h"
30 #include "network.h"
31 #include "networkmodel.h"
32 #include "quassel.h"
33 #include "signalproxy.h"
34 #include "util.h"
35
36 CoreConnection::CoreConnection(CoreAccountModel *model, QObject *parent)
37   : QObject(parent),
38   _model(model),
39   _blockSize(0),
40   _progressMinimum(0),
41   _progressMaximum(-1),
42   _progressValue(-1)
43 {
44   qRegisterMetaType<ConnectionState>("CoreConnection::ConnectionState");
45
46 }
47
48 void CoreConnection::start() {
49   connectToCore(1);
50 }
51
52 void CoreConnection::init() {
53   connect(Client::signalProxy(), SIGNAL(disconnected()), SLOT(coreSocketDisconnected()));
54 }
55
56 void CoreConnection::setProgressText(const QString &text) {
57   if(_progressText != text) {
58     _progressText = text;
59     emit progressTextChanged(text);
60   }
61 }
62
63 void CoreConnection::setProgressValue(int value) {
64   if(_progressValue != value) {
65     _progressValue = value;
66     emit progressValueChanged(value);
67   }
68 }
69
70 void CoreConnection::setProgressMinimum(int minimum) {
71   if(_progressMinimum != minimum) {
72     _progressMinimum = minimum;
73     emit progressRangeChanged(minimum, _progressMaximum);
74   }
75 }
76
77 void CoreConnection::setProgressMaximum(int maximum) {
78   if(_progressMaximum != maximum) {
79     _progressMaximum = maximum;
80     emit progressRangeChanged(_progressMinimum, maximum);
81   }
82 }
83
84 void CoreConnection::updateProgress(int value, int max) {
85   if(max != _progressMaximum) {
86     _progressMaximum = max;
87     emit progressRangeChanged(_progressMinimum, _progressMaximum);
88   }
89   setProgressValue(value);
90 }
91
92 void CoreConnection::resetConnection() {
93   if(_socket) {
94     disconnect(_socket, 0, this, 0);
95     _socket->deleteLater();
96     _socket = 0;
97   }
98   _blockSize = 0;
99
100   _coreMsgBuffer.clear();
101
102   _netsToSync.clear();
103   _numNetsToSync = 0;
104
105   setProgressMaximum(-1); // disable
106   emit connectionMsg(tr("Disconnected from core."));
107 }
108
109 void CoreConnection::socketStateChanged(QAbstractSocket::SocketState socketState) {
110   QString text;
111
112   switch(socketState) {
113   case QAbstractSocket::UnconnectedState:
114     text = tr("Disconnected.");
115     break;
116   case QAbstractSocket::HostLookupState:
117     text = tr("Looking up %1...").arg(currentAccount().hostName());
118     break;
119   case QAbstractSocket::ConnectingState:
120     text = tr("Connecting to %1...").arg(currentAccount().hostName());
121     break;
122   case QAbstractSocket::ConnectedState:
123     text = tr("Connected to %1.").arg(currentAccount().hostName());
124     break;
125   case QAbstractSocket::ClosingState:
126     text = tr("Disconnecting from %1...").arg(currentAccount().hostName());
127     break;
128   default:
129     break;
130   }
131
132   if(!text.isEmpty())
133     emit progressTextChanged(text);
134
135   setState(socketState);
136 }
137
138 void CoreConnection::setState(QAbstractSocket::SocketState socketState) {
139   ConnectionState state;
140
141   switch(socketState) {
142   case QAbstractSocket::UnconnectedState:
143     state = Disconnected;
144     break;
145   case QAbstractSocket::HostLookupState:
146   case QAbstractSocket::ConnectingState:
147     state = Connecting;
148     break;
149   case QAbstractSocket::ConnectedState:
150     state = Connected;
151     break;
152   default:
153     state = Disconnected;
154   }
155
156   setState(state);
157 }
158
159 void CoreConnection::setState(ConnectionState state) {
160   if(state != _state) {
161     _state = state;
162     emit stateChanged(state);
163   }
164 }
165
166 void CoreConnection::setWarningsHandler(const char *slot) {
167   resetWarningsHandler();
168   connect(this, SIGNAL(handleIgnoreWarnings(bool)), this, slot);
169 }
170
171 void CoreConnection::resetWarningsHandler() {
172   disconnect(this, SIGNAL(handleIgnoreWarnings(bool)), this, 0);
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   setState(Disconnected);
183   emit disconnected();
184   resetConnection();
185   // FIXME handle disconnects gracefully
186 }
187
188 void CoreConnection::coreHasData() {
189   QVariant item;
190   while(SignalProxy::readDataFromDevice(_socket, _blockSize, item)) {
191     QVariantMap msg = item.toMap();
192     if(!msg.contains("MsgType")) {
193       // This core is way too old and does not even speak our init protocol...
194       emit connectionError(tr("The Quassel Core you try to connect to is too old! Please consider upgrading."));
195       disconnectFromCore();
196       return;
197     }
198     if(msg["MsgType"] == "ClientInitAck") {
199       clientInitAck(msg);
200     } else if(msg["MsgType"] == "ClientInitReject") {
201       emit connectionError(msg["Error"].toString());
202       disconnectFromCore();
203       return;
204     } else if(msg["MsgType"] == "CoreSetupAck") {
205       //emit coreSetupSuccess();
206     } else if(msg["MsgType"] == "CoreSetupReject") {
207       //emit coreSetupFailed(msg["Error"].toString());
208     } else if(msg["MsgType"] == "ClientLoginReject") {
209       loginFailed(msg["Error"].toString());
210     } else if(msg["MsgType"] == "ClientLoginAck") {
211       loginSuccess();
212     } else if(msg["MsgType"] == "SessionInit") {
213       // that's it, let's hand over to the signal proxy
214       // if the socket is an orphan, the signalProxy adopts it.
215       // -> we don't need to care about it anymore
216       _socket->setParent(0);
217       Client::signalProxy()->addPeer(_socket);
218
219       sessionStateReceived(msg["SessionState"].toMap());
220       break; // this is definitively the last message we process here!
221     } else {
222       emit connectionError(tr("<b>Invalid data received from core!</b><br>Disconnecting."));
223       disconnectFromCore();
224       return;
225     }
226   }
227   if(_blockSize > 0) {
228     updateProgress(_socket->bytesAvailable(), _blockSize);
229   }
230 }
231
232 void CoreConnection::disconnectFromCore() {
233   if(isConnected()) {
234     Client::signalProxy()->removeAllPeers();
235     resetConnection();
236   }
237 }
238
239 void CoreConnection::reconnectToCore() {
240
241 }
242
243 void CoreConnection::connectToCore(AccountId accId) {
244   resetConnection();
245   _account = accountModel()->account(accId);
246
247   if(!_account.accountId().isValid()) {
248     emit connectionError(tr("Invalid core account, cannot connect!"));
249     return;
250   }
251
252   Q_ASSERT(!_socket);
253 #ifdef HAVE_SSL
254   QSslSocket *sock = new QSslSocket(Client::instance());
255 #else
256   if(_account.useSsl()) {
257     emit connectionError(tr("<b>This client is built without SSL Support!</b><br />Disable the usage of SSL in the account settings."));
258     return;
259   }
260   QTcpSocket *sock = new QTcpSocket(Client::instance());
261 #endif
262
263 #ifndef QT_NO_NETWORKPROXY
264   if(_account.useProxy()) {
265     QNetworkProxy proxy(_account.proxyType(), _account.proxyHostName(), _account.proxyPort(), _account.proxyUser(), _account.proxyPassword());
266     sock->setProxy(proxy);
267   }
268 #endif
269
270   _socket = sock;
271   connect(sock, SIGNAL(readyRead()), SLOT(coreHasData()));
272   connect(sock, SIGNAL(connected()), SLOT(coreSocketConnected()));
273   connect(sock, SIGNAL(disconnected()), SLOT(coreSocketDisconnected()));
274   connect(sock, SIGNAL(error(QAbstractSocket::SocketError)), SLOT(coreSocketError(QAbstractSocket::SocketError)));
275   connect(sock, SIGNAL(stateChanged(QAbstractSocket::SocketState)), SLOT(socketStateChanged(QAbstractSocket::SocketState)));
276
277   emit connectionMsg(tr("Connecting to %1...").arg(currentAccount().accountName()));
278   sock->connectToHost(_account.hostName(), _account.port());
279 }
280
281 void CoreConnection::coreSocketConnected() {
282   // Phase One: Send client info and wait for core info
283
284   emit connectionMsg(tr("Synchronizing to core..."));
285
286   QVariantMap clientInit;
287   clientInit["MsgType"] = "ClientInit";
288   clientInit["ClientVersion"] = Quassel::buildInfo().fancyVersionString;
289   clientInit["ClientDate"] = Quassel::buildInfo().buildDate;
290   clientInit["ProtocolVersion"] = Quassel::buildInfo().protocolVersion;
291   clientInit["UseSsl"] = _account.useSsl();
292 #ifndef QT_NO_COMPRESS
293   clientInit["UseCompression"] = true;
294 #else
295   clientInit["UseCompression"] = false;
296 #endif
297
298   SignalProxy::writeDataToDevice(_socket, clientInit);
299 }
300
301 void CoreConnection::clientInitAck(const QVariantMap &msg) {
302   // Core has accepted our version info and sent its own. Let's see if we accept it as well...
303   uint ver = msg["ProtocolVersion"].toUInt();
304   if(ver < Quassel::buildInfo().clientNeedsProtocol) {
305     emit connectionError(tr("<b>The Quassel Core you are trying to connect to is too old!</b><br>"
306         "Need at least core/client protocol v%1 to connect.").arg(Quassel::buildInfo().clientNeedsProtocol));
307     disconnectFromCore();
308     return;
309   }
310
311 #ifndef QT_NO_COMPRESS
312   if(msg["SupportsCompression"].toBool()) {
313     _socket->setProperty("UseCompression", true);
314   }
315 #endif
316
317   _coreMsgBuffer = msg;
318 #ifdef HAVE_SSL
319   if(currentAccount().useSsl()) {
320     if(msg["SupportSsl"].toBool()) {
321       QSslSocket *sslSocket = qobject_cast<QSslSocket *>(_socket);
322       Q_ASSERT(sslSocket);
323       connect(sslSocket, SIGNAL(encrypted()), this, SLOT(sslSocketEncrypted()));
324       connect(sslSocket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
325
326       sslSocket->startClientEncryption();
327     } else {
328       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."));
329       disconnectFromCore();
330     }
331     return;
332   }
333 #endif
334   // if we use SSL we wait for the next step until every SSL warning has been cleared
335   connectionReady();
336
337 }
338
339 void CoreConnection::connectionReady() {
340   if(!_coreMsgBuffer["Configured"].toBool()) {
341     // start wizard
342     emit startCoreSetup(_coreMsgBuffer["StorageBackends"].toList());
343   } else if(_coreMsgBuffer["LoginEnabled"].toBool()) {
344     loginToCore();
345   }
346   _coreMsgBuffer.clear();
347   resetWarningsHandler();
348 }
349
350 void CoreConnection::loginToCore() {
351   emit connectionMsg(tr("Logging in..."));
352   if(currentAccount().user().isEmpty() || currentAccount().password().isEmpty()) {
353     emit userAuthenticationRequired(&_account);  // *must* be a synchronous call
354     if(currentAccount().user().isEmpty() || currentAccount().password().isEmpty()) {
355       disconnectFromCore();
356       return;
357     }
358   }
359
360   QVariantMap clientLogin;
361   clientLogin["MsgType"] = "ClientLogin";
362   clientLogin["User"] = currentAccount().user();
363   clientLogin["Password"] = currentAccount().password();
364   SignalProxy::writeDataToDevice(_socket, clientLogin);
365 }
366
367 void CoreConnection::loginFailed(const QString &error) {
368   emit userAuthenticationRequired(&_account, error);  // *must* be a synchronous call
369   if(currentAccount().user().isEmpty() || currentAccount().password().isEmpty()) {
370     disconnectFromCore();
371     return;
372   }
373   loginToCore();
374 }
375
376 void CoreConnection::loginSuccess() {
377   updateProgress(0, 0);
378   setProgressText(tr("Receiving session state"));
379   setState(Synchronizing);
380   emit connectionMsg(tr("Synchronizing to %1...").arg(currentAccount().accountName()));
381 }
382
383 void CoreConnection::sessionStateReceived(const QVariantMap &state) {
384   updateProgress(100, 100);
385
386   // rest of communication happens through SignalProxy...
387   disconnect(_socket, SIGNAL(readyRead()), this, 0);
388   disconnect(_socket, SIGNAL(connected()), this, 0);
389
390   //Client::instance()->setConnectedToCore(currentAccount().accountId(), _socket);
391   syncToCore(state);
392 }
393
394 void CoreConnection::syncToCore(const QVariantMap &sessionState) {
395   setProgressText(tr("Receiving network states"));
396   updateProgress(0, 100);
397
398   // create identities
399   foreach(QVariant vid, sessionState["Identities"].toList()) {
400     Client::instance()->coreIdentityCreated(vid.value<Identity>());
401   }
402
403   // create buffers
404   // FIXME: get rid of this crap -- why?
405   QVariantList bufferinfos = sessionState["BufferInfos"].toList();
406   NetworkModel *networkModel = Client::networkModel();
407   Q_ASSERT(networkModel);
408   foreach(QVariant vinfo, bufferinfos)
409     networkModel->bufferUpdated(vinfo.value<BufferInfo>());  // create BufferItems
410
411   QVariantList networkids = sessionState["NetworkIds"].toList();
412
413   // prepare sync progress thingys...
414   // FIXME: Care about removal of networks
415   _numNetsToSync = networkids.count();
416   updateProgress(0, _numNetsToSync);
417
418   // create network objects
419   foreach(QVariant networkid, networkids) {
420     NetworkId netid = networkid.value<NetworkId>();
421     if(Client::network(netid))
422       continue;
423     Network *net = new Network(netid, Client::instance());
424     _netsToSync.insert(net);
425     connect(net, SIGNAL(initDone()), SLOT(networkInitDone()));
426     connect(net, SIGNAL(destroyed()), SLOT(networkInitDone()));
427     Client::addNetwork(net);
428   }
429   checkSyncState();
430 }
431
432 void CoreConnection::networkInitDone() {
433   Network *net = qobject_cast<Network *>(sender());
434   Q_ASSERT(net);
435   disconnect(net, 0, this, 0);
436   _netsToSync.remove(net);
437   updateProgress(_numNetsToSync - _netsToSync.count(), _numNetsToSync);
438   checkSyncState();
439 }
440
441 void CoreConnection::checkSyncState() {
442   if(_netsToSync.isEmpty()) {
443     setState(Synchronized);
444     setProgressText(QString());
445     setProgressMaximum(-1);
446     emit synchronized();
447   }
448 }