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"
35 ClientSyncer::ClientSyncer(QObject *parent)
41 connect(Client::signalProxy(), SIGNAL(disconnected()), this, SLOT(coreSocketDisconnected()));
44 ClientSyncer::~ClientSyncer() {
47 void ClientSyncer::coreHasData() {
49 while(SignalProxy::readDataFromDevice(socket, blockSize, item)) {
50 emit recvPartialItem(1,1);
51 QVariantMap msg = item.toMap();
52 if(!msg.contains("MsgType")) {
53 // This core is way too old and does not even speak our init protocol...
54 emit connectionError(tr("The Quassel Core you try to connect to is too old! Please consider upgrading."));
58 if(msg["MsgType"] == "ClientInitAck") {
60 } else if(msg["MsgType"] == "ClientInitReject") {
61 emit connectionError(msg["Error"].toString());
64 } else if(msg["MsgType"] == "CoreSetupAck") {
65 emit coreSetupSuccess();
66 } else if(msg["MsgType"] == "CoreSetupReject") {
67 emit coreSetupFailed(msg["Error"].toString());
68 } else if(msg["MsgType"] == "ClientLoginReject") {
69 emit loginFailed(msg["Error"].toString());
70 } else if(msg["MsgType"] == "ClientLoginAck") {
71 // prevent multiple signal connections
72 disconnect(this, SIGNAL(recvPartialItem(quint32, quint32)), this, SIGNAL(sessionProgress(quint32, quint32)));
73 connect(this, SIGNAL(recvPartialItem(quint32, quint32)), this, SIGNAL(sessionProgress(quint32, quint32)));
75 } else if(msg["MsgType"] == "SessionInit") {
76 sessionStateReceived(msg["SessionState"].toMap());
77 break; // this is definitively the last message we process here!
79 emit connectionError(tr("<b>Invalid data received from core!</b><br>Disconnecting."));
85 emit recvPartialItem(socket->bytesAvailable(), blockSize);
89 void ClientSyncer::coreSocketError(QAbstractSocket::SocketError) {
90 qDebug() << "coreSocketError" << socket << socket->errorString();
91 emit connectionError(socket->errorString());
92 socket->deleteLater();
95 void ClientSyncer::disconnectFromCore() {
96 if(socket) socket->close();
99 void ClientSyncer::connectToCore(const QVariantMap &conn) {
100 // TODO implement SSL
101 coreConnectionInfo = conn;
102 //if(isConnected()) {
103 // emit coreConnectionError(tr("Already connected to Core!"));
107 socket->deleteLater();
110 if(conn["Host"].toString().isEmpty()) {
111 emit connectionError(tr("Internal connections not yet supported."));
112 return; // FIXME implement internal connections
113 //clientMode = LocalCore;
114 socket = new QBuffer(this);
115 connect(socket, SIGNAL(readyRead()), this, SLOT(coreHasData()));
116 socket->open(QIODevice::ReadWrite);
117 //QVariant state = connectToLocalCore(coreConnectionInfo["User"].toString(), coreConnectionInfo["Password"].toString());
119 coreSocketConnected();
121 //clientMode = RemoteCore;
122 //emit coreConnectionMsg(tr("Connecting..."));
126 QSslSocket *sock = new QSslSocket(Client::instance());
127 connect(sock, SIGNAL(encrypted()), this, SIGNAL(encrypted()));
129 if(conn["useSsl"].toBool()) {
130 emit connectionError(tr("<b>This client is built without SSL Support!</b><br />Disable the usage of SSL in the account settings."));
133 QTcpSocket *sock = new QTcpSocket(Client::instance());
135 #ifndef QT_NO_NETWORKPROXY
136 if(conn.contains("useProxy") && conn["useProxy"].toBool()) {
137 QNetworkProxy proxy((QNetworkProxy::ProxyType)conn["proxyType"].toInt(), conn["proxyHost"].toString(), conn["proxyPort"].toUInt(), conn["proxyUser"].toString(), conn["proxyPassword"].toString());
138 sock->setProxy(proxy);
142 connect(sock, SIGNAL(readyRead()), this, SLOT(coreHasData()));
143 connect(sock, SIGNAL(connected()), this, SLOT(coreSocketConnected()));
144 connect(sock, SIGNAL(disconnected()), this, SLOT(coreSocketDisconnected()));
145 connect(sock, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(coreSocketError(QAbstractSocket::SocketError)));
146 connect(sock, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SIGNAL(socketStateChanged(QAbstractSocket::SocketState)));
147 sock->connectToHost(conn["Host"].toString(), conn["Port"].toUInt());
151 void ClientSyncer::coreSocketConnected() {
152 //connect(this, SIGNAL(recvPartialItem(uint, uint)), this, SIGNAL(coreConnectionProgress(uint, uint)));
153 // Phase One: Send client info and wait for core info
155 //emit coreConnectionMsg(tr("Synchronizing to core..."));
156 QVariantMap clientInit;
157 clientInit["MsgType"] = "ClientInit";
158 clientInit["ClientVersion"] = Quassel::buildInfo().fancyVersionString;
159 clientInit["ClientDate"] = Quassel::buildInfo().buildDate;
160 clientInit["ProtocolVersion"] = Quassel::buildInfo().protocolVersion;
161 clientInit["UseSsl"] = coreConnectionInfo["useSsl"];
162 #ifndef QT_NO_COMPRESS
163 clientInit["UseCompression"] = true;
165 clientInit["UseCompression"] = false;
168 SignalProxy::writeDataToDevice(socket, clientInit);
171 void ClientSyncer::useInternalCore() {
172 AccountId internalAccountId;
174 CoreAccountSettings accountSettings;
175 QList<AccountId> knownAccounts = accountSettings.knownAccounts();
176 foreach(AccountId id, knownAccounts) {
179 QVariantMap data = accountSettings.retrieveAccountData(id);
180 if(data.contains("InternalAccount") && data["InternalAccount"].toBool()) {
181 internalAccountId = id;
186 if(!internalAccountId.isValid()) {
187 for(AccountId i = 1;; i++) {
188 if(!knownAccounts.contains(i)) {
189 internalAccountId = i;
194 data["InternalAccount"] = true;
195 accountSettings.storeAccountData(internalAccountId, data);
198 coreConnectionInfo["AccountId"] = QVariant::fromValue<AccountId>(internalAccountId);
199 emit startInternalCore(this);
200 emit connectToInternalCore(Client::instance()->signalProxy());
203 void ClientSyncer::coreSocketDisconnected() {
204 emit socketDisconnected();
205 Client::instance()->disconnectFromCore();
207 // FIXME handle disconnects gracefully in here as well!
209 coreConnectionInfo.clear();
212 //restartPhaseNull();
215 void ClientSyncer::clientInitAck(const QVariantMap &msg) {
216 // Core has accepted our version info and sent its own. Let's see if we accept it as well...
217 uint ver = msg["ProtocolVersion"].toUInt();
218 if(ver < Quassel::buildInfo().clientNeedsProtocol) {
219 emit connectionError(tr("<b>The Quassel Core you are trying to connect to is too old!</b><br>"
220 "Need at least core/client protocol v%1 to connect.").arg(Quassel::buildInfo().clientNeedsProtocol));
221 disconnectFromCore();
224 emit connectionMsg(msg["CoreInfo"].toString());
226 #ifndef QT_NO_COMPRESS
227 if(msg["SupportsCompression"].toBool()) {
228 socket->setProperty("UseCompression", true);
232 _coreMsgBuffer = msg;
234 if(coreConnectionInfo["useSsl"].toBool()) {
235 if(msg["SupportSsl"].toBool()) {
236 QSslSocket *sslSocket = qobject_cast<QSslSocket *>(socket);
238 connect(sslSocket, SIGNAL(encrypted()), this, SLOT(sslSocketEncrypted()));
239 connect(sslSocket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
241 sslSocket->startClientEncryption();
243 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."));
244 disconnectFromCore();
249 // if we use SSL we wait for the next step until every SSL warning has been cleared
253 void ClientSyncer::connectionReady() {
254 if(!_coreMsgBuffer["Configured"].toBool()) {
256 emit startCoreSetup(_coreMsgBuffer["StorageBackends"].toList());
257 } else if(_coreMsgBuffer["LoginEnabled"].toBool()) {
260 _coreMsgBuffer.clear();
261 resetWarningsHandler();
264 void ClientSyncer::doCoreSetup(const QVariant &setupData) {
266 setup["MsgType"] = "CoreSetupData";
267 setup["SetupData"] = setupData;
268 SignalProxy::writeDataToDevice(socket, setup);
271 void ClientSyncer::loginToCore(const QString &user, const QString &passwd) {
272 emit connectionMsg(tr("Logging in..."));
273 QVariantMap clientLogin;
274 clientLogin["MsgType"] = "ClientLogin";
275 clientLogin["User"] = user;
276 clientLogin["Password"] = passwd;
277 SignalProxy::writeDataToDevice(socket, clientLogin);
280 void ClientSyncer::internalSessionStateReceived(const QVariant &packedState) {
281 QVariantMap state = packedState.toMap();
282 emit sessionProgress(1, 1);
283 Client::instance()->setConnectedToCore(coreConnectionInfo["AccountId"].value<AccountId>());
287 void ClientSyncer::sessionStateReceived(const QVariantMap &state) {
288 emit sessionProgress(1, 1);
289 disconnect(this, SIGNAL(recvPartialItem(quint32, quint32)), this, SIGNAL(sessionProgress(quint32, quint32)));
290 disconnect(socket, 0, this, 0); // rest of communication happens through SignalProxy
291 Client::instance()->setConnectedToCore(coreConnectionInfo["AccountId"].value<AccountId>(), socket);
295 void ClientSyncer::syncToCore(const QVariantMap &sessionState) {
297 foreach(QVariant vid, sessionState["Identities"].toList()) {
298 Client::instance()->coreIdentityCreated(vid.value<Identity>());
302 // FIXME: get rid of this crap
303 QVariantList bufferinfos = sessionState["BufferInfos"].toList();
304 NetworkModel *networkModel = Client::networkModel();
305 Q_ASSERT(networkModel);
306 foreach(QVariant vinfo, bufferinfos)
307 networkModel->bufferUpdated(vinfo.value<BufferInfo>()); // create BufferItems
309 QVariantList networkids = sessionState["NetworkIds"].toList();
311 // prepare sync progress thingys...
312 // FIXME: Care about removal of networks
313 numNetsToSync = networkids.count();
314 emit networksProgress(0, numNetsToSync);
316 // create network objects
317 foreach(QVariant networkid, networkids) {
318 NetworkId netid = networkid.value<NetworkId>();
319 if(Client::network(netid))
321 Network *net = new Network(netid, Client::instance());
322 netsToSync.insert(net);
323 connect(net, SIGNAL(initDone()), this, SLOT(networkInitDone()));
324 Client::addNetwork(net);
329 void ClientSyncer::networkInitDone() {
330 netsToSync.remove(sender());
331 emit networksProgress(numNetsToSync - netsToSync.count(), numNetsToSync);
335 void ClientSyncer::checkSyncState() {
336 if(netsToSync.isEmpty()) {
337 Client::instance()->setSyncedToCore();
342 void ClientSyncer::setWarningsHandler(const char *slot) {
343 resetWarningsHandler();
344 connect(this, SIGNAL(handleIgnoreWarnings(bool)), this, slot);
347 void ClientSyncer::resetWarningsHandler() {
348 disconnect(this, SIGNAL(handleIgnoreWarnings(bool)), this, 0);
352 void ClientSyncer::ignoreSslWarnings(bool permanently) {
353 QSslSocket *sock = qobject_cast<QSslSocket *>(socket);
355 // ensure that a proper state is displayed and no longer a warning
356 emit socketStateChanged(sock->state());
360 qWarning() << Q_FUNC_INFO << "unable to save cert digest! Socket is either a nullptr or not a QSslSocket";
362 KnownHostsSettings().saveKnownHost(sock);
364 emit connectionMsg(_coreMsgBuffer["CoreInfo"].toString());
368 void ClientSyncer::sslSocketEncrypted() {
369 QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
371 QByteArray digest = socket->peerCertificate().digest();
375 void ClientSyncer::sslErrors(const QList<QSslError> &errors) {
376 QByteArray knownDigest;
377 QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
379 socket->ignoreSslErrors();
380 knownDigest = KnownHostsSettings().knownDigest(socket);
381 if(knownDigest == socket->peerCertificate().digest()) {
387 QStringList warnings;
389 foreach(QSslError err, errors)
390 warnings << err.errorString();
392 if(!knownDigest.isEmpty()) {
393 warnings << tr("Cert Digest changed! was: %1").arg(QString(prettyDigest(knownDigest)));
396 setWarningsHandler(SLOT(ignoreSslWarnings(bool)));
397 emit connectionWarnings(warnings);