style: перевести комментарии на русский, убрать очевидные

This commit is contained in:
samosvalishe committed 2026-05-21 12:31:50 +03:00
1 parent ada9b949a4
commit e417dac087
48 files changed
+659 -671

No files matched your search

+13 -15
View File
@@ -1,19 +1,17 @@
// DTLS-as-obfuscation note (V2-8):
// DTLS как обфускация (V2-8):
//
// DTLS in this project is used primarily as an *obfuscation* layer, not as a
// security boundary. The VK TURN content-filter drops payloads that do not
// look like a legitimate DTLS handshake followed by encrypted records, so the
// handshake is what gets us through. The encryption it provides is a free
// side-effect — we already trust the wrapped tunnel (WireGuard inside UDP
// mode, or smux+KCP inside tcpfwd mode) to handle confidentiality and
// integrity end-to-end.
// DTLS в этом проекте используется прежде всего как слой *обфускации*, а не
// как граница безопасности. VK TURN content-filter дропает payload, не
// похожий на легитимный DTLS handshake с зашифрованными записями, — именно
// handshake пропускает нас. Шифрование — бесплатный побочный эффект; мы уже
// доверяем внутреннему туннелю (WireGuard в UDP-режиме или smux+KCP в tcpfwd)
// для обеспечения конфиденциальности и целостности end-to-end.
//
// This is why the older `-no-dtls` / `Direct` flag was removed in V2-0: with
// DTLS off, VK drops packets and the proxy effectively does not work in
// production. There is no scenario in which disabling DTLS is the right
// call against the live VK filter.
// Именно поэтому старый флаг `-no-dtls` / `Direct` удалён в V2-0: без DTLS
// VK дропает пакеты и прокси фактически не работает в production. Нет
// сценария, в котором отключение DTLS против живого VK-фильтра — верное решение.
//
// Implication for future changes: do not treat the DTLS layer as if it were
// security-critical (e.g. it is fine to use self-signed certs, send-only CID,
// and no peer-cert validation — those are deliberate, not oversights).
// Для будущих изменений: не трактуй DTLS-слой как security-critical
// (самоподписанные сертификаты, send-only CID, отсутствие проверки peer-cert —
// это намеренно, не упущения).
package dtlsdial
+11 -15
View File
@@ -1,6 +1,6 @@
// Package dtlsdial wraps pion-dtls client setup (self-signed cert, EMS,
// AES-128-GCM, send-only CID) plus an optional concurrency gate around the
// handshake. Used by the client UDP and VLESS pipelines.
// Package dtlsdial оборачивает настройку pion-dtls клиента (self-signed cert, EMS,
// AES-128-GCM, send-only CID) плюс опциональный конкурентный gate на handshake.
// Используется UDP и VLESS pipeline'ами клиента.
package dtlsdial
import (
@@ -14,19 +14,16 @@ import (
"github.com/pion/dtls/v3/pkg/crypto/selfsign"
)
// GenerateSelfSignedCert returns a new self-signed TLS certificate for use
// as the DTLS identity. It is a thin wrapper around selfsign.GenerateSelfSigned
// and exists so both cmd/server and Dialer share one call-site.
func GenerateSelfSignedCert() (tls.Certificate, error) {
return selfsign.GenerateSelfSigned()
}
// Dialer configures the DTLS client handshake.
// Dialer конфигурирует DTLS-handshake клиента.
type Dialer struct {
// HandshakeTimeout caps the handshake context. Zero means no timeout.
// HandshakeTimeout ограничивает контекст handshake. Ноль — без таймаута.
HandshakeTimeout time.Duration
// HandshakeSem, if non-nil, gates concurrent handshakes (Dial blocks
// until a slot is available or ctx fires).
// HandshakeSem, если non-nil, ограничивает параллельные handshake
// (Dial блокируется до появления слота или отмены ctx).
HandshakeSem chan struct{}
certOnce sync.Once
@@ -34,11 +31,10 @@ type Dialer struct {
certErr error
}
// Dial acquires the optional handshake slot and performs a DTLS client
// handshake over pc to peer. On success returns the connected *dtls.Conn.
// Caller closes it. The self-signed cert is generated once per Dialer and
// reused across handshakes (DTLS is used here for obfuscation, not auth —
// see internal/transport/dtlsdial/doc.go).
// Dial захватывает опциональный handshake-слот и выполняет DTLS-handshake
// клиента поверх pc к peer. При успехе возвращает *dtls.Conn (закрывает вызывающий).
// Self-signed сертификат генерируется один раз на Dialer и переиспользуется
// (DTLS здесь — для обфускации, не аутентификации; см. doc.go).
func (d *Dialer) Dial(ctx context.Context, pc net.PacketConn, peer *net.UDPAddr) (*dtls.Conn, error) {
d.certOnce.Do(func() {
d.cert, d.certErr = GenerateSelfSignedCert()
+13 -13
View File
@@ -11,7 +11,7 @@ import (
"github.com/xtaci/smux"
)
// Profile holds the tunable KCP parameters. Both sides of a tunnel must agree.
// Profile — настраиваемые KCP-параметры. Обе стороны туннеля должны совпадать.
type Profile struct {
NoDelay int
Interval int
@@ -23,13 +23,13 @@ type Profile struct {
ACKNoDelay bool
}
// FEC controls KCP forward-error-correction shards. Zero values disable FEC.
// FEC управляет шардами KCP forward-error-correction. Нулевые значения отключают FEC.
type FEC struct {
Data int
Parity int
}
// DefaultProfile mirrors the historical balanced profile shipped with the proxy.
// DefaultProfile — исторический balanced-профиль, поставляемый с прокси.
func DefaultProfile() Profile {
return Profile{
NoDelay: 1,
@@ -43,8 +43,8 @@ func DefaultProfile() Profile {
}
}
// LoadProfileFromEnv reads VK_TURN_KCP_PROFILE and per-field VK_TURN_KCP_*
// overrides. Unknown profile name → DefaultProfile.
// LoadProfileFromEnv читает VK_TURN_KCP_PROFILE и per-field переопределения
// VK_TURN_KCP_*. Неизвестное имя профиля → DefaultProfile.
func LoadProfileFromEnv() Profile {
name := strings.ToLower(strings.TrimSpace(os.Getenv("VK_TURN_KCP_PROFILE")))
var p Profile
@@ -69,8 +69,8 @@ func LoadProfileFromEnv() Profile {
return p
}
// LoadFECFromEnv parses VK_TURN_KCP_FEC as "data:parity" (e.g. "10:3").
// Empty/invalid → disabled.
// LoadFECFromEnv парсит VK_TURN_KCP_FEC как "data:parity" (напр. "10:3").
// Пустое/невалидное → отключено.
func LoadFECFromEnv() FEC {
raw := strings.TrimSpace(os.Getenv("VK_TURN_KCP_FEC"))
if raw == "" {
@@ -112,8 +112,8 @@ func envBool(name string, fallback bool) bool {
}
}
// DtlsPacketConn wraps a net.Conn (DTLS) as a net.PacketConn for KCP.
// Each DTLS Read/Write preserves message boundaries (datagram semantics).
// DtlsPacketConn оборачивает net.Conn (DTLS) как net.PacketConn для KCP.
// Каждый DTLS Read/Write сохраняет границы сообщений (datagram семантика).
type DtlsPacketConn struct {
conn net.Conn
}
@@ -151,12 +151,12 @@ func (d *DtlsPacketConn) SetWriteDeadline(t time.Time) error {
return d.conn.SetWriteDeadline(t)
}
// NewKCPOverDTLS creates a KCP session over a DTLS connection.
// isServer: true for server-side (listener), false for client-side (dialer).
// NewKCPOverDTLS создаёт KCP-сессию поверх DTLS-соединения.
// isServer: true — серверная сторона (listener), false — клиентская (dialer).
func NewKCPOverDTLS(dtlsConn net.Conn, isServer bool, profile Profile, fec FEC) (*kcp.UDPSession, error) {
pc := NewDtlsPacketConn(dtlsConn)
block, err := kcp.NewNoneBlockCrypt(nil) // DTLS already encrypts
block, err := kcp.NewNoneBlockCrypt(nil) // DTLS уже шифрует
if err != nil {
return nil, err
}
@@ -193,7 +193,7 @@ func NewKCPOverDTLS(dtlsConn net.Conn, isServer bool, profile Profile, fec FEC)
return sess, nil
}
// DefaultSmuxConfig returns smux config tuned for TURN tunnel.
// DefaultSmuxConfig возвращает smux-конфигурацию, настроенную под TURN-туннель.
func DefaultSmuxConfig() *smux.Config {
cfg := smux.DefaultConfig()
cfg.MaxReceiveBuffer = 4 * 1024 * 1024
+18 -22
View File
@@ -1,10 +1,10 @@
// Package turndial centralizes the TURN dial+allocate pipeline shared by
// the client UDP (oneTurnConnection) and VLESS (createSmuxSession) modes.
// Package turndial централизует TURN dial+allocate pipeline, общий для
// UDP (oneTurnConnection) и VLESS (createSmuxSession) режимов клиента.
//
// One call to Open performs: parse target, apply host/port overrides,
// resolve UDP addr, dial UDP-or-TCP (with SplitFirstWriteConn over TCP),
// turn.NewClient, Listen, Allocate. Returns the relay PacketConn plus a
// Close that tears down the allocation, TURN client, and underlying conn.
// Один вызов Open выполняет: парсинг цели, применение host/port override,
// резолв UDP-адреса, dial UDP-или-TCP (с SplitFirstWriteConn поверх TCP),
// turn.NewClient, Listen, Allocate. Возвращает relay PacketConn и Close,
// который разрушает аллокацию, TURN-клиент и транспорт.
package turndial
import (
@@ -18,32 +18,29 @@ import (
"github.com/pion/turn/v5"
)
// Config configures one Open call.
// Config конфигурирует один вызов Open.
type Config struct {
// HostOverride, if non-empty, replaces the host part returned by the
// credentials lookup.
// HostOverride, если непустой, заменяет host из lookup credentials.
HostOverride string
// PortOverride, if non-empty, replaces the port part returned by the
// credentials lookup.
// PortOverride, если непустой, заменяет port из lookup credentials.
PortOverride string
// UDP=true dials TURN over UDP; otherwise over TCP via STUNConn.
// UDP=true — dial TURN по UDP; иначе по TCP через STUNConn.
UDP bool
// DialTimeout caps the TCP dial. Zero defaults to 5s.
// DialTimeout ограничивает TCP dial. Ноль → 5s.
DialTimeout time.Duration
}
// Stream is a live TURN allocation with its dependencies. Close tears
// everything down in reverse order.
// Stream — активная TURN-аллокация с зависимостями. Close разрушает в обратном порядке.
type Stream struct {
// Relay is the allocated relay PacketConn returned by turn.Client.Allocate.
// Relay — выделенный relay PacketConn из turn.Client.Allocate.
Relay net.PacketConn
// ServerUDPAddr is the resolved TURN server UDP address (host:port).
// ServerUDPAddr — резолвнутый UDP-адрес TURN-сервера (host:port).
ServerUDPAddr *net.UDPAddr
close func() error
}
// Close releases the allocation, TURN client and underlying transport.
// Safe to call once. Returns the first non-nil error (if any).
// Close освобождает аллокацию, TURN-клиент и транспорт.
// Безопасно вызвать один раз. Возвращает первую non-nil ошибку.
func (s *Stream) Close() error {
if s == nil || s.close == nil {
return nil
@@ -51,9 +48,8 @@ func (s *Stream) Close() error {
return s.close()
}
// Open dials TURN, creates a turn.Client and allocates a relay. rawAddr is
// the host:port returned by the credentials lookup; user/pass are the TURN
// long-term credentials.
// Open подключается к TURN, создаёт turn.Client и выделяет relay. rawAddr —
// host:port из lookup credentials; user/pass — долгосрочные TURN-реквизиты.
func Open(ctx context.Context, cfg Config, peer *net.UDPAddr, user, pass, rawAddr string) (*Stream, error) {
urlhost, urlport, err := net.SplitHostPort(rawAddr)
if err != nil {