1 /***************************************************************************
2 * Copyright (C) 2005-2015 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 // TODO: Handle system proxy
79 #ifndef QT_NO_NETWORKPROXY
80 if (_account.useProxy()) {
81 QNetworkProxy proxy(_account.proxyType(), _account.proxyHostName(), _account.proxyPort(), _account.proxyUser(), _account.proxyPassword());
82 socket->setProxy(proxy);
87 connect(socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), SLOT(onSocketStateChanged(QAbstractSocket::SocketState)));
88 connect(socket, SIGNAL(readyRead()), SLOT(onReadyRead()));
89 connect(socket, SIGNAL(connected()), SLOT(onSocketConnected()));
91 emit statusMessage(tr("Connecting to %1...").arg(_account.accountName()));
92 socket->connectToHost(_account.hostName(), _account.port());
96 void ClientAuthHandler::onSocketStateChanged(QAbstractSocket::SocketState socketState)
100 switch(socketState) {
101 case QAbstractSocket::HostLookupState:
103 text = tr("Looking up %1...").arg(_account.hostName());
105 case QAbstractSocket::ConnectingState:
107 text = tr("Connecting to %1...").arg(_account.hostName());
109 case QAbstractSocket::ConnectedState:
110 text = tr("Connected to %1").arg(_account.hostName());
112 case QAbstractSocket::ClosingState:
114 text = tr("Disconnecting from %1...").arg(_account.hostName());
116 case QAbstractSocket::UnconnectedState:
118 text = tr("Disconnected");
119 // Ensure the disconnected() signal is sent even if we haven't reached the Connected state yet.
120 // The baseclass implementation will make sure to only send the signal once.
121 // However, we do want to prefer a potential socket error signal that may be on route already, so
122 // give this a chance to overtake us by spinning the loop...
123 QTimer::singleShot(0, this, SLOT(onSocketDisconnected()));
130 if (!text.isEmpty()) {
131 emit statusMessage(text);
135 void ClientAuthHandler::onSocketError(QAbstractSocket::SocketError error)
137 if (_probing && error == QAbstractSocket::RemoteHostClosedError) {
142 _probing = false; // all other errors are unrelated to probing and should be handled
143 AuthHandler::onSocketError(error);
147 void ClientAuthHandler::onSocketDisconnected()
149 if (_probing && _legacy) {
150 // Remote host has closed the connection while probing
152 disconnect(socket(), SIGNAL(readyRead()), this, SLOT(onReadyRead()));
153 emit statusMessage(tr("Reconnecting in compatibility mode..."));
154 socket()->connectToHost(_account.hostName(), _account.port());
158 AuthHandler::onSocketDisconnected();
162 void ClientAuthHandler::onSocketConnected()
165 qWarning() << Q_FUNC_INFO << "Peer already exists!";
169 socket()->setSocketOption(QAbstractSocket::KeepAliveOption, true);
172 // First connection attempt, try probing for a capable core
175 QDataStream stream(socket()); // stream handles the endianness for us
176 stream.setVersion(QDataStream::Qt_4_2);
178 quint32 magic = Protocol::magic;
180 if (_account.useSsl())
181 magic |= Protocol::Encryption;
183 magic |= Protocol::Compression;
187 // here goes the list of protocols we support, in order of preference
188 PeerFactory::ProtoList protos = PeerFactory::supportedProtocols();
189 for (int i = 0; i < protos.count(); ++i) {
190 quint32 reply = protos[i].first;
191 reply |= protos[i].second<<8;
192 if (i == protos.count() - 1)
193 reply |= 0x80000000; // end list
197 socket()->flush(); // make sure the probing data is sent immediately
201 // If we arrive here, it's the second connection attempt, meaning probing was not successful -> enable legacy support
203 qDebug() << "Legacy core detected, switching to compatibility mode";
205 RemotePeer *peer = PeerFactory::createPeer(PeerFactory::ProtoDescriptor(Protocol::LegacyProtocol, 0), this, socket(), Compressor::NoCompression, this);
206 // Only needed for the legacy peer, as all others check the protocol version before instantiation
207 connect(peer, SIGNAL(protocolVersionMismatch(int,int)), SLOT(onProtocolVersionMismatch(int,int)));
213 void ClientAuthHandler::onReadyRead()
215 if (socket()->bytesAvailable() < 4)
219 return; // make sure to not read more data than needed
222 disconnect(socket(), SIGNAL(readyRead()), this, SLOT(onReadyRead()));
225 socket()->read((char *)&reply, 4);
226 reply = qFromBigEndian<quint32>(reply);
228 Protocol::Type type = static_cast<Protocol::Type>(reply & 0xff);
229 quint16 protoFeatures = static_cast<quint16>(reply>>8 & 0xffff);
230 _connectionFeatures = static_cast<quint8>(reply>>24);
232 Compressor::CompressionLevel level;
233 if (_connectionFeatures & Protocol::Compression)
234 level = Compressor::BestCompression;
236 level = Compressor::NoCompression;
238 RemotePeer *peer = PeerFactory::createPeer(PeerFactory::ProtoDescriptor(type, protoFeatures), this, socket(), level, this);
240 qWarning() << "No valid protocol supported for this core!";
241 emit errorPopup(tr("<b>Incompatible Quassel Core!</b><br>"
242 "None of the protocols this client speaks are supported by the core you are trying to connect to."));
244 requestDisconnect(tr("Core speaks none of the protocols we support"));
248 if (peer->protocol() == Protocol::LegacyProtocol) {
249 connect(peer, SIGNAL(protocolVersionMismatch(int,int)), SLOT(onProtocolVersionMismatch(int,int)));
257 void ClientAuthHandler::onProtocolVersionMismatch(int actual, int expected)
259 emit errorPopup(tr("<b>The Quassel Core you are trying to connect to is too old!</b><br>"
260 "We need at least protocol v%1, but the core speaks v%2 only.").arg(expected, actual));
261 requestDisconnect(tr("Incompatible protocol version, connection to core refused"));
265 void ClientAuthHandler::setPeer(RemotePeer *peer)
267 qDebug().nospace() << "Using " << qPrintable(peer->protocolName()) << "...";
270 connect(_peer, SIGNAL(transferProgress(int,int)), SIGNAL(transferProgress(int,int)));
272 // The legacy protocol enables SSL later, after registration
273 if (!_account.useSsl() || _legacy)
275 // otherwise, do it now
277 checkAndEnableSsl(_connectionFeatures & Protocol::Encryption);
281 void ClientAuthHandler::startRegistration()
283 emit statusMessage(tr("Synchronizing to core..."));
285 // useSsl will be ignored by non-legacy peers
288 useSsl = _account.useSsl();
291 _peer->dispatch(RegisterClient(Quassel::buildInfo().fancyVersionString, Quassel::buildInfo().buildDate, useSsl));
295 void ClientAuthHandler::handle(const ClientDenied &msg)
297 emit errorPopup(msg.errorString);
298 requestDisconnect(tr("The core refused connection from this client"));
302 void ClientAuthHandler::handle(const ClientRegistered &msg)
304 _coreConfigured = msg.coreConfigured;
305 _backendInfo = msg.backendInfo;
307 Client::setCoreFeatures(static_cast<Quassel::Features>(msg.coreFeatures));
309 // The legacy protocol enables SSL at this point
310 if(_legacy && _account.useSsl())
311 checkAndEnableSsl(msg.sslSupported);
317 void ClientAuthHandler::onConnectionReady()
319 emit connectionReady();
320 emit statusMessage(tr("Connected to %1").arg(_account.accountName()));
322 if (!_coreConfigured) {
324 emit startCoreSetup(_backendInfo);
326 else // TODO: check if we need LoginEnabled
331 void ClientAuthHandler::setupCore(const SetupData &setupData)
333 _peer->dispatch(setupData);
337 void ClientAuthHandler::handle(const SetupFailed &msg)
339 emit coreSetupFailed(msg.errorString);
343 void ClientAuthHandler::handle(const SetupDone &msg)
347 emit coreSetupSuccessful();
351 void ClientAuthHandler::login(const QString &user, const QString &password, bool remember)
353 _account.setUser(user);
354 _account.setPassword(password);
355 _account.setStorePassword(remember);
360 void ClientAuthHandler::login(const QString &previousError)
362 emit statusMessage(tr("Logging in..."));
363 if (_account.user().isEmpty() || _account.password().isEmpty() || !previousError.isEmpty()) {
365 emit userAuthenticationRequired(&_account, &valid, previousError); // *must* be a synchronous call
366 if (!valid || _account.user().isEmpty() || _account.password().isEmpty()) {
367 requestDisconnect(tr("Login canceled"));
372 _peer->dispatch(Login(_account.user(), _account.password()));
376 void ClientAuthHandler::handle(const LoginFailed &msg)
378 login(msg.errorString);
382 void ClientAuthHandler::handle(const LoginSuccess &msg)
386 emit loginSuccessful(_account);
390 void ClientAuthHandler::handle(const SessionState &msg)
392 disconnect(socket(), 0, this, 0); // this is the last message we shall ever get
394 // give up ownership of the peer; CoreSession takes responsibility now
396 emit handshakeComplete(_peer, msg);
402 void ClientAuthHandler::checkAndEnableSsl(bool coreSupportsSsl)
405 Q_UNUSED(coreSupportsSsl);
407 CoreAccountSettings s;
408 if (coreSupportsSsl && _account.useSsl()) {
409 // Make sure the warning is shown next time we don't have SSL in the core
410 s.setAccountValue("ShowNoCoreSslWarning", true);
412 QSslSocket *sslSocket = qobject_cast<QSslSocket *>(socket());
414 connect(sslSocket, SIGNAL(encrypted()), SLOT(onSslSocketEncrypted()));
415 connect(sslSocket, SIGNAL(sslErrors(QList<QSslError>)), SLOT(onSslErrors()));
416 qDebug() << "Starting encryption...";
418 sslSocket->startClientEncryption();
421 if (s.accountValue("ShowNoCoreSslWarning", true).toBool()) {
422 bool accepted = false;
423 emit handleNoSslInCore(&accepted);
425 requestDisconnect(tr("Unencrypted connection cancelled"));
428 s.setAccountValue("ShowNoCoreSslWarning", false);
429 s.setAccountValue("SslCert", QString());
430 s.setAccountValue("SslCertDigestVersion", QVariant(QVariant::Int));
442 void ClientAuthHandler::onSslSocketEncrypted()
444 QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
447 if (!socket->sslErrors().count()) {
448 // Cert is valid, so we don't want to store it as known
449 // That way, a warning will appear in case it becomes invalid at some point
450 CoreAccountSettings s;
451 s.setAccountValue("SSLCert", QString());
452 s.setAccountValue("SslCertDigestVersion", QVariant(QVariant::Int));
455 emit encrypted(true);
464 void ClientAuthHandler::onSslErrors()
466 QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
469 CoreAccountSettings s;
470 QByteArray knownDigest = s.accountValue("SslCert").toByteArray();
471 ClientAuthHandler::DigestVersion knownDigestVersion = static_cast<ClientAuthHandler::DigestVersion>(s.accountValue("SslCertDigestVersion").toInt());
473 QByteArray calculatedDigest;
474 switch (knownDigestVersion) {
475 case ClientAuthHandler::DigestVersion::Md5:
476 calculatedDigest = socket->peerCertificate().digest(QCryptographicHash::Md5);
479 case ClientAuthHandler::DigestVersion::Sha2_512:
480 #if QT_VERSION >= 0x050000
481 calculatedDigest = socket->peerCertificate().digest(QCryptographicHash::Sha512);
483 calculatedDigest = sha2_512(socket->peerCertificate().toDer());
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 #if QT_VERSION >= 0x050000
503 s.setAccountValue("SslCert", socket->peerCertificate().digest(QCryptographicHash::Sha512));
505 s.setAccountValue("SslCert", sha2_512(socket->peerCertificate().toDer()));
507 s.setAccountValue("SslCertDigestVersion", ClientAuthHandler::DigestVersion::Latest);
510 s.setAccountValue("SslCert", QString());
511 s.setAccountValue("SslCertDigestVersion", QVariant(QVariant::Int));
514 else if (knownDigestVersion != ClientAuthHandler::DigestVersion::Latest) {
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 socket->ignoreSslErrors();
526 #if QT_VERSION < 0x050000
527 QByteArray ClientAuthHandler::sha2_512(const QByteArray &input) {
528 unsigned char output[64];
529 sha512((unsigned char*) input.constData(), input.size(), output, false);
530 // QByteArray::fromRawData() cannot be used here because that constructor
531 // does not copy "output" and the data is clobbered when the variable goes
534 result.append((char*) output, 64);
539 #endif /* HAVE_SSL */