1 /***************************************************************************
2 * Copyright (C) 2005-2016 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"
23 // TODO: support system application proxy (new in Qt 4.6)
34 #include "clientsettings.h"
35 #include "peerfactory.h"
37 #if QT_VERSION < 0x050000
38 # include "../../3rdparty/sha512/sha512.h"
41 using namespace Protocol;
43 ClientAuthHandler::ClientAuthHandler(CoreAccount account, QObject *parent)
44 : AuthHandler(parent),
49 _connectionFeatures(0)
55 void ClientAuthHandler::connectToCore()
57 CoreAccountSettings s;
60 QSslSocket *socket = new QSslSocket(this);
61 // make sure the warning is shown if we happen to connect without SSL support later
62 s.setAccountValue("ShowNoClientSslWarning", true);
64 if (_account.useSsl()) {
65 if (s.accountValue("ShowNoClientSslWarning", true).toBool()) {
66 bool accepted = false;
67 emit handleNoSslInClient(&accepted);
69 emit errorMessage(tr("Unencrypted connection canceled"));
72 s.setAccountValue("ShowNoClientSslWarning", false);
75 QTcpSocket *socket = new QTcpSocket(this);
78 #ifndef QT_NO_NETWORKPROXY
80 proxy.setType(_account.proxyType());
81 if (_account.proxyType() == QNetworkProxy::Socks5Proxy ||
82 _account.proxyType() == QNetworkProxy::HttpProxy) {
83 proxy.setHostName(_account.proxyHostName());
84 proxy.setPort(_account.proxyPort());
85 proxy.setUser(_account.proxyUser());
86 proxy.setPassword(_account.proxyPassword());
89 if (_account.proxyType() == QNetworkProxy::DefaultProxy) {
90 QNetworkProxyFactory::setUseSystemConfiguration(true);
92 QNetworkProxyFactory::setUseSystemConfiguration(false);
93 socket->setProxy(proxy);
98 connect(socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), SLOT(onSocketStateChanged(QAbstractSocket::SocketState)));
99 connect(socket, SIGNAL(readyRead()), SLOT(onReadyRead()));
100 connect(socket, SIGNAL(connected()), SLOT(onSocketConnected()));
102 emit statusMessage(tr("Connecting to %1...").arg(_account.accountName()));
103 socket->connectToHost(_account.hostName(), _account.port());
107 void ClientAuthHandler::onSocketStateChanged(QAbstractSocket::SocketState socketState)
111 switch(socketState) {
112 case QAbstractSocket::HostLookupState:
114 text = tr("Looking up %1...").arg(_account.hostName());
116 case QAbstractSocket::ConnectingState:
118 text = tr("Connecting to %1...").arg(_account.hostName());
120 case QAbstractSocket::ConnectedState:
121 text = tr("Connected to %1").arg(_account.hostName());
123 case QAbstractSocket::ClosingState:
125 text = tr("Disconnecting from %1...").arg(_account.hostName());
127 case QAbstractSocket::UnconnectedState:
129 text = tr("Disconnected");
130 // Ensure the disconnected() signal is sent even if we haven't reached the Connected state yet.
131 // The baseclass implementation will make sure to only send the signal once.
132 // However, we do want to prefer a potential socket error signal that may be on route already, so
133 // give this a chance to overtake us by spinning the loop...
134 QTimer::singleShot(0, this, SLOT(onSocketDisconnected()));
141 if (!text.isEmpty()) {
142 emit statusMessage(text);
146 void ClientAuthHandler::onSocketError(QAbstractSocket::SocketError error)
148 if (_probing && error == QAbstractSocket::RemoteHostClosedError) {
153 _probing = false; // all other errors are unrelated to probing and should be handled
154 AuthHandler::onSocketError(error);
158 void ClientAuthHandler::onSocketDisconnected()
160 if (_probing && _legacy) {
161 // Remote host has closed the connection while probing
163 disconnect(socket(), SIGNAL(readyRead()), this, SLOT(onReadyRead()));
164 emit statusMessage(tr("Reconnecting in compatibility mode..."));
165 socket()->connectToHost(_account.hostName(), _account.port());
169 AuthHandler::onSocketDisconnected();
173 void ClientAuthHandler::onSocketConnected()
176 qWarning() << Q_FUNC_INFO << "Peer already exists!";
180 socket()->setSocketOption(QAbstractSocket::KeepAliveOption, true);
183 // First connection attempt, try probing for a capable core
186 QDataStream stream(socket()); // stream handles the endianness for us
187 stream.setVersion(QDataStream::Qt_4_2);
189 quint32 magic = Protocol::magic;
191 if (_account.useSsl())
192 magic |= Protocol::Encryption;
194 magic |= Protocol::Compression;
198 // here goes the list of protocols we support, in order of preference
199 PeerFactory::ProtoList protos = PeerFactory::supportedProtocols();
200 for (int i = 0; i < protos.count(); ++i) {
201 quint32 reply = protos[i].first;
202 reply |= protos[i].second<<8;
203 if (i == protos.count() - 1)
204 reply |= 0x80000000; // end list
208 socket()->flush(); // make sure the probing data is sent immediately
212 // If we arrive here, it's the second connection attempt, meaning probing was not successful -> enable legacy support
214 qDebug() << "Legacy core detected, switching to compatibility mode";
216 RemotePeer *peer = PeerFactory::createPeer(PeerFactory::ProtoDescriptor(Protocol::LegacyProtocol, 0), this, socket(), Compressor::NoCompression, this);
217 // Only needed for the legacy peer, as all others check the protocol version before instantiation
218 connect(peer, SIGNAL(protocolVersionMismatch(int,int)), SLOT(onProtocolVersionMismatch(int,int)));
224 void ClientAuthHandler::onReadyRead()
226 if (socket()->bytesAvailable() < 4)
230 return; // make sure to not read more data than needed
233 disconnect(socket(), SIGNAL(readyRead()), this, SLOT(onReadyRead()));
236 socket()->read((char *)&reply, 4);
237 reply = qFromBigEndian<quint32>(reply);
239 Protocol::Type type = static_cast<Protocol::Type>(reply & 0xff);
240 quint16 protoFeatures = static_cast<quint16>(reply>>8 & 0xffff);
241 _connectionFeatures = static_cast<quint8>(reply>>24);
243 Compressor::CompressionLevel level;
244 if (_connectionFeatures & Protocol::Compression)
245 level = Compressor::BestCompression;
247 level = Compressor::NoCompression;
249 RemotePeer *peer = PeerFactory::createPeer(PeerFactory::ProtoDescriptor(type, protoFeatures), this, socket(), level, this);
251 qWarning() << "No valid protocol supported for this core!";
252 emit errorPopup(tr("<b>Incompatible Quassel Core!</b><br>"
253 "None of the protocols this client speaks are supported by the core you are trying to connect to."));
255 requestDisconnect(tr("Core speaks none of the protocols we support"));
259 if (peer->protocol() == Protocol::LegacyProtocol) {
260 connect(peer, SIGNAL(protocolVersionMismatch(int,int)), SLOT(onProtocolVersionMismatch(int,int)));
268 void ClientAuthHandler::onProtocolVersionMismatch(int actual, int expected)
270 emit errorPopup(tr("<b>The Quassel Core you are trying to connect to is too old!</b><br>"
271 "We need at least protocol v%1, but the core speaks v%2 only.").arg(expected, actual));
272 requestDisconnect(tr("Incompatible protocol version, connection to core refused"));
276 void ClientAuthHandler::setPeer(RemotePeer *peer)
278 qDebug().nospace() << "Using " << qPrintable(peer->protocolName()) << "...";
281 connect(_peer, SIGNAL(transferProgress(int,int)), SIGNAL(transferProgress(int,int)));
283 // The legacy protocol enables SSL later, after registration
284 if (!_account.useSsl() || _legacy)
286 // otherwise, do it now
288 checkAndEnableSsl(_connectionFeatures & Protocol::Encryption);
292 void ClientAuthHandler::startRegistration()
294 emit statusMessage(tr("Synchronizing to core..."));
296 // useSsl will be ignored by non-legacy peers
299 useSsl = _account.useSsl();
302 _peer->dispatch(RegisterClient(Quassel::buildInfo().fancyVersionString, Quassel::buildInfo().commitDate, useSsl, Quassel::features()));
306 void ClientAuthHandler::handle(const ClientDenied &msg)
308 emit errorPopup(msg.errorString);
309 requestDisconnect(tr("The core refused connection from this client"));
313 void ClientAuthHandler::handle(const ClientRegistered &msg)
315 _coreConfigured = msg.coreConfigured;
316 _backendInfo = msg.backendInfo;
317 _authenticatorInfo = msg.authenticatorInfo;
319 Client::setCoreFeatures(Quassel::Features(msg.coreFeatures));
320 SignalProxy::current()->sourcePeer()->setFeatures(Quassel::Features(msg.coreFeatures));
322 // The legacy protocol enables SSL at this point
323 if(_legacy && _account.useSsl())
324 checkAndEnableSsl(msg.sslSupported);
330 void ClientAuthHandler::onConnectionReady()
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
344 void ClientAuthHandler::setupCore(const SetupData &setupData)
346 _peer->dispatch(setupData);
350 void ClientAuthHandler::handle(const SetupFailed &msg)
352 emit coreSetupFailed(msg.errorString);
356 void ClientAuthHandler::handle(const SetupDone &msg)
360 emit coreSetupSuccessful();
364 void ClientAuthHandler::login(const QString &user, const QString &password, bool remember)
366 _account.setUser(user);
367 _account.setPassword(password);
368 _account.setStorePassword(remember);
373 void ClientAuthHandler::login(const QString &previousError)
375 emit statusMessage(tr("Logging in..."));
376 if (_account.user().isEmpty() || _account.password().isEmpty() || !previousError.isEmpty()) {
378 emit userAuthenticationRequired(&_account, &valid, previousError); // *must* be a synchronous call
379 if (!valid || _account.user().isEmpty() || _account.password().isEmpty()) {
380 requestDisconnect(tr("Login canceled"));
385 _peer->dispatch(Login(_account.user(), _account.password()));
389 void ClientAuthHandler::handle(const LoginFailed &msg)
391 login(msg.errorString);
395 void ClientAuthHandler::handle(const LoginSuccess &msg)
399 emit loginSuccessful(_account);
403 void ClientAuthHandler::handle(const SessionState &msg)
405 disconnect(socket(), 0, this, 0); // this is the last message we shall ever get
407 // give up ownership of the peer; CoreSession takes responsibility now
409 emit handshakeComplete(_peer, msg);
415 void ClientAuthHandler::checkAndEnableSsl(bool coreSupportsSsl)
418 Q_UNUSED(coreSupportsSsl);
420 CoreAccountSettings s;
421 if (coreSupportsSsl && _account.useSsl()) {
422 // Make sure the warning is shown next time we don't have SSL in the core
423 s.setAccountValue("ShowNoCoreSslWarning", true);
425 QSslSocket *sslSocket = qobject_cast<QSslSocket *>(socket());
427 connect(sslSocket, SIGNAL(encrypted()), SLOT(onSslSocketEncrypted()));
428 connect(sslSocket, SIGNAL(sslErrors(QList<QSslError>)), SLOT(onSslErrors()));
429 qDebug() << "Starting encryption...";
431 sslSocket->startClientEncryption();
434 if (s.accountValue("ShowNoCoreSslWarning", true).toBool()) {
435 bool accepted = false;
436 emit handleNoSslInCore(&accepted);
438 requestDisconnect(tr("Unencrypted connection cancelled"));
441 s.setAccountValue("ShowNoCoreSslWarning", false);
442 s.setAccountValue("SslCert", QString());
443 s.setAccountValue("SslCertDigestVersion", QVariant(QVariant::Int));
455 void ClientAuthHandler::onSslSocketEncrypted()
457 QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
460 if (!socket->sslErrors().count()) {
461 // Cert is valid, so we don't want to store it as known
462 // That way, a warning will appear in case it becomes invalid at some point
463 CoreAccountSettings s;
464 s.setAccountValue("SSLCert", QString());
465 s.setAccountValue("SslCertDigestVersion", QVariant(QVariant::Int));
468 emit encrypted(true);
477 void ClientAuthHandler::onSslErrors()
479 QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
482 CoreAccountSettings s;
483 QByteArray knownDigest = s.accountValue("SslCert").toByteArray();
484 ClientAuthHandler::DigestVersion knownDigestVersion = static_cast<ClientAuthHandler::DigestVersion>(s.accountValue("SslCertDigestVersion").toInt());
486 QByteArray calculatedDigest;
487 switch (knownDigestVersion) {
488 case ClientAuthHandler::DigestVersion::Md5:
489 calculatedDigest = socket->peerCertificate().digest(QCryptographicHash::Md5);
492 case ClientAuthHandler::DigestVersion::Sha2_512:
493 #if QT_VERSION >= 0x050000
494 calculatedDigest = socket->peerCertificate().digest(QCryptographicHash::Sha512);
496 calculatedDigest = sha2_512(socket->peerCertificate().toDer());
501 qWarning() << "Certificate digest version" << QString(knownDigestVersion) << "is not supported";
504 if (knownDigest != calculatedDigest) {
505 bool accepted = false;
506 bool permanently = false;
507 emit handleSslErrors(socket, &accepted, &permanently);
510 requestDisconnect(tr("Unencrypted connection canceled"));
515 #if QT_VERSION >= 0x050000
516 s.setAccountValue("SslCert", socket->peerCertificate().digest(QCryptographicHash::Sha512));
518 s.setAccountValue("SslCert", sha2_512(socket->peerCertificate().toDer()));
520 s.setAccountValue("SslCertDigestVersion", ClientAuthHandler::DigestVersion::Latest);
523 s.setAccountValue("SslCert", QString());
524 s.setAccountValue("SslCertDigestVersion", QVariant(QVariant::Int));
527 else if (knownDigestVersion != ClientAuthHandler::DigestVersion::Latest) {
528 #if QT_VERSION >= 0x050000
529 s.setAccountValue("SslCert", socket->peerCertificate().digest(QCryptographicHash::Sha512));
531 s.setAccountValue("SslCert", sha2_512(socket->peerCertificate().toDer()));
533 s.setAccountValue("SslCertDigestVersion", ClientAuthHandler::DigestVersion::Latest);
536 socket->ignoreSslErrors();
539 #if QT_VERSION < 0x050000
540 QByteArray ClientAuthHandler::sha2_512(const QByteArray &input) {
541 unsigned char output[64];
542 sha512((unsigned char*) input.constData(), input.size(), output, false);
543 // QByteArray::fromRawData() cannot be used here because that constructor
544 // does not copy "output" and the data is clobbered when the variable goes
547 result.append((char*) output, 64);
552 #endif /* HAVE_SSL */