1 /***************************************************************************
2 * Copyright (C) 2005-2018 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"
26 # include <QSslSocket>
28 # include <QTcpSocket>
32 #include "clientsettings.h"
33 #include "logmessage.h"
34 #include "peerfactory.h"
37 using namespace Protocol;
39 ClientAuthHandler::ClientAuthHandler(CoreAccount account, QObject* parent)
45 , _connectionFeatures(0)
48 Peer* ClientAuthHandler::peer() const
53 void ClientAuthHandler::connectToCore()
55 CoreAccountSettings s;
58 auto* socket = new QSslSocket(this);
59 // make sure the warning is shown if we happen to connect without SSL support later
60 s.setAccountValue("ShowNoClientSslWarning", true);
62 if (_account.useSsl()) {
63 if (s.accountValue("ShowNoClientSslWarning", true).toBool()) {
64 bool accepted = false;
65 emit handleNoSslInClient(&accepted);
67 emit errorMessage(tr("Unencrypted connection canceled"));
70 s.setAccountValue("ShowNoClientSslWarning", false);
73 QTcpSocket* socket = new QTcpSocket(this);
76 #ifndef QT_NO_NETWORKPROXY
78 proxy.setType(_account.proxyType());
79 if (_account.proxyType() == QNetworkProxy::Socks5Proxy || _account.proxyType() == QNetworkProxy::HttpProxy) {
80 proxy.setHostName(_account.proxyHostName());
81 proxy.setPort(_account.proxyPort());
82 proxy.setUser(_account.proxyUser());
83 proxy.setPassword(_account.proxyPassword());
86 if (_account.proxyType() == QNetworkProxy::DefaultProxy) {
87 QNetworkProxyFactory::setUseSystemConfiguration(true);
90 QNetworkProxyFactory::setUseSystemConfiguration(false);
91 socket->setProxy(proxy);
96 connect(socket, &QAbstractSocket::stateChanged, this, &ClientAuthHandler::onSocketStateChanged);
97 connect(socket, &QIODevice::readyRead, this, &ClientAuthHandler::onReadyRead);
98 connect(socket, &QAbstractSocket::connected, this, &ClientAuthHandler::onSocketConnected);
100 emit statusMessage(tr("Connecting to %1...").arg(_account.accountName()));
101 socket->connectToHost(_account.hostName(), _account.port());
104 void ClientAuthHandler::onSocketStateChanged(QAbstractSocket::SocketState socketState)
108 switch (socketState) {
109 case QAbstractSocket::HostLookupState:
111 text = tr("Looking up %1...").arg(_account.hostName());
113 case QAbstractSocket::ConnectingState:
115 text = tr("Connecting to %1...").arg(_account.hostName());
117 case QAbstractSocket::ConnectedState:
118 text = tr("Connected to %1").arg(_account.hostName());
120 case QAbstractSocket::ClosingState:
122 text = tr("Disconnecting from %1...").arg(_account.hostName());
124 case QAbstractSocket::UnconnectedState:
126 text = tr("Disconnected");
127 // Ensure the disconnected() signal is sent even if we haven't reached the Connected state yet.
128 // The baseclass implementation will make sure to only send the signal once.
129 // However, we do want to prefer a potential socket error signal that may be on route already, so
130 // give this a chance to overtake us by spinning the loop...
131 QTimer::singleShot(0, this, &ClientAuthHandler::onSocketDisconnected);
138 if (!text.isEmpty()) {
139 emit statusMessage(text);
143 void ClientAuthHandler::onSocketError(QAbstractSocket::SocketError error)
145 if (_probing && error == QAbstractSocket::RemoteHostClosedError) {
150 _probing = false; // all other errors are unrelated to probing and should be handled
151 AuthHandler::onSocketError(error);
154 void ClientAuthHandler::onSocketDisconnected()
156 if (_probing && _legacy) {
157 // Remote host has closed the connection while probing
159 disconnect(socket(), &QIODevice::readyRead, this, &ClientAuthHandler::onReadyRead);
160 emit statusMessage(tr("Reconnecting in compatibility mode..."));
161 socket()->connectToHost(_account.hostName(), _account.port());
165 AuthHandler::onSocketDisconnected();
168 void ClientAuthHandler::onSocketConnected()
171 qWarning() << Q_FUNC_INFO << "Peer already exists!";
175 socket()->setSocketOption(QAbstractSocket::KeepAliveOption, true);
178 // First connection attempt, try probing for a capable core
181 QDataStream stream(socket()); // stream handles the endianness for us
182 stream.setVersion(QDataStream::Qt_4_2);
184 quint32 magic = Protocol::magic;
186 if (_account.useSsl())
187 magic |= Protocol::Encryption;
189 magic |= Protocol::Compression;
193 // here goes the list of protocols we support, in order of preference
194 PeerFactory::ProtoList protos = PeerFactory::supportedProtocols();
195 for (int i = 0; i < protos.count(); ++i) {
196 quint32 reply = protos[i].first;
197 reply |= protos[i].second << 8;
198 if (i == protos.count() - 1)
199 reply |= 0x80000000; // end list
203 socket()->flush(); // make sure the probing data is sent immediately
207 // If we arrive here, it's the second connection attempt, meaning probing was not successful -> enable legacy support
209 qDebug() << "Legacy core detected, switching to compatibility mode";
211 auto* peer = PeerFactory::createPeer(PeerFactory::ProtoDescriptor(Protocol::LegacyProtocol, 0),
214 Compressor::NoCompression,
216 // Only needed for the legacy peer, as all others check the protocol version before instantiation
217 connect(peer, &RemotePeer::protocolVersionMismatch, this, &ClientAuthHandler::onProtocolVersionMismatch);
222 void ClientAuthHandler::onReadyRead()
224 if (socket()->bytesAvailable() < 4)
228 return; // make sure to not read more data than needed
231 disconnect(socket(), &QIODevice::readyRead, this, &ClientAuthHandler::onReadyRead);
234 socket()->read((char*)&reply, 4);
235 reply = qFromBigEndian<quint32>(reply);
237 auto type = static_cast<Protocol::Type>(reply & 0xff);
238 auto protoFeatures = static_cast<quint16>(reply >> 8 & 0xffff);
239 _connectionFeatures = static_cast<quint8>(reply >> 24);
241 Compressor::CompressionLevel level;
242 if (_connectionFeatures & Protocol::Compression)
243 level = Compressor::BestCompression;
245 level = Compressor::NoCompression;
247 RemotePeer* peer = PeerFactory::createPeer(PeerFactory::ProtoDescriptor(type, protoFeatures), this, socket(), level, this);
249 qWarning() << "No valid protocol supported for this core!";
250 emit errorPopup(tr("<b>Incompatible Quassel Core!</b><br>"
251 "None of the protocols this client speaks are supported by the core you are trying to connect to."));
253 requestDisconnect(tr("Core speaks none of the protocols we support"));
257 if (peer->protocol() == Protocol::LegacyProtocol) {
258 connect(peer, &RemotePeer::protocolVersionMismatch, this, &ClientAuthHandler::onProtocolVersionMismatch);
265 void ClientAuthHandler::onProtocolVersionMismatch(int actual, int expected)
267 emit errorPopup(tr("<b>The Quassel Core you are trying to connect to is too old!</b><br>"
268 "We need at least protocol v%1, but the core speaks v%2 only.")
269 .arg(expected, actual));
270 requestDisconnect(tr("Incompatible protocol version, connection to core refused"));
273 void ClientAuthHandler::setPeer(RemotePeer* peer)
275 qDebug().nospace() << "Using " << qPrintable(peer->protocolName()) << "...";
278 connect(_peer, &RemotePeer::transferProgress, this, &ClientAuthHandler::transferProgress);
280 // The legacy protocol enables SSL later, after registration
281 if (!_account.useSsl() || _legacy)
283 // otherwise, do it now
285 checkAndEnableSsl(_connectionFeatures & Protocol::Encryption);
288 void ClientAuthHandler::startRegistration()
290 emit statusMessage(tr("Synchronizing to core..."));
292 // useSsl will be ignored by non-legacy peers
295 useSsl = _account.useSsl();
298 _peer->dispatch(RegisterClient(Quassel::Features{}, Quassel::buildInfo().fancyVersionString, Quassel::buildInfo().commitDate, useSsl));
301 void ClientAuthHandler::handle(const ClientDenied& msg)
303 emit errorPopup(msg.errorString);
304 requestDisconnect(tr("The core refused connection from this client"));
307 void ClientAuthHandler::handle(const ClientRegistered& msg)
309 _coreConfigured = msg.coreConfigured;
310 _backendInfo = msg.backendInfo;
311 _authenticatorInfo = msg.authenticatorInfo;
313 _peer->setFeatures(std::move(msg.features));
315 // The legacy protocol enables SSL at this point
316 if (_legacy && _account.useSsl())
317 checkAndEnableSsl(msg.sslSupported);
322 void ClientAuthHandler::onConnectionReady()
324 const auto& coreFeatures = _peer->features();
325 auto unsupported = coreFeatures.toStringList(false);
326 if (!unsupported.isEmpty()) {
327 quInfo() << qPrintable(tr("Core does not support the following features: %1").arg(unsupported.join(", ")));
329 if (!coreFeatures.unknownFeatures().isEmpty()) {
330 quInfo() << qPrintable(tr("Core supports unknown features: %1").arg(coreFeatures.unknownFeatures().join(", ")));
333 emit connectionReady();
334 emit statusMessage(tr("Connected to %1").arg(_account.accountName()));
336 if (!_coreConfigured) {
338 emit startCoreSetup(_backendInfo, _authenticatorInfo);
340 else // TODO: check if we need LoginEnabled
344 void ClientAuthHandler::setupCore(const SetupData& setupData)
346 _peer->dispatch(setupData);
349 void ClientAuthHandler::handle(const SetupFailed& msg)
351 emit coreSetupFailed(msg.errorString);
354 void ClientAuthHandler::handle(const SetupDone& msg)
358 emit coreSetupSuccessful();
361 void ClientAuthHandler::login(const QString& user, const QString& password, bool remember)
363 _account.setUser(user);
364 _account.setPassword(password);
365 _account.setStorePassword(remember);
369 void ClientAuthHandler::login(const QString& previousError)
371 emit statusMessage(tr("Logging in..."));
372 if (_account.user().isEmpty() || _account.password().isEmpty() || !previousError.isEmpty()) {
374 emit userAuthenticationRequired(&_account, &valid, previousError); // *must* be a synchronous call
375 if (!valid || _account.user().isEmpty() || _account.password().isEmpty()) {
376 requestDisconnect(tr("Login canceled"));
381 _peer->dispatch(Login(_account.user(), _account.password()));
384 void ClientAuthHandler::handle(const LoginFailed& msg)
386 login(msg.errorString);
389 void ClientAuthHandler::handle(const LoginSuccess& msg)
393 emit loginSuccessful(_account);
396 void ClientAuthHandler::handle(const SessionState& msg)
398 disconnect(socket(), nullptr, this, nullptr); // this is the last message we shall ever get
400 // give up ownership of the peer; CoreSession takes responsibility now
401 _peer->setParent(nullptr);
402 emit handshakeComplete(_peer, msg);
407 void ClientAuthHandler::checkAndEnableSsl(bool coreSupportsSsl)
410 Q_UNUSED(coreSupportsSsl);
412 CoreAccountSettings s;
413 if (coreSupportsSsl && _account.useSsl()) {
414 // Make sure the warning is shown next time we don't have SSL in the core
415 s.setAccountValue("ShowNoCoreSslWarning", true);
417 auto* sslSocket = qobject_cast<QSslSocket*>(socket());
419 connect(sslSocket, &QSslSocket::encrypted, this, &ClientAuthHandler::onSslSocketEncrypted);
420 connect(sslSocket, selectOverload<const QList<QSslError>&>(&QSslSocket::sslErrors), this, &ClientAuthHandler::onSslErrors);
421 qDebug() << "Starting encryption...";
423 sslSocket->startClientEncryption();
426 if (s.accountValue("ShowNoCoreSslWarning", true).toBool()) {
427 bool accepted = false;
428 emit handleNoSslInCore(&accepted);
430 requestDisconnect(tr("Unencrypted connection cancelled"));
433 s.setAccountValue("ShowNoCoreSslWarning", false);
434 s.setAccountValue("SslCert", QString());
435 s.setAccountValue("SslCertDigestVersion", QVariant(QVariant::Int));
447 void ClientAuthHandler::onSslSocketEncrypted()
449 auto* socket = qobject_cast<QSslSocket*>(sender());
452 if (!socket->sslErrors().count()) {
453 // Cert is valid, so we don't want to store it as known
454 // That way, a warning will appear in case it becomes invalid at some point
455 CoreAccountSettings s;
456 s.setAccountValue("SSLCert", QString());
457 s.setAccountValue("SslCertDigestVersion", QVariant(QVariant::Int));
460 emit encrypted(true);
468 void ClientAuthHandler::onSslErrors()
470 auto* socket = qobject_cast<QSslSocket*>(sender());
473 CoreAccountSettings s;
474 QByteArray knownDigest = s.accountValue("SslCert").toByteArray();
475 ClientAuthHandler::DigestVersion knownDigestVersion = static_cast<ClientAuthHandler::DigestVersion>(
476 s.accountValue("SslCertDigestVersion").toInt());
478 QByteArray calculatedDigest;
479 switch (knownDigestVersion) {
480 case ClientAuthHandler::DigestVersion::Md5:
481 calculatedDigest = socket->peerCertificate().digest(QCryptographicHash::Md5);
484 case ClientAuthHandler::DigestVersion::Sha2_512:
485 calculatedDigest = socket->peerCertificate().digest(QCryptographicHash::Sha512);
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 s.setAccountValue("SslCert", socket->peerCertificate().digest(QCryptographicHash::Sha512));
504 s.setAccountValue("SslCertDigestVersion", ClientAuthHandler::DigestVersion::Latest);
507 s.setAccountValue("SslCert", QString());
508 s.setAccountValue("SslCertDigestVersion", QVariant(QVariant::Int));
511 else if (knownDigestVersion != ClientAuthHandler::DigestVersion::Latest) {
512 s.setAccountValue("SslCert", socket->peerCertificate().digest(QCryptographicHash::Sha512));
513 s.setAccountValue("SslCertDigestVersion", ClientAuthHandler::DigestVersion::Latest);
516 socket->ignoreSslErrors();
519 #endif /* HAVE_SSL */