clazy: Convert many old-style connects into function pointer based
[quassel.git] / src / client / clientauthhandler.cpp
index a390ab6..68f545e 100644 (file)
@@ -1,5 +1,5 @@
 /***************************************************************************
- *   Copyright (C) 2005-2013 by the Quassel Project                        *
+ *   Copyright (C) 2005-2018 by the Quassel Project                        *
  *   devel@quassel-irc.org                                                 *
  *                                                                         *
  *   This program is free software; you can redistribute it and/or modify  *
@@ -20,7 +20,7 @@
 
 #include "clientauthhandler.h"
 
-// TODO: support system application proxy (new in Qt 4.6)
+#include <QtEndian>
 
 #ifdef HAVE_SSL
     #include <QSslSocket>
 
 #include "client.h"
 #include "clientsettings.h"
-
-#include "protocols/legacy/legacypeer.h"
+#include "logmessage.h"
+#include "peerfactory.h"
 
 using namespace Protocol;
 
 ClientAuthHandler::ClientAuthHandler(CoreAccount account, QObject *parent)
     : AuthHandler(parent),
-    _peer(0),
-    _account(account)
+    _peer(nullptr),
+    _account(account),
+    _probing(false),
+    _legacy(false),
+    _connectionFeatures(0)
 {
 
 }
 
 
+Peer *ClientAuthHandler::peer() const
+{
+    return _peer;
+}
+
+
 void ClientAuthHandler::connectToCore()
 {
     CoreAccountSettings s;
 
 #ifdef HAVE_SSL
-    QSslSocket *socket = new QSslSocket(this);
+    auto *socket = new QSslSocket(this);
     // make sure the warning is shown if we happen to connect without SSL support later
     s.setAccountValue("ShowNoClientSslWarning", true);
 #else
@@ -67,216 +76,274 @@ void ClientAuthHandler::connectToCore()
     QTcpSocket *socket = new QTcpSocket(this);
 #endif
 
-// TODO: Handle system proxy
 #ifndef QT_NO_NETWORKPROXY
-    if (_account.useProxy()) {
-        QNetworkProxy proxy(_account.proxyType(), _account.proxyHostName(), _account.proxyPort(), _account.proxyUser(), _account.proxyPassword());
+    QNetworkProxy proxy;
+    proxy.setType(_account.proxyType());
+    if (_account.proxyType() == QNetworkProxy::Socks5Proxy ||
+            _account.proxyType() == QNetworkProxy::HttpProxy) {
+        proxy.setHostName(_account.proxyHostName());
+        proxy.setPort(_account.proxyPort());
+        proxy.setUser(_account.proxyUser());
+        proxy.setPassword(_account.proxyPassword());
+    }
+
+    if (_account.proxyType() == QNetworkProxy::DefaultProxy) {
+        QNetworkProxyFactory::setUseSystemConfiguration(true);
+    } else {
+        QNetworkProxyFactory::setUseSystemConfiguration(false);
         socket->setProxy(proxy);
     }
 #endif
 
     setSocket(socket);
-    // handled by the base class for now; may need to rethink for protocol detection
-    //connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), SLOT(onSocketError(QAbstractSocket::SocketError)));
-    //connect(socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), SLOT(onSocketStateChanged(QAbstractSocket::SocketState)));
-    connect(socket, SIGNAL(connected()), SLOT(onSocketConnected()));
+    connect(socket, &QAbstractSocket::stateChanged, this, &ClientAuthHandler::onSocketStateChanged);
+    connect(socket, &QIODevice::readyRead, this, &ClientAuthHandler::onReadyRead);
+    connect(socket, &QAbstractSocket::connected, this, &ClientAuthHandler::onSocketConnected);
 
     emit statusMessage(tr("Connecting to %1...").arg(_account.accountName()));
     socket->connectToHost(_account.hostName(), _account.port());
 }
 
 
-// TODO: handle protocol detection
-// This method might go away anyway, unless we really need our own states...
-/*
 void ClientAuthHandler::onSocketStateChanged(QAbstractSocket::SocketState socketState)
 {
-    qDebug() << Q_FUNC_INFO << socketState;
     QString text;
-    AuthHandler::State state = UnconnectedState;
 
     switch(socketState) {
-        case QAbstractSocket::UnconnectedState:
-            text = tr("Disconnected");
-            state = UnconnectedState;
-            break;
         case QAbstractSocket::HostLookupState:
-            text = tr("Looking up %1...").arg(_account.hostName());
-            state = HostLookupState;
+            if (!_legacy)
+                text = tr("Looking up %1...").arg(_account.hostName());
             break;
         case QAbstractSocket::ConnectingState:
-            text = tr("Connecting to %1...").arg(_account.hostName());
-            state = ConnectingState;
+            if (!_legacy)
+                text = tr("Connecting to %1...").arg(_account.hostName());
             break;
         case QAbstractSocket::ConnectedState:
             text = tr("Connected to %1").arg(_account.hostName());
-            state = ConnectedState;
             break;
         case QAbstractSocket::ClosingState:
-            text = tr("Disconnecting from %1...").arg(_account.hostName());
-            state = ClosingState;
+            if (!_probing)
+                text = tr("Disconnecting from %1...").arg(_account.hostName());
+            break;
+        case QAbstractSocket::UnconnectedState:
+            if (!_probing) {
+                text = tr("Disconnected");
+                // Ensure the disconnected() signal is sent even if we haven't reached the Connected state yet.
+                // The baseclass implementation will make sure to only send the signal once.
+                // However, we do want to prefer a potential socket error signal that may be on route already, so
+                // give this a chance to overtake us by spinning the loop...
+                QTimer::singleShot(0, this, SLOT(onSocketDisconnected()));
+            }
             break;
         default:
             break;
     }
 
     if (!text.isEmpty()) {
-        setState(state);
         emit statusMessage(text);
     }
 }
-*/
 
-// TODO: handle protocol detection
-/*
 void ClientAuthHandler::onSocketError(QAbstractSocket::SocketError error)
 {
-    emit socketError(error, socket()->errorString());
+    if (_probing && error == QAbstractSocket::RemoteHostClosedError) {
+        _legacy = true;
+        return;
+    }
+
+    _probing = false; // all other errors are unrelated to probing and should be handled
+    AuthHandler::onSocketError(error);
 }
-*/
 
-void ClientAuthHandler::onSocketConnected()
+
+void ClientAuthHandler::onSocketDisconnected()
 {
-    // TODO: protocol detection
+    if (_probing && _legacy) {
+        // Remote host has closed the connection while probing
+        _probing = false;
+        disconnect(socket(), &QIODevice::readyRead, this, &ClientAuthHandler::onReadyRead);
+        emit statusMessage(tr("Reconnecting in compatibility mode..."));
+        socket()->connectToHost(_account.hostName(), _account.port());
+        return;
+    }
+
+    AuthHandler::onSocketDisconnected();
+}
 
+
+void ClientAuthHandler::onSocketConnected()
+{
     if (_peer) {
         qWarning() << Q_FUNC_INFO << "Peer already exists!";
         return;
     }
 
-    _peer = new LegacyPeer(this, socket(), this);
-
-    connect(_peer, SIGNAL(transferProgress(int,int)), SIGNAL(transferProgress(int,int)));
+    socket()->setSocketOption(QAbstractSocket::KeepAliveOption, true);
 
-    // compat only
-    connect(_peer, SIGNAL(protocolVersionMismatch(int,int)), SLOT(onProtocolVersionMismatch(int,int)));
+    if (!_legacy) {
+        // First connection attempt, try probing for a capable core
+        _probing = true;
 
-    emit statusMessage(tr("Synchronizing to core..."));
+        QDataStream stream(socket()); // stream handles the endianness for us
+        stream.setVersion(QDataStream::Qt_4_2);
 
-    bool useSsl = false;
+        quint32 magic = Protocol::magic;
 #ifdef HAVE_SSL
-    useSsl = _account.useSsl();
+        if (_account.useSsl())
+            magic |= Protocol::Encryption;
 #endif
+        magic |= Protocol::Compression;
+
+        stream << magic;
+
+        // here goes the list of protocols we support, in order of preference
+        PeerFactory::ProtoList protos = PeerFactory::supportedProtocols();
+        for (int i = 0; i < protos.count(); ++i) {
+            quint32 reply = protos[i].first;
+            reply |= protos[i].second<<8;
+            if (i == protos.count() - 1)
+                reply |= 0x80000000; // end list
+            stream << reply;
+        }
 
-    _peer->dispatch(RegisterClient(Quassel::buildInfo().fancyVersionString, useSsl));
-}
+        socket()->flush(); // make sure the probing data is sent immediately
+        return;
+    }
 
+    // If we arrive here, it's the second connection attempt, meaning probing was not successful -> enable legacy support
 
-void ClientAuthHandler::onProtocolVersionMismatch(int actual, int expected)
-{
-    emit errorPopup(tr("<b>The Quassel Core you are trying to connect to is too old!</b><br>"
-           "We need at least protocol v%1, but the core speaks v%2 only.").arg(expected, actual));
-    requestDisconnect();
-}
+    qDebug() << "Legacy core detected, switching to compatibility mode";
 
+    RemotePeer *peer = PeerFactory::createPeer(PeerFactory::ProtoDescriptor(Protocol::LegacyProtocol, 0), this, socket(), Compressor::NoCompression, this);
+    // Only needed for the legacy peer, as all others check the protocol version before instantiation
+    connect(peer, SIGNAL(protocolVersionMismatch(int,int)), SLOT(onProtocolVersionMismatch(int,int)));
 
-void ClientAuthHandler::handle(const ClientDenied &msg)
-{
-    emit errorPopup(msg.errorString);
-    requestDisconnect();
+    setPeer(peer);
 }
 
 
-void ClientAuthHandler::handle(const ClientRegistered &msg)
+void ClientAuthHandler::onReadyRead()
 {
-    _coreConfigured = msg.coreConfigured;
-    _backendInfo = msg.backendInfo;
+    if (socket()->bytesAvailable() < 4)
+        return;
 
-    Client::setCoreFeatures(static_cast<Quassel::Features>(msg.coreFeatures));
+    if (!_probing)
+        return; // make sure to not read more data than needed
 
-#ifdef HAVE_SSL
-    CoreAccountSettings s;
-    if (_account.useSsl()) {
-        if (msg.sslSupported) {
-            // Make sure the warning is shown next time we don't have SSL in the core
-            s.setAccountValue("ShowNoCoreSslWarning", true);
-
-            QSslSocket *sslSocket = qobject_cast<QSslSocket *>(socket());
-            Q_ASSERT(sslSocket);
-            connect(sslSocket, SIGNAL(encrypted()), SLOT(onSslSocketEncrypted()));
-            connect(sslSocket, SIGNAL(sslErrors(QList<QSslError>)), SLOT(onSslErrors()));
-            qDebug() << "Starting encryption...";
-            sslSocket->flush();
-            sslSocket->startClientEncryption();
-        }
-        else {
-            if (s.accountValue("ShowNoCoreSslWarning", true).toBool()) {
-                bool accepted = false;
-                emit handleNoSslInCore(&accepted);
-                if (!accepted) {
-                    requestDisconnect(tr("Unencrypted connection cancelled"));
-                    return;
-                }
-                s.setAccountValue("ShowNoCoreSslWarning", false);
-                s.setAccountValue("SslCert", QString());
-            }
-            onConnectionReady();
-        }
+    _probing = false;
+    disconnect(socket(), &QIODevice::readyRead, this, &ClientAuthHandler::onReadyRead);
+
+    quint32 reply;
+    socket()->read((char *)&reply, 4);
+    reply = qFromBigEndian<quint32>(reply);
+
+    auto type = static_cast<Protocol::Type>(reply & 0xff);
+    auto protoFeatures = static_cast<quint16>(reply>>8 & 0xffff);
+    _connectionFeatures = static_cast<quint8>(reply>>24);
+
+    Compressor::CompressionLevel level;
+    if (_connectionFeatures & Protocol::Compression)
+        level = Compressor::BestCompression;
+    else
+        level = Compressor::NoCompression;
+
+    RemotePeer *peer = PeerFactory::createPeer(PeerFactory::ProtoDescriptor(type, protoFeatures), this, socket(), level, this);
+    if (!peer) {
+        qWarning() << "No valid protocol supported for this core!";
+        emit errorPopup(tr("<b>Incompatible Quassel Core!</b><br>"
+                           "None of the protocols this client speaks are supported by the core you are trying to connect to."));
+
+        requestDisconnect(tr("Core speaks none of the protocols we support"));
         return;
     }
-#endif
-    // if we use SSL we wait for the next step until every SSL warning has been cleared
-    onConnectionReady();
+
+    if (peer->protocol() == Protocol::LegacyProtocol) {
+        connect(peer, SIGNAL(protocolVersionMismatch(int,int)), SLOT(onProtocolVersionMismatch(int,int)));
+        _legacy = true;
+    }
+
+    setPeer(peer);
 }
 
 
-#ifdef HAVE_SSL
+void ClientAuthHandler::onProtocolVersionMismatch(int actual, int expected)
+{
+    emit errorPopup(tr("<b>The Quassel Core you are trying to connect to is too old!</b><br>"
+           "We need at least protocol v%1, but the core speaks v%2 only.").arg(expected, actual));
+    requestDisconnect(tr("Incompatible protocol version, connection to core refused"));
+}
 
-void ClientAuthHandler::onSslSocketEncrypted()
+
+void ClientAuthHandler::setPeer(RemotePeer *peer)
 {
-    QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
-    Q_ASSERT(socket);
+    qDebug().nospace() << "Using " << qPrintable(peer->protocolName()) << "...";
 
-    if (!socket->sslErrors().count()) {
-        // Cert is valid, so we don't want to store it as known
-        // That way, a warning will appear in case it becomes invalid at some point
-        CoreAccountSettings s;
-        s.setAccountValue("SSLCert", QString());
-    }
+    _peer = peer;
+    connect(_peer, &RemotePeer::transferProgress, this, &ClientAuthHandler::transferProgress);
 
-    emit encrypted(true);
-    onConnectionReady();
+    // The legacy protocol enables SSL later, after registration
+    if (!_account.useSsl() || _legacy)
+        startRegistration();
+    // otherwise, do it now
+    else
+        checkAndEnableSsl(_connectionFeatures & Protocol::Encryption);
 }
 
 
-void ClientAuthHandler::onSslErrors()
+void ClientAuthHandler::startRegistration()
 {
-    QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
-    Q_ASSERT(socket);
-
-    CoreAccountSettings s;
-    QByteArray knownDigest = s.accountValue("SslCert").toByteArray();
+    emit statusMessage(tr("Synchronizing to core..."));
 
-    if (knownDigest != socket->peerCertificate().digest()) {
-        bool accepted = false;
-        bool permanently = false;
-        emit handleSslErrors(socket, &accepted, &permanently);
+    // useSsl will be ignored by non-legacy peers
+    bool useSsl = false;
+#ifdef HAVE_SSL
+    useSsl = _account.useSsl();
+#endif
 
-        if (!accepted) {
-            requestDisconnect(tr("Unencrypted connection canceled"));
-            return;
-        }
+    _peer->dispatch(RegisterClient(Quassel::Features{}, Quassel::buildInfo().fancyVersionString, Quassel::buildInfo().commitDate, useSsl));
+}
 
-        if (permanently)
-            s.setAccountValue("SslCert", socket->peerCertificate().digest());
-        else
-            s.setAccountValue("SslCert", QString());
-    }
 
-    socket->ignoreSslErrors();
+void ClientAuthHandler::handle(const ClientDenied &msg)
+{
+    emit errorPopup(msg.errorString);
+    requestDisconnect(tr("The core refused connection from this client"));
 }
 
-#endif /* HAVE_SSL */
+
+void ClientAuthHandler::handle(const ClientRegistered &msg)
+{
+    _coreConfigured = msg.coreConfigured;
+    _backendInfo = msg.backendInfo;
+    _authenticatorInfo = msg.authenticatorInfo;
+
+    _peer->setFeatures(std::move(msg.features));
+
+    // The legacy protocol enables SSL at this point
+    if(_legacy && _account.useSsl())
+        checkAndEnableSsl(msg.sslSupported);
+    else
+        onConnectionReady();
+}
 
 
 void ClientAuthHandler::onConnectionReady()
 {
+    const auto &coreFeatures = _peer->features();
+    auto unsupported = coreFeatures.toStringList(false);
+    if (!unsupported.isEmpty()) {
+        quInfo() << qPrintable(tr("Core does not support the following features: %1").arg(unsupported.join(", ")));
+    }
+    if (!coreFeatures.unknownFeatures().isEmpty()) {
+        quInfo() << qPrintable(tr("Core supports unknown features: %1").arg(coreFeatures.unknownFeatures().join(", ")));
+    }
+
     emit connectionReady();
     emit statusMessage(tr("Connected to %1").arg(_account.accountName()));
 
     if (!_coreConfigured) {
         // start wizard
-        emit startCoreSetup(_backendInfo);
+        emit startCoreSetup(_backendInfo, _authenticatorInfo);
     }
     else // TODO: check if we need LoginEnabled
         login();
@@ -344,9 +411,126 @@ void ClientAuthHandler::handle(const LoginSuccess &msg)
 
 void ClientAuthHandler::handle(const SessionState &msg)
 {
-    disconnect(socket(), 0, this, 0); // this is the last message we shall ever get
+    disconnect(socket(), nullptr, this, nullptr); // this is the last message we shall ever get
 
     // give up ownership of the peer; CoreSession takes responsibility now
-    _peer->setParent(0);
+    _peer->setParent(nullptr);
     emit handshakeComplete(_peer, msg);
 }
+
+
+/*** SSL Stuff ***/
+
+void ClientAuthHandler::checkAndEnableSsl(bool coreSupportsSsl)
+{
+#ifndef HAVE_SSL
+    Q_UNUSED(coreSupportsSsl);
+#else
+    CoreAccountSettings s;
+    if (coreSupportsSsl && _account.useSsl()) {
+        // Make sure the warning is shown next time we don't have SSL in the core
+        s.setAccountValue("ShowNoCoreSslWarning", true);
+
+        auto *sslSocket = qobject_cast<QSslSocket *>(socket());
+        Q_ASSERT(sslSocket);
+        connect(sslSocket, &QSslSocket::encrypted, this, &ClientAuthHandler::onSslSocketEncrypted);
+        connect(sslSocket, SIGNAL(sslErrors(QList<QSslError>)), SLOT(onSslErrors()));
+        qDebug() << "Starting encryption...";
+        sslSocket->flush();
+        sslSocket->startClientEncryption();
+    }
+    else {
+        if (s.accountValue("ShowNoCoreSslWarning", true).toBool()) {
+            bool accepted = false;
+            emit handleNoSslInCore(&accepted);
+            if (!accepted) {
+                requestDisconnect(tr("Unencrypted connection cancelled"));
+                return;
+            }
+            s.setAccountValue("ShowNoCoreSslWarning", false);
+            s.setAccountValue("SslCert", QString());
+            s.setAccountValue("SslCertDigestVersion", QVariant(QVariant::Int));
+        }
+        if (_legacy)
+            onConnectionReady();
+        else
+            startRegistration();
+    }
+#endif
+}
+
+#ifdef HAVE_SSL
+
+void ClientAuthHandler::onSslSocketEncrypted()
+{
+    auto *socket = qobject_cast<QSslSocket *>(sender());
+    Q_ASSERT(socket);
+
+    if (!socket->sslErrors().count()) {
+        // Cert is valid, so we don't want to store it as known
+        // That way, a warning will appear in case it becomes invalid at some point
+        CoreAccountSettings s;
+        s.setAccountValue("SSLCert", QString());
+        s.setAccountValue("SslCertDigestVersion", QVariant(QVariant::Int));
+    }
+
+    emit encrypted(true);
+
+    if (_legacy)
+        onConnectionReady();
+    else
+        startRegistration();
+}
+
+
+void ClientAuthHandler::onSslErrors()
+{
+    auto *socket = qobject_cast<QSslSocket *>(sender());
+    Q_ASSERT(socket);
+
+    CoreAccountSettings s;
+    QByteArray knownDigest = s.accountValue("SslCert").toByteArray();
+    ClientAuthHandler::DigestVersion knownDigestVersion = static_cast<ClientAuthHandler::DigestVersion>(s.accountValue("SslCertDigestVersion").toInt());
+
+    QByteArray calculatedDigest;
+    switch (knownDigestVersion) {
+    case ClientAuthHandler::DigestVersion::Md5:
+        calculatedDigest = socket->peerCertificate().digest(QCryptographicHash::Md5);
+        break;
+
+    case ClientAuthHandler::DigestVersion::Sha2_512:
+        calculatedDigest = socket->peerCertificate().digest(QCryptographicHash::Sha512);
+        break;
+
+    default:
+        qWarning() << "Certificate digest version" << QString(knownDigestVersion) << "is not supported";
+    }
+
+    if (knownDigest != calculatedDigest) {
+        bool accepted = false;
+        bool permanently = false;
+        emit handleSslErrors(socket, &accepted, &permanently);
+
+        if (!accepted) {
+            requestDisconnect(tr("Unencrypted connection canceled"));
+            return;
+        }
+
+        if (permanently) {
+            s.setAccountValue("SslCert", socket->peerCertificate().digest(QCryptographicHash::Sha512));
+            s.setAccountValue("SslCertDigestVersion", ClientAuthHandler::DigestVersion::Latest);
+        }
+        else {
+            s.setAccountValue("SslCert", QString());
+            s.setAccountValue("SslCertDigestVersion", QVariant(QVariant::Int));
+        }
+    }
+    else if (knownDigestVersion != ClientAuthHandler::DigestVersion::Latest) {
+        s.setAccountValue("SslCert", socket->peerCertificate().digest(QCryptographicHash::Sha512));
+        s.setAccountValue("SslCertDigestVersion", ClientAuthHandler::DigestVersion::Latest);
+    }
+
+    socket->ignoreSslErrors();
+}
+
+#endif /* HAVE_SSL */