1 /***************************************************************************
2 * Copyright (C) 2005-2020 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"
27 #include "clientsettings.h"
28 #include "peerfactory.h"
31 ClientAuthHandler::ClientAuthHandler(CoreAccount account, QObject* parent)
37 , _connectionFeatures(0)
40 Peer* ClientAuthHandler::peer() const
45 void ClientAuthHandler::connectToCore()
47 CoreAccountSettings s;
49 auto* socket = new QSslSocket(this);
50 // make sure the warning is shown if we happen to connect without SSL support later
51 s.setAccountValue("ShowNoClientSslWarning", true);
53 #ifndef QT_NO_NETWORKPROXY
55 proxy.setType(_account.proxyType());
56 if (_account.proxyType() == QNetworkProxy::Socks5Proxy || _account.proxyType() == QNetworkProxy::HttpProxy) {
57 proxy.setHostName(_account.proxyHostName());
58 proxy.setPort(_account.proxyPort());
59 proxy.setUser(_account.proxyUser());
60 proxy.setPassword(_account.proxyPassword());
63 if (_account.proxyType() == QNetworkProxy::DefaultProxy) {
64 QNetworkProxyFactory::setUseSystemConfiguration(true);
67 QNetworkProxyFactory::setUseSystemConfiguration(false);
68 socket->setProxy(proxy);
73 connect(socket, &QAbstractSocket::stateChanged, this, &ClientAuthHandler::onSocketStateChanged);
74 connect(socket, &QIODevice::readyRead, this, &ClientAuthHandler::onReadyRead);
75 connect(socket, &QAbstractSocket::connected, this, &ClientAuthHandler::onSocketConnected);
77 emit statusMessage(tr("Connecting to %1...").arg(_account.accountName()));
78 socket->connectToHost(_account.hostName(), _account.port());
81 void ClientAuthHandler::onSocketStateChanged(QAbstractSocket::SocketState socketState)
85 switch (socketState) {
86 case QAbstractSocket::HostLookupState:
88 text = tr("Looking up %1...").arg(_account.hostName());
90 case QAbstractSocket::ConnectingState:
92 text = tr("Connecting to %1...").arg(_account.hostName());
94 case QAbstractSocket::ConnectedState:
95 text = tr("Connected to %1").arg(_account.hostName());
97 case QAbstractSocket::ClosingState:
99 text = tr("Disconnecting from %1...").arg(_account.hostName());
101 case QAbstractSocket::UnconnectedState:
103 text = tr("Disconnected");
104 // Ensure the disconnected() signal is sent even if we haven't reached the Connected state yet.
105 // The baseclass implementation will make sure to only send the signal once.
106 // However, we do want to prefer a potential socket error signal that may be on route already, so
107 // give this a chance to overtake us by spinning the loop...
108 QTimer::singleShot(0, this, &ClientAuthHandler::onSocketDisconnected);
115 if (!text.isEmpty()) {
116 emit statusMessage(text);
120 void ClientAuthHandler::onSocketError(QAbstractSocket::SocketError error)
122 if (_probing && error == QAbstractSocket::RemoteHostClosedError) {
127 _probing = false; // all other errors are unrelated to probing and should be handled
128 AuthHandler::onSocketError(error);
131 void ClientAuthHandler::onSocketDisconnected()
133 if (_probing && _legacy) {
134 // Remote host has closed the connection while probing
136 disconnect(socket(), &QIODevice::readyRead, this, &ClientAuthHandler::onReadyRead);
137 emit statusMessage(tr("Reconnecting in compatibility mode..."));
138 socket()->connectToHost(_account.hostName(), _account.port());
142 AuthHandler::onSocketDisconnected();
145 void ClientAuthHandler::onSocketConnected()
148 qWarning() << Q_FUNC_INFO << "Peer already exists!";
152 socket()->setSocketOption(QAbstractSocket::KeepAliveOption, true);
155 // First connection attempt, try probing for a capable core
158 QDataStream stream(socket()); // stream handles the endianness for us
159 stream.setVersion(QDataStream::Qt_4_2);
161 quint32 magic = Protocol::magic;
162 if (_account.useSsl())
163 magic |= Protocol::Encryption;
164 magic |= Protocol::Compression;
168 // here goes the list of protocols we support, in order of preference
169 PeerFactory::ProtoList protos = PeerFactory::supportedProtocols();
170 for (int i = 0; i < protos.count(); ++i) {
171 quint32 reply = protos[i].first;
172 reply |= protos[i].second << 8;
173 if (i == protos.count() - 1)
174 reply |= 0x80000000; // end list
178 socket()->flush(); // make sure the probing data is sent immediately
182 // If we arrive here, it's the second connection attempt, meaning probing was not successful -> enable legacy support
184 qDebug() << "Legacy core detected, switching to compatibility mode";
186 auto* peer = PeerFactory::createPeer(PeerFactory::ProtoDescriptor(Protocol::LegacyProtocol, 0),
189 Compressor::NoCompression,
191 // Only needed for the legacy peer, as all others check the protocol version before instantiation
192 connect(peer, &RemotePeer::protocolVersionMismatch, this, &ClientAuthHandler::onProtocolVersionMismatch);
197 void ClientAuthHandler::onReadyRead()
199 if (socket()->bytesAvailable() < 4)
203 return; // make sure to not read more data than needed
206 disconnect(socket(), &QIODevice::readyRead, this, &ClientAuthHandler::onReadyRead);
209 socket()->read((char*)&reply, 4);
210 reply = qFromBigEndian<quint32>(reply);
212 auto type = static_cast<Protocol::Type>(reply & 0xff);
213 auto protoFeatures = static_cast<quint16>(reply >> 8 & 0xffff);
214 _connectionFeatures = static_cast<quint8>(reply >> 24);
216 Compressor::CompressionLevel level;
217 if (_connectionFeatures & Protocol::Compression)
218 level = Compressor::BestCompression;
220 level = Compressor::NoCompression;
222 RemotePeer* peer = PeerFactory::createPeer(PeerFactory::ProtoDescriptor(type, protoFeatures), this, socket(), level, this);
224 qWarning() << "No valid protocol supported for this core!";
225 emit errorPopup(tr("<b>Incompatible Quassel Core!</b><br>"
226 "None of the protocols this client speaks are supported by the core you are trying to connect to."));
228 requestDisconnect(tr("Core speaks none of the protocols we support"));
232 if (peer->protocol() == Protocol::LegacyProtocol) {
233 connect(peer, &RemotePeer::protocolVersionMismatch, this, &ClientAuthHandler::onProtocolVersionMismatch);
240 void ClientAuthHandler::onProtocolVersionMismatch(int actual, int expected)
242 emit errorPopup(tr("<b>The Quassel Core you are trying to connect to is too old!</b><br>"
243 "We need at least protocol v%1, but the core speaks v%2 only.")
244 .arg(expected, actual));
245 requestDisconnect(tr("Incompatible protocol version, connection to core refused"));
248 void ClientAuthHandler::setPeer(RemotePeer* peer)
250 qDebug().nospace() << "Using " << qPrintable(peer->protocolName()) << "...";
253 connect(_peer, &RemotePeer::transferProgress, this, &ClientAuthHandler::transferProgress);
255 // The legacy protocol enables SSL later, after registration
256 if (!_account.useSsl() || _legacy)
258 // otherwise, do it now
260 checkAndEnableSsl(_connectionFeatures & Protocol::Encryption);
263 void ClientAuthHandler::startRegistration()
265 emit statusMessage(tr("Synchronizing to core..."));
267 // useSsl will be ignored by non-legacy peers
269 useSsl = _account.useSsl();
271 _peer->dispatch(Protocol::RegisterClient(Quassel::Features{}, Quassel::buildInfo().fancyVersionString, Quassel::buildInfo().commitDate, useSsl));
274 void ClientAuthHandler::handle(const Protocol::ClientDenied& msg)
276 emit errorPopup(msg.errorString);
277 requestDisconnect(tr("The core refused connection from this client"));
280 void ClientAuthHandler::handle(const Protocol::ClientRegistered& msg)
282 _coreConfigured = msg.coreConfigured;
283 _backendInfo = msg.backendInfo;
284 _authenticatorInfo = msg.authenticatorInfo;
286 _peer->setFeatures(std::move(msg.features));
288 // The legacy protocol enables SSL at this point
289 if (_legacy && _account.useSsl())
290 checkAndEnableSsl(msg.sslSupported);
295 void ClientAuthHandler::onConnectionReady()
297 const auto& coreFeatures = _peer->features();
298 auto unsupported = coreFeatures.toStringList(false);
299 if (!unsupported.isEmpty()) {
300 qInfo() << qPrintable(tr("Core does not support the following features: %1").arg(unsupported.join(", ")));
302 if (!coreFeatures.unknownFeatures().isEmpty()) {
303 qInfo() << qPrintable(tr("Core supports unknown features: %1").arg(coreFeatures.unknownFeatures().join(", ")));
306 emit connectionReady();
307 emit statusMessage(tr("Connected to %1").arg(_account.accountName()));
309 if (!_coreConfigured) {
311 emit startCoreSetup(_backendInfo, _authenticatorInfo);
313 else // TODO: check if we need LoginEnabled
317 void ClientAuthHandler::setupCore(const Protocol::SetupData& setupData)
319 _peer->dispatch(setupData);
322 void ClientAuthHandler::handle(const Protocol::SetupFailed& msg)
324 emit coreSetupFailed(msg.errorString);
327 void ClientAuthHandler::handle(const Protocol::SetupDone& msg)
331 emit coreSetupSuccessful();
334 void ClientAuthHandler::login(const QString& user, const QString& password, bool remember)
336 _account.setUser(user);
337 _account.setPassword(password);
338 _account.setStorePassword(remember);
342 void ClientAuthHandler::login(const QString& previousError)
344 emit statusMessage(tr("Logging in..."));
345 if (_account.user().isEmpty() || _account.password().isEmpty() || !previousError.isEmpty()) {
347 emit userAuthenticationRequired(&_account, &valid, previousError); // *must* be a synchronous call
348 if (!valid || _account.user().isEmpty() || _account.password().isEmpty()) {
349 requestDisconnect(tr("Login canceled"));
354 _peer->dispatch(Protocol::Login(_account.user(), _account.password()));
357 void ClientAuthHandler::handle(const Protocol::LoginFailed& msg)
359 login(msg.errorString);
362 void ClientAuthHandler::handle(const Protocol::LoginSuccess& msg)
366 emit loginSuccessful(_account);
369 void ClientAuthHandler::handle(const Protocol::SessionState& msg)
371 disconnect(socket(), nullptr, this, nullptr); // this is the last message we shall ever get
373 // give up ownership of the peer; CoreSession takes responsibility now
374 _peer->setParent(nullptr);
375 emit handshakeComplete(_peer, msg);
380 void ClientAuthHandler::checkAndEnableSsl(bool coreSupportsSsl)
382 CoreAccountSettings s;
383 if (coreSupportsSsl && _account.useSsl()) {
384 // Make sure the warning is shown next time we don't have SSL in the core
385 s.setAccountValue("ShowNoCoreSslWarning", true);
387 connect(socket(), &QSslSocket::encrypted, this, &ClientAuthHandler::onSslSocketEncrypted);
388 connect(socket(), selectOverload<const QList<QSslError>&>(&QSslSocket::sslErrors), this, &ClientAuthHandler::onSslErrors);
389 qDebug() << "Starting encryption...";
391 socket()->startClientEncryption();
394 if (s.accountValue("ShowNoCoreSslWarning", true).toBool()) {
395 bool accepted = false;
396 emit handleNoSslInCore(&accepted);
398 requestDisconnect(tr("Unencrypted connection cancelled"));
401 s.setAccountValue("ShowNoCoreSslWarning", false);
402 s.setAccountValue("SslCert", QString());
403 s.setAccountValue("SslCertDigestVersion", QVariant(QVariant::Int));
413 void ClientAuthHandler::onSslSocketEncrypted()
415 auto* socket = qobject_cast<QSslSocket*>(sender());
418 if (!socket->sslErrors().count()) {
419 // Cert is valid, so we don't want to store it as known
420 // That way, a warning will appear in case it becomes invalid at some point
421 CoreAccountSettings s;
422 s.setAccountValue("SSLCert", QString());
423 s.setAccountValue("SslCertDigestVersion", QVariant(QVariant::Int));
426 emit encrypted(true);
434 void ClientAuthHandler::onSslErrors()
436 CoreAccountSettings s;
437 QByteArray knownDigest = s.accountValue("SslCert").toByteArray();
438 ClientAuthHandler::DigestVersion knownDigestVersion = static_cast<ClientAuthHandler::DigestVersion>(
439 s.accountValue("SslCertDigestVersion").toInt());
441 QByteArray calculatedDigest;
442 switch (knownDigestVersion) {
443 case ClientAuthHandler::DigestVersion::Md5:
444 calculatedDigest = socket()->peerCertificate().digest(QCryptographicHash::Md5);
447 case ClientAuthHandler::DigestVersion::Sha2_512:
448 calculatedDigest = socket()->peerCertificate().digest(QCryptographicHash::Sha512);
452 qWarning() << "Certificate digest version" << QString(knownDigestVersion) << "is not supported";
455 if (knownDigest != calculatedDigest) {
456 bool accepted = false;
457 bool permanently = false;
458 emit handleSslErrors(socket(), &accepted, &permanently);
461 requestDisconnect(tr("Unencrypted connection canceled"));
466 s.setAccountValue("SslCert", socket()->peerCertificate().digest(QCryptographicHash::Sha512));
467 s.setAccountValue("SslCertDigestVersion", ClientAuthHandler::DigestVersion::Latest);
470 s.setAccountValue("SslCert", QString());
471 s.setAccountValue("SslCertDigestVersion", QVariant(QVariant::Int));
474 else if (knownDigestVersion != ClientAuthHandler::DigestVersion::Latest) {
475 s.setAccountValue("SslCert", socket()->peerCertificate().digest(QCryptographicHash::Sha512));
476 s.setAccountValue("SslCertDigestVersion", ClientAuthHandler::DigestVersion::Latest);
479 socket()->ignoreSslErrors();