1 /***************************************************************************
2 * Copyright (C) 2005-08 by the Quassel IRC Team *
3 * devel@quassel-irc.org *
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. *
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. *
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 ***************************************************************************/
21 #include "clientsyncer.h"
23 #ifndef QT_NO_NETWORKPROXY
24 # include <QNetworkProxy>
30 #include "ircchannel.h"
32 #include "networkmodel.h"
34 #include "signalproxy.h"
40 ClientSyncer::ClientSyncer(QObject *parent)
46 connect(Client::signalProxy(), SIGNAL(disconnected()), this, SLOT(coreSocketDisconnected()));
49 connect(this, SIGNAL(connectToInternalCore(SignalProxy *)), Core::instance(), SLOT(setupInternalClientSession(SignalProxy *)));
50 connect(Core::instance(), SIGNAL(sessionState(const QVariant &)), this, SLOT(internalSessionStateReceived(const QVariant &)));
54 ClientSyncer::~ClientSyncer() {
57 void ClientSyncer::coreHasData() {
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."));
68 if(msg["MsgType"] == "ClientInitAck") {
70 } else if(msg["MsgType"] == "ClientInitReject") {
71 emit connectionError(msg["Error"].toString());
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)));
85 } else if(msg["MsgType"] == "SessionInit") {
86 sessionStateReceived(msg["SessionState"].toMap());
87 break; // this is definitively the last message we process here!
89 emit connectionError(tr("<b>Invalid data received from core!</b><br>Disconnecting."));
95 emit recvPartialItem(socket->bytesAvailable(), blockSize);
99 void ClientSyncer::coreSocketError(QAbstractSocket::SocketError) {
100 qDebug() << "coreSocketError" << socket << socket->errorString();
101 emit connectionError(socket->errorString());
102 socket->deleteLater();
105 void ClientSyncer::disconnectFromCore() {
106 if(socket) socket->close();
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!"));
117 socket->deleteLater();
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());
129 coreSocketConnected();
131 //clientMode = RemoteCore;
132 //emit coreConnectionMsg(tr("Connecting..."));
136 QSslSocket *sock = new QSslSocket(Client::instance());
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);
143 QTcpSocket *sock = new QTcpSocket(Client::instance());
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);
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());
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
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;
175 clientInit["UseCompression"] = false;
178 SignalProxy::writeDataToDevice(socket, clientInit);
181 void ClientSyncer::useInternalCore() {
182 emit connectToInternalCore(Client::instance()->signalProxy());
185 void ClientSyncer::coreSocketDisconnected() {
186 emit socketDisconnected();
187 Client::instance()->disconnectFromCore();
189 // FIXME handle disconnects gracefully in here as well!
191 coreConnectionInfo.clear();
194 //restartPhaseNull();
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();
206 emit connectionMsg(msg["CoreInfo"].toString());
209 if(coreConnectionInfo["useSsl"].toBool()) {
210 if(msg["SupportSsl"].toBool()) {
211 QSslSocket *sslSocket = qobject_cast<QSslSocket *>(socket);
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();
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();
226 #ifndef QT_NO_COMPRESS
227 if(msg["SupportsCompression"].toBool()) {
228 socket->setProperty("UseCompression", true);
232 if(!msg["Configured"].toBool()) {
234 emit startCoreSetup(msg["StorageBackends"].toList());
235 } else if(msg["LoginEnabled"].toBool()) {
240 void ClientSyncer::doCoreSetup(const QVariant &setupData) {
242 setup["MsgType"] = "CoreSetupData";
243 setup["SetupData"] = setupData;
244 SignalProxy::writeDataToDevice(socket, setup);
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);
256 void ClientSyncer::internalSessionStateReceived(const QVariant &packedState) {
257 QVariantMap state = packedState.toMap();
258 emit sessionProgress(1, 1);
259 // Client::instance()->setConnectedToCore(socket, AccountId());
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>());
272 void ClientSyncer::syncToCore(const QVariantMap &sessionState) {
275 foreach(QVariant vid, sessionState["Identities"].toList()) {
276 Client::instance()->coreIdentityCreated(vid.value<Identity>());
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
287 QVariantList networkids = sessionState["NetworkIds"].toList();
289 // prepare sync progress thingys...
290 // FIXME: Care about removal of networks
291 numNetsToSync = networkids.count();
292 emit networksProgress(0, numNetsToSync);
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);
305 void ClientSyncer::networkInitDone() {
306 netsToSync.remove(sender());
307 emit networksProgress(numNetsToSync - netsToSync.count(), numNetsToSync);
311 void ClientSyncer::checkSyncState() {
312 if(netsToSync.isEmpty()) {
313 Client::instance()->setSyncedToCore();
319 void ClientSyncer::sslErrors(const QList<QSslError> &errors) {
320 qDebug() << "SSL Errors:";
321 foreach(QSslError err, errors)
322 qDebug() << " " << err;
324 QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
326 socket->ignoreSslErrors();