ZaStoGram_desktop/Telegram/SourceFiles/mtproto/proxy/wss/socket.h
loop-uh 1e19d26187
All checks were successful
Desktop source guards / guards (push) Successful in 12s
Качать файлы через туннель частями по 8 КБ на коротких соединениях
ТСПУ замораживает каждое соединение с Cloudflare примерно после 16 КБ
входящих: на ПК (лог 25.09) ни одна сессия туннеля к DC1 не получила больше
13 КБ, а часть файла 128 КБ целиком не проходила ни разу (send_count=51),
поэтому файлы в «Избранном» стояли на 0.

- Для DC, чей медийный релей подавлен и ушёл в туннель, часть 128 КБ
  собирается из 16 кусков по 8 КБ; для CDN части не делятся.
- До 8 сессий сразу, в каждой один запрос: скорость даёт параллельность.
- Файловое соединение туннеля переоткрывается на границе пакета после
  4 КБ входящих, до заморозки; такие сокеты пишутся одной сводной строкой
  wss_tunnel_rotated, строки переподключения для них не пишутся.
- Туннель подавляется только если после upgrade не пришло ничего: раньше
  три заморозки отправляли DC1 в прямой TCP, который сеть режет целиком,
  и файлы не грузились совсем по две минуты.
2026-09-25 15:01:01 +03:00

126 lines
4.2 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/transport/details/mtproto_abstract_socket.h"
#include <QtNetwork/QSslSocket>
#include <optional>
namespace MTP::details {
struct WssRoute {
QString relayHost;
QString relayHostFallback; // retried once if relayHost fails (e.g. domain)
int relayPort = 443;
QString domain;
QString path;
bool tunnel = false; // path gets ?dst=<datacenter address> on connect
};
// A passive snapshot for user-facing media diagnostics. It observes the
// relay preference and health maps, but never changes connection admission,
// retry timing or the lifetime of a live session.
struct WssRouteDiagnostics {
std::optional<WssRoute> route;
QString selectedRelayHost;
bool custom = false;
bool prefersFallback = false;
bool suppressed = false;
int consecutiveFailures = 0;
crl::time suppressedFor = 0;
};
// Official MTProto-over-WebSocket route for a data center, mirroring the
// web.telegram.org transport. Every production DC (1-5) has a working web
// relay, but the ingress addresses are NOT interchangeable: each one serves
// only its own datacenters. Reaching the wrong ingress answers 302 (with an
// X-Redirect-Host header naming the right relay) or accepts the connection
// and stays silent - which is where the widespread "web sockets exist only
// for DC2/DC4" belief came from. Measured against live relays 2026-08-08.
[[nodiscard]] std::optional<WssRoute> WssOfficialRoute(
int16 protocolDcId);
// Expert-only user-configured relay (ProxyStealthOptions.wssCustom*), used
// for any DC when set and verified against the configured relay domain.
[[nodiscard]] std::optional<WssRoute> WssCustomRoute(
const ProxyStealthOptions &stealth);
[[nodiscard]] WssRouteDiagnostics WssRouteDiagnosticsForDc(
const ProxyStealthOptions &stealth,
int16 protocolDcId);
// The media relay of this DC is suppressed and its files go through the
// Cloudflare tunnel, where every connection freezes after ~16 KB downstream.
// File downloads then use small parts over many short-lived connections.
[[nodiscard]] bool WssMediaTunneled(int dcId);
// A clean, self-contained MTProto-over-WebSocket(-over-TLS) transport. It
// speaks RFC 6455 over a real QSslSocket and carries the obfuscated MTProto
// stream transparently inside binary frames, so the rest of the connection
// stack (obfuscation, protocol negotiation) is unchanged.
class WssSocket final : public AbstractSocket {
public:
WssSocket(
not_null<RuntimeEnvironment*> runtime,
not_null<QThread*> thread,
const QNetworkProxy &proxy,
bool protocolForFiles,
WssRoute route);
~WssSocket();
void connectToHost(const QString &address, int port) override;
bool isGoodStartNonce(bytes::const_span nonce) override;
void timedOut() override;
[[nodiscard]] bool takeRotation() override;
bool isConnected() override;
bool hasBytesAvailable() override;
int64 read(bytes::span buffer) override;
void write(bytes::const_span prefix, bytes::const_span buffer) override;
int32 debugState() override;
QString debugPostfix() const override;
HandshakePhase handshakePhase() const override;
QString transportName() const override;
private:
void handleError(int errorCode);
void connectToRelayHost();
void onTcpConnected();
void onEncrypted();
void onReadyRead();
void sendHttpUpgrade();
[[nodiscard]] bool tryFinishUpgrade();
[[nodiscard]] bool checkUpgradeAccept(const QByteArray &header) const;
void parseFrames();
void sendFrame(quint8 opcode, bytes::const_span data);
QSslSocket _socket;
WssRoute _route;
QString _secWebSocketKey;
QByteArray _incoming;
QByteArray _readBuffer;
bool _upgraded = false;
bool _usedFallback = false;
bool _hostFlipped = false;
QString _currentHost;
bool _tcpConnected = false;
qint64 _bytesReceived = 0;
qint64 _bytesSent = 0;
bool _tunnelProven = false;
bool _forFiles = false;
bool _rotated = false;
crl::time _openedAt = 0;
crl::time _upgradedAt = 0;
crl::time _firstDataAt = 0;
HandshakePhase _phase = HandshakePhase::None;
};
} // namespace MTP::details