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