Fix protocol version check
[quassel.git] / src / client / clientsyncer.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-08 by the Quassel IRC Team                         *
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 "clientsyncer.h"
22
23 #ifndef QT_NO_NETWORKPROXY
24 #  include <QNetworkProxy>
25 #endif
26
27 #include "client.h"
28 #include "global.h"
29 #include "identity.h"
30 #include "ircuser.h"
31 #include "ircchannel.h"
32 #include "network.h"
33 #include "signalproxy.h"
34
35
36 ClientSyncer::ClientSyncer(QObject *parent)
37   : QObject(parent)
38 {
39   socket = 0;
40   blockSize = 0;
41
42   connect(Client::signalProxy(), SIGNAL(disconnected()), this, SLOT(coreSocketDisconnected()));
43 }
44
45 ClientSyncer::~ClientSyncer() {
46 }
47
48 void ClientSyncer::coreHasData() {
49   QVariant item;
50   while(SignalProxy::readDataFromDevice(socket, blockSize, item)) {
51     emit recvPartialItem(1,1);
52     QVariantMap msg = item.toMap();
53     if(!msg.contains("MsgType")) {
54       // This core is way too old and does not even speak our init protocol...
55       emit connectionError(tr("The Quassel Core you try to connect to is too old! Please consider upgrading."));
56       disconnectFromCore();
57       return;
58     }
59     if(msg["MsgType"] == "ClientInitAck") {
60       clientInitAck(msg);
61     } else if(msg["MsgType"] == "ClientInitReject") {
62       emit connectionError(msg["Error"].toString());
63       disconnectFromCore();
64       return;
65     } else if(msg["MsgType"] == "CoreSetupAck") {
66       emit coreSetupSuccess();
67     } else if(msg["MsgType"] == "CoreSetupReject") {
68       emit coreSetupFailed(msg["Error"].toString());
69     } else if(msg["MsgType"] == "ClientLoginReject") {
70       emit loginFailed(msg["Error"].toString());
71     } else if(msg["MsgType"] == "ClientLoginAck") {
72       // prevent multiple signal connections
73       disconnect(this, SIGNAL(recvPartialItem(quint32, quint32)), this, SIGNAL(sessionProgress(quint32, quint32)));
74       connect(this, SIGNAL(recvPartialItem(quint32, quint32)), this, SIGNAL(sessionProgress(quint32, quint32)));
75       emit loginSuccess();
76     } else if(msg["MsgType"] == "SessionInit") {
77       sessionStateReceived(msg["SessionState"].toMap());
78       break; // this is definitively the last message we process here!
79     } else {
80       emit connectionError(tr("<b>Invalid data received from core!</b><br>Disconnecting."));
81       disconnectFromCore();
82       return;
83     }
84   }
85   if(blockSize > 0) {
86     emit recvPartialItem(socket->bytesAvailable(), blockSize);
87   }
88 }
89
90 void ClientSyncer::coreSocketError(QAbstractSocket::SocketError) {
91   qDebug() << "coreSocketError" << socket << socket->errorString();
92   emit connectionError(socket->errorString());
93   socket->deleteLater();
94 }
95
96 void ClientSyncer::disconnectFromCore() {
97   if(socket) socket->close();
98 }
99
100 void ClientSyncer::connectToCore(const QVariantMap &conn) {
101   // TODO implement SSL
102   coreConnectionInfo = conn;
103   //if(isConnected()) {
104   //  emit coreConnectionError(tr("Already connected to Core!"));
105   //  return;
106   // }
107   if(socket != 0) {
108     socket->deleteLater();
109     socket = 0;
110   }
111   if(conn["Host"].toString().isEmpty()) {
112     emit connectionError(tr("Internal connections not yet supported."));
113     return; // FIXME implement internal connections
114     //clientMode = LocalCore;
115     socket = new QBuffer(this);
116     connect(socket, SIGNAL(readyRead()), this, SLOT(coreHasData()));
117     socket->open(QIODevice::ReadWrite);
118     //QVariant state = connectToLocalCore(coreConnectionInfo["User"].toString(), coreConnectionInfo["Password"].toString());
119     //syncToCore(state);
120     coreSocketConnected();
121   } else {
122     //clientMode = RemoteCore;
123     //emit coreConnectionMsg(tr("Connecting..."));
124     Q_ASSERT(!socket);
125
126 #ifndef QT_NO_OPENSSL
127     QSslSocket *sock = new QSslSocket(Client::instance());
128 #else
129     if(conn["useSsl"].toBool()) {
130         emit connectionError(tr("<b>This client is built without SSL Support!</b><br />Disable the usage of SSL in the account settings."));
131         emit encrypted(false);
132         return;
133     }
134     QTcpSocket *sock = new QTcpSocket(Client::instance());
135 #endif
136 #ifndef QT_NO_NETWORKPROXY
137     if(conn.contains("useProxy") && conn["useProxy"].toBool()) {
138       QNetworkProxy proxy((QNetworkProxy::ProxyType)conn["proxyType"].toInt(), conn["proxyHost"].toString(), conn["proxyPort"].toUInt(), conn["proxyUser"].toString(), conn["proxyPassword"].toString());
139       sock->setProxy(proxy);
140     }
141 #endif
142     socket = sock;
143     connect(sock, SIGNAL(readyRead()), this, SLOT(coreHasData()));
144     connect(sock, SIGNAL(connected()), this, SLOT(coreSocketConnected()));
145     connect(sock, SIGNAL(disconnected()), this, SLOT(coreSocketDisconnected()));
146     connect(sock, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(coreSocketError(QAbstractSocket::SocketError)));
147     connect(sock, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SIGNAL(socketStateChanged(QAbstractSocket::SocketState)));
148     sock->connectToHost(conn["Host"].toString(), conn["Port"].toUInt());
149   }
150 }
151
152 void ClientSyncer::coreSocketConnected() {
153   //connect(this, SIGNAL(recvPartialItem(uint, uint)), this, SIGNAL(coreConnectionProgress(uint, uint)));
154   // Phase One: Send client info and wait for core info
155
156   //emit coreConnectionMsg(tr("Synchronizing to core..."));
157   QVariantMap clientInit;
158   clientInit["MsgType"] = "ClientInit";
159   clientInit["ClientVersion"] = Global::quasselVersion;
160   clientInit["ClientBuild"] = 860; // FIXME legacy!
161   clientInit["ClientDate"] = Global::quasselBuildDate;
162   clientInit["ProtocolVersion"] = Global::protocolVersion;
163   clientInit["UseSsl"] = coreConnectionInfo["useSsl"];
164 #ifndef QT_NO_COMPRESS
165   clientInit["UseCompression"] = true;
166 #else
167   clientInit["UseCompression"] = false;
168 #endif
169
170   SignalProxy::writeDataToDevice(socket, clientInit);
171 }
172
173 void ClientSyncer::coreSocketDisconnected() {
174   emit socketDisconnected();
175   Client::instance()->disconnectFromCore();
176
177   // FIXME handle disconnects gracefully in here as well!
178
179   coreConnectionInfo.clear();
180   netsToSync.clear();
181   channelsToSync.clear();
182   usersToSync.clear();
183   blockSize = 0;
184   //restartPhaseNull();
185 }
186
187 void ClientSyncer::clientInitAck(const QVariantMap &msg) {
188   // Core has accepted our version info and sent its own. Let's see if we accept it as well...
189   uint ver = 0;
190   if(!msg.contains("ProtocolVersion") && msg["CoreBuild"].toUInt() >= 732) ver = 1; // legacy!
191   if(msg.contains("ProtocolVersion")) ver = msg["ProtocolVersion"].toUInt();
192   if(ver < Global::clientNeedsProtocol) {
193     emit connectionError(tr("<b>The Quassel Core you are trying to connect to is too old!</b><br>"
194         "Need at least core/client protocol v%1 to connect.").arg(Global::clientNeedsProtocol));
195     disconnectFromCore();
196     return;
197   }
198   emit connectionMsg(msg["CoreInfo"].toString());
199
200 #ifndef QT_NO_OPENSSL
201   if(coreConnectionInfo["useSsl"].toBool()) {
202     if(msg["SupportSsl"].toBool()) {
203       QSslSocket *sslSocket = qobject_cast<QSslSocket *>(socket);
204       Q_ASSERT(sslSocket);
205       connect(sslSocket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
206       sslSocket->startClientEncryption();
207       emit encrypted(true);
208       Client::instance()->setSecuredConnection();
209     } else {
210       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."));
211       emit encrypted(false);
212       disconnectFromCore();
213       return;
214     }
215   }
216 #endif
217
218 #ifndef QT_NO_COMPRESS
219   if(msg["SupportsCompression"].toBool()) {
220     socket->setProperty("UseCompression", true);
221   }
222 #endif
223   
224   if(!msg["Configured"].toBool()) {
225     // start wizard
226     emit startCoreSetup(msg["StorageBackends"].toList());
227   } else if(msg["LoginEnabled"].toBool()) {
228     emit startLogin();
229   }
230 }
231
232 void ClientSyncer::doCoreSetup(const QVariant &setupData) {
233   QVariantMap setup;
234   setup["MsgType"] = "CoreSetupData";
235   setup["SetupData"] = setupData;
236   SignalProxy::writeDataToDevice(socket, setup);
237 }
238
239 void ClientSyncer::loginToCore(const QString &user, const QString &passwd) {
240   emit connectionMsg(tr("Logging in..."));
241   QVariantMap clientLogin;
242   clientLogin["MsgType"] = "ClientLogin";
243   clientLogin["User"] = user;
244   clientLogin["Password"] = passwd;
245   SignalProxy::writeDataToDevice(socket, clientLogin);
246 }
247
248 void ClientSyncer::sessionStateReceived(const QVariantMap &state) {
249   emit sessionProgress(1, 1);
250   disconnect(this, SIGNAL(recvPartialItem(quint32, quint32)), this, SIGNAL(sessionProgress(quint32, quint32)));
251   disconnect(socket, 0, this, 0);  // rest of communication happens through SignalProxy
252   //Client::signalProxy()->addPeer(socket);
253   Client::instance()->setConnectedToCore(socket, coreConnectionInfo["AccountId"].value<AccountId>());
254   syncToCore(state);
255 }
256
257 void ClientSyncer::syncToCore(const QVariantMap &sessionState) {
258
259   // create identities
260   foreach(QVariant vid, sessionState["Identities"].toList()) {
261     Client::instance()->coreIdentityCreated(vid.value<Identity>());
262   }
263
264   // create buffers
265   // FIXME: get rid of this crap
266   QVariantList bufferinfos = sessionState["BufferInfos"].toList();
267   foreach(QVariant vinfo, bufferinfos) Client::buffer(vinfo.value<BufferInfo>());  // create Buffers and BufferItems
268
269   QVariantList networkids = sessionState["NetworkIds"].toList();
270
271   // prepare sync progress thingys... FIXME: Care about removal of networks
272   numNetsToSync = networkids.count();
273   numChannelsToSync = 0; //sessionState["IrcChannelCount"].toUInt();
274   numUsersToSync = 0; // sessionState["IrcUserCount"].toUInt(); qDebug() << numUsersToSync;
275   emit networksProgress(0, numNetsToSync);
276   emit channelsProgress(0, numChannelsToSync);
277   emit ircUsersProgress(0, numUsersToSync);
278
279   // create network objects
280   foreach(QVariant networkid, networkids) {
281     NetworkId netid = networkid.value<NetworkId>();
282     Network *net = new Network(netid, Client::instance());
283     netsToSync.insert(net);
284     connect(net, SIGNAL(initDone()), this, SLOT(networkInitDone()));
285     connect(net, SIGNAL(ircUserInitDone(IrcUser *)), this, SLOT(ircUserInitDone(IrcUser *)));
286     connect(net, SIGNAL(ircUserAdded(IrcUser *)), this, SLOT(ircUserAdded(IrcUser *)));
287     connect(net, SIGNAL(ircUserRemoved(QObject *)), this, SLOT(ircUserRemoved(QObject *)));
288     connect(net, SIGNAL(ircChannelInitDone(IrcChannel *)), this, SLOT(ircChannelInitDone(IrcChannel *)));
289     connect(net, SIGNAL(ircChannelAdded(IrcChannel *)), this, SLOT(ircChannelAdded(IrcChannel *)));
290     connect(net, SIGNAL(ircChannelRemoved(QObject *)), this, SLOT(ircChannelRemoved(QObject *)));
291     Client::addNetwork(net);
292   }
293   checkSyncState();
294 }
295
296 void ClientSyncer::networkInitDone() {
297   netsToSync.remove(sender());
298   emit networksProgress(numNetsToSync - netsToSync.count(), numNetsToSync);
299   checkSyncState();
300 }
301
302 void ClientSyncer::ircChannelInitDone(IrcChannel *chan) {
303   channelsToSync.remove(chan);
304   emit channelsProgress(numChannelsToSync - channelsToSync.count(), numChannelsToSync);
305   checkSyncState();
306 }
307
308 void ClientSyncer::ircChannelAdded(IrcChannel *chan) {
309   if(!chan->isInitialized()) {
310     channelsToSync.insert(chan);
311     numChannelsToSync++;
312     emit channelsProgress(numChannelsToSync - channelsToSync.count(), numChannelsToSync);
313     checkSyncState();
314   }
315 }
316
317 void ClientSyncer::ircChannelRemoved(QObject *chan) {
318   if(channelsToSync.contains(chan)) {
319     numChannelsToSync--;
320     channelsToSync.remove(chan);
321     emit channelsProgress(numChannelsToSync - channelsToSync.count(), numChannelsToSync);
322     checkSyncState();
323   }
324 }
325
326 void ClientSyncer::ircUserInitDone(IrcUser *user) {
327   usersToSync.remove(user);
328   emit ircUsersProgress(numUsersToSync - usersToSync.count(), numUsersToSync);
329   checkSyncState();
330 }
331
332 void ClientSyncer::ircUserAdded(IrcUser *user) {
333   if(!user->isInitialized()) {
334     usersToSync.insert(user);
335     numUsersToSync++;
336     emit ircUsersProgress(numUsersToSync - usersToSync.count(), numUsersToSync);
337     checkSyncState();
338   }
339 }
340
341 void ClientSyncer::ircUserRemoved(QObject *user) {
342   if(usersToSync.contains(user)) {
343     numUsersToSync--;
344     usersToSync.remove(user);
345     emit ircUsersProgress(numUsersToSync - usersToSync.count(), numUsersToSync);
346     checkSyncState();
347   }
348 }
349
350 void ClientSyncer::checkSyncState() {
351   if(usersToSync.count() + channelsToSync.count() + netsToSync.count() == 0) {
352     // done syncing!
353     /*
354     qDebug() << "done";
355     foreach(Network *net, _networks.values()) {
356       //disconnect(net, 0, this, SLOT(networkInitDone()));
357       //disconnect(net, 0, this, SLOT(ircUserInitDone(IrcUser *)));
358       //disconnect(net, 0, this, SLOT(ircUserAdded(IrcUser *)));
359       //disconnect(net, 0, this, SLOT(ircUserRemoved(QObject *)));
360       //disconnect(net, 0, this, SLOT(ircChannelInitDone(IrcChannel *)));
361       //disconnect(net, 0, this, SLOT(ircChannelAdded(IrcChannel *)));
362       //disconnect(net, 0, this, SLOT(ircChannelRemoved(QObject *)));
363       qDebug() << "disconnecting";
364       disconnect(net, SIGNAL(initDone()), this, SLOT(networkInitDone()));
365       disconnect(net, SIGNAL(ircUserInitDone(IrcUser *)), this, SLOT(ircUserInitDone(IrcUser *)));
366       disconnect(net, SIGNAL(ircUserAdded(IrcUser *)), this, SLOT(ircUserAdded(IrcUser *)));
367       disconnect(net, SIGNAL(ircUserRemoved(QObject *)), this, SLOT(ircUserRemoved(QObject *)));
368       disconnect(net, SIGNAL(ircChannelInitDone(IrcChannel *)), this, SLOT(ircChannelInitDone(IrcChannel *)));
369       disconnect(net, SIGNAL(ircChannelAdded(IrcChannel *)), this, SLOT(ircChannelAdded(IrcChannel *)));
370       disconnect(net, SIGNAL(ircChannelRemoved(QObject *)), this, SLOT(ircChannelRemoved(QObject *)));
371     }
372     */
373
374     Client::instance()->setSyncedToCore();
375     emit syncFinished();
376     //emit connected();
377     //emit connectionStateChanged(true);
378
379   }
380 }
381
382 #ifndef QT_NO_OPENSSL
383 void ClientSyncer::sslErrors(const QList<QSslError> &errors) {
384   qDebug() << "SSL Errors:";
385   foreach(QSslError err, errors)
386     qDebug() << "  " << err;
387
388   QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
389   if(socket)
390     socket->ignoreSslErrors();
391 }
392 #endif