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 magic |= Protocol::Encryption;
163 magic |= Protocol::Compression;
167 // here goes the list of protocols we support, in order of preference
168 PeerFactory::ProtoList protos = PeerFactory::supportedProtocols();
169 for (int i = 0; i < protos.count(); ++i) {
170 quint32 reply = protos[i].first;
171 reply |= protos[i].second << 8;
172 if (i == protos.count() - 1)
173 reply |= 0x80000000; // end list
177 socket()->flush(); // make sure the probing data is sent immediately
181 // If we arrive here, it's the second connection attempt, meaning probing was not successful -> enable legacy support
183 qDebug() << "Legacy core detected, switching to compatibility mode";
185 auto* peer = PeerFactory::createPeer(PeerFactory::ProtoDescriptor(Protocol::LegacyProtocol, 0),
188 Compressor::NoCompression,
190 // Only needed for the legacy peer, as all others check the protocol version before instantiation
191 connect(peer, &RemotePeer::protocolVersionMismatch, this, &ClientAuthHandler::onProtocolVersionMismatch);
196 void ClientAuthHandler::onReadyRead()
198 if (socket()->bytesAvailable() < 4)
202 return; // make sure to not read more data than needed
205 disconnect(socket(), &QIODevice::readyRead, this, &ClientAuthHandler::onReadyRead);
208 socket()->read((char*)&reply, 4);
209 reply = qFromBigEndian<quint32>(reply);
211 auto type = static_cast<Protocol::Type>(reply & 0xff);
212 auto protoFeatures = static_cast<quint16>(reply >> 8 & 0xffff);
213 _connectionFeatures = static_cast<quint8>(reply >> 24);
215 Compressor::CompressionLevel level;
216 if (_connectionFeatures & Protocol::Compression)
217 level = Compressor::BestCompression;
219 level = Compressor::NoCompression;
221 RemotePeer* peer = PeerFactory::createPeer(PeerFactory::ProtoDescriptor(type, protoFeatures), this, socket(), level, this);
223 qWarning() << "No valid protocol supported for this core!";
224 emit errorPopup(tr("<b>Incompatible Quassel Core!</b><br>"
225 "None of the protocols this client speaks are supported by the core you are trying to connect to."));
227 requestDisconnect(tr("Core speaks none of the protocols we support"));
231 if (peer->protocol() == Protocol::LegacyProtocol) {
232 connect(peer, &RemotePeer::protocolVersionMismatch, this, &ClientAuthHandler::onProtocolVersionMismatch);
239 void ClientAuthHandler::onProtocolVersionMismatch(int actual, int expected)
241 emit errorPopup(tr("<b>The Quassel Core you are trying to connect to is too old!</b><br>"
242 "We need at least protocol v%1, but the core speaks v%2 only.")
243 .arg(expected, actual));
244 requestDisconnect(tr("Incompatible protocol version, connection to core refused"));
247 void ClientAuthHandler::setPeer(RemotePeer* peer)
249 qDebug().nospace() << "Using " << qPrintable(peer->protocolName()) << "...";
252 connect(_peer, &RemotePeer::transferProgress, this, &ClientAuthHandler::transferProgress);
254 // The legacy protocol enables SSL later, after registration
257 // otherwise, do it now
259 checkAndEnableSsl(_connectionFeatures & Protocol::Encryption);
262 void ClientAuthHandler::startRegistration()
264 emit statusMessage(tr("Synchronizing to core..."));
266 _peer->dispatch(Protocol::RegisterClient(Quassel::Features{}, Quassel::buildInfo().fancyVersionString, Quassel::buildInfo().commitDate));
269 void ClientAuthHandler::handle(const Protocol::ClientDenied& msg)
271 emit errorPopup(msg.errorString);
272 requestDisconnect(tr("The core refused connection from this client"));
275 void ClientAuthHandler::handle(const Protocol::ClientRegistered& msg)
277 _coreConfigured = msg.coreConfigured;
278 _backendInfo = msg.backendInfo;
279 _authenticatorInfo = msg.authenticatorInfo;
281 _peer->setFeatures(std::move(msg.features));
283 // The legacy protocol enables SSL at this point
285 checkAndEnableSsl(msg.sslSupported);
290 void ClientAuthHandler::onConnectionReady()
292 const auto& coreFeatures = _peer->features();
293 auto unsupported = coreFeatures.toStringList(false);
294 if (!unsupported.isEmpty()) {
295 qInfo() << qPrintable(tr("Core does not support the following features: %1").arg(unsupported.join(", ")));
297 if (!coreFeatures.unknownFeatures().isEmpty()) {
298 qInfo() << qPrintable(tr("Core supports unknown features: %1").arg(coreFeatures.unknownFeatures().join(", ")));
301 emit connectionReady();
302 emit statusMessage(tr("Connected to %1").arg(_account.accountName()));
304 if (!_coreConfigured) {
306 emit startCoreSetup(_backendInfo, _authenticatorInfo);
308 else // TODO: check if we need LoginEnabled
312 void ClientAuthHandler::setupCore(const Protocol::SetupData& setupData)
314 _peer->dispatch(setupData);
317 void ClientAuthHandler::handle(const Protocol::SetupFailed& msg)
319 emit coreSetupFailed(msg.errorString);
322 void ClientAuthHandler::handle(const Protocol::SetupDone& msg)
326 emit coreSetupSuccessful();
329 void ClientAuthHandler::login(const QString& user, const QString& password, bool remember)
331 _account.setUser(user);
332 _account.setPassword(password);
333 _account.setStorePassword(remember);
337 void ClientAuthHandler::login(const QString& previousError)
339 emit statusMessage(tr("Logging in..."));
340 if (_account.user().isEmpty() || _account.password().isEmpty() || !previousError.isEmpty()) {
342 emit userAuthenticationRequired(&_account, &valid, previousError); // *must* be a synchronous call
343 if (!valid || _account.user().isEmpty() || _account.password().isEmpty()) {
344 requestDisconnect(tr("Login canceled"));
349 _peer->dispatch(Protocol::Login(_account.user(), _account.password()));
352 void ClientAuthHandler::handle(const Protocol::LoginFailed& msg)
354 login(msg.errorString);
357 void ClientAuthHandler::handle(const Protocol::LoginSuccess& msg)
361 emit loginSuccessful(_account);
364 void ClientAuthHandler::handle(const Protocol::SessionState& msg)
366 disconnect(socket(), nullptr, this, nullptr); // this is the last message we shall ever get
368 // give up ownership of the peer; CoreSession takes responsibility now
369 _peer->setParent(nullptr);
370 emit handshakeComplete(_peer, msg);
375 void ClientAuthHandler::checkAndEnableSsl(bool coreSupportsSsl)
377 CoreAccountSettings s;
378 if (coreSupportsSsl) {
379 // Make sure the warning is shown next time we don't have SSL in the core
380 s.setAccountValue("ShowNoCoreSslWarning", true);
382 connect(socket(), &QSslSocket::encrypted, this, &ClientAuthHandler::onSslSocketEncrypted);
383 connect(socket(), selectOverload<const QList<QSslError>&>(&QSslSocket::sslErrors), this, &ClientAuthHandler::onSslErrors);
384 qDebug() << "Starting encryption...";
386 socket()->startClientEncryption();
389 if (s.accountValue("ShowNoCoreSslWarning", true).toBool()) {
390 bool accepted = false;
391 emit handleNoSslInCore(&accepted);
393 requestDisconnect(tr("Unencrypted connection cancelled"));
396 s.setAccountValue("ShowNoCoreSslWarning", false);
397 s.setAccountValue("SslCert", QString());
398 s.setAccountValue("SslCertDigestVersion", QVariant(QVariant::Int));
408 void ClientAuthHandler::onSslSocketEncrypted()
410 auto* socket = qobject_cast<QSslSocket*>(sender());
413 if (!socket->sslErrors().count()) {
414 // Cert is valid, so we don't want to store it as known
415 // That way, a warning will appear in case it becomes invalid at some point
416 CoreAccountSettings s;
417 s.setAccountValue("SSLCert", QString());
418 s.setAccountValue("SslCertDigestVersion", QVariant(QVariant::Int));
421 emit encrypted(true);
429 void ClientAuthHandler::onSslErrors()
431 CoreAccountSettings s;
432 QByteArray knownDigest = s.accountValue("SslCert").toByteArray();
433 ClientAuthHandler::DigestVersion knownDigestVersion = static_cast<ClientAuthHandler::DigestVersion>(
434 s.accountValue("SslCertDigestVersion").toInt());
436 QByteArray calculatedDigest;
437 switch (knownDigestVersion) {
438 case ClientAuthHandler::DigestVersion::Md5:
439 calculatedDigest = socket()->peerCertificate().digest(QCryptographicHash::Md5);
442 case ClientAuthHandler::DigestVersion::Sha2_512:
443 calculatedDigest = socket()->peerCertificate().digest(QCryptographicHash::Sha512);
447 qWarning() << "Certificate digest version" << QString(knownDigestVersion) << "is not supported";
450 if (knownDigest != calculatedDigest) {
451 bool accepted = false;
452 bool permanently = false;
453 emit handleSslErrors(socket(), &accepted, &permanently);
456 requestDisconnect(tr("Unencrypted connection canceled"));
461 s.setAccountValue("SslCert", socket()->peerCertificate().digest(QCryptographicHash::Sha512));
462 s.setAccountValue("SslCertDigestVersion", ClientAuthHandler::DigestVersion::Latest);
465 s.setAccountValue("SslCert", QString());
466 s.setAccountValue("SslCertDigestVersion", QVariant(QVariant::Int));
469 else if (knownDigestVersion != ClientAuthHandler::DigestVersion::Latest) {
470 s.setAccountValue("SslCert", socket()->peerCertificate().digest(QCryptographicHash::Sha512));
471 s.setAccountValue("SslCertDigestVersion", ClientAuthHandler::DigestVersion::Latest);
474 socket()->ignoreSslErrors();