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 "peerfactory.h"
36 using namespace Protocol;
38 ClientAuthHandler::ClientAuthHandler(CoreAccount account, QObject* parent)
44 , _connectionFeatures(0)
47 Peer* ClientAuthHandler::peer() const
52 void ClientAuthHandler::connectToCore()
54 CoreAccountSettings s;
57 auto* socket = new QSslSocket(this);
58 // make sure the warning is shown if we happen to connect without SSL support later
59 s.setAccountValue("ShowNoClientSslWarning", true);
61 if (_account.useSsl()) {
62 if (s.accountValue("ShowNoClientSslWarning", true).toBool()) {
63 bool accepted = false;
64 emit handleNoSslInClient(&accepted);
66 emit errorMessage(tr("Unencrypted connection canceled"));
69 s.setAccountValue("ShowNoClientSslWarning", false);
72 QTcpSocket* socket = new QTcpSocket(this);
75 #ifndef QT_NO_NETWORKPROXY
77 proxy.setType(_account.proxyType());
78 if (_account.proxyType() == QNetworkProxy::Socks5Proxy || _account.proxyType() == QNetworkProxy::HttpProxy) {
79 proxy.setHostName(_account.proxyHostName());
80 proxy.setPort(_account.proxyPort());
81 proxy.setUser(_account.proxyUser());
82 proxy.setPassword(_account.proxyPassword());
85 if (_account.proxyType() == QNetworkProxy::DefaultProxy) {
86 QNetworkProxyFactory::setUseSystemConfiguration(true);
89 QNetworkProxyFactory::setUseSystemConfiguration(false);
90 socket->setProxy(proxy);
95 connect(socket, &QAbstractSocket::stateChanged, this, &ClientAuthHandler::onSocketStateChanged);
96 connect(socket, &QIODevice::readyRead, this, &ClientAuthHandler::onReadyRead);
97 connect(socket, &QAbstractSocket::connected, this, &ClientAuthHandler::onSocketConnected);
99 emit statusMessage(tr("Connecting to %1...").arg(_account.accountName()));
100 socket->connectToHost(_account.hostName(), _account.port());
103 void ClientAuthHandler::onSocketStateChanged(QAbstractSocket::SocketState socketState)
107 switch (socketState) {
108 case QAbstractSocket::HostLookupState:
110 text = tr("Looking up %1...").arg(_account.hostName());
112 case QAbstractSocket::ConnectingState:
114 text = tr("Connecting to %1...").arg(_account.hostName());
116 case QAbstractSocket::ConnectedState:
117 text = tr("Connected to %1").arg(_account.hostName());
119 case QAbstractSocket::ClosingState:
121 text = tr("Disconnecting from %1...").arg(_account.hostName());
123 case QAbstractSocket::UnconnectedState:
125 text = tr("Disconnected");
126 // Ensure the disconnected() signal is sent even if we haven't reached the Connected state yet.
127 // The baseclass implementation will make sure to only send the signal once.
128 // However, we do want to prefer a potential socket error signal that may be on route already, so
129 // give this a chance to overtake us by spinning the loop...
130 QTimer::singleShot(0, this, &ClientAuthHandler::onSocketDisconnected);
137 if (!text.isEmpty()) {
138 emit statusMessage(text);
142 void ClientAuthHandler::onSocketError(QAbstractSocket::SocketError error)
144 if (_probing && error == QAbstractSocket::RemoteHostClosedError) {
149 _probing = false; // all other errors are unrelated to probing and should be handled
150 AuthHandler::onSocketError(error);
153 void ClientAuthHandler::onSocketDisconnected()
155 if (_probing && _legacy) {
156 // Remote host has closed the connection while probing
158 disconnect(socket(), &QIODevice::readyRead, this, &ClientAuthHandler::onReadyRead);
159 emit statusMessage(tr("Reconnecting in compatibility mode..."));
160 socket()->connectToHost(_account.hostName(), _account.port());
164 AuthHandler::onSocketDisconnected();
167 void ClientAuthHandler::onSocketConnected()
170 qWarning() << Q_FUNC_INFO << "Peer already exists!";
174 socket()->setSocketOption(QAbstractSocket::KeepAliveOption, true);
177 // First connection attempt, try probing for a capable core
180 QDataStream stream(socket()); // stream handles the endianness for us
181 stream.setVersion(QDataStream::Qt_4_2);
183 quint32 magic = Protocol::magic;
185 if (_account.useSsl())
186 magic |= Protocol::Encryption;
188 magic |= Protocol::Compression;
192 // here goes the list of protocols we support, in order of preference
193 PeerFactory::ProtoList protos = PeerFactory::supportedProtocols();
194 for (int i = 0; i < protos.count(); ++i) {
195 quint32 reply = protos[i].first;
196 reply |= protos[i].second << 8;
197 if (i == protos.count() - 1)
198 reply |= 0x80000000; // end list
202 socket()->flush(); // make sure the probing data is sent immediately
206 // If we arrive here, it's the second connection attempt, meaning probing was not successful -> enable legacy support
208 qDebug() << "Legacy core detected, switching to compatibility mode";
210 auto* peer = PeerFactory::createPeer(PeerFactory::ProtoDescriptor(Protocol::LegacyProtocol, 0),
213 Compressor::NoCompression,
215 // Only needed for the legacy peer, as all others check the protocol version before instantiation
216 connect(peer, &RemotePeer::protocolVersionMismatch, this, &ClientAuthHandler::onProtocolVersionMismatch);
221 void ClientAuthHandler::onReadyRead()
223 if (socket()->bytesAvailable() < 4)
227 return; // make sure to not read more data than needed
230 disconnect(socket(), &QIODevice::readyRead, this, &ClientAuthHandler::onReadyRead);
233 socket()->read((char*)&reply, 4);
234 reply = qFromBigEndian<quint32>(reply);
236 auto type = static_cast<Protocol::Type>(reply & 0xff);
237 auto protoFeatures = static_cast<quint16>(reply >> 8 & 0xffff);
238 _connectionFeatures = static_cast<quint8>(reply >> 24);
240 Compressor::CompressionLevel level;
241 if (_connectionFeatures & Protocol::Compression)
242 level = Compressor::BestCompression;
244 level = Compressor::NoCompression;
246 RemotePeer* peer = PeerFactory::createPeer(PeerFactory::ProtoDescriptor(type, protoFeatures), this, socket(), level, this);
248 qWarning() << "No valid protocol supported for this core!";
249 emit errorPopup(tr("<b>Incompatible Quassel Core!</b><br>"
250 "None of the protocols this client speaks are supported by the core you are trying to connect to."));
252 requestDisconnect(tr("Core speaks none of the protocols we support"));
256 if (peer->protocol() == Protocol::LegacyProtocol) {
257 connect(peer, &RemotePeer::protocolVersionMismatch, this, &ClientAuthHandler::onProtocolVersionMismatch);
264 void ClientAuthHandler::onProtocolVersionMismatch(int actual, int expected)
266 emit errorPopup(tr("<b>The Quassel Core you are trying to connect to is too old!</b><br>"
267 "We need at least protocol v%1, but the core speaks v%2 only.")
268 .arg(expected, actual));
269 requestDisconnect(tr("Incompatible protocol version, connection to core refused"));
272 void ClientAuthHandler::setPeer(RemotePeer* peer)
274 qDebug().nospace() << "Using " << qPrintable(peer->protocolName()) << "...";
277 connect(_peer, &RemotePeer::transferProgress, this, &ClientAuthHandler::transferProgress);
279 // The legacy protocol enables SSL later, after registration
280 if (!_account.useSsl() || _legacy)
282 // otherwise, do it now
284 checkAndEnableSsl(_connectionFeatures & Protocol::Encryption);
287 void ClientAuthHandler::startRegistration()
289 emit statusMessage(tr("Synchronizing to core..."));
291 // useSsl will be ignored by non-legacy peers
294 useSsl = _account.useSsl();
297 _peer->dispatch(RegisterClient(Quassel::Features{}, Quassel::buildInfo().fancyVersionString, Quassel::buildInfo().commitDate, useSsl));
300 void ClientAuthHandler::handle(const ClientDenied& msg)
302 emit errorPopup(msg.errorString);
303 requestDisconnect(tr("The core refused connection from this client"));
306 void ClientAuthHandler::handle(const ClientRegistered& msg)
308 _coreConfigured = msg.coreConfigured;
309 _backendInfo = msg.backendInfo;
310 _authenticatorInfo = msg.authenticatorInfo;
312 _peer->setFeatures(std::move(msg.features));
314 // The legacy protocol enables SSL at this point
315 if (_legacy && _account.useSsl())
316 checkAndEnableSsl(msg.sslSupported);
321 void ClientAuthHandler::onConnectionReady()
323 const auto& coreFeatures = _peer->features();
324 auto unsupported = coreFeatures.toStringList(false);
325 if (!unsupported.isEmpty()) {
326 qInfo() << qPrintable(tr("Core does not support the following features: %1").arg(unsupported.join(", ")));
328 if (!coreFeatures.unknownFeatures().isEmpty()) {
329 qInfo() << qPrintable(tr("Core supports unknown features: %1").arg(coreFeatures.unknownFeatures().join(", ")));
332 emit connectionReady();
333 emit statusMessage(tr("Connected to %1").arg(_account.accountName()));
335 if (!_coreConfigured) {
337 emit startCoreSetup(_backendInfo, _authenticatorInfo);
339 else // TODO: check if we need LoginEnabled
343 void ClientAuthHandler::setupCore(const SetupData& setupData)
345 _peer->dispatch(setupData);
348 void ClientAuthHandler::handle(const SetupFailed& msg)
350 emit coreSetupFailed(msg.errorString);
353 void ClientAuthHandler::handle(const SetupDone& msg)
357 emit coreSetupSuccessful();
360 void ClientAuthHandler::login(const QString& user, const QString& password, bool remember)
362 _account.setUser(user);
363 _account.setPassword(password);
364 _account.setStorePassword(remember);
368 void ClientAuthHandler::login(const QString& previousError)
370 emit statusMessage(tr("Logging in..."));
371 if (_account.user().isEmpty() || _account.password().isEmpty() || !previousError.isEmpty()) {
373 emit userAuthenticationRequired(&_account, &valid, previousError); // *must* be a synchronous call
374 if (!valid || _account.user().isEmpty() || _account.password().isEmpty()) {
375 requestDisconnect(tr("Login canceled"));
380 _peer->dispatch(Login(_account.user(), _account.password()));
383 void ClientAuthHandler::handle(const LoginFailed& msg)
385 login(msg.errorString);
388 void ClientAuthHandler::handle(const LoginSuccess& msg)
392 emit loginSuccessful(_account);
395 void ClientAuthHandler::handle(const SessionState& msg)
397 disconnect(socket(), nullptr, this, nullptr); // this is the last message we shall ever get
399 // give up ownership of the peer; CoreSession takes responsibility now
400 _peer->setParent(nullptr);
401 emit handshakeComplete(_peer, msg);
406 void ClientAuthHandler::checkAndEnableSsl(bool coreSupportsSsl)
409 Q_UNUSED(coreSupportsSsl);
411 CoreAccountSettings s;
412 if (coreSupportsSsl && _account.useSsl()) {
413 // Make sure the warning is shown next time we don't have SSL in the core
414 s.setAccountValue("ShowNoCoreSslWarning", true);
416 auto* sslSocket = qobject_cast<QSslSocket*>(socket());
418 connect(sslSocket, &QSslSocket::encrypted, this, &ClientAuthHandler::onSslSocketEncrypted);
419 connect(sslSocket, selectOverload<const QList<QSslError>&>(&QSslSocket::sslErrors), this, &ClientAuthHandler::onSslErrors);
420 qDebug() << "Starting encryption...";
422 sslSocket->startClientEncryption();
425 if (s.accountValue("ShowNoCoreSslWarning", true).toBool()) {
426 bool accepted = false;
427 emit handleNoSslInCore(&accepted);
429 requestDisconnect(tr("Unencrypted connection cancelled"));
432 s.setAccountValue("ShowNoCoreSslWarning", false);
433 s.setAccountValue("SslCert", QString());
434 s.setAccountValue("SslCertDigestVersion", QVariant(QVariant::Int));
446 void ClientAuthHandler::onSslSocketEncrypted()
448 auto* socket = qobject_cast<QSslSocket*>(sender());
451 if (!socket->sslErrors().count()) {
452 // Cert is valid, so we don't want to store it as known
453 // That way, a warning will appear in case it becomes invalid at some point
454 CoreAccountSettings s;
455 s.setAccountValue("SSLCert", QString());
456 s.setAccountValue("SslCertDigestVersion", QVariant(QVariant::Int));
459 emit encrypted(true);
467 void ClientAuthHandler::onSslErrors()
469 auto* socket = qobject_cast<QSslSocket*>(sender());
472 CoreAccountSettings s;
473 QByteArray knownDigest = s.accountValue("SslCert").toByteArray();
474 ClientAuthHandler::DigestVersion knownDigestVersion = static_cast<ClientAuthHandler::DigestVersion>(
475 s.accountValue("SslCertDigestVersion").toInt());
477 QByteArray calculatedDigest;
478 switch (knownDigestVersion) {
479 case ClientAuthHandler::DigestVersion::Md5:
480 calculatedDigest = socket->peerCertificate().digest(QCryptographicHash::Md5);
483 case ClientAuthHandler::DigestVersion::Sha2_512:
484 calculatedDigest = socket->peerCertificate().digest(QCryptographicHash::Sha512);
488 qWarning() << "Certificate digest version" << QString(knownDigestVersion) << "is not supported";
491 if (knownDigest != calculatedDigest) {
492 bool accepted = false;
493 bool permanently = false;
494 emit handleSslErrors(socket, &accepted, &permanently);
497 requestDisconnect(tr("Unencrypted connection canceled"));
502 s.setAccountValue("SslCert", socket->peerCertificate().digest(QCryptographicHash::Sha512));
503 s.setAccountValue("SslCertDigestVersion", ClientAuthHandler::DigestVersion::Latest);
506 s.setAccountValue("SslCert", QString());
507 s.setAccountValue("SslCertDigestVersion", QVariant(QVariant::Int));
510 else if (knownDigestVersion != ClientAuthHandler::DigestVersion::Latest) {
511 s.setAccountValue("SslCert", socket->peerCertificate().digest(QCryptographicHash::Sha512));
512 s.setAccountValue("SslCertDigestVersion", ClientAuthHandler::DigestVersion::Latest);
515 socket->ignoreSslErrors();
518 #endif /* HAVE_SSL */