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"
26 # include <QSslSocket>
28 # include <QTcpSocket>
32 #include "clientsettings.h"
33 #include "peerfactory.h"
36 ClientAuthHandler::ClientAuthHandler(CoreAccount account, QObject* parent)
42 , _connectionFeatures(0)
45 Peer* ClientAuthHandler::peer() const
50 void ClientAuthHandler::connectToCore()
52 CoreAccountSettings s;
55 auto* socket = new QSslSocket(this);
56 // make sure the warning is shown if we happen to connect without SSL support later
57 s.setAccountValue("ShowNoClientSslWarning", true);
59 if (_account.useSsl()) {
60 if (s.accountValue("ShowNoClientSslWarning", true).toBool()) {
61 bool accepted = false;
62 emit handleNoSslInClient(&accepted);
64 emit errorMessage(tr("Unencrypted connection canceled"));
67 s.setAccountValue("ShowNoClientSslWarning", false);
70 QTcpSocket* socket = new QTcpSocket(this);
73 #ifndef QT_NO_NETWORKPROXY
75 proxy.setType(_account.proxyType());
76 if (_account.proxyType() == QNetworkProxy::Socks5Proxy || _account.proxyType() == QNetworkProxy::HttpProxy) {
77 proxy.setHostName(_account.proxyHostName());
78 proxy.setPort(_account.proxyPort());
79 proxy.setUser(_account.proxyUser());
80 proxy.setPassword(_account.proxyPassword());
83 if (_account.proxyType() == QNetworkProxy::DefaultProxy) {
84 QNetworkProxyFactory::setUseSystemConfiguration(true);
87 QNetworkProxyFactory::setUseSystemConfiguration(false);
88 socket->setProxy(proxy);
93 connect(socket, &QAbstractSocket::stateChanged, this, &ClientAuthHandler::onSocketStateChanged);
94 connect(socket, &QIODevice::readyRead, this, &ClientAuthHandler::onReadyRead);
95 connect(socket, &QAbstractSocket::connected, this, &ClientAuthHandler::onSocketConnected);
97 emit statusMessage(tr("Connecting to %1...").arg(_account.accountName()));
98 socket->connectToHost(_account.hostName(), _account.port());
101 void ClientAuthHandler::onSocketStateChanged(QAbstractSocket::SocketState socketState)
105 switch (socketState) {
106 case QAbstractSocket::HostLookupState:
108 text = tr("Looking up %1...").arg(_account.hostName());
110 case QAbstractSocket::ConnectingState:
112 text = tr("Connecting to %1...").arg(_account.hostName());
114 case QAbstractSocket::ConnectedState:
115 text = tr("Connected to %1").arg(_account.hostName());
117 case QAbstractSocket::ClosingState:
119 text = tr("Disconnecting from %1...").arg(_account.hostName());
121 case QAbstractSocket::UnconnectedState:
123 text = tr("Disconnected");
124 // Ensure the disconnected() signal is sent even if we haven't reached the Connected state yet.
125 // The baseclass implementation will make sure to only send the signal once.
126 // However, we do want to prefer a potential socket error signal that may be on route already, so
127 // give this a chance to overtake us by spinning the loop...
128 QTimer::singleShot(0, this, &ClientAuthHandler::onSocketDisconnected);
135 if (!text.isEmpty()) {
136 emit statusMessage(text);
140 void ClientAuthHandler::onSocketError(QAbstractSocket::SocketError error)
142 if (_probing && error == QAbstractSocket::RemoteHostClosedError) {
147 _probing = false; // all other errors are unrelated to probing and should be handled
148 AuthHandler::onSocketError(error);
151 void ClientAuthHandler::onSocketDisconnected()
153 if (_probing && _legacy) {
154 // Remote host has closed the connection while probing
156 disconnect(socket(), &QIODevice::readyRead, this, &ClientAuthHandler::onReadyRead);
157 emit statusMessage(tr("Reconnecting in compatibility mode..."));
158 socket()->connectToHost(_account.hostName(), _account.port());
162 AuthHandler::onSocketDisconnected();
165 void ClientAuthHandler::onSocketConnected()
168 qWarning() << Q_FUNC_INFO << "Peer already exists!";
172 socket()->setSocketOption(QAbstractSocket::KeepAliveOption, true);
175 // First connection attempt, try probing for a capable core
178 QDataStream stream(socket()); // stream handles the endianness for us
179 stream.setVersion(QDataStream::Qt_4_2);
181 quint32 magic = Protocol::magic;
183 if (_account.useSsl())
184 magic |= Protocol::Encryption;
186 magic |= Protocol::Compression;
190 // here goes the list of protocols we support, in order of preference
191 PeerFactory::ProtoList protos = PeerFactory::supportedProtocols();
192 for (int i = 0; i < protos.count(); ++i) {
193 quint32 reply = protos[i].first;
194 reply |= protos[i].second << 8;
195 if (i == protos.count() - 1)
196 reply |= 0x80000000; // end list
200 socket()->flush(); // make sure the probing data is sent immediately
204 // If we arrive here, it's the second connection attempt, meaning probing was not successful -> enable legacy support
206 qDebug() << "Legacy core detected, switching to compatibility mode";
208 auto* peer = PeerFactory::createPeer(PeerFactory::ProtoDescriptor(Protocol::LegacyProtocol, 0),
211 Compressor::NoCompression,
213 // Only needed for the legacy peer, as all others check the protocol version before instantiation
214 connect(peer, &RemotePeer::protocolVersionMismatch, this, &ClientAuthHandler::onProtocolVersionMismatch);
219 void ClientAuthHandler::onReadyRead()
221 if (socket()->bytesAvailable() < 4)
225 return; // make sure to not read more data than needed
228 disconnect(socket(), &QIODevice::readyRead, this, &ClientAuthHandler::onReadyRead);
231 socket()->read((char*)&reply, 4);
232 reply = qFromBigEndian<quint32>(reply);
234 auto type = static_cast<Protocol::Type>(reply & 0xff);
235 auto protoFeatures = static_cast<quint16>(reply >> 8 & 0xffff);
236 _connectionFeatures = static_cast<quint8>(reply >> 24);
238 Compressor::CompressionLevel level;
239 if (_connectionFeatures & Protocol::Compression)
240 level = Compressor::BestCompression;
242 level = Compressor::NoCompression;
244 RemotePeer* peer = PeerFactory::createPeer(PeerFactory::ProtoDescriptor(type, protoFeatures), this, socket(), level, this);
246 qWarning() << "No valid protocol supported for this core!";
247 emit errorPopup(tr("<b>Incompatible Quassel Core!</b><br>"
248 "None of the protocols this client speaks are supported by the core you are trying to connect to."));
250 requestDisconnect(tr("Core speaks none of the protocols we support"));
254 if (peer->protocol() == Protocol::LegacyProtocol) {
255 connect(peer, &RemotePeer::protocolVersionMismatch, this, &ClientAuthHandler::onProtocolVersionMismatch);
262 void ClientAuthHandler::onProtocolVersionMismatch(int actual, int expected)
264 emit errorPopup(tr("<b>The Quassel Core you are trying to connect to is too old!</b><br>"
265 "We need at least protocol v%1, but the core speaks v%2 only.")
266 .arg(expected, actual));
267 requestDisconnect(tr("Incompatible protocol version, connection to core refused"));
270 void ClientAuthHandler::setPeer(RemotePeer* peer)
272 qDebug().nospace() << "Using " << qPrintable(peer->protocolName()) << "...";
275 connect(_peer, &RemotePeer::transferProgress, this, &ClientAuthHandler::transferProgress);
277 // The legacy protocol enables SSL later, after registration
278 if (!_account.useSsl() || _legacy)
280 // otherwise, do it now
282 checkAndEnableSsl(_connectionFeatures & Protocol::Encryption);
285 void ClientAuthHandler::startRegistration()
287 emit statusMessage(tr("Synchronizing to core..."));
289 // useSsl will be ignored by non-legacy peers
292 useSsl = _account.useSsl();
295 _peer->dispatch(Protocol::RegisterClient(Quassel::Features{}, Quassel::buildInfo().fancyVersionString, Quassel::buildInfo().commitDate, useSsl));
298 void ClientAuthHandler::handle(const Protocol::ClientDenied& msg)
300 emit errorPopup(msg.errorString);
301 requestDisconnect(tr("The core refused connection from this client"));
304 void ClientAuthHandler::handle(const Protocol::ClientRegistered& msg)
306 _coreConfigured = msg.coreConfigured;
307 _backendInfo = msg.backendInfo;
308 _authenticatorInfo = msg.authenticatorInfo;
310 _peer->setFeatures(std::move(msg.features));
312 // The legacy protocol enables SSL at this point
313 if (_legacy && _account.useSsl())
314 checkAndEnableSsl(msg.sslSupported);
319 void ClientAuthHandler::onConnectionReady()
321 const auto& coreFeatures = _peer->features();
322 auto unsupported = coreFeatures.toStringList(false);
323 if (!unsupported.isEmpty()) {
324 qInfo() << qPrintable(tr("Core does not support the following features: %1").arg(unsupported.join(", ")));
326 if (!coreFeatures.unknownFeatures().isEmpty()) {
327 qInfo() << qPrintable(tr("Core supports unknown features: %1").arg(coreFeatures.unknownFeatures().join(", ")));
330 emit connectionReady();
331 emit statusMessage(tr("Connected to %1").arg(_account.accountName()));
333 if (!_coreConfigured) {
335 emit startCoreSetup(_backendInfo, _authenticatorInfo);
337 else // TODO: check if we need LoginEnabled
341 void ClientAuthHandler::setupCore(const Protocol::SetupData& setupData)
343 _peer->dispatch(setupData);
346 void ClientAuthHandler::handle(const Protocol::SetupFailed& msg)
348 emit coreSetupFailed(msg.errorString);
351 void ClientAuthHandler::handle(const Protocol::SetupDone& msg)
355 emit coreSetupSuccessful();
358 void ClientAuthHandler::login(const QString& user, const QString& password, bool remember)
360 _account.setUser(user);
361 _account.setPassword(password);
362 _account.setStorePassword(remember);
366 void ClientAuthHandler::login(const QString& previousError)
368 emit statusMessage(tr("Logging in..."));
369 if (_account.user().isEmpty() || _account.password().isEmpty() || !previousError.isEmpty()) {
371 emit userAuthenticationRequired(&_account, &valid, previousError); // *must* be a synchronous call
372 if (!valid || _account.user().isEmpty() || _account.password().isEmpty()) {
373 requestDisconnect(tr("Login canceled"));
378 _peer->dispatch(Protocol::Login(_account.user(), _account.password()));
381 void ClientAuthHandler::handle(const Protocol::LoginFailed& msg)
383 login(msg.errorString);
386 void ClientAuthHandler::handle(const Protocol::LoginSuccess& msg)
390 emit loginSuccessful(_account);
393 void ClientAuthHandler::handle(const Protocol::SessionState& msg)
395 disconnect(socket(), nullptr, this, nullptr); // this is the last message we shall ever get
397 // give up ownership of the peer; CoreSession takes responsibility now
398 _peer->setParent(nullptr);
399 emit handshakeComplete(_peer, msg);
404 void ClientAuthHandler::checkAndEnableSsl(bool coreSupportsSsl)
407 Q_UNUSED(coreSupportsSsl);
409 CoreAccountSettings s;
410 if (coreSupportsSsl && _account.useSsl()) {
411 // Make sure the warning is shown next time we don't have SSL in the core
412 s.setAccountValue("ShowNoCoreSslWarning", true);
414 auto* sslSocket = qobject_cast<QSslSocket*>(socket());
416 connect(sslSocket, &QSslSocket::encrypted, this, &ClientAuthHandler::onSslSocketEncrypted);
417 connect(sslSocket, selectOverload<const QList<QSslError>&>(&QSslSocket::sslErrors), this, &ClientAuthHandler::onSslErrors);
418 qDebug() << "Starting encryption...";
420 sslSocket->startClientEncryption();
423 if (s.accountValue("ShowNoCoreSslWarning", true).toBool()) {
424 bool accepted = false;
425 emit handleNoSslInCore(&accepted);
427 requestDisconnect(tr("Unencrypted connection cancelled"));
430 s.setAccountValue("ShowNoCoreSslWarning", false);
431 s.setAccountValue("SslCert", QString());
432 s.setAccountValue("SslCertDigestVersion", QVariant(QVariant::Int));
444 void ClientAuthHandler::onSslSocketEncrypted()
446 auto* socket = qobject_cast<QSslSocket*>(sender());
449 if (!socket->sslErrors().count()) {
450 // Cert is valid, so we don't want to store it as known
451 // That way, a warning will appear in case it becomes invalid at some point
452 CoreAccountSettings s;
453 s.setAccountValue("SSLCert", QString());
454 s.setAccountValue("SslCertDigestVersion", QVariant(QVariant::Int));
457 emit encrypted(true);
465 void ClientAuthHandler::onSslErrors()
467 auto* socket = qobject_cast<QSslSocket*>(sender());
470 CoreAccountSettings s;
471 QByteArray knownDigest = s.accountValue("SslCert").toByteArray();
472 ClientAuthHandler::DigestVersion knownDigestVersion = static_cast<ClientAuthHandler::DigestVersion>(
473 s.accountValue("SslCertDigestVersion").toInt());
475 QByteArray calculatedDigest;
476 switch (knownDigestVersion) {
477 case ClientAuthHandler::DigestVersion::Md5:
478 calculatedDigest = socket->peerCertificate().digest(QCryptographicHash::Md5);
481 case ClientAuthHandler::DigestVersion::Sha2_512:
482 calculatedDigest = socket->peerCertificate().digest(QCryptographicHash::Sha512);
486 qWarning() << "Certificate digest version" << QString(knownDigestVersion) << "is not supported";
489 if (knownDigest != calculatedDigest) {
490 bool accepted = false;
491 bool permanently = false;
492 emit handleSslErrors(socket, &accepted, &permanently);
495 requestDisconnect(tr("Unencrypted connection canceled"));
500 s.setAccountValue("SslCert", socket->peerCertificate().digest(QCryptographicHash::Sha512));
501 s.setAccountValue("SslCertDigestVersion", ClientAuthHandler::DigestVersion::Latest);
504 s.setAccountValue("SslCert", QString());
505 s.setAccountValue("SslCertDigestVersion", QVariant(QVariant::Int));
508 else if (knownDigestVersion != ClientAuthHandler::DigestVersion::Latest) {
509 s.setAccountValue("SslCert", socket->peerCertificate().digest(QCryptographicHash::Sha512));
510 s.setAccountValue("SslCertDigestVersion", ClientAuthHandler::DigestVersion::Latest);
513 socket->ignoreSslErrors();
516 #endif /* HAVE_SSL */