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