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