1 /***************************************************************************
2 * Copyright (C) 2005-09 by the Quassel Project *
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 "networkmodel.h"
32 #include "signalproxy.h"
34 ClientSyncer::ClientSyncer(QObject *parent)
40 connect(Client::signalProxy(), SIGNAL(disconnected()), this, SLOT(coreSocketDisconnected()));
43 ClientSyncer::~ClientSyncer() {
46 void ClientSyncer::coreHasData() {
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."));
57 if(msg["MsgType"] == "ClientInitAck") {
59 } else if(msg["MsgType"] == "ClientInitReject") {
60 emit connectionError(msg["Error"].toString());
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)));
74 } else if(msg["MsgType"] == "SessionInit") {
75 sessionStateReceived(msg["SessionState"].toMap());
76 break; // this is definitively the last message we process here!
78 emit connectionError(tr("<b>Invalid data received from core!</b><br>Disconnecting."));
84 emit recvPartialItem(socket->bytesAvailable(), blockSize);
88 void ClientSyncer::coreSocketError(QAbstractSocket::SocketError) {
89 qDebug() << "coreSocketError" << socket << socket->errorString();
90 emit connectionError(socket->errorString());
91 socket->deleteLater();
94 void ClientSyncer::disconnectFromCore() {
95 if(socket) socket->close();
98 void ClientSyncer::connectToCore(const QVariantMap &conn) {
100 coreConnectionInfo = conn;
101 //if(isConnected()) {
102 // emit coreConnectionError(tr("Already connected to Core!"));
106 socket->deleteLater();
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());
118 coreSocketConnected();
120 //clientMode = RemoteCore;
121 //emit coreConnectionMsg(tr("Connecting..."));
125 QSslSocket *sock = new QSslSocket(Client::instance());
126 connect(sock, SIGNAL(encrypted()), this, SIGNAL(encrypted()));
128 if(conn["useSsl"].toBool()) {
129 emit connectionError(tr("<b>This client is built without SSL Support!</b><br />Disable the usage of SSL in the account settings."));
132 QTcpSocket *sock = new QTcpSocket(Client::instance());
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);
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());
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
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;
164 clientInit["UseCompression"] = false;
167 SignalProxy::writeDataToDevice(socket, clientInit);
170 void ClientSyncer::useInternalCore() {
171 AccountId internalAccountId;
173 CoreAccountSettings accountSettings;
174 QList<AccountId> knownAccounts = accountSettings.knownAccounts();
175 foreach(AccountId id, knownAccounts) {
178 QVariantMap data = accountSettings.retrieveAccountData(id);
179 if(data.contains("InternalAccount") && data["InternalAccount"].toBool()) {
180 internalAccountId = id;
185 if(!internalAccountId.isValid()) {
186 for(AccountId i = 1;; i++) {
187 if(!knownAccounts.contains(i)) {
188 internalAccountId = i;
193 data["InternalAccount"] = true;
194 accountSettings.storeAccountData(internalAccountId, data);
197 coreConnectionInfo["AccountId"] = QVariant::fromValue<AccountId>(internalAccountId);
198 emit startInternalCore(this);
199 emit connectToInternalCore(Client::instance()->signalProxy());
202 void ClientSyncer::coreSocketDisconnected() {
203 emit socketDisconnected();
204 Client::instance()->disconnectFromCore();
206 // FIXME handle disconnects gracefully in here as well!
208 coreConnectionInfo.clear();
211 //restartPhaseNull();
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();
223 emit connectionMsg(msg["CoreInfo"].toString());
225 #ifndef QT_NO_COMPRESS
226 if(msg["SupportsCompression"].toBool()) {
227 socket->setProperty("UseCompression", true);
231 _coreMsgBuffer = msg;
233 if(coreConnectionInfo["useSsl"].toBool()) {
234 if(msg["SupportSsl"].toBool()) {
235 QSslSocket *sslSocket = qobject_cast<QSslSocket *>(socket);
237 connect(sslSocket, SIGNAL(encrypted()), this, SLOT(sslSocketEncrypted()));
238 connect(sslSocket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
240 sslSocket->startClientEncryption();
242 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."));
243 disconnectFromCore();
248 // if we use SSL we wait for the next step until every SSL warning has been cleared
252 void ClientSyncer::connectionReady() {
253 if(!_coreMsgBuffer["Configured"].toBool()) {
255 emit startCoreSetup(_coreMsgBuffer["StorageBackends"].toList());
256 } else if(_coreMsgBuffer["LoginEnabled"].toBool()) {
259 _coreMsgBuffer.clear();
260 resetWarningsHandler();
263 void ClientSyncer::doCoreSetup(const QVariant &setupData) {
265 setup["MsgType"] = "CoreSetupData";
266 setup["SetupData"] = setupData;
267 SignalProxy::writeDataToDevice(socket, setup);
270 void ClientSyncer::loginToCore(const QString &user, const QString &passwd) {
271 emit connectionMsg(tr("Logging in..."));
272 QVariantMap clientLogin;
273 clientLogin["MsgType"] = "ClientLogin";
274 clientLogin["User"] = user;
275 clientLogin["Password"] = passwd;
276 SignalProxy::writeDataToDevice(socket, clientLogin);
279 void ClientSyncer::internalSessionStateReceived(const QVariant &packedState) {
280 QVariantMap state = packedState.toMap();
281 emit sessionProgress(1, 1);
282 Client::instance()->setConnectedToCore(coreConnectionInfo["AccountId"].value<AccountId>());
286 void ClientSyncer::sessionStateReceived(const QVariantMap &state) {
287 emit sessionProgress(1, 1);
288 disconnect(this, SIGNAL(recvPartialItem(quint32, quint32)), this, SIGNAL(sessionProgress(quint32, quint32)));
289 disconnect(socket, 0, this, 0); // rest of communication happens through SignalProxy
290 Client::instance()->setConnectedToCore(coreConnectionInfo["AccountId"].value<AccountId>(), socket);
294 void ClientSyncer::syncToCore(const QVariantMap &sessionState) {
296 foreach(QVariant vid, sessionState["Identities"].toList()) {
297 Client::instance()->coreIdentityCreated(vid.value<Identity>());
301 // FIXME: get rid of this crap
302 QVariantList bufferinfos = sessionState["BufferInfos"].toList();
303 NetworkModel *networkModel = Client::networkModel();
304 Q_ASSERT(networkModel);
305 foreach(QVariant vinfo, bufferinfos)
306 networkModel->bufferUpdated(vinfo.value<BufferInfo>()); // create BufferItems
308 QVariantList networkids = sessionState["NetworkIds"].toList();
310 // prepare sync progress thingys...
311 // FIXME: Care about removal of networks
312 numNetsToSync = networkids.count();
313 emit networksProgress(0, numNetsToSync);
315 // create network objects
316 foreach(QVariant networkid, networkids) {
317 NetworkId netid = networkid.value<NetworkId>();
318 if(Client::network(netid))
320 Network *net = new Network(netid, Client::instance());
321 netsToSync.insert(net);
322 connect(net, SIGNAL(initDone()), this, SLOT(networkInitDone()));
323 Client::addNetwork(net);
328 void ClientSyncer::networkInitDone() {
329 netsToSync.remove(sender());
330 emit networksProgress(numNetsToSync - netsToSync.count(), numNetsToSync);
334 void ClientSyncer::checkSyncState() {
335 if(netsToSync.isEmpty()) {
336 Client::instance()->setSyncedToCore();
341 void ClientSyncer::setWarningsHandler(const char *slot) {
342 resetWarningsHandler();
343 connect(this, SIGNAL(handleIgnoreWarnings(bool)), this, slot);
346 void ClientSyncer::resetWarningsHandler() {
347 disconnect(this, SIGNAL(handleIgnoreWarnings(bool)), this, 0);
351 void ClientSyncer::ignoreSslWarnings(bool permanently) {
352 QAbstractSocket *sock = qobject_cast<QAbstractSocket *>(socket);
354 // ensure that a proper state is displayed and no longer a warning
355 emit socketStateChanged(sock->state());
357 emit connectionMsg(_coreMsgBuffer["CoreInfo"].toString());
361 void ClientSyncer::sslSocketEncrypted() {
362 QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
364 QByteArray digest = socket->peerCertificate().digest();
368 void ClientSyncer::sslErrors(const QList<QSslError> &errors) {
369 QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
371 socket->ignoreSslErrors();
374 QStringList warnings;
375 foreach(QSslError err, errors)
376 warnings << err.errorString();
378 setWarningsHandler(SLOT(ignoreSslWarnings(bool)));
379 emit connectionWarnings(warnings);