You can now add a core to the known hosts.
[quassel.git] / src / client / clientsyncer.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-09 by the Quassel Project                          *
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 "identity.h"
29 #include "network.h"
30 #include "networkmodel.h"
31 #include "quassel.h"
32 #include "signalproxy.h"
33 #include "util.h"
34
35 ClientSyncer::ClientSyncer(QObject *parent)
36   : QObject(parent)
37 {
38   socket = 0;
39   blockSize = 0;
40
41   connect(Client::signalProxy(), SIGNAL(disconnected()), this, SLOT(coreSocketDisconnected()));
42 }
43
44 ClientSyncer::~ClientSyncer() {
45 }
46
47 void ClientSyncer::coreHasData() {
48   QVariant item;
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."));
55       disconnectFromCore();
56       return;
57     }
58     if(msg["MsgType"] == "ClientInitAck") {
59       clientInitAck(msg);
60     } else if(msg["MsgType"] == "ClientInitReject") {
61       emit connectionError(msg["Error"].toString());
62       disconnectFromCore();
63       return;
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)));
74       emit loginSuccess();
75     } else if(msg["MsgType"] == "SessionInit") {
76       sessionStateReceived(msg["SessionState"].toMap());
77       break; // this is definitively the last message we process here!
78     } else {
79       emit connectionError(tr("<b>Invalid data received from core!</b><br>Disconnecting."));
80       disconnectFromCore();
81       return;
82     }
83   }
84   if(blockSize > 0) {
85     emit recvPartialItem(socket->bytesAvailable(), blockSize);
86   }
87 }
88
89 void ClientSyncer::coreSocketError(QAbstractSocket::SocketError) {
90   qDebug() << "coreSocketError" << socket << socket->errorString();
91   emit connectionError(socket->errorString());
92   socket->deleteLater();
93 }
94
95 void ClientSyncer::disconnectFromCore() {
96   if(socket) socket->close();
97 }
98
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!"));
104   //  return;
105   // }
106   if(socket != 0) {
107     socket->deleteLater();
108     socket = 0;
109   }
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());
118     //syncToCore(state);
119     coreSocketConnected();
120   } else {
121     //clientMode = RemoteCore;
122     //emit coreConnectionMsg(tr("Connecting..."));
123     Q_ASSERT(!socket);
124
125 #ifdef HAVE_SSL
126     QSslSocket *sock = new QSslSocket(Client::instance());
127     connect(sock, SIGNAL(encrypted()), this, SIGNAL(encrypted()));
128 #else
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."));
131         return;
132     }
133     QTcpSocket *sock = new QTcpSocket(Client::instance());
134 #endif
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);
139     }
140 #endif
141     socket = sock;
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());
148   }
149 }
150
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
154
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;
164 #else
165   clientInit["UseCompression"] = false;
166 #endif
167
168   SignalProxy::writeDataToDevice(socket, clientInit);
169 }
170
171 void ClientSyncer::useInternalCore() {
172   AccountId internalAccountId;
173
174   CoreAccountSettings accountSettings;
175   QList<AccountId> knownAccounts = accountSettings.knownAccounts();
176   foreach(AccountId id, knownAccounts) {
177     if(!id.isValid())
178       continue;
179     QVariantMap data = accountSettings.retrieveAccountData(id);
180     if(data.contains("InternalAccount") && data["InternalAccount"].toBool()) {
181       internalAccountId = id;
182       break;
183     }
184   }
185
186   if(!internalAccountId.isValid()) {
187     for(AccountId i = 1;; i++) {
188       if(!knownAccounts.contains(i)) {
189         internalAccountId = i;
190         break;
191       }
192     }
193     QVariantMap data;
194     data["InternalAccount"] = true;
195     accountSettings.storeAccountData(internalAccountId, data);
196   }
197
198   coreConnectionInfo["AccountId"] = QVariant::fromValue<AccountId>(internalAccountId);
199   emit startInternalCore(this);
200   emit connectToInternalCore(Client::instance()->signalProxy());
201 }
202
203 void ClientSyncer::coreSocketDisconnected() {
204   emit socketDisconnected();
205   Client::instance()->disconnectFromCore();
206
207   // FIXME handle disconnects gracefully in here as well!
208
209   coreConnectionInfo.clear();
210   netsToSync.clear();
211   blockSize = 0;
212   //restartPhaseNull();
213 }
214
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();
222     return;
223   }
224   emit connectionMsg(msg["CoreInfo"].toString());
225
226 #ifndef QT_NO_COMPRESS
227   if(msg["SupportsCompression"].toBool()) {
228     socket->setProperty("UseCompression", true);
229   }
230 #endif
231
232   _coreMsgBuffer = msg;
233 #ifdef HAVE_SSL
234   if(coreConnectionInfo["useSsl"].toBool()) {
235     if(msg["SupportSsl"].toBool()) {
236       QSslSocket *sslSocket = qobject_cast<QSslSocket *>(socket);
237       Q_ASSERT(sslSocket);
238       connect(sslSocket, SIGNAL(encrypted()), this, SLOT(sslSocketEncrypted()));
239       connect(sslSocket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
240
241       sslSocket->startClientEncryption();
242     } else {
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();
245     }
246     return;
247   }
248 #endif
249   // if we use SSL we wait for the next step until every SSL warning has been cleared
250   connectionReady();
251 }
252
253 void ClientSyncer::connectionReady() {
254   if(!_coreMsgBuffer["Configured"].toBool()) {
255     // start wizard
256     emit startCoreSetup(_coreMsgBuffer["StorageBackends"].toList());
257   } else if(_coreMsgBuffer["LoginEnabled"].toBool()) {
258     emit startLogin();
259   }
260   _coreMsgBuffer.clear();
261   resetWarningsHandler();
262 }
263
264 void ClientSyncer::doCoreSetup(const QVariant &setupData) {
265   QVariantMap setup;
266   setup["MsgType"] = "CoreSetupData";
267   setup["SetupData"] = setupData;
268   SignalProxy::writeDataToDevice(socket, setup);
269 }
270
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);
278 }
279
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>());
284   syncToCore(state);
285 }
286
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);
292   syncToCore(state);
293 }
294
295 void ClientSyncer::syncToCore(const QVariantMap &sessionState) {
296   // create identities
297   foreach(QVariant vid, sessionState["Identities"].toList()) {
298     Client::instance()->coreIdentityCreated(vid.value<Identity>());
299   }
300
301   // create buffers
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
308
309   QVariantList networkids = sessionState["NetworkIds"].toList();
310
311   // prepare sync progress thingys...
312   // FIXME: Care about removal of networks
313   numNetsToSync = networkids.count();
314   emit networksProgress(0, numNetsToSync);
315
316   // create network objects
317   foreach(QVariant networkid, networkids) {
318     NetworkId netid = networkid.value<NetworkId>();
319     if(Client::network(netid))
320       continue;
321     Network *net = new Network(netid, Client::instance());
322     netsToSync.insert(net);
323     connect(net, SIGNAL(initDone()), this, SLOT(networkInitDone()));
324     Client::addNetwork(net);
325   }
326   checkSyncState();
327 }
328
329 void ClientSyncer::networkInitDone() {
330   netsToSync.remove(sender());
331   emit networksProgress(numNetsToSync - netsToSync.count(), numNetsToSync);
332   checkSyncState();
333 }
334
335 void ClientSyncer::checkSyncState() {
336   if(netsToSync.isEmpty()) {
337     Client::instance()->setSyncedToCore();
338     emit syncFinished();
339   }
340 }
341
342 void ClientSyncer::setWarningsHandler(const char *slot) {
343   resetWarningsHandler();
344   connect(this, SIGNAL(handleIgnoreWarnings(bool)), this, slot);
345 }
346
347 void ClientSyncer::resetWarningsHandler() {
348   disconnect(this, SIGNAL(handleIgnoreWarnings(bool)), this, 0);
349 }
350
351 #ifdef HAVE_SSL
352 void ClientSyncer::ignoreSslWarnings(bool permanently) {
353   QSslSocket *sock = qobject_cast<QSslSocket *>(socket);
354   if(sock) {
355     // ensure that a proper state is displayed and no longer a warning
356     emit socketStateChanged(sock->state());
357   }
358   if(permanently) {
359     if(!sock)
360       qWarning() << Q_FUNC_INFO << "unable to save cert digest! Socket is either a nullptr or not a QSslSocket";
361     else
362       KnownHostsSettings().saveKnownHost(sock);
363   }
364   emit connectionMsg(_coreMsgBuffer["CoreInfo"].toString());
365   connectionReady();
366 }
367
368 void ClientSyncer::sslSocketEncrypted() {
369   QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
370   if(socket) {
371     QByteArray digest = socket->peerCertificate().digest();
372   }
373 }
374
375 void ClientSyncer::sslErrors(const QList<QSslError> &errors) {
376   QByteArray knownDigest;
377   QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
378   if(socket) {
379     socket->ignoreSslErrors();
380     knownDigest = KnownHostsSettings().knownDigest(socket);
381     if(knownDigest == socket->peerCertificate().digest()) {
382       connectionReady();
383       return;
384     }
385   }
386
387   QStringList warnings;
388
389   foreach(QSslError err, errors)
390     warnings << err.errorString();
391
392   if(!knownDigest.isEmpty()) {
393     warnings << tr("Cert Digest changed! was: %1").arg(QString(prettyDigest(knownDigest)));
394   }
395
396   setWarningsHandler(SLOT(ignoreSslWarnings(bool)));
397   emit connectionWarnings(warnings);
398 }
399 #endif