51b51f17880ee859b975120899d8195776d93c08
[quassel.git] / src / client / clientsyncer.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-09 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 "clientsyncer.h"
22
23 #ifndef QT_NO_NETWORKPROXY
24 #  include <QNetworkProxy>
25 #endif
26
27 #include "client.h"
28 #include "identity.h"
29 #include "network.h"
30 #include "networkmodel.h"
31 #include "quassel.h"
32 #include "signalproxy.h"
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 #ifdef HAVE_SSL
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 #ifndef QT_NO_NETWORKPROXY
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 #endif
140     socket = sock;
141     connect(sock, SIGNAL(readyRead()), this, SLOT(coreHasData()));
142     connect(sock, SIGNAL(connected()), this, SLOT(coreSocketConnected()));
143     connect(sock, SIGNAL(disconnected()), this, SLOT(coreSocketDisconnected()));
144     connect(sock, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(coreSocketError(QAbstractSocket::SocketError)));
145     connect(sock, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SIGNAL(socketStateChanged(QAbstractSocket::SocketState)));
146     sock->connectToHost(conn["Host"].toString(), conn["Port"].toUInt());
147   }
148 }
149
150 void ClientSyncer::coreSocketConnected() {
151   //connect(this, SIGNAL(recvPartialItem(uint, uint)), this, SIGNAL(coreConnectionProgress(uint, uint)));
152   // Phase One: Send client info and wait for core info
153
154   //emit coreConnectionMsg(tr("Synchronizing to core..."));
155   QVariantMap clientInit;
156   clientInit["MsgType"] = "ClientInit";
157   clientInit["ClientVersion"] = Quassel::buildInfo().fancyVersionString;
158   clientInit["ClientDate"] = Quassel::buildInfo().buildDate;
159   clientInit["ProtocolVersion"] = Quassel::buildInfo().protocolVersion;
160   clientInit["UseSsl"] = coreConnectionInfo["useSsl"];
161 #ifndef QT_NO_COMPRESS
162   clientInit["UseCompression"] = true;
163 #else
164   clientInit["UseCompression"] = false;
165 #endif
166
167   SignalProxy::writeDataToDevice(socket, clientInit);
168 }
169
170 void ClientSyncer::useInternalCore() {
171   AccountId internalAccountId;
172
173   CoreAccountSettings accountSettings;
174   QList<AccountId> knownAccounts = accountSettings.knownAccounts();
175   foreach(AccountId id, knownAccounts) {
176     if(!id.isValid())
177       continue;
178     QVariantMap data = accountSettings.retrieveAccountData(id);
179     if(data.contains("InternalAccount") && data["InternalAccount"].toBool()) {
180       internalAccountId = id;
181       break;
182     }
183   }
184
185   if(!internalAccountId.isValid()) {
186     for(AccountId i = 1;; i++) {
187       if(!knownAccounts.contains(i)) {
188         internalAccountId = i;
189         break;
190       }
191     }
192     QVariantMap data;
193     data["InternalAccount"] = true;
194     accountSettings.storeAccountData(internalAccountId, data);
195   }
196
197   coreConnectionInfo["AccountId"] = QVariant::fromValue<AccountId>(internalAccountId);
198   emit startInternalCore(this);
199   emit connectToInternalCore(Client::instance()->signalProxy());
200 }
201
202 void ClientSyncer::coreSocketDisconnected() {
203   emit socketDisconnected();
204   Client::instance()->disconnectFromCore();
205
206   // FIXME handle disconnects gracefully in here as well!
207
208   coreConnectionInfo.clear();
209   netsToSync.clear();
210   blockSize = 0;
211   //restartPhaseNull();
212 }
213
214 void ClientSyncer::clientInitAck(const QVariantMap &msg) {
215   // Core has accepted our version info and sent its own. Let's see if we accept it as well...
216   uint ver = msg["ProtocolVersion"].toUInt();
217   if(ver < Quassel::buildInfo().clientNeedsProtocol) {
218     emit connectionError(tr("<b>The Quassel Core you are trying to connect to is too old!</b><br>"
219         "Need at least core/client protocol v%1 to connect.").arg(Quassel::buildInfo().clientNeedsProtocol));
220     disconnectFromCore();
221     return;
222   }
223   emit connectionMsg(msg["CoreInfo"].toString());
224
225 #ifdef HAVE_SSL
226   if(coreConnectionInfo["useSsl"].toBool()) {
227     if(msg["SupportSsl"].toBool()) {
228       QSslSocket *sslSocket = qobject_cast<QSslSocket *>(socket);
229       Q_ASSERT(sslSocket);
230       connect(sslSocket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
231       sslSocket->startClientEncryption();
232       emit encrypted(true);
233       Client::instance()->setSecuredConnection();
234     } else {
235       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."));
236       emit encrypted(false);
237       disconnectFromCore();
238       return;
239     }
240   }
241 #endif
242
243 #ifndef QT_NO_COMPRESS
244   if(msg["SupportsCompression"].toBool()) {
245     socket->setProperty("UseCompression", true);
246   }
247 #endif
248
249   if(!msg["Configured"].toBool()) {
250     // start wizard
251     emit startCoreSetup(msg["StorageBackends"].toList());
252   } else if(msg["LoginEnabled"].toBool()) {
253     emit startLogin();
254   }
255 }
256
257 void ClientSyncer::doCoreSetup(const QVariant &setupData) {
258   QVariantMap setup;
259   setup["MsgType"] = "CoreSetupData";
260   setup["SetupData"] = setupData;
261   SignalProxy::writeDataToDevice(socket, setup);
262 }
263
264 void ClientSyncer::loginToCore(const QString &user, const QString &passwd) {
265   emit connectionMsg(tr("Logging in..."));
266   QVariantMap clientLogin;
267   clientLogin["MsgType"] = "ClientLogin";
268   clientLogin["User"] = user;
269   clientLogin["Password"] = passwd;
270   SignalProxy::writeDataToDevice(socket, clientLogin);
271 }
272
273 void ClientSyncer::internalSessionStateReceived(const QVariant &packedState) {
274   QVariantMap state = packedState.toMap();
275   emit sessionProgress(1, 1);
276   Client::instance()->setConnectedToCore(coreConnectionInfo["AccountId"].value<AccountId>());
277   syncToCore(state);
278 }
279
280 void ClientSyncer::sessionStateReceived(const QVariantMap &state) {
281   emit sessionProgress(1, 1);
282   disconnect(this, SIGNAL(recvPartialItem(quint32, quint32)), this, SIGNAL(sessionProgress(quint32, quint32)));
283   disconnect(socket, 0, this, 0);  // rest of communication happens through SignalProxy
284   Client::instance()->setConnectedToCore(coreConnectionInfo["AccountId"].value<AccountId>(), socket);
285   syncToCore(state);
286 }
287
288 void ClientSyncer::syncToCore(const QVariantMap &sessionState) {
289   // create identities
290   foreach(QVariant vid, sessionState["Identities"].toList()) {
291     Client::instance()->coreIdentityCreated(vid.value<Identity>());
292   }
293
294   // create buffers
295   // FIXME: get rid of this crap
296   QVariantList bufferinfos = sessionState["BufferInfos"].toList();
297   NetworkModel *networkModel = Client::networkModel();
298   Q_ASSERT(networkModel);
299   foreach(QVariant vinfo, bufferinfos)
300     networkModel->bufferUpdated(vinfo.value<BufferInfo>());  // create BufferItems
301
302   QVariantList networkids = sessionState["NetworkIds"].toList();
303
304   // prepare sync progress thingys...
305   // FIXME: Care about removal of networks
306   numNetsToSync = networkids.count();
307   emit networksProgress(0, numNetsToSync);
308
309   // create network objects
310   foreach(QVariant networkid, networkids) {
311     NetworkId netid = networkid.value<NetworkId>();
312     if(Client::network(netid))
313       continue;
314     Network *net = new Network(netid, Client::instance());
315     netsToSync.insert(net);
316     connect(net, SIGNAL(initDone()), this, SLOT(networkInitDone()));
317     Client::addNetwork(net);
318   }
319   checkSyncState();
320 }
321
322 void ClientSyncer::networkInitDone() {
323   netsToSync.remove(sender());
324   emit networksProgress(numNetsToSync - netsToSync.count(), numNetsToSync);
325   checkSyncState();
326 }
327
328 void ClientSyncer::checkSyncState() {
329   if(netsToSync.isEmpty()) {
330     Client::instance()->setSyncedToCore();
331     emit syncFinished();
332   }
333 }
334
335 #ifdef HAVE_SSL
336 void ClientSyncer::sslErrors(const QList<QSslError> &errors) {
337   qDebug() << "SSL Errors:";
338   foreach(QSslError err, errors)
339     qDebug() << "  " << err;
340
341   QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
342   if(socket)
343     socket->ignoreSslErrors();
344 }
345 #endif