Allow for clients to negotiate whether compression is used
[quassel.git] / src / client / clientauthhandler.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2014 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  *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
19  ***************************************************************************/
20
21 #include "clientauthhandler.h"
22
23 // TODO: support system application proxy (new in Qt 4.6)
24
25 #include <QtEndian>
26
27 #ifdef HAVE_SSL
28     #include <QSslSocket>
29 #else
30     #include <QTcpSocket>
31 #endif
32
33 #include "client.h"
34 #include "clientsettings.h"
35 #include "peerfactory.h"
36
37 using namespace Protocol;
38
39 ClientAuthHandler::ClientAuthHandler(CoreAccount account, QObject *parent)
40     : AuthHandler(parent),
41     _peer(0),
42     _account(account),
43     _probing(false),
44     _legacy(false),
45     _connectionFeatures(0)
46 {
47
48 }
49
50
51 void ClientAuthHandler::connectToCore()
52 {
53     CoreAccountSettings s;
54
55 #ifdef HAVE_SSL
56     QSslSocket *socket = new QSslSocket(this);
57     // make sure the warning is shown if we happen to connect without SSL support later
58     s.setAccountValue("ShowNoClientSslWarning", true);
59 #else
60     if (_account.useSsl()) {
61         if (s.accountValue("ShowNoClientSslWarning", true).toBool()) {
62             bool accepted = false;
63             emit handleNoSslInClient(&accepted);
64             if (!accepted) {
65                 emit errorMessage(tr("Unencrypted connection canceled"));
66                 return;
67             }
68             s.setAccountValue("ShowNoClientSslWarning", false);
69         }
70     }
71     QTcpSocket *socket = new QTcpSocket(this);
72 #endif
73
74 // TODO: Handle system proxy
75 #ifndef QT_NO_NETWORKPROXY
76     if (_account.useProxy()) {
77         QNetworkProxy proxy(_account.proxyType(), _account.proxyHostName(), _account.proxyPort(), _account.proxyUser(), _account.proxyPassword());
78         socket->setProxy(proxy);
79     }
80 #endif
81
82     setSocket(socket);
83     connect(socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), SLOT(onSocketStateChanged(QAbstractSocket::SocketState)));
84     connect(socket, SIGNAL(readyRead()), SLOT(onReadyRead()));
85     connect(socket, SIGNAL(connected()), SLOT(onSocketConnected()));
86
87     emit statusMessage(tr("Connecting to %1...").arg(_account.accountName()));
88     socket->connectToHost(_account.hostName(), _account.port());
89 }
90
91
92 void ClientAuthHandler::onSocketStateChanged(QAbstractSocket::SocketState socketState)
93 {
94     QString text;
95
96     switch(socketState) {
97         case QAbstractSocket::HostLookupState:
98             if (!_legacy)
99                 text = tr("Looking up %1...").arg(_account.hostName());
100             break;
101         case QAbstractSocket::ConnectingState:
102             if (!_legacy)
103                 text = tr("Connecting to %1...").arg(_account.hostName());
104             break;
105         case QAbstractSocket::ConnectedState:
106             text = tr("Connected to %1").arg(_account.hostName());
107             break;
108         case QAbstractSocket::ClosingState:
109             if (!_probing)
110                 text = tr("Disconnecting from %1...").arg(_account.hostName());
111             break;
112         case QAbstractSocket::UnconnectedState:
113             if (!_probing) {
114                 text = tr("Disconnected");
115                 // Ensure the disconnected() signal is sent even if we haven't reached the Connected state yet.
116                 // The baseclass implementation will make sure to only send the signal once.
117                 onSocketDisconnected();
118             }
119             break;
120         default:
121             break;
122     }
123
124     if (!text.isEmpty()) {
125         emit statusMessage(text);
126     }
127 }
128
129 void ClientAuthHandler::onSocketError(QAbstractSocket::SocketError error)
130 {
131     if (_probing && error == QAbstractSocket::RemoteHostClosedError) {
132         _legacy = true;
133         return;
134     }
135
136     _probing = false; // all other errors are unrelated to probing and should be handled
137     AuthHandler::onSocketError(error);
138 }
139
140
141 void ClientAuthHandler::onSocketDisconnected()
142 {
143     if (_probing && _legacy) {
144         // Remote host has closed the connection while probing
145         _probing = false;
146         disconnect(socket(), SIGNAL(readyRead()), this, SLOT(onReadyRead()));
147         emit statusMessage(tr("Reconnecting in compatibility mode..."));
148         socket()->connectToHost(_account.hostName(), _account.port());
149         return;
150     }
151
152     AuthHandler::onSocketDisconnected();
153 }
154
155
156 void ClientAuthHandler::onSocketConnected()
157 {
158     if (_peer) {
159         qWarning() << Q_FUNC_INFO << "Peer already exists!";
160         return;
161     }
162
163     socket()->setSocketOption(QAbstractSocket::KeepAliveOption, true);
164
165     if (!_legacy) {
166         // First connection attempt, try probing for a capable core
167         _probing = true;
168
169         QDataStream stream(socket()); // stream handles the endianness for us
170
171         quint32 magic = Protocol::magic;
172 #ifdef HAVE_SSL
173         if (_account.useSsl())
174             magic |= Protocol::Encryption;
175 #endif
176         magic |= Protocol::Compression;
177
178         stream << magic;
179
180         // here goes the list of protocols we support, in order of preference
181         PeerFactory::ProtoList protos = PeerFactory::supportedProtocols();
182         for (int i = 0; i < protos.count(); ++i) {
183             quint32 reply = protos[i].first;
184             reply |= protos[i].second<<8;
185             if (i == protos.count() - 1)
186                 reply |= 0x80000000; // end list
187             stream << reply;
188         }
189
190         socket()->flush(); // make sure the probing data is sent immediately
191         return;
192     }
193
194     // If we arrive here, it's the second connection attempt, meaning probing was not successful -> enable legacy support
195
196     qDebug() << "Legacy core detected, switching to compatibility mode";
197
198     RemotePeer *peer = PeerFactory::createPeer(PeerFactory::ProtoDescriptor(Protocol::LegacyProtocol, 0), this, socket(), Compressor::NoCompression, this);
199     // Only needed for the legacy peer, as all others check the protocol version before instantiation
200     connect(peer, SIGNAL(protocolVersionMismatch(int,int)), SLOT(onProtocolVersionMismatch(int,int)));
201
202     setPeer(peer);
203 }
204
205
206 void ClientAuthHandler::onReadyRead()
207 {
208     if (socket()->bytesAvailable() < 4)
209         return;
210
211     if (!_probing)
212         return; // make sure to not read more data than needed
213
214     _probing = false;
215     disconnect(socket(), SIGNAL(readyRead()), this, SLOT(onReadyRead()));
216
217     quint32 reply;
218     socket()->read((char *)&reply, 4);
219     reply = qFromBigEndian<quint32>(reply);
220
221     Protocol::Type type = static_cast<Protocol::Type>(reply & 0xff);
222     quint16 protoFeatures = static_cast<quint16>(reply>>8 & 0xffff);
223     _connectionFeatures = static_cast<quint8>(reply>>24);
224
225     Compressor::CompressionLevel level;
226     if (_connectionFeatures & Protocol::Compression)
227         level = Compressor::BestCompression;
228     else
229         level = Compressor::NoCompression;
230
231     RemotePeer *peer = PeerFactory::createPeer(PeerFactory::ProtoDescriptor(type, protoFeatures), this, socket(), level, this);
232     if (!peer) {
233         qWarning() << "No valid protocol supported for this core!";
234         emit errorPopup(tr("<b>Incompatible Quassel Core!</b><br>"
235                            "None of the protocols this client speaks are supported by the core you are trying to connect to."));
236
237         requestDisconnect(tr("Core speaks none of the protocols we support"));
238         return;
239     }
240
241     if (peer->protocol() == Protocol::LegacyProtocol) {
242         connect(peer, SIGNAL(protocolVersionMismatch(int,int)), SLOT(onProtocolVersionMismatch(int,int)));
243         _legacy = true;
244     }
245
246     setPeer(peer);
247 }
248
249
250 void ClientAuthHandler::onProtocolVersionMismatch(int actual, int expected)
251 {
252     emit errorPopup(tr("<b>The Quassel Core you are trying to connect to is too old!</b><br>"
253            "We need at least protocol v%1, but the core speaks v%2 only.").arg(expected, actual));
254     requestDisconnect(tr("Incompatible protocol version, connection to core refused"));
255 }
256
257
258 void ClientAuthHandler::setPeer(RemotePeer *peer)
259 {
260     qDebug().nospace() << "Using " << qPrintable(peer->protocolName()) << "...";
261
262     _peer = peer;
263     connect(_peer, SIGNAL(transferProgress(int,int)), SIGNAL(transferProgress(int,int)));
264
265     // The legacy protocol enables SSL later, after registration
266     if (!_account.useSsl() || _legacy)
267         startRegistration();
268     // otherwise, do it now
269     else
270         checkAndEnableSsl(_connectionFeatures & Protocol::Encryption);
271 }
272
273
274 void ClientAuthHandler::startRegistration()
275 {
276     emit statusMessage(tr("Synchronizing to core..."));
277
278     // useSsl will be ignored by non-legacy peers
279     bool useSsl = false;
280 #ifdef HAVE_SSL
281     useSsl = _account.useSsl();
282 #endif
283
284     _peer->dispatch(RegisterClient(Quassel::buildInfo().fancyVersionString, useSsl));
285 }
286
287
288 void ClientAuthHandler::handle(const ClientDenied &msg)
289 {
290     emit errorPopup(msg.errorString);
291     requestDisconnect(tr("The core refused connection from this client"));
292 }
293
294
295 void ClientAuthHandler::handle(const ClientRegistered &msg)
296 {
297     _coreConfigured = msg.coreConfigured;
298     _backendInfo = msg.backendInfo;
299
300     Client::setCoreFeatures(static_cast<Quassel::Features>(msg.coreFeatures));
301
302     // The legacy protocol enables SSL at this point
303     if(_legacy && _account.useSsl())
304         checkAndEnableSsl(msg.sslSupported);
305     else
306         onConnectionReady();
307 }
308
309
310 void ClientAuthHandler::onConnectionReady()
311 {
312     emit connectionReady();
313     emit statusMessage(tr("Connected to %1").arg(_account.accountName()));
314
315     if (!_coreConfigured) {
316         // start wizard
317         emit startCoreSetup(_backendInfo);
318     }
319     else // TODO: check if we need LoginEnabled
320         login();
321 }
322
323
324 void ClientAuthHandler::setupCore(const SetupData &setupData)
325 {
326     _peer->dispatch(setupData);
327 }
328
329
330 void ClientAuthHandler::handle(const SetupFailed &msg)
331 {
332     emit coreSetupFailed(msg.errorString);
333 }
334
335
336 void ClientAuthHandler::handle(const SetupDone &msg)
337 {
338     Q_UNUSED(msg)
339
340     emit coreSetupSuccessful();
341 }
342
343
344 void ClientAuthHandler::login(const QString &user, const QString &password, bool remember)
345 {
346     _account.setUser(user);
347     _account.setPassword(password);
348     _account.setStorePassword(remember);
349     login();
350 }
351
352
353 void ClientAuthHandler::login(const QString &previousError)
354 {
355     emit statusMessage(tr("Logging in..."));
356     if (_account.user().isEmpty() || _account.password().isEmpty() || !previousError.isEmpty()) {
357         bool valid = false;
358         emit userAuthenticationRequired(&_account, &valid, previousError); // *must* be a synchronous call
359         if (!valid || _account.user().isEmpty() || _account.password().isEmpty()) {
360             requestDisconnect(tr("Login canceled"));
361             return;
362         }
363     }
364
365     _peer->dispatch(Login(_account.user(), _account.password()));
366 }
367
368
369 void ClientAuthHandler::handle(const LoginFailed &msg)
370 {
371     login(msg.errorString);
372 }
373
374
375 void ClientAuthHandler::handle(const LoginSuccess &msg)
376 {
377     Q_UNUSED(msg)
378
379     emit loginSuccessful(_account);
380 }
381
382
383 void ClientAuthHandler::handle(const SessionState &msg)
384 {
385     disconnect(socket(), 0, this, 0); // this is the last message we shall ever get
386
387     // give up ownership of the peer; CoreSession takes responsibility now
388     _peer->setParent(0);
389     emit handshakeComplete(_peer, msg);
390 }
391
392
393 /*** SSL Stuff ***/
394
395 void ClientAuthHandler::checkAndEnableSsl(bool coreSupportsSsl)
396 {
397 #ifndef HAVE_SSL
398     Q_UNUSED(coreSupportsSsl);
399 #else
400     CoreAccountSettings s;
401     if (coreSupportsSsl && _account.useSsl()) {
402         // Make sure the warning is shown next time we don't have SSL in the core
403         s.setAccountValue("ShowNoCoreSslWarning", true);
404
405         QSslSocket *sslSocket = qobject_cast<QSslSocket *>(socket());
406         Q_ASSERT(sslSocket);
407         connect(sslSocket, SIGNAL(encrypted()), SLOT(onSslSocketEncrypted()));
408         connect(sslSocket, SIGNAL(sslErrors(QList<QSslError>)), SLOT(onSslErrors()));
409         qDebug() << "Starting encryption...";
410         sslSocket->flush();
411         sslSocket->startClientEncryption();
412     }
413     else {
414         if (s.accountValue("ShowNoCoreSslWarning", true).toBool()) {
415             bool accepted = false;
416             emit handleNoSslInCore(&accepted);
417             if (!accepted) {
418                 requestDisconnect(tr("Unencrypted connection cancelled"));
419                 return;
420             }
421             s.setAccountValue("ShowNoCoreSslWarning", false);
422             s.setAccountValue("SslCert", QString());
423         }
424         if (_legacy)
425             onConnectionReady();
426         else
427             startRegistration();
428     }
429 #endif
430 }
431
432 #ifdef HAVE_SSL
433
434 void ClientAuthHandler::onSslSocketEncrypted()
435 {
436     QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
437     Q_ASSERT(socket);
438
439     if (!socket->sslErrors().count()) {
440         // Cert is valid, so we don't want to store it as known
441         // That way, a warning will appear in case it becomes invalid at some point
442         CoreAccountSettings s;
443         s.setAccountValue("SSLCert", QString());
444     }
445
446     emit encrypted(true);
447
448     if (_legacy)
449         onConnectionReady();
450     else
451         startRegistration();
452 }
453
454
455 void ClientAuthHandler::onSslErrors()
456 {
457     QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
458     Q_ASSERT(socket);
459
460     CoreAccountSettings s;
461     QByteArray knownDigest = s.accountValue("SslCert").toByteArray();
462
463     if (knownDigest != socket->peerCertificate().digest()) {
464         bool accepted = false;
465         bool permanently = false;
466         emit handleSslErrors(socket, &accepted, &permanently);
467
468         if (!accepted) {
469             requestDisconnect(tr("Unencrypted connection canceled"));
470             return;
471         }
472
473         if (permanently)
474             s.setAccountValue("SslCert", socket->peerCertificate().digest());
475         else
476             s.setAccountValue("SslCert", QString());
477     }
478
479     socket->ignoreSslErrors();
480 }
481
482 #endif /* HAVE_SSL */