1 /***************************************************************************
2 * Copyright (C) 2005-2016 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 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
19 ***************************************************************************/
21 #include "clientauthhandler.h"
23 // TODO: support system application proxy (new in Qt 4.6)
34 #include "clientsettings.h"
35 #include "peerfactory.h"
37 #if QT_VERSION < 0x050000
38 # include "../../3rdparty/sha512/sha512.h"
41 using namespace Protocol;
43 ClientAuthHandler::ClientAuthHandler(CoreAccount account, QObject *parent)
44 : AuthHandler(parent),
49 _connectionFeatures(0)
55 void ClientAuthHandler::connectToCore()
57 CoreAccountSettings s;
60 QSslSocket *socket = new QSslSocket(this);
61 // make sure the warning is shown if we happen to connect without SSL support later
62 s.setAccountValue("ShowNoClientSslWarning", true);
64 if (_account.useSsl()) {
65 if (s.accountValue("ShowNoClientSslWarning", true).toBool()) {
66 bool accepted = false;
67 emit handleNoSslInClient(&accepted);
69 emit errorMessage(tr("Unencrypted connection canceled"));
72 s.setAccountValue("ShowNoClientSslWarning", false);
75 QTcpSocket *socket = new QTcpSocket(this);
78 // TODO: Handle system proxy
79 #ifndef QT_NO_NETWORKPROXY
80 if (_account.useProxy()) {
81 QNetworkProxy proxy(_account.proxyType(), _account.proxyHostName(), _account.proxyPort(), _account.proxyUser(), _account.proxyPassword());
82 socket->setProxy(proxy);
87 connect(socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), SLOT(onSocketStateChanged(QAbstractSocket::SocketState)));
88 connect(socket, SIGNAL(readyRead()), SLOT(onReadyRead()));
89 connect(socket, SIGNAL(connected()), SLOT(onSocketConnected()));
91 emit statusMessage(tr("Connecting to %1...").arg(_account.accountName()));
92 socket->connectToHost(_account.hostName(), _account.port());
96 void ClientAuthHandler::onSocketStateChanged(QAbstractSocket::SocketState socketState)
100 switch(socketState) {
101 case QAbstractSocket::HostLookupState:
103 text = tr("Looking up %1...").arg(_account.hostName());
105 case QAbstractSocket::ConnectingState:
107 text = tr("Connecting to %1...").arg(_account.hostName());
109 case QAbstractSocket::ConnectedState:
110 text = tr("Connected to %1").arg(_account.hostName());
112 case QAbstractSocket::ClosingState:
114 text = tr("Disconnecting from %1...").arg(_account.hostName());
116 case QAbstractSocket::UnconnectedState:
118 text = tr("Disconnected");
119 // Ensure the disconnected() signal is sent even if we haven't reached the Connected state yet.
120 // The baseclass implementation will make sure to only send the signal once.
121 // However, we do want to prefer a potential socket error signal that may be on route already, so
122 // give this a chance to overtake us by spinning the loop...
123 QTimer::singleShot(0, this, SLOT(onSocketDisconnected()));
130 if (!text.isEmpty()) {
131 emit statusMessage(text);
135 void ClientAuthHandler::onSocketError(QAbstractSocket::SocketError error)
137 if (_probing && error == QAbstractSocket::RemoteHostClosedError) {
142 _probing = false; // all other errors are unrelated to probing and should be handled
143 AuthHandler::onSocketError(error);
147 void ClientAuthHandler::onSocketDisconnected()
149 if (_probing && _legacy) {
150 // Remote host has closed the connection while probing
152 disconnect(socket(), SIGNAL(readyRead()), this, SLOT(onReadyRead()));
153 emit statusMessage(tr("Reconnecting in compatibility mode..."));
154 socket()->connectToHost(_account.hostName(), _account.port());
158 AuthHandler::onSocketDisconnected();
162 void ClientAuthHandler::onSocketConnected()
165 qWarning() << Q_FUNC_INFO << "Peer already exists!";
169 socket()->setSocketOption(QAbstractSocket::KeepAliveOption, true);
172 // First connection attempt, try probing for a capable core
175 QDataStream stream(socket()); // stream handles the endianness for us
176 stream.setVersion(QDataStream::Qt_4_2);
178 quint32 magic = Protocol::magic;
180 if (_account.useSsl())
181 magic |= Protocol::Encryption;
183 magic |= Protocol::Compression;
187 // here goes the list of protocols we support, in order of preference
188 PeerFactory::ProtoList protos = PeerFactory::supportedProtocols();
189 for (int i = 0; i < protos.count(); ++i) {
190 quint32 reply = protos[i].first;
191 reply |= protos[i].second<<8;
192 if (i == protos.count() - 1)
193 reply |= 0x80000000; // end list
197 socket()->flush(); // make sure the probing data is sent immediately
201 // If we arrive here, it's the second connection attempt, meaning probing was not successful -> enable legacy support
203 qDebug() << "Legacy core detected, switching to compatibility mode";
205 RemotePeer *peer = PeerFactory::createPeer(PeerFactory::ProtoDescriptor(Protocol::LegacyProtocol, 0), this, socket(), Compressor::NoCompression, this);
206 // Only needed for the legacy peer, as all others check the protocol version before instantiation
207 connect(peer, SIGNAL(protocolVersionMismatch(int,int)), SLOT(onProtocolVersionMismatch(int,int)));
213 void ClientAuthHandler::onReadyRead()
215 if (socket()->bytesAvailable() < 4)
219 return; // make sure to not read more data than needed
222 disconnect(socket(), SIGNAL(readyRead()), this, SLOT(onReadyRead()));
225 socket()->read((char *)&reply, 4);
226 reply = qFromBigEndian<quint32>(reply);
228 Protocol::Type type = static_cast<Protocol::Type>(reply & 0xff);
229 quint16 protoFeatures = static_cast<quint16>(reply>>8 & 0xffff);
230 _connectionFeatures = static_cast<quint8>(reply>>24);
232 Compressor::CompressionLevel level;
233 if (_connectionFeatures & Protocol::Compression)
234 level = Compressor::BestCompression;
236 level = Compressor::NoCompression;
238 RemotePeer *peer = PeerFactory::createPeer(PeerFactory::ProtoDescriptor(type, protoFeatures), this, socket(), level, this);
240 qWarning() << "No valid protocol supported for this core!";
241 emit errorPopup(tr("<b>Incompatible Quassel Core!</b><br>"
242 "None of the protocols this client speaks are supported by the core you are trying to connect to."));
244 requestDisconnect(tr("Core speaks none of the protocols we support"));
248 if (peer->protocol() == Protocol::LegacyProtocol) {
249 connect(peer, SIGNAL(protocolVersionMismatch(int,int)), SLOT(onProtocolVersionMismatch(int,int)));
257 void ClientAuthHandler::onProtocolVersionMismatch(int actual, int expected)
259 emit errorPopup(tr("<b>The Quassel Core you are trying to connect to is too old!</b><br>"
260 "We need at least protocol v%1, but the core speaks v%2 only.").arg(expected, actual));
261 requestDisconnect(tr("Incompatible protocol version, connection to core refused"));
265 void ClientAuthHandler::setPeer(RemotePeer *peer)
267 qDebug().nospace() << "Using " << qPrintable(peer->protocolName()) << "...";
270 connect(_peer, SIGNAL(transferProgress(int,int)), SIGNAL(transferProgress(int,int)));
272 // The legacy protocol enables SSL later, after registration
273 if (!_account.useSsl() || _legacy)
275 // otherwise, do it now
277 checkAndEnableSsl(_connectionFeatures & Protocol::Encryption);
281 void ClientAuthHandler::startRegistration()
283 emit statusMessage(tr("Synchronizing to core..."));
285 // useSsl will be ignored by non-legacy peers
288 useSsl = _account.useSsl();
291 _peer->dispatch(RegisterClient(Quassel::buildInfo().fancyVersionString, Quassel::buildInfo().commitDate, useSsl));
295 void ClientAuthHandler::handle(const ClientDenied &msg)
297 emit errorPopup(msg.errorString);
298 requestDisconnect(tr("The core refused connection from this client"));
302 void ClientAuthHandler::handle(const ClientRegistered &msg)
304 _coreConfigured = msg.coreConfigured;
305 _backendInfo = msg.backendInfo;
306 _authenticatorInfo = msg.authenticatorInfo;
308 Client::setCoreFeatures(static_cast<Quassel::Features>(msg.coreFeatures));
310 // The legacy protocol enables SSL at this point
311 if(_legacy && _account.useSsl())
312 checkAndEnableSsl(msg.sslSupported);
318 void ClientAuthHandler::onConnectionReady()
320 emit connectionReady();
321 emit statusMessage(tr("Connected to %1").arg(_account.accountName()));
323 if (!_coreConfigured) {
325 emit startCoreSetup(_backendInfo, _authenticatorInfo);
327 else // TODO: check if we need LoginEnabled
332 void ClientAuthHandler::setupCore(const SetupData &setupData)
334 _peer->dispatch(setupData);
338 void ClientAuthHandler::handle(const SetupFailed &msg)
340 emit coreSetupFailed(msg.errorString);
344 void ClientAuthHandler::handle(const SetupDone &msg)
348 emit coreSetupSuccessful();
352 void ClientAuthHandler::login(const QString &user, const QString &password, bool remember)
354 _account.setUser(user);
355 _account.setPassword(password);
356 _account.setStorePassword(remember);
361 void ClientAuthHandler::login(const QString &previousError)
363 emit statusMessage(tr("Logging in..."));
364 if (_account.user().isEmpty() || _account.password().isEmpty() || !previousError.isEmpty()) {
366 emit userAuthenticationRequired(&_account, &valid, previousError); // *must* be a synchronous call
367 if (!valid || _account.user().isEmpty() || _account.password().isEmpty()) {
368 requestDisconnect(tr("Login canceled"));
373 _peer->dispatch(Login(_account.user(), _account.password()));
377 void ClientAuthHandler::handle(const LoginFailed &msg)
379 login(msg.errorString);
383 void ClientAuthHandler::handle(const LoginSuccess &msg)
387 emit loginSuccessful(_account);
391 void ClientAuthHandler::handle(const SessionState &msg)
393 disconnect(socket(), 0, this, 0); // this is the last message we shall ever get
395 // give up ownership of the peer; CoreSession takes responsibility now
397 emit handshakeComplete(_peer, msg);
403 void ClientAuthHandler::checkAndEnableSsl(bool coreSupportsSsl)
406 Q_UNUSED(coreSupportsSsl);
408 CoreAccountSettings s;
409 if (coreSupportsSsl && _account.useSsl()) {
410 // Make sure the warning is shown next time we don't have SSL in the core
411 s.setAccountValue("ShowNoCoreSslWarning", true);
413 QSslSocket *sslSocket = qobject_cast<QSslSocket *>(socket());
415 connect(sslSocket, SIGNAL(encrypted()), SLOT(onSslSocketEncrypted()));
416 connect(sslSocket, SIGNAL(sslErrors(QList<QSslError>)), SLOT(onSslErrors()));
417 qDebug() << "Starting encryption...";
419 sslSocket->startClientEncryption();
422 if (s.accountValue("ShowNoCoreSslWarning", true).toBool()) {
423 bool accepted = false;
424 emit handleNoSslInCore(&accepted);
426 requestDisconnect(tr("Unencrypted connection cancelled"));
429 s.setAccountValue("ShowNoCoreSslWarning", false);
430 s.setAccountValue("SslCert", QString());
431 s.setAccountValue("SslCertDigestVersion", QVariant(QVariant::Int));
443 void ClientAuthHandler::onSslSocketEncrypted()
445 QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
448 if (!socket->sslErrors().count()) {
449 // Cert is valid, so we don't want to store it as known
450 // That way, a warning will appear in case it becomes invalid at some point
451 CoreAccountSettings s;
452 s.setAccountValue("SSLCert", QString());
453 s.setAccountValue("SslCertDigestVersion", QVariant(QVariant::Int));
456 emit encrypted(true);
465 void ClientAuthHandler::onSslErrors()
467 QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
470 CoreAccountSettings s;
471 QByteArray knownDigest = s.accountValue("SslCert").toByteArray();
472 ClientAuthHandler::DigestVersion knownDigestVersion = static_cast<ClientAuthHandler::DigestVersion>(s.accountValue("SslCertDigestVersion").toInt());
474 QByteArray calculatedDigest;
475 switch (knownDigestVersion) {
476 case ClientAuthHandler::DigestVersion::Md5:
477 calculatedDigest = socket->peerCertificate().digest(QCryptographicHash::Md5);
480 case ClientAuthHandler::DigestVersion::Sha2_512:
481 #if QT_VERSION >= 0x050000
482 calculatedDigest = socket->peerCertificate().digest(QCryptographicHash::Sha512);
484 calculatedDigest = sha2_512(socket->peerCertificate().toDer());
489 qWarning() << "Certificate digest version" << QString(knownDigestVersion) << "is not supported";
492 if (knownDigest != calculatedDigest) {
493 bool accepted = false;
494 bool permanently = false;
495 emit handleSslErrors(socket, &accepted, &permanently);
498 requestDisconnect(tr("Unencrypted connection canceled"));
503 #if QT_VERSION >= 0x050000
504 s.setAccountValue("SslCert", socket->peerCertificate().digest(QCryptographicHash::Sha512));
506 s.setAccountValue("SslCert", sha2_512(socket->peerCertificate().toDer()));
508 s.setAccountValue("SslCertDigestVersion", ClientAuthHandler::DigestVersion::Latest);
511 s.setAccountValue("SslCert", QString());
512 s.setAccountValue("SslCertDigestVersion", QVariant(QVariant::Int));
515 else if (knownDigestVersion != ClientAuthHandler::DigestVersion::Latest) {
516 #if QT_VERSION >= 0x050000
517 s.setAccountValue("SslCert", socket->peerCertificate().digest(QCryptographicHash::Sha512));
519 s.setAccountValue("SslCert", sha2_512(socket->peerCertificate().toDer()));
521 s.setAccountValue("SslCertDigestVersion", ClientAuthHandler::DigestVersion::Latest);
524 socket->ignoreSslErrors();
527 #if QT_VERSION < 0x050000
528 QByteArray ClientAuthHandler::sha2_512(const QByteArray &input) {
529 unsigned char output[64];
530 sha512((unsigned char*) input.constData(), input.size(), output, false);
531 // QByteArray::fromRawData() cannot be used here because that constructor
532 // does not copy "output" and the data is clobbered when the variable goes
535 result.append((char*) output, 64);
540 #endif /* HAVE_SSL */