1 /***************************************************************************
2 * Copyright (C) 2005-2014 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 #include "protocols/legacy/legacypeer.h"
39 using namespace Protocol;
41 ClientAuthHandler::ClientAuthHandler(CoreAccount account, QObject *parent)
42 : AuthHandler(parent),
47 _connectionFeatures(0)
53 void ClientAuthHandler::connectToCore()
55 CoreAccountSettings s;
58 QSslSocket *socket = new QSslSocket(this);
59 // make sure the warning is shown if we happen to connect without SSL support later
60 s.setAccountValue("ShowNoClientSslWarning", true);
62 if (_account.useSsl()) {
63 if (s.accountValue("ShowNoClientSslWarning", true).toBool()) {
64 bool accepted = false;
65 emit handleNoSslInClient(&accepted);
67 emit errorMessage(tr("Unencrypted connection canceled"));
70 s.setAccountValue("ShowNoClientSslWarning", false);
73 QTcpSocket *socket = new QTcpSocket(this);
76 // TODO: Handle system proxy
77 #ifndef QT_NO_NETWORKPROXY
78 if (_account.useProxy()) {
79 QNetworkProxy proxy(_account.proxyType(), _account.proxyHostName(), _account.proxyPort(), _account.proxyUser(), _account.proxyPassword());
80 socket->setProxy(proxy);
85 connect(socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), SLOT(onSocketStateChanged(QAbstractSocket::SocketState)));
86 connect(socket, SIGNAL(readyRead()), SLOT(onReadyRead()));
87 connect(socket, SIGNAL(connected()), SLOT(onSocketConnected()));
89 emit statusMessage(tr("Connecting to %1...").arg(_account.accountName()));
90 socket->connectToHost(_account.hostName(), _account.port());
94 void ClientAuthHandler::onSocketStateChanged(QAbstractSocket::SocketState socketState)
99 case QAbstractSocket::HostLookupState:
101 text = tr("Looking up %1...").arg(_account.hostName());
103 case QAbstractSocket::ConnectingState:
105 text = tr("Connecting to %1...").arg(_account.hostName());
107 case QAbstractSocket::ConnectedState:
108 text = tr("Connected to %1").arg(_account.hostName());
110 case QAbstractSocket::ClosingState:
112 text = tr("Disconnecting from %1...").arg(_account.hostName());
114 case QAbstractSocket::UnconnectedState:
116 text = tr("Disconnected");
117 // Ensure the disconnected() signal is sent even if we haven't reached the Connected state yet.
118 // The baseclass implementation will make sure to only send the signal once.
119 onSocketDisconnected();
126 if (!text.isEmpty()) {
127 emit statusMessage(text);
131 void ClientAuthHandler::onSocketError(QAbstractSocket::SocketError error)
133 if (_probing && error == QAbstractSocket::RemoteHostClosedError) {
138 _probing = false; // all other errors are unrelated to probing and should be handled
139 AuthHandler::onSocketError(error);
143 void ClientAuthHandler::onSocketDisconnected()
145 if (_probing && _legacy) {
146 // Remote host has closed the connection while probing
148 disconnect(socket(), SIGNAL(readyRead()), this, SLOT(onReadyRead()));
149 emit statusMessage(tr("Reconnecting in compatibility mode..."));
150 socket()->connectToHost(_account.hostName(), _account.port());
154 AuthHandler::onSocketDisconnected();
158 void ClientAuthHandler::onSocketConnected()
161 qWarning() << Q_FUNC_INFO << "Peer already exists!";
165 socket()->setSocketOption(QAbstractSocket::KeepAliveOption, true);
168 // First connection attempt, try probing for a capable core
171 QDataStream stream(socket()); // stream handles the endianness for us
173 quint32 magic = Protocol::magic;
175 if (_account.useSsl())
176 magic |= Protocol::Encryption;
178 //magic |= Protocol::Compression; // not implemented yet
182 // here goes the list of protocols we support, in order of preference
183 stream << ((quint32)Protocol::LegacyProtocol | 0x80000000); // end list
185 socket()->flush(); // make sure the probing data is sent immediately
189 // If we arrive here, it's the second connection attempt, meaning probing was not successful -> enable legacy support
191 qDebug() << "Legacy core detected, switching to compatibility mode";
193 RemotePeer *peer = new LegacyPeer(this, socket(), this);
194 // Only needed for the legacy peer, as all others check the protocol version before instantiation
195 connect(peer, SIGNAL(protocolVersionMismatch(int,int)), SLOT(onProtocolVersionMismatch(int,int)));
201 void ClientAuthHandler::onReadyRead()
203 if (socket()->bytesAvailable() < 4)
207 return; // make sure to not read more data than needed
210 disconnect(socket(), SIGNAL(readyRead()), this, SLOT(onReadyRead()));
213 socket()->read((char *)&reply, 4);
214 reply = qFromBigEndian<quint32>(reply);
216 Protocol::Type type = static_cast<Protocol::Type>(reply & 0xff);
217 quint16 protoFeatures = static_cast<quint16>(reply>>8 & 0xffff);
218 _connectionFeatures = static_cast<quint8>(reply>>24);
220 RemotePeer *peer = PeerFactory::createPeer(PeerFactory::ProtoDescriptor(type, protoFeatures), this, socket(), this);
222 qWarning() << "No valid protocol supported for this core!";
223 emit errorPopup(tr("<b>Incompatible Quassel Core!</b><br>"
224 "None of the protocols this client speaks are supported by the core you are trying to connect to."));
226 requestDisconnect(tr("Core speaks none of the protocols we support"));
230 if (peer->protocol() == Protocol::LegacyProtocol) {
231 connect(peer, SIGNAL(protocolVersionMismatch(int,int)), SLOT(onProtocolVersionMismatch(int,int)));
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.").arg(expected, actual));
243 requestDisconnect(tr("Incompatible protocol version, connection to core refused"));
247 void ClientAuthHandler::setPeer(RemotePeer *peer)
250 connect(_peer, SIGNAL(transferProgress(int,int)), SIGNAL(transferProgress(int,int)));
252 // The legacy protocol enables SSL later, after registration
253 if (!_account.useSsl() || _legacy)
255 // otherwise, do it now
257 checkAndEnableSsl(_connectionFeatures & Protocol::Encryption);
261 void ClientAuthHandler::startRegistration()
263 emit statusMessage(tr("Synchronizing to core..."));
265 // useSsl will be ignored by non-legacy peers
268 useSsl = _account.useSsl();
271 _peer->dispatch(RegisterClient(Quassel::buildInfo().fancyVersionString, useSsl));
275 void ClientAuthHandler::handle(const ClientDenied &msg)
277 emit errorPopup(msg.errorString);
278 requestDisconnect(tr("The core refused connection from this client"));
282 void ClientAuthHandler::handle(const ClientRegistered &msg)
284 _coreConfigured = msg.coreConfigured;
285 _backendInfo = msg.backendInfo;
287 Client::setCoreFeatures(static_cast<Quassel::Features>(msg.coreFeatures));
289 // The legacy protocol enables SSL at this point
290 if(_legacy && _account.useSsl())
291 checkAndEnableSsl(msg.sslSupported);
297 void ClientAuthHandler::onConnectionReady()
299 emit connectionReady();
300 emit statusMessage(tr("Connected to %1").arg(_account.accountName()));
302 if (!_coreConfigured) {
304 emit startCoreSetup(_backendInfo);
306 else // TODO: check if we need LoginEnabled
311 void ClientAuthHandler::setupCore(const SetupData &setupData)
313 _peer->dispatch(setupData);
317 void ClientAuthHandler::handle(const SetupFailed &msg)
319 emit coreSetupFailed(msg.errorString);
323 void ClientAuthHandler::handle(const SetupDone &msg)
327 emit coreSetupSuccessful();
331 void ClientAuthHandler::login(const QString &user, const QString &password, bool remember)
333 _account.setUser(user);
334 _account.setPassword(password);
335 _account.setStorePassword(remember);
340 void ClientAuthHandler::login(const QString &previousError)
342 emit statusMessage(tr("Logging in..."));
343 if (_account.user().isEmpty() || _account.password().isEmpty() || !previousError.isEmpty()) {
345 emit userAuthenticationRequired(&_account, &valid, previousError); // *must* be a synchronous call
346 if (!valid || _account.user().isEmpty() || _account.password().isEmpty()) {
347 requestDisconnect(tr("Login canceled"));
352 _peer->dispatch(Login(_account.user(), _account.password()));
356 void ClientAuthHandler::handle(const LoginFailed &msg)
358 login(msg.errorString);
362 void ClientAuthHandler::handle(const LoginSuccess &msg)
366 emit loginSuccessful(_account);
370 void ClientAuthHandler::handle(const SessionState &msg)
372 disconnect(socket(), 0, this, 0); // this is the last message we shall ever get
374 // give up ownership of the peer; CoreSession takes responsibility now
376 emit handshakeComplete(_peer, msg);
382 void ClientAuthHandler::checkAndEnableSsl(bool coreSupportsSsl)
385 Q_UNUSED(coreSupportsSsl);
387 CoreAccountSettings s;
388 if (coreSupportsSsl && _account.useSsl()) {
389 // Make sure the warning is shown next time we don't have SSL in the core
390 s.setAccountValue("ShowNoCoreSslWarning", true);
392 QSslSocket *sslSocket = qobject_cast<QSslSocket *>(socket());
394 connect(sslSocket, SIGNAL(encrypted()), SLOT(onSslSocketEncrypted()));
395 connect(sslSocket, SIGNAL(sslErrors(QList<QSslError>)), SLOT(onSslErrors()));
396 qDebug() << "Starting encryption...";
398 sslSocket->startClientEncryption();
401 if (s.accountValue("ShowNoCoreSslWarning", true).toBool()) {
402 bool accepted = false;
403 emit handleNoSslInCore(&accepted);
405 requestDisconnect(tr("Unencrypted connection cancelled"));
408 s.setAccountValue("ShowNoCoreSslWarning", false);
409 s.setAccountValue("SslCert", QString());
421 void ClientAuthHandler::onSslSocketEncrypted()
423 QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
426 if (!socket->sslErrors().count()) {
427 // Cert is valid, so we don't want to store it as known
428 // That way, a warning will appear in case it becomes invalid at some point
429 CoreAccountSettings s;
430 s.setAccountValue("SSLCert", QString());
433 emit encrypted(true);
442 void ClientAuthHandler::onSslErrors()
444 QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
447 CoreAccountSettings s;
448 QByteArray knownDigest = s.accountValue("SslCert").toByteArray();
450 if (knownDigest != socket->peerCertificate().digest()) {
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());
463 s.setAccountValue("SslCert", QString());
466 socket->ignoreSslErrors();
469 #endif /* HAVE_SSL */