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 using namespace Protocol;
39 ClientAuthHandler::ClientAuthHandler(CoreAccount account, QObject *parent)
40 : AuthHandler(parent),
45 _connectionFeatures(0)
51 void ClientAuthHandler::connectToCore()
53 CoreAccountSettings s;
56 QSslSocket *socket = new QSslSocket(this);
57 // make sure the warning is shown if we happen to connect without SSL support later
58 s.setAccountValue("ShowNoClientSslWarning", true);
60 if (_account.useSsl()) {
61 if (s.accountValue("ShowNoClientSslWarning", true).toBool()) {
62 bool accepted = false;
63 emit handleNoSslInClient(&accepted);
65 emit errorMessage(tr("Unencrypted connection canceled"));
68 s.setAccountValue("ShowNoClientSslWarning", false);
71 QTcpSocket *socket = new QTcpSocket(this);
74 // TODO: Handle system proxy
75 #ifndef QT_NO_NETWORKPROXY
76 if (_account.useProxy()) {
77 QNetworkProxy proxy(_account.proxyType(), _account.proxyHostName(), _account.proxyPort(), _account.proxyUser(), _account.proxyPassword());
78 socket->setProxy(proxy);
83 connect(socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), SLOT(onSocketStateChanged(QAbstractSocket::SocketState)));
84 connect(socket, SIGNAL(readyRead()), SLOT(onReadyRead()));
85 connect(socket, SIGNAL(connected()), SLOT(onSocketConnected()));
87 emit statusMessage(tr("Connecting to %1...").arg(_account.accountName()));
88 socket->connectToHost(_account.hostName(), _account.port());
92 void ClientAuthHandler::onSocketStateChanged(QAbstractSocket::SocketState socketState)
97 case QAbstractSocket::HostLookupState:
99 text = tr("Looking up %1...").arg(_account.hostName());
101 case QAbstractSocket::ConnectingState:
103 text = tr("Connecting to %1...").arg(_account.hostName());
105 case QAbstractSocket::ConnectedState:
106 text = tr("Connected to %1").arg(_account.hostName());
108 case QAbstractSocket::ClosingState:
110 text = tr("Disconnecting from %1...").arg(_account.hostName());
112 case QAbstractSocket::UnconnectedState:
114 text = tr("Disconnected");
115 // Ensure the disconnected() signal is sent even if we haven't reached the Connected state yet.
116 // The baseclass implementation will make sure to only send the signal once.
117 onSocketDisconnected();
124 if (!text.isEmpty()) {
125 emit statusMessage(text);
129 void ClientAuthHandler::onSocketError(QAbstractSocket::SocketError error)
131 if (_probing && error == QAbstractSocket::RemoteHostClosedError) {
136 _probing = false; // all other errors are unrelated to probing and should be handled
137 AuthHandler::onSocketError(error);
141 void ClientAuthHandler::onSocketDisconnected()
143 if (_probing && _legacy) {
144 // Remote host has closed the connection while probing
146 disconnect(socket(), SIGNAL(readyRead()), this, SLOT(onReadyRead()));
147 emit statusMessage(tr("Reconnecting in compatibility mode..."));
148 socket()->connectToHost(_account.hostName(), _account.port());
152 AuthHandler::onSocketDisconnected();
156 void ClientAuthHandler::onSocketConnected()
159 qWarning() << Q_FUNC_INFO << "Peer already exists!";
163 socket()->setSocketOption(QAbstractSocket::KeepAliveOption, true);
166 // First connection attempt, try probing for a capable core
169 QDataStream stream(socket()); // stream handles the endianness for us
171 quint32 magic = Protocol::magic;
173 if (_account.useSsl())
174 magic |= Protocol::Encryption;
176 //magic |= Protocol::Compression; // not implemented yet
180 // here goes the list of protocols we support, in order of preference
181 PeerFactory::ProtoList protos = PeerFactory::supportedProtocols();
182 for (int i = 0; i < protos.count(); ++i) {
183 quint32 reply = protos[i].first;
184 reply |= protos[i].second<<8;
185 if (i == protos.count() - 1)
186 reply |= 0x80000000; // end list
190 socket()->flush(); // make sure the probing data is sent immediately
194 // If we arrive here, it's the second connection attempt, meaning probing was not successful -> enable legacy support
196 qDebug() << "Legacy core detected, switching to compatibility mode";
198 RemotePeer *peer = PeerFactory::createPeer(PeerFactory::ProtoDescriptor(Protocol::LegacyProtocol, 0), this, socket(), this);
199 // Only needed for the legacy peer, as all others check the protocol version before instantiation
200 connect(peer, SIGNAL(protocolVersionMismatch(int,int)), SLOT(onProtocolVersionMismatch(int,int)));
206 void ClientAuthHandler::onReadyRead()
208 if (socket()->bytesAvailable() < 4)
212 return; // make sure to not read more data than needed
215 disconnect(socket(), SIGNAL(readyRead()), this, SLOT(onReadyRead()));
218 socket()->read((char *)&reply, 4);
219 reply = qFromBigEndian<quint32>(reply);
221 Protocol::Type type = static_cast<Protocol::Type>(reply & 0xff);
222 quint16 protoFeatures = static_cast<quint16>(reply>>8 & 0xffff);
223 _connectionFeatures = static_cast<quint8>(reply>>24);
225 RemotePeer *peer = PeerFactory::createPeer(PeerFactory::ProtoDescriptor(type, protoFeatures), this, socket(), this);
227 qWarning() << "No valid protocol supported for this core!";
228 emit errorPopup(tr("<b>Incompatible Quassel Core!</b><br>"
229 "None of the protocols this client speaks are supported by the core you are trying to connect to."));
231 requestDisconnect(tr("Core speaks none of the protocols we support"));
235 if (peer->protocol() == Protocol::LegacyProtocol) {
236 connect(peer, SIGNAL(protocolVersionMismatch(int,int)), SLOT(onProtocolVersionMismatch(int,int)));
244 void ClientAuthHandler::onProtocolVersionMismatch(int actual, int expected)
246 emit errorPopup(tr("<b>The Quassel Core you are trying to connect to is too old!</b><br>"
247 "We need at least protocol v%1, but the core speaks v%2 only.").arg(expected, actual));
248 requestDisconnect(tr("Incompatible protocol version, connection to core refused"));
252 void ClientAuthHandler::setPeer(RemotePeer *peer)
254 qDebug().nospace() << "Using " << qPrintable(peer->protocolName()) << "...";
257 connect(_peer, SIGNAL(transferProgress(int,int)), SIGNAL(transferProgress(int,int)));
259 // The legacy protocol enables SSL later, after registration
260 if (!_account.useSsl() || _legacy)
262 // otherwise, do it now
264 checkAndEnableSsl(_connectionFeatures & Protocol::Encryption);
268 void ClientAuthHandler::startRegistration()
270 emit statusMessage(tr("Synchronizing to core..."));
272 // useSsl will be ignored by non-legacy peers
275 useSsl = _account.useSsl();
278 _peer->dispatch(RegisterClient(Quassel::buildInfo().fancyVersionString, useSsl));
282 void ClientAuthHandler::handle(const ClientDenied &msg)
284 emit errorPopup(msg.errorString);
285 requestDisconnect(tr("The core refused connection from this client"));
289 void ClientAuthHandler::handle(const ClientRegistered &msg)
291 _coreConfigured = msg.coreConfigured;
292 _backendInfo = msg.backendInfo;
294 Client::setCoreFeatures(static_cast<Quassel::Features>(msg.coreFeatures));
296 // The legacy protocol enables SSL at this point
297 if(_legacy && _account.useSsl())
298 checkAndEnableSsl(msg.sslSupported);
304 void ClientAuthHandler::onConnectionReady()
306 emit connectionReady();
307 emit statusMessage(tr("Connected to %1").arg(_account.accountName()));
309 if (!_coreConfigured) {
311 emit startCoreSetup(_backendInfo);
313 else // TODO: check if we need LoginEnabled
318 void ClientAuthHandler::setupCore(const SetupData &setupData)
320 _peer->dispatch(setupData);
324 void ClientAuthHandler::handle(const SetupFailed &msg)
326 emit coreSetupFailed(msg.errorString);
330 void ClientAuthHandler::handle(const SetupDone &msg)
334 emit coreSetupSuccessful();
338 void ClientAuthHandler::login(const QString &user, const QString &password, bool remember)
340 _account.setUser(user);
341 _account.setPassword(password);
342 _account.setStorePassword(remember);
347 void ClientAuthHandler::login(const QString &previousError)
349 emit statusMessage(tr("Logging in..."));
350 if (_account.user().isEmpty() || _account.password().isEmpty() || !previousError.isEmpty()) {
352 emit userAuthenticationRequired(&_account, &valid, previousError); // *must* be a synchronous call
353 if (!valid || _account.user().isEmpty() || _account.password().isEmpty()) {
354 requestDisconnect(tr("Login canceled"));
359 _peer->dispatch(Login(_account.user(), _account.password()));
363 void ClientAuthHandler::handle(const LoginFailed &msg)
365 login(msg.errorString);
369 void ClientAuthHandler::handle(const LoginSuccess &msg)
373 emit loginSuccessful(_account);
377 void ClientAuthHandler::handle(const SessionState &msg)
379 disconnect(socket(), 0, this, 0); // this is the last message we shall ever get
381 // give up ownership of the peer; CoreSession takes responsibility now
383 emit handshakeComplete(_peer, msg);
389 void ClientAuthHandler::checkAndEnableSsl(bool coreSupportsSsl)
392 Q_UNUSED(coreSupportsSsl);
394 CoreAccountSettings s;
395 if (coreSupportsSsl && _account.useSsl()) {
396 // Make sure the warning is shown next time we don't have SSL in the core
397 s.setAccountValue("ShowNoCoreSslWarning", true);
399 QSslSocket *sslSocket = qobject_cast<QSslSocket *>(socket());
401 connect(sslSocket, SIGNAL(encrypted()), SLOT(onSslSocketEncrypted()));
402 connect(sslSocket, SIGNAL(sslErrors(QList<QSslError>)), SLOT(onSslErrors()));
403 qDebug() << "Starting encryption...";
405 sslSocket->startClientEncryption();
408 if (s.accountValue("ShowNoCoreSslWarning", true).toBool()) {
409 bool accepted = false;
410 emit handleNoSslInCore(&accepted);
412 requestDisconnect(tr("Unencrypted connection cancelled"));
415 s.setAccountValue("ShowNoCoreSslWarning", false);
416 s.setAccountValue("SslCert", QString());
428 void ClientAuthHandler::onSslSocketEncrypted()
430 QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
433 if (!socket->sslErrors().count()) {
434 // Cert is valid, so we don't want to store it as known
435 // That way, a warning will appear in case it becomes invalid at some point
436 CoreAccountSettings s;
437 s.setAccountValue("SSLCert", QString());
440 emit encrypted(true);
449 void ClientAuthHandler::onSslErrors()
451 QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
454 CoreAccountSettings s;
455 QByteArray knownDigest = s.accountValue("SslCert").toByteArray();
457 if (knownDigest != socket->peerCertificate().digest()) {
458 bool accepted = false;
459 bool permanently = false;
460 emit handleSslErrors(socket, &accepted, &permanently);
463 requestDisconnect(tr("Unencrypted connection canceled"));
468 s.setAccountValue("SslCert", socket->peerCertificate().digest());
470 s.setAccountValue("SslCert", QString());
473 socket->ignoreSslErrors();
476 #endif /* HAVE_SSL */