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)
42 ClientSyncer::~ClientSyncer() {
45 void ClientSyncer::coreHasData() {
47 while(SignalProxy::readDataFromDevice(_socket, _blockSize, item)) {
48 emit recvPartialItem(1,1);
49 QVariantMap msg = item.toMap();
50 if(!msg.contains("MsgType")) {
51 // This core is way too old and does not even speak our init protocol...
52 emit connectionError(tr("The Quassel Core you try to connect to is too old! Please consider upgrading."));
56 if(msg["MsgType"] == "ClientInitAck") {
58 } else if(msg["MsgType"] == "ClientInitReject") {
59 emit connectionError(msg["Error"].toString());
62 } else if(msg["MsgType"] == "CoreSetupAck") {
63 emit coreSetupSuccess();
64 } else if(msg["MsgType"] == "CoreSetupReject") {
65 emit coreSetupFailed(msg["Error"].toString());
66 } else if(msg["MsgType"] == "ClientLoginReject") {
67 emit loginFailed(msg["Error"].toString());
68 } else if(msg["MsgType"] == "ClientLoginAck") {
69 // prevent multiple signal connections
70 disconnect(this, SIGNAL(recvPartialItem(quint32, quint32)), this, SIGNAL(sessionProgress(quint32, quint32)));
71 connect(this, SIGNAL(recvPartialItem(quint32, quint32)), this, SIGNAL(sessionProgress(quint32, quint32)));
73 } else if(msg["MsgType"] == "SessionInit") {
74 sessionStateReceived(msg["SessionState"].toMap());
75 break; // this is definitively the last message we process here!
77 emit connectionError(tr("<b>Invalid data received from core!</b><br>Disconnecting."));
83 emit recvPartialItem(_socket->bytesAvailable(), _blockSize);
87 void ClientSyncer::coreSocketError(QAbstractSocket::SocketError) {
88 qDebug() << "coreSocketError" << _socket << _socket->errorString();
89 emit connectionError(_socket->errorString());
93 void ClientSyncer::disconnectFromCore() {
99 void ClientSyncer::connectToCore(const QVariantMap &conn) {
101 coreConnectionInfo = conn;
103 if(conn["Host"].toString().isEmpty()) {
104 emit connectionError(tr("No Host to connect to specified."));
110 QSslSocket *sock = new QSslSocket(Client::instance());
112 if(conn["useSsl"].toBool()) {
113 emit connectionError(tr("<b>This client is built without SSL Support!</b><br />Disable the usage of SSL in the account settings."));
116 QTcpSocket *sock = new QTcpSocket(Client::instance());
119 #ifndef QT_NO_NETWORKPROXY
120 if(conn.contains("useProxy") && conn["useProxy"].toBool()) {
121 QNetworkProxy proxy((QNetworkProxy::ProxyType)conn["proxyType"].toInt(), conn["proxyHost"].toString(), conn["proxyPort"].toUInt(), conn["proxyUser"].toString(), conn["proxyPassword"].toString());
122 sock->setProxy(proxy);
127 connect(sock, SIGNAL(readyRead()), this, SLOT(coreHasData()));
128 connect(sock, SIGNAL(connected()), this, SLOT(coreSocketConnected()));
129 connect(sock, SIGNAL(disconnected()), this, SLOT(coreSocketDisconnected()));
130 connect(sock, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(coreSocketError(QAbstractSocket::SocketError)));
131 connect(sock, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SIGNAL(socketStateChanged(QAbstractSocket::SocketState)));
132 sock->connectToHost(conn["Host"].toString(), conn["Port"].toUInt());
135 void ClientSyncer::coreSocketConnected() {
136 //connect(this, SIGNAL(recvPartialItem(uint, uint)), this, SIGNAL(coreConnectionProgress(uint, uint)));
137 // Phase One: Send client info and wait for core info
139 //emit coreConnectionMsg(tr("Synchronizing to core..."));
140 QVariantMap clientInit;
141 clientInit["MsgType"] = "ClientInit";
142 clientInit["ClientVersion"] = Quassel::buildInfo().fancyVersionString;
143 clientInit["ClientDate"] = Quassel::buildInfo().buildDate;
144 clientInit["ProtocolVersion"] = Quassel::buildInfo().protocolVersion;
145 clientInit["UseSsl"] = coreConnectionInfo["useSsl"];
146 #ifndef QT_NO_COMPRESS
147 clientInit["UseCompression"] = true;
149 clientInit["UseCompression"] = false;
152 SignalProxy::writeDataToDevice(_socket, clientInit);
155 void ClientSyncer::useInternalCore() {
156 AccountId internalAccountId;
158 CoreAccountSettings accountSettings;
159 QList<AccountId> knownAccounts = accountSettings.knownAccounts();
160 foreach(AccountId id, knownAccounts) {
163 QVariantMap data = accountSettings.retrieveAccountData(id);
164 if(data.contains("InternalAccount") && data["InternalAccount"].toBool()) {
165 internalAccountId = id;
170 if(!internalAccountId.isValid()) {
171 for(AccountId i = 1;; i++) {
172 if(!knownAccounts.contains(i)) {
173 internalAccountId = i;
178 data["InternalAccount"] = true;
179 accountSettings.storeAccountData(internalAccountId, data);
182 coreConnectionInfo["AccountId"] = QVariant::fromValue<AccountId>(internalAccountId);
183 emit startInternalCore(this);
184 emit connectToInternalCore(Client::instance()->signalProxy());
187 void ClientSyncer::coreSocketDisconnected() {
188 emit socketDisconnected();
190 // FIXME handle disconnects gracefully
193 void ClientSyncer::clientInitAck(const QVariantMap &msg) {
194 // Core has accepted our version info and sent its own. Let's see if we accept it as well...
195 uint ver = msg["ProtocolVersion"].toUInt();
196 if(ver < Quassel::buildInfo().clientNeedsProtocol) {
197 emit connectionError(tr("<b>The Quassel Core you are trying to connect to is too old!</b><br>"
198 "Need at least core/client protocol v%1 to connect.").arg(Quassel::buildInfo().clientNeedsProtocol));
199 disconnectFromCore();
202 emit connectionMsg(msg["CoreInfo"].toString());
204 #ifndef QT_NO_COMPRESS
205 if(msg["SupportsCompression"].toBool()) {
206 _socket->setProperty("UseCompression", true);
210 _coreMsgBuffer = msg;
212 if(coreConnectionInfo["useSsl"].toBool()) {
213 if(msg["SupportSsl"].toBool()) {
214 QSslSocket *sslSocket = qobject_cast<QSslSocket *>(_socket);
216 connect(sslSocket, SIGNAL(encrypted()), this, SLOT(sslSocketEncrypted()));
217 connect(sslSocket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
219 sslSocket->startClientEncryption();
221 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."));
222 disconnectFromCore();
227 // if we use SSL we wait for the next step until every SSL warning has been cleared
231 void ClientSyncer::connectionReady() {
232 if(!_coreMsgBuffer["Configured"].toBool()) {
234 emit startCoreSetup(_coreMsgBuffer["StorageBackends"].toList());
235 } else if(_coreMsgBuffer["LoginEnabled"].toBool()) {
238 _coreMsgBuffer.clear();
239 resetWarningsHandler();
242 void ClientSyncer::doCoreSetup(const QVariant &setupData) {
244 setup["MsgType"] = "CoreSetupData";
245 setup["SetupData"] = setupData;
246 SignalProxy::writeDataToDevice(_socket, setup);
249 void ClientSyncer::loginToCore(const QString &user, const QString &passwd) {
250 emit connectionMsg(tr("Logging in..."));
251 QVariantMap clientLogin;
252 clientLogin["MsgType"] = "ClientLogin";
253 clientLogin["User"] = user;
254 clientLogin["Password"] = passwd;
255 SignalProxy::writeDataToDevice(_socket, clientLogin);
258 void ClientSyncer::internalSessionStateReceived(const QVariant &packedState) {
259 QVariantMap state = packedState.toMap();
260 emit sessionProgress(1, 1);
261 Client::instance()->setConnectedToCore(coreConnectionInfo["AccountId"].value<AccountId>());
265 void ClientSyncer::sessionStateReceived(const QVariantMap &state) {
266 emit sessionProgress(1, 1);
267 disconnect(this, SIGNAL(recvPartialItem(quint32, quint32)), this, SIGNAL(sessionProgress(quint32, quint32)));
269 // rest of communication happens through SignalProxy...
270 disconnect(_socket, 0, this, 0);
271 // ... but we still want to be notified about errors...
272 connect(_socket, SIGNAL(disconnected()), this, SLOT(coreSocketDisconnected()));
273 connect(_socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(coreSocketError(QAbstractSocket::SocketError)));
275 Client::instance()->setConnectedToCore(coreConnectionInfo["AccountId"].value<AccountId>(), _socket);
279 void ClientSyncer::syncToCore(const QVariantMap &sessionState) {
281 foreach(QVariant vid, sessionState["Identities"].toList()) {
282 Client::instance()->coreIdentityCreated(vid.value<Identity>());
286 // FIXME: get rid of this crap
287 QVariantList bufferinfos = sessionState["BufferInfos"].toList();
288 NetworkModel *networkModel = Client::networkModel();
289 Q_ASSERT(networkModel);
290 foreach(QVariant vinfo, bufferinfos)
291 networkModel->bufferUpdated(vinfo.value<BufferInfo>()); // create BufferItems
293 QVariantList networkids = sessionState["NetworkIds"].toList();
295 // prepare sync progress thingys...
296 // FIXME: Care about removal of networks
297 numNetsToSync = networkids.count();
298 emit networksProgress(0, numNetsToSync);
300 // create network objects
301 foreach(QVariant networkid, networkids) {
302 NetworkId netid = networkid.value<NetworkId>();
303 if(Client::network(netid))
305 Network *net = new Network(netid, Client::instance());
306 netsToSync.insert(net);
307 connect(net, SIGNAL(initDone()), this, SLOT(networkInitDone()));
308 Client::addNetwork(net);
313 void ClientSyncer::networkInitDone() {
314 netsToSync.remove(sender());
315 emit networksProgress(numNetsToSync - netsToSync.count(), numNetsToSync);
319 void ClientSyncer::checkSyncState() {
320 if(netsToSync.isEmpty()) {
321 Client::instance()->setSyncedToCore();
326 void ClientSyncer::setWarningsHandler(const char *slot) {
327 resetWarningsHandler();
328 connect(this, SIGNAL(handleIgnoreWarnings(bool)), this, slot);
331 void ClientSyncer::resetWarningsHandler() {
332 disconnect(this, SIGNAL(handleIgnoreWarnings(bool)), this, 0);
335 void ClientSyncer::resetConnection() {
337 disconnect(_socket, 0, this, 0);
338 _socket->deleteLater();
343 coreConnectionInfo.clear();
344 _coreMsgBuffer.clear();
351 void ClientSyncer::ignoreSslWarnings(bool permanently) {
352 QSslSocket *sock = qobject_cast<QSslSocket *>(_socket);
354 // ensure that a proper state is displayed and no longer a warning
355 emit socketStateChanged(sock->state());
359 qWarning() << Q_FUNC_INFO << "unable to save cert digest! Socket is either a nullptr or not a QSslSocket";
361 KnownHostsSettings().saveKnownHost(sock);
363 emit connectionMsg(_coreMsgBuffer["CoreInfo"].toString());
367 void ClientSyncer::sslSocketEncrypted() {
368 QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
371 // if there were sslErrors we already had extensive error handling
372 // no need to check for a digest change again.
373 if(!socket->sslErrors().isEmpty())
376 QByteArray knownDigest = KnownHostsSettings().knownDigest(socket);
377 if(knownDigest == socket->peerCertificate().digest()) {
382 QStringList warnings;
383 if(!knownDigest.isEmpty()) {
384 warnings << tr("Cert Digest changed! was: %1").arg(QString(prettyDigest(knownDigest)));
387 setWarningsHandler(SLOT(ignoreSslWarnings(bool)));
388 emit connectionWarnings(warnings);
391 void ClientSyncer::sslErrors(const QList<QSslError> &errors) {
392 QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
395 socket->ignoreSslErrors();
397 QByteArray knownDigest = KnownHostsSettings().knownDigest(socket);
398 if(knownDigest == socket->peerCertificate().digest()) {
403 QStringList warnings;
405 foreach(QSslError err, errors)
406 warnings << err.errorString();
408 if(!knownDigest.isEmpty()) {
409 warnings << tr("Cert Digest changed! was: %1").arg(QString(prettyDigest(knownDigest)));
412 setWarningsHandler(SLOT(ignoreSslWarnings(bool)));
413 emit connectionWarnings(warnings);