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