mtp

package
v0.3.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 20, 2026 License: GPL-3.0 Imports: 17 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultWindowSize     = 512                    // Увеличено для быстрого старта
	MaxWindowSize         = 2048                   // Увеличено для гигабитных сетей
	InitialRTO            = 100 * time.Millisecond // Уменьшено для быстрой реакции
	MinRTO                = 10 * time.Millisecond  // Минимальный RTO для локальных сетей
	MaxRTO                = 5 * time.Second        // Уменьшено для быстрого восстановления
	MaxRetransmissions    = 8                      // Уменьшено для быстрого отказа
	DuplicateACKThreshold = 2                      // Уменьшено для быстрой детекции потерь

	// BBR parameters - more aggressive for high-speed
	BBRGain = 1.5 // Более агрессивный gain для высоких скоростей

	// FEC адаптивные параметры - optimized
	FECMinDataShards   = 16 // Увеличено для лучшего соотношения
	FECMaxDataShards   = 32 // Увеличено
	FECMinParityShards = 2  // Минимум parity
	FECMaxParityShards = 4  // Максимум parity
)

ARQ engine constants - OPTIMIZED for high-speed networks (100 Mbps+)

View Source
const (
	PacketDATA   uint8 = 0x01
	PacketACK    uint8 = 0x02
	PacketSYN    uint8 = 0x03
	PacketSYNACK uint8 = 0x04
	PacketFIN    uint8 = 0x05
	PacketFINACK uint8 = 0x06
	PacketPING   uint8 = 0x07
	PacketPONG   uint8 = 0x08
	PacketFEC    uint8 = 0x09
)

Packet types

View Source
const (
	FlagNone       uint8 = 0x00
	FlagMigrate    uint8 = 0x01 // Session migration
	FlagSACK       uint8 = 0x02 // Selective ACK
	FlagFragment   uint8 = 0x04 // Fragmented payload
	FlagCompressed uint8 = 0x08 // Payload is compressed (applied BEFORE encryption)
)

Packet flags

View Source
const FECMaxPayload = MaxPayloadSize

FECMaxPayload is the maximum payload size for FEC shards

View Source
const MaxPayloadSize = 1200

MaxPayloadSize is the max payload per MTP packet (safe UDP MTU)

Variables

This section is empty.

Functions

This section is empty.

Types

type ARQEngine

type ARQEngine struct {
	// contains filtered or unexported fields
}

ARQEngine manages reliable delivery over unreliable UDP OPTIMIZED: split locks for better concurrency

func NewARQEngine

func NewARQEngine(codec *PacketCodec, sendFunc func([]byte) error, deliverBufSize int) *ARQEngine

NewARQEngine creates a new ARQ engine with optimized parameters

func (*ARQEngine) Close

func (a *ARQEngine) Close()

Close stops the ARQ engine OPTIMIZED: split locks for better concurrency

func (*ARQEngine) Delivered

func (a *ARQEngine) Delivered() <-chan *Packet

Delivered returns the channel for in-order delivered packets

func (*ARQEngine) GetFECConfig added in v0.3.4

func (a *ARQEngine) GetFECConfig() *FECConfig

GetFECConfig returns current FEC configuration

func (*ARQEngine) GetLossRate added in v0.3.4

func (a *ARQEngine) GetLossRate() float64

GetLossRate returns current packet loss rate OPTIMIZED: split locks for better concurrency

func (*ARQEngine) HandlePacket

func (a *ARQEngine) HandlePacket(pkt *Packet)

HandlePacket processes a received packet OPTIMIZED: split locks for better concurrency

func (*ARQEngine) Send

func (a *ARQEngine) Send(payload []byte) error

Send queues a DATA packet for reliable delivery with pacing OPTIMIZED: split locks for better concurrency

func (*ARQEngine) SendControl

func (a *ARQEngine) SendControl(pkt *Packet) error

SendControl sends a control packet without ARQ tracking or pacing

func (*ARQEngine) SetFECConfig added in v0.3.4

func (a *ARQEngine) SetFECConfig(config *FECConfig)

SetFECConfig updates FEC configuration OPTIMIZED: split locks for better concurrency

func (*ARQEngine) Stats

func (a *ARQEngine) Stats() (sent, recv, retransmissions uint64, window int, rto time.Duration)

Stats returns current engine statistics OPTIMIZED: split locks for better concurrency

type CodecConfig added in v0.3.4

type CodecConfig struct {
	Secret          string
	EnableDCIDRot   bool               // Enable DCID rotation for security
	DCIDRotInterval int                // DCID rotation interval in seconds
	Compression     *CompressionConfig // Optional compression config
}

CodecConfig holds configuration for PacketCodec

type CompressionConfig added in v0.3.5

type CompressionConfig struct {
	Enable  bool
	Level   int
	MinSize int
}

CompressionConfig holds compression configuration

type FECConfig added in v0.3.4

type FECConfig struct {
	DataShards   int
	ParityShards int
	AutoAdjust   bool
	PacketLoss   float64 // текущий уровень потерь
}

FECConfig - адаптивная конфигурация FEC

func NewFECConfig added in v0.3.4

func NewFECConfig() *FECConfig

NewFECConfig создает конфигурацию FEC по умолчанию

func (*FECConfig) Adjust added in v0.3.4

func (c *FECConfig) Adjust(packetLoss float64)

Adjust адаптирует параметры FEC на основе потерь OPTIMIZED: reduced overhead for high-speed networks

type FecDecoder

type FecDecoder struct {
	// contains filtered or unexported fields
}

FecDecoder collects incoming DATA and FEC packets, and recovers missing DATA packets

func NewFecDecoder

func NewFecDecoder(onRecover func(uint32, []byte), config *FECConfig) (*FecDecoder, error)

NewFecDecoder creates a new FEC decoder

func (*FecDecoder) AddData

func (f *FecDecoder) AddData(seq uint32, payload []byte)

AddData records a received DATA packet

func (*FecDecoder) AddParity

func (f *FecDecoder) AddParity(startSeq uint32, parityIdx uint8, payload []byte)

AddParity records a received FEC packet

func (*FecDecoder) Reconfigure added in v0.3.4

func (f *FecDecoder) Reconfigure(config *FECConfig)

Reconfigure обновляет конфигурацию FEC

type FecEncoder

type FecEncoder struct {
	// contains filtered or unexported fields
}

FecEncoder collects outgoing DATA payloads and generates Parity packets

func NewFecEncoder

func NewFecEncoder(onParity func(uint32, uint8, []byte), config *FECConfig) (*FecEncoder, error)

NewFecEncoder creates a new FEC encoder with the given configuration

func (*FecEncoder) AddDataPacket

func (f *FecEncoder) AddDataPacket(seq uint32, payload []byte)

AddDataPacket adds a DATA packet to the current FEC group

func (*FecEncoder) Reconfigure added in v0.3.4

func (f *FecEncoder) Reconfigure(config *FECConfig)

Reconfigure обновляет конфигурацию FEC

type FecGroup added in v0.3.4

type FecGroup struct {
	// contains filtered or unexported fields
}

FecGroup represents a group of shards for Reed-Solomon decoding

type Listener

type Listener struct {
	// contains filtered or unexported fields
}

Listener is an MTP server-side listener that accepts MTP connections over UDP. It implements a net.Listener-compatible interface.

func Listen

func Listen(address string, secret string) (*Listener, error)

Listen creates a new MTP listener on the given address

func ListenWithConfig added in v0.3.5

func ListenWithConfig(address string, secret string, compression *CompressionConfig) (*Listener, error)

ListenWithConfig creates a new MTP listener with custom configuration

func (*Listener) Accept

func (l *Listener) Accept() (net.Conn, error)

Accept waits for and returns the next incoming connection. It implements net.Listener.Accept().

func (*Listener) Addr

func (l *Listener) Addr() net.Addr

Addr returns the listener's network address.

func (*Listener) Close

func (l *Listener) Close() error

Close stops the listener and closes the UDP socket.

func (*Listener) GetSession

func (l *Listener) GetSession(sessionID string) *MTPConn

GetSession returns the MTPConn for a given session ID (for VirtualConn swap)

func (*Listener) RemoveConnection

func (l *Listener) RemoveConnection(sessionID string)

RemoveConnection removes a connection from tracking (called on disconnect)

type MTPConn

type MTPConn struct {

	// Traffic stats
	BytesSent   atomic.Int64
	BytesRecv   atomic.Int64
	PacketsSent atomic.Int64
	PacketsRecv atomic.Int64
	// contains filtered or unexported fields
}

MTPConn implements net.Conn over a reliable UDP transport using the MTP protocol. It provides ordered, reliable delivery with polymorphic packet encoding.

func Dial

func Dial(resolver UDPResolver, address string, secret string) (*MTPConn, error)

Dial creates a client-side MTPConn to the given server address Uses protected dialer when running under Android VpnService.

func DialMigrate

func DialMigrate(resolver UDPResolver, address string, secret string, sessionID string) (*MTPConn, error)

DialMigrate creates a new MTPConn for session migration (seamless rotation) Uses protected dialer when running under Android VpnService.

func DialMigrateWithConfig added in v0.3.5

func DialMigrateWithConfig(resolver UDPResolver, address string, secret string, sessionID string, compression *CompressionConfig) (*MTPConn, error)

DialMigrateWithConfig creates a new MTPConn for session migration with custom configuration Uses protected dialer when running under Android VpnService.

func DialWithConfig added in v0.3.5

func DialWithConfig(resolver UDPResolver, address string, secret string, compression *CompressionConfig) (*MTPConn, error)

DialWithConfig creates a client-side MTPConn with custom configuration Uses protected dialer when running under Android VpnService.

func (*MTPConn) Close

func (c *MTPConn) Close() error

Close implements net.Conn

func (*MTPConn) DispatchPacket

func (c *MTPConn) DispatchPacket(data []byte)

DispatchPacket is called by the listener to route a raw datagram to this connection

func (*MTPConn) LocalAddr

func (c *MTPConn) LocalAddr() net.Addr

LocalAddr implements net.Conn

func (*MTPConn) Read

func (c *MTPConn) Read(b []byte) (int, error)

Read implements net.Conn. Blocks until data is available, deadline expires, or conn closes.

func (*MTPConn) RemoteAddr

func (c *MTPConn) RemoteAddr() net.Addr

RemoteAddr implements net.Conn

func (*MTPConn) SessionID

func (c *MTPConn) SessionID() string

SessionID returns the session identifier

func (*MTPConn) SetDeadline

func (c *MTPConn) SetDeadline(t time.Time) error

SetDeadline implements net.Conn

func (*MTPConn) SetReadDeadline

func (c *MTPConn) SetReadDeadline(t time.Time) error

SetReadDeadline implements net.Conn

func (*MTPConn) SetWriteDeadline

func (c *MTPConn) SetWriteDeadline(t time.Time) error

SetWriteDeadline implements net.Conn

func (*MTPConn) Write

func (c *MTPConn) Write(b []byte) (int, error)

Write implements net.Conn. It segments data and sends via ARQ.

type Pacer added in v0.3.4

type Pacer struct {
	// contains filtered or unexported fields
}

Pacer implements token bucket rate limiting for smooth packet transmission This prevents burst loss and improves throughput on congested networks

func NewPacer added in v0.3.4

func NewPacer(rate int, burst int) *Pacer

NewPacer creates a new pacer with the given rate limit rate: packets per second burst: maximum burst size (tokens)

func (*Pacer) GetTokens added in v0.3.4

func (p *Pacer) GetTokens() float64

GetTokens returns current token count (for debugging)

func (*Pacer) SetBurst added in v0.3.4

func (p *Pacer) SetBurst(burst int)

SetBurst updates the maximum burst size

func (*Pacer) SetRate added in v0.3.4

func (p *Pacer) SetRate(rate int)

SetRate updates the pacing rate dynamically

func (*Pacer) Wait added in v0.3.4

func (p *Pacer) Wait()

Wait blocks until a token is available

type Packet

type Packet struct {
	Type       uint8
	SeqNum     uint32
	AckNum     uint32
	Flags      uint8
	Payload    []byte
	SACKBlocks []uint32
}

Packet represents a decoded MTP packet

type PacketCodec

type PacketCodec struct {
	// contains filtered or unexported fields
}

PacketCodec handles polymorphic encoding and decoding of MTP packets with optional compression (compression is applied BEFORE encryption)

func NewPacketCodec

func NewPacketCodec(secret string) *PacketCodec

NewPacketCodec creates a new codec with the given shared secret

func NewPacketCodecWithConfig added in v0.3.4

func NewPacketCodecWithConfig(cfg CodecConfig) *PacketCodec

NewPacketCodecWithConfig creates a codec with custom configuration

func (*PacketCodec) Decode

func (c *PacketCodec) Decode(wire []byte) (*Packet, error)

Decode decrypts and deserializes wire bytes into a Packet

func (*PacketCodec) Encode

func (c *PacketCodec) Encode(pkt *Packet) ([]byte, error)

Encode serializes and encrypts a Packet into wire format: Pipeline: Payload -> Compress (optional) -> Encrypt -> Add QUIC header [ QUIC Short Header: 9 bytes ] [ padLen: 2 ] [ padding: N ] [ nonce: 24 ] [ ciphertext: M ]

func (*PacketCodec) GetDCID added in v0.3.4

func (c *PacketCodec) GetDCID() []byte

GetDCID returns current DCID (for debugging)

type UDPResolver

type UDPResolver interface {
	ResolveUDPAddr(network, address string) (*net.UDPAddr, error)
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL