1 /***************************************************************************
2 * Copyright (C) 2005-2018 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 ***************************************************************************/
23 #include <QHostAddress>
27 # include <QSslSocket>
29 # include <QTcpSocket>
32 #include "remotepeer.h"
35 using namespace Protocol;
37 const quint32 maxMessageSize = 64 * 1024 * 1024; // This is uncompressed size. 64 MB should be enough for any sort of initData or backlog chunk
39 RemotePeer::RemotePeer(::AuthHandler *authHandler, QTcpSocket *socket, Compressor::CompressionLevel level, QObject *parent)
40 : Peer(authHandler, parent),
42 _compressor(new Compressor(socket, level, this)),
43 _signalProxy(nullptr),
44 _heartBeatTimer(new QTimer(this)),
49 socket->setParent(this);
50 connect(socket, &QAbstractSocket::stateChanged, this, &RemotePeer::onSocketStateChanged);
51 connect(socket, selectOverload<QAbstractSocket::SocketError>(&QAbstractSocket::error), this, &RemotePeer::onSocketError);
52 connect(socket, &QAbstractSocket::disconnected, this, &Peer::disconnected);
55 auto *sslSocket = qobject_cast<QSslSocket *>(socket);
57 connect(sslSocket, &QSslSocket::encrypted, this, [this]() { emit secureStateChanged(true); });
61 connect(_compressor, &Compressor::readyRead, this, &RemotePeer::onReadyRead);
62 connect(_compressor, &Compressor::error, this, &RemotePeer::onCompressionError);
64 connect(_heartBeatTimer, &QTimer::timeout, this, &RemotePeer::sendHeartBeat);
68 void RemotePeer::onSocketStateChanged(QAbstractSocket::SocketState state)
70 if (state == QAbstractSocket::ClosingState) {
71 emit statusMessage(tr("Disconnecting..."));
76 void RemotePeer::onSocketError(QAbstractSocket::SocketError error)
78 emit socketError(error, socket()->errorString());
82 void RemotePeer::onCompressionError(Compressor::Error error)
84 close(QString("Compression error %1").arg(error));
88 QString RemotePeer::description() const
91 return socket()->peerAddress().toString();
96 QString RemotePeer::address() const
99 return socket()->peerAddress().toString();
104 quint16 RemotePeer::port() const
107 return socket()->peerPort();
113 ::SignalProxy *RemotePeer::signalProxy() const
119 void RemotePeer::setSignalProxy(::SignalProxy *proxy)
121 if (proxy == _signalProxy)
125 _heartBeatTimer->stop();
126 disconnect(signalProxy(), nullptr, this, nullptr);
127 _signalProxy = nullptr;
133 qWarning() << Q_FUNC_INFO << "Setting another SignalProxy not supported, ignoring!";
136 _signalProxy = proxy;
137 connect(proxy, &SignalProxy::heartBeatIntervalChanged, this, &RemotePeer::changeHeartBeatInterval);
138 _heartBeatTimer->setInterval(proxy->heartBeatInterval() * 1000);
139 _heartBeatTimer->start();
144 void RemotePeer::changeHeartBeatInterval(int secs)
147 _heartBeatTimer->stop();
149 _heartBeatTimer->setInterval(secs * 1000);
150 _heartBeatTimer->start();
155 int RemotePeer::lag() const
161 QTcpSocket *RemotePeer::socket() const
167 bool RemotePeer::isSecure() const
173 auto *sslSocket = qobject_cast<QSslSocket *>(socket());
174 if (sslSocket && sslSocket->isEncrypted())
182 bool RemotePeer::isLocal() const
185 if (socket()->peerAddress() == QHostAddress::LocalHost || socket()->peerAddress() == QHostAddress::LocalHostIPv6)
192 bool RemotePeer::isOpen() const
194 return socket() && socket()->state() == QTcpSocket::ConnectedState;
198 void RemotePeer::close(const QString &reason)
200 if (!reason.isEmpty()) {
201 qWarning() << "Disconnecting:" << reason;
204 if (socket() && socket()->state() != QTcpSocket::UnconnectedState) {
205 socket()->disconnectFromHost();
210 void RemotePeer::onReadyRead()
213 while (readMessage(msg)) {
214 if (SignalProxy::current())
215 SignalProxy::current()->setSourcePeer(this);
219 if (SignalProxy::current())
220 SignalProxy::current()->setSourcePeer(nullptr);
225 bool RemotePeer::readMessage(QByteArray &msg)
228 if (_compressor->bytesAvailable() < 4)
230 _compressor->read((char*)&_msgSize, 4);
231 _msgSize = qFromBigEndian<quint32>(_msgSize);
233 if (_msgSize > maxMessageSize) {
234 close("Peer tried to send package larger than max package size!");
239 close("Peer tried to send an empty message!");
244 if (_compressor->bytesAvailable() < _msgSize) {
245 emit transferProgress(socket()->bytesAvailable(), _msgSize);
249 emit transferProgress(_msgSize, _msgSize);
251 msg.resize(_msgSize);
252 qint64 bytesRead = _compressor->read(msg.data(), _msgSize);
253 if (bytesRead != _msgSize) {
254 close("Premature end of data stream!");
263 void RemotePeer::writeMessage(const QByteArray &msg)
265 auto size = qToBigEndian<quint32>(msg.size());
266 _compressor->write((const char*)&size, 4, Compressor::NoFlush);
267 _compressor->write(msg.constData(), msg.size());
271 void RemotePeer::handle(const HeartBeat &heartBeat)
273 dispatch(HeartBeatReply(heartBeat.timestamp));
277 void RemotePeer::handle(const HeartBeatReply &heartBeatReply)
280 emit lagUpdated(heartBeatReply.timestamp.msecsTo(QDateTime::currentDateTime().toUTC()) / 2);
284 void RemotePeer::sendHeartBeat()
286 if (signalProxy()->maxHeartBeatCount() > 0 && _heartBeatCount >= signalProxy()->maxHeartBeatCount()) {
287 qWarning() << "Disconnecting peer:" << description()
288 << "(didn't receive a heartbeat for over" << _heartBeatCount *_heartBeatTimer->interval() / 1000 << "seconds)";
290 _heartBeatTimer->stop();
294 if (_heartBeatCount > 0) {
295 _lag = _heartBeatCount * _heartBeatTimer->interval();
296 emit lagUpdated(_lag);
299 dispatch(HeartBeat(QDateTime::currentDateTime().toUTC()));