style: перевести комментарии на русский, убрать очевидные
This commit is contained in:
1 parent
ada9b949a4
commit
e417dac087
48 files changed
+659
-671
No files matched your search
@@ -1,6 +1,6 @@
|
||||
// Package bondframe contains the wire format used by the VLESS bond multi-lane
|
||||
// transport (hello + framed data/FIN). Both the client (initiator) and the
|
||||
// server (acceptor) speak the same encoding.
|
||||
// Package bondframe содержит wire-формат VLESS bond multi-lane transport
|
||||
// (hello + framed data/FIN). Клиент (инициатор) и сервер (акцептор) используют
|
||||
// одинаковую кодировку.
|
||||
package bondframe
|
||||
|
||||
import (
|
||||
@@ -24,21 +24,20 @@ const (
|
||||
LaneAttachTimeout = 300 * time.Millisecond
|
||||
)
|
||||
|
||||
// Hello is the per-lane handshake header sent right after a smux stream opens.
|
||||
// Hello — per-lane handshake header, отправляемый сразу после открытия smux-потока.
|
||||
type Hello struct {
|
||||
ConnID uint64
|
||||
LaneIndex uint16
|
||||
LaneCount uint16
|
||||
}
|
||||
|
||||
// Frame is a single bonded data or FIN unit, identified by Seq within a ConnID.
|
||||
// Frame — одна bonded data или FIN единица, идентифицированная Seq внутри ConnID.
|
||||
type Frame struct {
|
||||
Type byte
|
||||
Seq uint64
|
||||
Data []byte
|
||||
}
|
||||
|
||||
// WriteHello encodes and writes a Hello to w using the bond wire format.
|
||||
func WriteHello(w io.Writer, connID uint64, laneIndex, laneCount uint16) error {
|
||||
var hdr [17]byte
|
||||
copy(hdr[0:4], Magic)
|
||||
@@ -50,8 +49,8 @@ func WriteHello(w io.Writer, connID uint64, laneIndex, laneCount uint16) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// ReadHelloAfterMagic finishes reading a Hello whose first 4 magic bytes have
|
||||
// already been consumed (server pre-peeks the magic to multiplex protocols).
|
||||
// ReadHelloAfterMagic завершает чтение Hello, у которого первые 4 magic-байта
|
||||
// уже прочитаны (сервер pre-peek для мультиплексирования протоколов).
|
||||
func ReadHelloAfterMagic(r io.Reader, magic [4]byte) (Hello, error) {
|
||||
var hdr [17]byte
|
||||
copy(hdr[0:4], magic[:])
|
||||
@@ -61,7 +60,6 @@ func ReadHelloAfterMagic(r io.Reader, magic [4]byte) (Hello, error) {
|
||||
return ParseHelloHeader(hdr[:])
|
||||
}
|
||||
|
||||
// ParseHelloHeader decodes a 17-byte Hello header from hdr.
|
||||
func ParseHelloHeader(hdr []byte) (Hello, error) {
|
||||
if len(hdr) != 17 {
|
||||
return Hello{}, fmt.Errorf("bad bond hello size: %d", len(hdr))
|
||||
@@ -79,7 +77,6 @@ func ParseHelloHeader(hdr []byte) (Hello, error) {
|
||||
}, nil
|
||||
}
|
||||
|
||||
// WriteFrame writes a single Frame to w (header + payload).
|
||||
func WriteFrame(w io.Writer, typ byte, seq uint64, data []byte) error {
|
||||
var hdr [13]byte
|
||||
hdr[0] = typ
|
||||
@@ -95,7 +92,6 @@ func WriteFrame(w io.Writer, typ byte, seq uint64, data []byte) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// ReadFrame reads one Frame from r. Payloads over 4 MiB are rejected.
|
||||
func ReadFrame(r io.Reader) (Frame, error) {
|
||||
var hdr [13]byte
|
||||
if _, err := io.ReadFull(r, hdr[:]); err != nil {
|
||||
@@ -118,11 +114,11 @@ func ReadFrame(r io.Reader) (Frame, error) {
|
||||
return f, nil
|
||||
}
|
||||
|
||||
// PendingCap bounds the per-bond reorder buffer. A peer that emits seq with
|
||||
// permanent gaps cannot grow it past this many frames.
|
||||
// PendingCap ограничивает per-bond буфер переупорядочивания. Пир, генерирующий
|
||||
// seq с постоянными пропусками, не вырастит его больше этого числа фреймов.
|
||||
const PendingCap = 1024
|
||||
|
||||
// ReorderHooks plugs caller-specific logging into Reorder. All fields may be nil.
|
||||
// ReorderHooks подключает caller-специфичное логирование к Reorder. Все поля могут быть nil.
|
||||
type ReorderHooks struct {
|
||||
OnOverflow func(have int)
|
||||
OnUnknownType func(typ byte)
|
||||
@@ -130,12 +126,12 @@ type ReorderHooks struct {
|
||||
OnCloseWrite func(format string, v ...any)
|
||||
}
|
||||
|
||||
// Reorder consumes Frames from recv, writes payloads to dst in Seq order, and
|
||||
// returns the number of fully delivered chunks. It returns when:
|
||||
// - the FIN seq has been reached (CloseWrite is called on dst);
|
||||
// - recv is closed;
|
||||
// - ctx is cancelled;
|
||||
// - an unknown frame type, pending overflow, or write error fires.
|
||||
// Reorder потребляет Frame из recv, пишет payload в dst в порядке Seq и
|
||||
// возвращает число полностью доставленных чанков. Возвращается когда:
|
||||
// - достигнут FIN seq (на dst вызывается CloseWrite);
|
||||
// - recv закрыт;
|
||||
// - ctx отменён;
|
||||
// - неизвестный тип фрейма, переполнение pending или ошибка записи.
|
||||
func Reorder(ctx context.Context, dst net.Conn, recv <-chan Frame, h ReorderHooks) uint64 {
|
||||
pending := make(map[uint64][]byte)
|
||||
var expect uint64
|
||||
@@ -193,10 +189,9 @@ func Reorder(ctx context.Context, dst net.Conn, recv <-chan Frame, h ReorderHook
|
||||
}
|
||||
}
|
||||
|
||||
// CloseWrite half-closes the write side of conn if the underlying type
|
||||
// supports it (TCPConn, smux.Stream, …); otherwise it is a no-op. errf is
|
||||
// invoked with the error if CloseWrite fails; callers typically pass a
|
||||
// debug-gated log func.
|
||||
// CloseWrite полузакрывает write-сторону conn, если базовый тип поддерживает
|
||||
// это (TCPConn, smux.Stream, …); иначе no-op. errf вызывается с ошибкой при
|
||||
// сбое CloseWrite; вызывающие обычно передают debug-gated log func.
|
||||
func CloseWrite(conn net.Conn, errf func(format string, v ...any)) {
|
||||
type closeWriter interface {
|
||||
CloseWrite() error
|
||||
|
||||
@@ -13,8 +13,8 @@ import (
|
||||
pionudp "github.com/pion/transport/v4/udp"
|
||||
)
|
||||
|
||||
// bufPool eliminates per-packet heap allocation on the hot read/write paths
|
||||
// of the server-side wrapped PacketConn.
|
||||
// bufPool устраняет per-packet heap-аллокацию на горячих путях чтения/записи
|
||||
// серверного wrapped PacketConn.
|
||||
var bufPool = sync.Pool{
|
||||
New: func() any {
|
||||
b := make([]byte, 1600+Overhead)
|
||||
@@ -22,7 +22,7 @@ var bufPool = sync.Pool{
|
||||
},
|
||||
}
|
||||
|
||||
// Listen returns a dtls PacketListener that AEAD-wraps every accepted PacketConn.
|
||||
// Listen возвращает dtls PacketListener, AEAD-оборачивающий каждый принятый PacketConn.
|
||||
func Listen(addr *net.UDPAddr, key []byte) (dtlsnet.PacketListener, error) {
|
||||
state, err := NewState(key)
|
||||
if err != nil {
|
||||
@@ -58,8 +58,8 @@ func (l *packetListener) Accept() (net.PacketConn, net.Addr, error) {
|
||||
func (l *packetListener) Close() error { return l.inner.Close() }
|
||||
func (l *packetListener) Addr() net.Addr { return l.inner.Addr() }
|
||||
|
||||
// packetConn is a per-peer net.PacketConn that AEAD-wraps reads and writes
|
||||
// using bufPool to keep the hot path allocation-free.
|
||||
// packetConn — per-peer net.PacketConn, AEAD-оборачивающий чтение/запись
|
||||
// через bufPool для allocation-free горячего пути.
|
||||
type packetConn struct {
|
||||
inner net.PacketConn
|
||||
conn *Conn
|
||||
|
||||
@@ -7,8 +7,9 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// RelayPacketConn wraps a TURN relay PacketConn to direct all writes to a fixed peer.
|
||||
// When Conn is non-nil, packets are wrapped/unwrapped with SRTP-mimicry AEAD.
|
||||
// RelayPacketConn оборачивает TURN relay PacketConn, направляя все записи
|
||||
// фиксированному пиру. Если Conn non-nil, пакеты оборачиваются/разворачиваются
|
||||
// SRTP-mimicry AEAD.
|
||||
type RelayPacketConn struct {
|
||||
Relay net.PacketConn
|
||||
Peer net.Addr
|
||||
|
||||
@@ -1,30 +1,30 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// Package srtpmimicry implements an SRTP-mimicry AEAD framing used to bypass
|
||||
// the VK TURN content filter.
|
||||
// Package srtpmimicry реализует AEAD-фрейминг с мимикрией SRTP для обхода
|
||||
// VK TURN content-filter.
|
||||
//
|
||||
// Purpose: obfuscation, not security. DTLS already provides confidentiality
|
||||
// and integrity on the inner channel. This layer exists to make traffic look
|
||||
// like SRTP so the VK content-filter does not drop it; it is not a defense
|
||||
// against an active adversary on its own.
|
||||
// Назначение: обфускация, а не безопасность. DTLS уже обеспечивает
|
||||
// конфиденциальность и целостность внутреннего канала. Этот слой существует,
|
||||
// чтобы трафик выглядел как SRTP — VK content-filter его не дропает;
|
||||
// сам по себе не является защитой от активного противника.
|
||||
//
|
||||
// Wire format:
|
||||
// Wire-формат:
|
||||
//
|
||||
// [12B RTP header | 12B explicit nonce | AEAD ciphertext | 16B tag]
|
||||
//
|
||||
// RTP header (RFC 3550):
|
||||
//
|
||||
// byte 0: 0x80 V=2, P=0, X=0, CC=0
|
||||
// byte 1: 0x6F M=0, PT=111 (opus, typical voice PT)
|
||||
// byte 2-3: seq16 BE monotonic, init random
|
||||
// byte 4-7: ts32 BE monotonic, init random, increments by 960 (20ms @ 48kHz)
|
||||
// byte 8-11: SSRC random per conn, MSB encodes direction
|
||||
// byte 1: 0x6F M=0, PT=111 (opus, типичный voice PT)
|
||||
// byte 2-3: seq16 BE монотонный, init random
|
||||
// byte 4-7: ts32 BE монотонный, init random, шаг 960 (20ms @ 48kHz)
|
||||
// byte 8-11: SSRC random per conn, MSB кодирует направление
|
||||
//
|
||||
// 12B explicit nonce = 4B sessionID || 8B counter (BE). sessionID MSB
|
||||
// matches SSRC MSB (direction bit). counter starts at a random uint64.
|
||||
// AAD = first 24 bytes (RTP header || nonce).
|
||||
// 12B explicit nonce = 4B sessionID || 8B counter (BE). MSB sessionID
|
||||
// совпадает с MSB SSRC (direction bit). counter стартует с random uint64.
|
||||
// AAD = первые 24 байта (RTP header || nonce).
|
||||
//
|
||||
// Wire format is frozen — bit-exact compatibility with deployed peers is required.
|
||||
// Wire-формат заморожен — требуется побитовая совместимость с задеплоенными пирами.
|
||||
package srtpmimicry
|
||||
|
||||
import (
|
||||
@@ -51,11 +51,10 @@ const (
|
||||
tsStep = 960 // 20ms @ 48kHz
|
||||
)
|
||||
|
||||
// MaxWire returns max wire bytes for a given payload size.
|
||||
func MaxWire(payloadLen int) int { return Overhead + payloadLen }
|
||||
|
||||
// State holds an AEAD instance derived from the shared key.
|
||||
// One State can be shared across many Conns (e.g. server-side listener).
|
||||
// State хранит AEAD-экземпляр, выведенный из общего ключа.
|
||||
// Один State может разделяться между многими Conn (напр. server-side listener).
|
||||
type State struct {
|
||||
aead cipher.AEAD
|
||||
}
|
||||
@@ -71,18 +70,17 @@ func NewState(key []byte) (*State, error) {
|
||||
return &State{aead: aead}, nil
|
||||
}
|
||||
|
||||
// Conn carries per-stream RTP state (seq/timestamp/SSRC/counter) plus a
|
||||
// reference to the shared AEAD State.
|
||||
// Conn несёт per-stream RTP-состояние (seq/timestamp/SSRC/counter) и
|
||||
// ссылку на общий AEAD State.
|
||||
type Conn struct {
|
||||
state *State
|
||||
sessionID [4]byte // 4B prefix for nonce; MSB encodes direction
|
||||
ssrc [4]byte // SSRC for RTP header; MSB encodes direction
|
||||
sessionID [4]byte // 4B префикс nonce; MSB кодирует направление
|
||||
ssrc [4]byte // SSRC для RTP header; MSB кодирует направление
|
||||
counter atomic.Uint64
|
||||
seq atomic.Uint32 // RTP sequence (used as uint16)
|
||||
timestamp atomic.Uint32 // RTP timestamp
|
||||
}
|
||||
|
||||
// NewConn allocates a fresh State from key and a Conn bound to it.
|
||||
func NewConn(key []byte, isServer bool) (*Conn, error) {
|
||||
s, err := NewState(key)
|
||||
if err != nil {
|
||||
@@ -91,8 +89,8 @@ func NewConn(key []byte, isServer bool) (*Conn, error) {
|
||||
return NewConnFromState(s, isServer)
|
||||
}
|
||||
|
||||
// NewConnFromState builds a Conn with random per-stream RTP fields,
|
||||
// reusing the supplied State.
|
||||
// NewConnFromState создаёт Conn со случайными per-stream RTP-полями,
|
||||
// переиспользуя переданный State.
|
||||
func NewConnFromState(state *State, isServer bool) (*Conn, error) {
|
||||
if state == nil {
|
||||
return nil, errors.New("wrap: nil state")
|
||||
@@ -123,15 +121,15 @@ func NewConnFromState(state *State, isServer bool) (*Conn, error) {
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// WrapInto encodes payload into dst (must be at least MaxWire(len(payload)) bytes)
|
||||
// and returns the number of wire bytes written.
|
||||
// WrapInto кодирует payload в dst (минимум MaxWire(len(payload)) байт)
|
||||
// и возвращает число записанных wire-байт.
|
||||
func (c *Conn) WrapInto(dst, payload []byte) (int, error) {
|
||||
wireLen := Overhead + len(payload)
|
||||
if len(dst) < wireLen {
|
||||
return 0, errors.New("wrap: dst buffer too small")
|
||||
}
|
||||
|
||||
// RTP header.
|
||||
// RTP-заголовок.
|
||||
dst[0] = rtpVersion
|
||||
dst[1] = rtpPT
|
||||
seq := uint16(c.seq.Add(1) - 1)
|
||||
@@ -140,7 +138,7 @@ func (c *Conn) WrapInto(dst, payload []byte) (int, error) {
|
||||
binary.BigEndian.PutUint32(dst[4:8], ts)
|
||||
copy(dst[8:12], c.ssrc[:])
|
||||
|
||||
// Explicit nonce.
|
||||
// Явный nonce.
|
||||
noncePos := rtpHdrLen
|
||||
copy(dst[noncePos:noncePos+4], c.sessionID[:])
|
||||
ctr := c.counter.Add(1) - 1
|
||||
@@ -155,9 +153,9 @@ func (c *Conn) WrapInto(dst, payload []byte) (int, error) {
|
||||
return wireLen, nil
|
||||
}
|
||||
|
||||
// Unwrap decodes a wire packet into dst and returns the plaintext length.
|
||||
// Note: the AEAD opens in-place inside wire, so callers must treat wire as
|
||||
// consumed after this call (do not reuse its contents).
|
||||
// Unwrap декодирует wire-пакет в dst и возвращает длину plaintext.
|
||||
// AEAD открывает in-place внутри wire — вызывающий должен считать wire
|
||||
// потреблённым после вызова (содержимое нельзя переиспользовать).
|
||||
func (c *Conn) Unwrap(wire, dst []byte) (int, error) {
|
||||
if len(wire) < Overhead {
|
||||
return 0, errors.New("wrap: packet too short")
|
||||
@@ -177,9 +175,6 @@ func (c *Conn) Unwrap(wire, dst []byte) (int, error) {
|
||||
return len(plain), nil
|
||||
}
|
||||
|
||||
// --- Key helpers ---
|
||||
|
||||
// GenKeyHex returns a fresh hex-encoded random key.
|
||||
func GenKeyHex() (string, error) {
|
||||
key := make([]byte, KeyLen)
|
||||
if _, err := rand.Read(key); err != nil {
|
||||
@@ -188,8 +183,8 @@ func GenKeyHex() (string, error) {
|
||||
return hex.EncodeToString(key), nil
|
||||
}
|
||||
|
||||
// DecodeKey decodes a hex key and validates length when enabled.
|
||||
// When enabled is false, returns (nil, nil).
|
||||
// DecodeKey декодирует hex-ключ и проверяет длину если enabled.
|
||||
// Если enabled=false, возвращает (nil, nil).
|
||||
func DecodeKey(enabled bool, raw string) ([]byte, error) {
|
||||
if !enabled {
|
||||
return nil, nil
|
||||
|
||||
Reference in new issue
Block a user