All checks were successful
Desktop source guards / guards (push) Successful in 12s
ТСПУ замораживает каждое соединение с Cloudflare примерно после 16 КБ входящих: на ПК (лог 25.09) ни одна сессия туннеля к DC1 не получила больше 13 КБ, а часть файла 128 КБ целиком не проходила ни разу (send_count=51), поэтому файлы в «Избранном» стояли на 0. - Для DC, чей медийный релей подавлен и ушёл в туннель, часть 128 КБ собирается из 16 кусков по 8 КБ; для CDN части не делятся. - До 8 сессий сразу, в каждой один запрос: скорость даёт параллельность. - Файловое соединение туннеля переоткрывается на границе пакета после 4 КБ входящих, до заморозки; такие сокеты пишутся одной сводной строкой wss_tunnel_rotated, строки переподключения для них не пишутся. - Туннель подавляется только если после upgrade не пришло ничего: раньше три заморозки отправляли DC1 в прямой TCP, который сеть режет целиком, и файлы не грузились совсем по две минуты.
269 lines
7.3 KiB
C++
269 lines
7.3 KiB
C++
/*
|
|
This file is part of Telegram Desktop,
|
|
the official desktop application for the Telegram messaging service.
|
|
|
|
For license and copyright information please follow this link:
|
|
https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
|
|
*/
|
|
#pragma once
|
|
|
|
#include "mtproto/protocol/mtproto_binary.h"
|
|
#include "mtproto/config/mtproto_dc_options.h"
|
|
#include "mtproto/proxy/data.h"
|
|
#include "mtproto/proxy/status.h"
|
|
#include "base/bytes.h"
|
|
|
|
#include <QtCore/QObject>
|
|
#include <QtCore/QThread>
|
|
#include <QtCore/QtEndian>
|
|
|
|
#include <deque>
|
|
|
|
namespace MTP {
|
|
|
|
class Instance;
|
|
class RuntimeEnvironment;
|
|
|
|
namespace details {
|
|
|
|
struct ConnectionOptions;
|
|
|
|
class AbstractConnection;
|
|
enum class HandshakePhase;
|
|
|
|
inline constexpr auto kTestModeDcIdShift = 10000;
|
|
|
|
// Asked when a session saw no reply for its receive timeout. Sockets that
|
|
// share one carrier with other connections can tell a reply still queued
|
|
// in that carrier from a dead connection; everything else answers "dead".
|
|
struct ReceiveWaitVerdict {
|
|
crl::time waitMore = 0;
|
|
QString details;
|
|
};
|
|
|
|
class ConnectionPointer {
|
|
public:
|
|
ConnectionPointer();
|
|
ConnectionPointer(std::nullptr_t);
|
|
ConnectionPointer(ConnectionPointer &&other);
|
|
ConnectionPointer &operator=(ConnectionPointer &&other);
|
|
|
|
template <typename ConnectionType, typename ...Args>
|
|
static ConnectionPointer New(Args &&...args) {
|
|
return ConnectionPointer(new ConnectionType(
|
|
std::forward<Args>(args)...
|
|
));
|
|
}
|
|
|
|
AbstractConnection *get() const;
|
|
void reset(AbstractConnection *value = nullptr);
|
|
operator AbstractConnection*() const;
|
|
AbstractConnection *operator->() const;
|
|
AbstractConnection &operator*() const;
|
|
explicit operator bool() const;
|
|
|
|
~ConnectionPointer();
|
|
|
|
private:
|
|
explicit ConnectionPointer(AbstractConnection *value);
|
|
|
|
AbstractConnection *_value = nullptr;
|
|
|
|
};
|
|
|
|
class AbstractConnection : public QObject {
|
|
Q_OBJECT
|
|
|
|
public:
|
|
struct SendDataContext {
|
|
uint64 keyId = 0;
|
|
};
|
|
struct ConnectionStartContext {
|
|
ProxyConnectionAttempt mtproxyAttempt;
|
|
MtProxyAttemptPlan mtproxyPlan;
|
|
crl::time mtproxyAttemptStartedAt = 0;
|
|
};
|
|
|
|
enum class TransportServiceRequest {
|
|
None,
|
|
HttpWait,
|
|
};
|
|
|
|
AbstractConnection(
|
|
not_null<RuntimeEnvironment*> runtime,
|
|
QThread *thread,
|
|
const ProxyData &proxy);
|
|
AbstractConnection(const AbstractConnection &other) = delete;
|
|
AbstractConnection &operator=(const AbstractConnection &other) = delete;
|
|
virtual ~AbstractConnection() = default;
|
|
|
|
// virtual constructor
|
|
[[nodiscard]] static ConnectionPointer Create(
|
|
not_null<RuntimeEnvironment*> runtime,
|
|
DcOptions::Variants::Protocol protocol,
|
|
QThread *thread,
|
|
const bytes::vector &secret,
|
|
const ProxyData &proxy,
|
|
const ProxyStealthOptions &stealth);
|
|
|
|
[[nodiscard]] virtual ConnectionPointer clone(const ProxyData &proxy) = 0;
|
|
|
|
[[nodiscard]] virtual crl::time pingTime() const = 0;
|
|
[[nodiscard]] virtual crl::time fullConnectTimeout() const = 0;
|
|
virtual void sendData(mtpBuffer &&buffer, SendDataContext context) = 0;
|
|
void sendData(mtpBuffer &&buffer) {
|
|
sendData(std::move(buffer), {});
|
|
}
|
|
virtual void disconnectFromServer() = 0;
|
|
virtual void connectToServer(
|
|
const QString &ip,
|
|
int port,
|
|
const bytes::vector &protocolSecret,
|
|
int16 protocolDcId,
|
|
bool protocolForFiles,
|
|
ConnectionStartContext context = {}) = 0;
|
|
virtual void timedOut() {
|
|
}
|
|
virtual void markProxyMtprotoPayloadReceived() {
|
|
}
|
|
[[nodiscard]] virtual HandshakePhase handshakePhase() const;
|
|
[[nodiscard]] virtual ProxyConnectionAttempt proxyConnectionAttempt() const;
|
|
[[nodiscard]] virtual ProxyTransportFailure proxyTransportFailure() const;
|
|
[[nodiscard]] virtual ReceiveWaitVerdict receiveWaitVerdict(
|
|
crl::time /*waitStartedAt*/) const {
|
|
return {};
|
|
}
|
|
[[nodiscard]] virtual bool isConnected() const = 0;
|
|
[[nodiscard]] virtual TransportServiceRequest serviceRequest() const {
|
|
return TransportServiceRequest::None;
|
|
}
|
|
[[nodiscard]] virtual bool serviceRequestNeeded(
|
|
TransportServiceRequest request) const;
|
|
|
|
[[nodiscard]] virtual int32 debugState() const = 0;
|
|
|
|
[[nodiscard]] virtual QString transport() const = 0;
|
|
[[nodiscard]] virtual QString tag() const = 0;
|
|
|
|
using BuffersQueue = std::deque<mtpBuffer>;
|
|
[[nodiscard]] BuffersQueue &received() {
|
|
return _receivedQueue;
|
|
}
|
|
|
|
template <typename Request>
|
|
[[nodiscard]] mtpBuffer prepareNotSecurePacket(
|
|
const Request &request,
|
|
mtpMsgId newId) const;
|
|
[[nodiscard]] mtpBuffer prepareSecurePacket(
|
|
uint64 keyId,
|
|
MTPint128 msgKey,
|
|
uint32 size) const;
|
|
|
|
[[nodiscard]] gsl::span<const mtpPrime> parseNotSecureResponse(
|
|
const mtpBuffer &buffer) const;
|
|
|
|
[[nodiscard]] static QString ProtocolDcDebugId(int16 protocolDcId);
|
|
[[nodiscard]] QString debugId() const {
|
|
return _debugId;
|
|
}
|
|
enum class TransportMode {
|
|
None,
|
|
Direct,
|
|
Socks5,
|
|
Http,
|
|
PlainMtproxy,
|
|
FakeTlsMtproxy,
|
|
};
|
|
[[nodiscard]] TransportMode transportMode() const {
|
|
return _transport;
|
|
}
|
|
void logInfo(const QString &message);
|
|
void logError(const QString &message);
|
|
|
|
// Closed on purpose to dodge a per-connection byte limit, not failed.
|
|
[[nodiscard]] bool rotating() const {
|
|
return _rotating;
|
|
}
|
|
|
|
// Used to emit error(...) with no real code from the server.
|
|
static constexpr auto kErrorCodeOther = -499;
|
|
|
|
Q_SIGNALS:
|
|
void receivedData();
|
|
void receivedSome(); // to stop restart timer
|
|
void handshakeProgress();
|
|
|
|
void error(qint32 errorCode);
|
|
|
|
void connected();
|
|
void disconnected();
|
|
|
|
void syncTimeRequest();
|
|
|
|
protected:
|
|
const not_null<RuntimeEnvironment*> _runtime;
|
|
BuffersQueue _receivedQueue; // list of received packets, not processed yet
|
|
bool _rotating = false;
|
|
int _pingTime = 0;
|
|
ProxyData _proxy;
|
|
TransportMode _transport = TransportMode::None;
|
|
|
|
QString _debugId;
|
|
|
|
// first we always send fake MTPReq_pq to see if connection works at all
|
|
// we send them simultaneously through TCP/HTTP/IPv4/IPv6 to choose the working one
|
|
[[nodiscard]] mtpBuffer preparePQFake(const MTPint128 &nonce) const;
|
|
[[nodiscard]] std::optional<MTPResPQ> readPQFakeReply(
|
|
const mtpBuffer &buffer) const;
|
|
|
|
private:
|
|
[[nodiscard]] uint32 extendedNotSecurePadding() const;
|
|
|
|
};
|
|
|
|
template <typename Request>
|
|
mtpBuffer AbstractConnection::prepareNotSecurePacket(
|
|
const Request &request,
|
|
mtpMsgId newId) const {
|
|
const auto intsSize = tl::count_length(request) >> 2;
|
|
const auto intsPadding = extendedNotSecurePadding();
|
|
|
|
auto result = mtpBuffer();
|
|
constexpr auto kTcpPrefixInts = 2;
|
|
constexpr auto kAuthKeyIdInts = 2;
|
|
constexpr auto kMessageIdInts = 2;
|
|
constexpr auto kMessageLengthInts = 1;
|
|
constexpr auto kPrefixInts = kTcpPrefixInts
|
|
+ kAuthKeyIdInts
|
|
+ kMessageIdInts
|
|
+ kMessageLengthInts;
|
|
constexpr auto kTcpPostfixInts = 4;
|
|
|
|
result.reserve(kPrefixInts + intsSize + intsPadding + kTcpPostfixInts);
|
|
result.resize(kPrefixInts);
|
|
|
|
const auto messageId = &result[kTcpPrefixInts + kAuthKeyIdInts];
|
|
details::binary::Write<mtpMsgId>(
|
|
bytes::make_span(messageId, kMessageIdInts),
|
|
newId);
|
|
|
|
request.write(result);
|
|
|
|
const auto messageLength = messageId + kMessageIdInts;
|
|
*messageLength = (result.size() - kPrefixInts + intsPadding) << 2;
|
|
|
|
if (intsPadding > 0) {
|
|
const auto skipPrimes = result.size();
|
|
result.resize(skipPrimes + intsPadding);
|
|
const auto skipBytes = skipPrimes * sizeof(mtpPrime);
|
|
bytes::set_random(bytes::make_span(result).subspan(skipBytes));
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
#define CONNECTION_LOG_INFO(x) if (Logs::DebugEnabled()) { logInfo(x); }
|
|
#define CONNECTION_LOG_ERROR(x) if (Logs::DebugEnabled()) { logError(x); }
|
|
|
|
} // namespace details
|
|
} // namespace MTP
|