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 "coreauthhandler.h"
24 # include <QSslSocket>
30 using namespace Protocol;
32 CoreAuthHandler::CoreAuthHandler(QTcpSocket *socket, QObject *parent)
33 : AuthHandler(parent),
35 _magicReceived(false),
37 _clientRegistered(false),
38 _connectionFeatures(0)
41 connect(socket, SIGNAL(readyRead()), SLOT(onReadyRead()));
43 // TODO: Timeout for the handshake phase
48 void CoreAuthHandler::onReadyRead()
50 if (socket()->bytesAvailable() < 4)
53 // once we have selected a peer, we certainly don't want to read more data!
57 if (!_magicReceived) {
59 socket()->peek((char*)&magic, 4);
60 magic = qFromBigEndian<quint32>(magic);
62 if ((magic & 0xffffff00) != Protocol::magic) {
63 // no magic, assume legacy protocol
64 qDebug() << "Legacy client detected, switching to compatibility mode";
66 RemotePeer *peer = PeerFactory::createPeer(PeerFactory::ProtoDescriptor(Protocol::LegacyProtocol, 0), this, socket(), Compressor::NoCompression, this);
67 connect(peer, SIGNAL(protocolVersionMismatch(int,int)), SLOT(onProtocolVersionMismatch(int,int)));
72 _magicReceived = true;
73 quint8 features = magic & 0xff;
74 // figure out which connection features we'll use based on the client's support
75 if (Core::sslSupported() && (features & Protocol::Encryption))
76 _connectionFeatures |= Protocol::Encryption;
77 if (features & Protocol::Compression)
78 _connectionFeatures |= Protocol::Compression;
80 socket()->read((char*)&magic, 4); // read the 4 bytes we've just peeked at
83 // read the list of protocols supported by the client
84 while (socket()->bytesAvailable() >= 4 && _supportedProtos.size() < 16) { // sanity check
86 socket()->read((char*)&data, 4);
87 data = qFromBigEndian<quint32>(data);
89 Protocol::Type type = static_cast<Protocol::Type>(data & 0xff);
90 quint16 protoFeatures = static_cast<quint16>(data>>8 & 0xffff);
91 _supportedProtos.append(PeerFactory::ProtoDescriptor(type, protoFeatures));
93 if (data >= 0x80000000) { // last protocol
94 Compressor::CompressionLevel level;
95 if (_connectionFeatures & Protocol::Compression)
96 level = Compressor::BestCompression;
98 level = Compressor::NoCompression;
100 RemotePeer *peer = PeerFactory::createPeer(_supportedProtos, this, socket(), level, this);
102 qWarning() << "Received invalid handshake data from client" << socket()->peerAddress().toString();
107 if (peer->protocol() == Protocol::LegacyProtocol) {
109 connect(peer, SIGNAL(protocolVersionMismatch(int,int)), SLOT(onProtocolVersionMismatch(int,int)));
114 quint32 reply = peer->protocol() | peer->enabledFeatures()<<8 | _connectionFeatures<<24;
115 reply = qToBigEndian<quint32>(reply);
116 socket()->write((char*)&reply, 4);
119 if (!_legacy && (_connectionFeatures & Protocol::Encryption))
120 startSsl(); // legacy peer enables it later
127 void CoreAuthHandler::setPeer(RemotePeer *peer)
129 qDebug().nospace() << "Using " << qPrintable(peer->protocolName()) << "...";
132 disconnect(socket(), SIGNAL(readyRead()), this, SLOT(onReadyRead()));
135 // only in compat mode
136 void CoreAuthHandler::onProtocolVersionMismatch(int actual, int expected)
138 qWarning() << qPrintable(tr("Client")) << _peer->description() << qPrintable(tr("too old, rejecting."));
139 QString errorString = tr("<b>Your Quassel Client is too old!</b><br>"
140 "This core needs at least client/core protocol version %1 (got: %2).<br>"
141 "Please consider upgrading your client.").arg(expected, actual);
142 _peer->dispatch(ClientDenied(errorString));
147 bool CoreAuthHandler::checkClientRegistered()
149 if (!_clientRegistered) {
150 qWarning() << qPrintable(tr("Client")) << qPrintable(socket()->peerAddress().toString()) << qPrintable(tr("did not send a registration message before trying to login, rejecting."));
151 _peer->dispatch(ClientDenied(tr("<b>Client not initialized!</b><br>You need to send a registration message before trying to login.")));
159 void CoreAuthHandler::handle(const RegisterClient &msg)
163 useSsl = Core::sslSupported() && msg.sslSupported;
165 useSsl = _connectionFeatures & Protocol::Encryption;
167 if (Quassel::isOptionSet("require-ssl") && !useSsl && !_peer->isLocal()) {
168 quInfo() << qPrintable(tr("SSL required but non-SSL connection attempt from %1").arg(socket()->peerAddress().toString()));
169 _peer->dispatch(ClientDenied(tr("<b>SSL is required!</b><br>You need to use SSL in order to connect to this core.")));
174 QVariantList backends;
175 QVariantList authenticators;
176 bool configured = Core::isConfigured();
178 backends = Core::backendInfo();
179 authenticators = Core::authenticatorInfo();
182 // useSsl is only used for the legacy protocol
183 // XXX: FIXME: use client features here: we cannot pass authenticators if the client is too old!
184 _peer->dispatch(ClientRegistered(Quassel::features(), configured, backends, useSsl, authenticators));
186 _peer->setBuildDate(msg.buildDate);
187 _peer->setClientVersion(msg.clientVersion);
188 _peer->setFeatures(Quassel::Features(msg.clientFeatures));
190 if (_legacy && useSsl)
193 _clientRegistered = true;
197 void CoreAuthHandler::handle(const SetupData &msg)
199 if (!checkClientRegistered())
202 // The default parameter to authenticator is Database.
203 // Maybe this should be hardcoded elsewhere, i.e. as a define.
204 QString authenticator = msg.authenticator;
205 quInfo() << "[" << authenticator << "]";
206 if (authenticator.trimmed().isEmpty()) {
207 authenticator = QString("Database");
210 QString result = Core::setup(msg.adminUser, msg.adminPassword, msg.backend, msg.setupData, authenticator, msg.authSetupData);
211 if (!result.isEmpty())
212 _peer->dispatch(SetupFailed(result));
214 _peer->dispatch(SetupDone());
218 void CoreAuthHandler::handle(const Login &msg)
220 if (!checkClientRegistered())
223 // First attempt local auth using the real username and password.
224 // If that fails, move onto the auth provider.
225 UserId uid = Core::validateUser(msg.user, msg.password);
227 uid = Core::authenticateUser(msg.user, msg.password);
231 quInfo() << qPrintable(tr("Invalid login attempt from %1 as \"%2\"").arg(socket()->peerAddress().toString(), msg.user));
232 _peer->dispatch(LoginFailed(tr("<b>Invalid username or password!</b><br>The username/password combination you supplied could not be found in the database.")));
235 _peer->dispatch(LoginSuccess());
237 quInfo() << qPrintable(tr("Client %1 initialized and authenticated successfully as \"%2\" (UserId: %3).").arg(socket()->peerAddress().toString(), msg.user, QString::number(uid.toInt())));
239 disconnect(socket(), 0, this, 0);
240 disconnect(_peer, 0, this, 0);
241 _peer->setParent(0); // Core needs to take care of this one now!
243 socket()->flush(); // Make sure all data is sent before handing over the peer (and socket) to the session thread (bug 682)
244 emit handshakeComplete(_peer, uid);
250 void CoreAuthHandler::startSsl()
253 QSslSocket *sslSocket = qobject_cast<QSslSocket *>(socket());
256 qDebug() << qPrintable(tr("Starting encryption for Client:")) << _peer->description();
257 connect(sslSocket, SIGNAL(sslErrors(const QList<QSslError> &)), SLOT(onSslErrors()));
258 sslSocket->flush(); // ensure that the write cache is flushed before we switch to ssl (bug 682)
259 sslSocket->startServerEncryption();
260 #endif /* HAVE_SSL */
265 void CoreAuthHandler::onSslErrors()
267 QSslSocket *sslSocket = qobject_cast<QSslSocket *>(socket());
269 sslSocket->ignoreSslErrors();