properly saving the layout when using the internal core
[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 "identity.h"
29 #include "ircuser.h"
30 #include "ircchannel.h"
31 #include "network.h"
32 #include "networkmodel.h"
33 #include "quassel.h"
34 #include "signalproxy.h"
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 #ifdef HAVE_SSL
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"] = Quassel::buildInfo().fancyVersionString;
160   clientInit["ClientDate"] = Quassel::buildInfo().buildDate;
161   clientInit["ProtocolVersion"] = Quassel::buildInfo().protocolVersion;
162   clientInit["UseSsl"] = coreConnectionInfo["useSsl"];
163 #ifndef QT_NO_COMPRESS
164   clientInit["UseCompression"] = true;
165 #else
166   clientInit["UseCompression"] = false;
167 #endif
168
169   SignalProxy::writeDataToDevice(socket, clientInit);
170 }
171
172 void ClientSyncer::useInternalCore(AccountId internalAccountId) {
173   coreConnectionInfo["AccountId"] = QVariant::fromValue<AccountId>(internalAccountId);
174   emit startInternalCore();
175   emit connectToInternalCore(Client::instance()->signalProxy());
176 }
177
178 void ClientSyncer::coreSocketDisconnected() {
179   emit socketDisconnected();
180   Client::instance()->disconnectFromCore();
181
182   // FIXME handle disconnects gracefully in here as well!
183
184   coreConnectionInfo.clear();
185   netsToSync.clear();
186   blockSize = 0;
187   //restartPhaseNull();
188 }
189
190 void ClientSyncer::clientInitAck(const QVariantMap &msg) {
191   // Core has accepted our version info and sent its own. Let's see if we accept it as well...
192   uint ver = msg["ProtocolVersion"].toUInt();
193   if(ver < Quassel::buildInfo().clientNeedsProtocol) {
194     emit connectionError(tr("<b>The Quassel Core you are trying to connect to is too old!</b><br>"
195         "Need at least core/client protocol v%1 to connect.").arg(Quassel::buildInfo().clientNeedsProtocol));
196     disconnectFromCore();
197     return;
198   }
199   emit connectionMsg(msg["CoreInfo"].toString());
200
201 #ifdef HAVE_SSL
202   if(coreConnectionInfo["useSsl"].toBool()) {
203     if(msg["SupportSsl"].toBool()) {
204       QSslSocket *sslSocket = qobject_cast<QSslSocket *>(socket);
205       Q_ASSERT(sslSocket);
206       connect(sslSocket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
207       sslSocket->startClientEncryption();
208       emit encrypted(true);
209       Client::instance()->setSecuredConnection();
210     } else {
211       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."));
212       emit encrypted(false);
213       disconnectFromCore();
214       return;
215     }
216   }
217 #endif
218
219 #ifndef QT_NO_COMPRESS
220   if(msg["SupportsCompression"].toBool()) {
221     socket->setProperty("UseCompression", true);
222   }
223 #endif
224
225   if(!msg["Configured"].toBool()) {
226     // start wizard
227     emit startCoreSetup(msg["StorageBackends"].toList());
228   } else if(msg["LoginEnabled"].toBool()) {
229     emit startLogin();
230   }
231 }
232
233 void ClientSyncer::doCoreSetup(const QVariant &setupData) {
234   QVariantMap setup;
235   setup["MsgType"] = "CoreSetupData";
236   setup["SetupData"] = setupData;
237   SignalProxy::writeDataToDevice(socket, setup);
238 }
239
240 void ClientSyncer::loginToCore(const QString &user, const QString &passwd) {
241   emit connectionMsg(tr("Logging in..."));
242   QVariantMap clientLogin;
243   clientLogin["MsgType"] = "ClientLogin";
244   clientLogin["User"] = user;
245   clientLogin["Password"] = passwd;
246   SignalProxy::writeDataToDevice(socket, clientLogin);
247 }
248
249 void ClientSyncer::internalSessionStateReceived(const QVariant &packedState) {
250   QVariantMap state = packedState.toMap();
251   emit sessionProgress(1, 1);
252   Client::instance()->setConnectedToCore(coreConnectionInfo["AccountId"].value<AccountId>());
253   syncToCore(state);
254 }
255
256 void ClientSyncer::sessionStateReceived(const QVariantMap &state) {
257   emit sessionProgress(1, 1);
258   disconnect(this, SIGNAL(recvPartialItem(quint32, quint32)), this, SIGNAL(sessionProgress(quint32, quint32)));
259   disconnect(socket, 0, this, 0);  // rest of communication happens through SignalProxy
260   Client::instance()->setConnectedToCore(coreConnectionInfo["AccountId"].value<AccountId>(), socket);
261   syncToCore(state);
262 }
263
264 void ClientSyncer::syncToCore(const QVariantMap &sessionState) {
265   // create identities
266   foreach(QVariant vid, sessionState["Identities"].toList()) {
267     Client::instance()->coreIdentityCreated(vid.value<Identity>());
268   }
269
270   // create buffers
271   // FIXME: get rid of this crap
272   QVariantList bufferinfos = sessionState["BufferInfos"].toList();
273   NetworkModel *networkModel = Client::networkModel();
274   Q_ASSERT(networkModel);
275   foreach(QVariant vinfo, bufferinfos)
276     networkModel->bufferUpdated(vinfo.value<BufferInfo>());  // create BufferItems
277
278   QVariantList networkids = sessionState["NetworkIds"].toList();
279
280   // prepare sync progress thingys...
281   // FIXME: Care about removal of networks
282   numNetsToSync = networkids.count();
283   emit networksProgress(0, numNetsToSync);
284
285   // create network objects
286   foreach(QVariant networkid, networkids) {
287     NetworkId netid = networkid.value<NetworkId>();
288     if(Client::network(netid))
289       continue;
290     Network *net = new Network(netid, Client::instance());
291     netsToSync.insert(net);
292     connect(net, SIGNAL(initDone()), this, SLOT(networkInitDone()));
293     Client::addNetwork(net);
294   }
295   checkSyncState();
296 }
297
298 void ClientSyncer::networkInitDone() {
299   netsToSync.remove(sender());
300   emit networksProgress(numNetsToSync - netsToSync.count(), numNetsToSync);
301   checkSyncState();
302 }
303
304 void ClientSyncer::checkSyncState() {
305   if(netsToSync.isEmpty()) {
306     Client::instance()->setSyncedToCore();
307     emit syncFinished();
308   }
309 }
310
311 #ifdef HAVE_SSL
312 void ClientSyncer::sslErrors(const QList<QSslError> &errors) {
313   qDebug() << "SSL Errors:";
314   foreach(QSslError err, errors)
315     qDebug() << "  " << err;
316
317   QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
318   if(socket)
319     socket->ignoreSslErrors();
320 }
321 #endif