perf: убрать аллокации на горячем пути, TCP DPI-split и KCP FEC

- Атомарный счётчик nonce вместо per-packet rand.Read (syscall getrandom);
  wire-формат не изменён, сервер декодирует без правок
- wrapInto: TX-путь без аллокаций с заранее выделенным буфером;
  wrapPacket оставлен для тестов и control-путей
- Кеш указателя при приёме WG исключает аллокацию addr.String() на пакет
  (быстрый путь — сравнение указателей, медленный — строк)
- Атомики статистики throughput спрятаны за isDebug — снижает трафик
  cache-line по N стримам в production-сборках
- splitFirstWriteConn разбивает первую TCP-запись на байте 6 + задержка
  20ms, ломая STUN magic cookie между сегментами против поверхностного DPI
- VK_TURN_KCP_FEC=data:parity включает Reed-Solomon FEC поверх KCP;
  обе стороны должны совпадать; по умолчанию 0:0 (выключено)
- Исправлен WaitGroup: wg.Add(1) → wg.Add(2) для двух горутин в
  oneDtlsConnection; раньше wg.Wait() возвращался слишком рано
This commit is contained in:
samosvalishe authored and antongospod committed 2026-05-11 23:46:27 +03:00
1 parent 334a17f1af
commit 7a0f98f730
7 files changed
+168 -36

No files matched your search

+62 -17
View File
@@ -175,15 +175,20 @@ type throughputStats struct {
}
func (s *throughputStats) addTx(n int) {
if n > 0 {
s.tx.Add(uint64(n))
// Counters are only consumed by logEvery, which is itself debug-gated.
// Skip the atomic add (and the cache-line traffic across N streams)
// when nobody is going to read the result.
if !isDebug || n <= 0 {
return
}
s.tx.Add(uint64(n))
}
func (s *throughputStats) addRx(n int) {
if n > 0 {
s.rx.Add(uint64(n))
if !isDebug || n <= 0 {
return
}
s.rx.Add(uint64(n))
}
func (s *throughputStats) logEvery(ctx context.Context, label, txName, rxName string) {
@@ -1730,7 +1735,7 @@ func oneDtlsConnection(ctx context.Context, peer *net.UDPAddr, listenConn net.Pa
}
wg := sync.WaitGroup{}
wg.Add(1)
wg.Add(2)
context.AfterFunc(dtlsctx, func() {
if err := dtlsConn.SetDeadline(time.Now()); err != nil {
log.Printf("[STREAM %d] Warning: SetDeadline failed: %v", streamID, err)
@@ -1738,6 +1743,7 @@ func oneDtlsConnection(ctx context.Context, peer *net.UDPAddr, listenConn net.Pa
})
go func() {
defer wg.Done()
defer dtlscancel()
for {
select {
@@ -1786,6 +1792,32 @@ func (c *connectedUDPConn) WriteTo(p []byte, _ net.Addr) (int, error) {
return c.Write(p)
}
// splitFirstWriteConn wraps a TCP net.Conn and splits the first Write into two
// segments (default 6 bytes + remainder) with a small delay, so the STUN magic
// cookie at offset 4-7 is broken across two TCP segments. Defeats DPI rules
// that match on the first segment without reassembly.
type splitFirstWriteConn struct {
net.Conn
splitAt int
delay time.Duration
done atomic.Bool
}
func (s *splitFirstWriteConn) Write(b []byte) (int, error) {
if s.done.CompareAndSwap(false, true) && len(b) > s.splitAt {
n1, err := s.Conn.Write(b[:s.splitAt])
if err != nil {
return n1, err
}
if s.delay > 0 {
time.Sleep(s.delay)
}
n2, err := s.Conn.Write(b[s.splitAt:])
return n1 + n2, err
}
return s.Conn.Write(b)
}
type turnParams struct {
host string
port string
@@ -1854,7 +1886,8 @@ func oneTurnConnection(ctx context.Context, turnParams *turnParams, peer *net.UD
return
}
}()
turnConn = turn.NewSTUNConn(conn)
wrappedConn := &splitFirstWriteConn{Conn: conn, splitAt: 6, delay: 20 * time.Millisecond}
turnConn = turn.NewSTUNConn(wrappedConn)
}
var addrFamily turn.RequestedAddressFamily
if peer.IP.To4() != nil {
@@ -1930,6 +1963,12 @@ func oneTurnConnection(ctx context.Context, turnParams *turnParams, peer *net.UD
go func() {
defer turncancel()
buf := make([]byte, 1600)
// Reusable scratch buffer for wrapped wire bytes; sized once per
// stream so the hot-path TX loop performs zero allocations.
var wireBuf []byte
if useWrap {
wireBuf = make([]byte, wrapNonceLen+len(buf))
}
for {
if turnctx.Err() != nil {
return
@@ -1946,12 +1985,12 @@ func oneTurnConnection(ctx context.Context, turnParams *turnParams, peer *net.UD
out := buf[:n]
if useWrap {
wrapped, wrapErr := wrapPacket(turnParams.wrapKey, out)
written, wrapErr := wrapInto(wireBuf, turnParams.wrapKey, out)
if wrapErr != nil {
log.Printf("[STREAM %d] WRAP failed: %v", streamID, wrapErr)
return
}
out = wrapped
out = wireBuf[:written]
}
written, err1 := relayConn.WriteTo(out, peer)
@@ -2248,6 +2287,14 @@ func main() {
inboundChan := make(chan *UDPPacket, 2000)
go func() {
// Pointer-cache for the last seen local peer addr. Avoids the
// per-packet addr.String() allocation pair on the hot WG ingest path:
// most packets come from the same UDPAddr instance, so a pointer
// equality check covers the fast path. The slow path (new instance
// from ReadFrom for the same ip:port) does one String compare and
// then refreshes the cache.
var lastAddr net.Addr
var lastAddrStr string
for {
pktIface := packetPool.Get()
pkt, ok := pktIface.(*UDPPacket)
@@ -2260,16 +2307,13 @@ func main() {
return
}
// Save the local WireGuard peer address
current := activeLocalPeer.Load()
if current == nil {
activeLocalPeer.Store(addr)
} else if addrStr, ok := current.(net.Addr); ok {
if addrStr.String() != addr.String() {
if addr != lastAddr {
s := addr.String()
if s != lastAddrStr {
activeLocalPeer.Store(addr)
lastAddrStr = s
}
} else {
activeLocalPeer.Store(addr)
lastAddr = addr
}
pkt.N = nRead
@@ -2919,7 +2963,8 @@ func createSmuxSession(ctx context.Context, tp *turnParams, peer *net.UDPAddr, i
return nil, nil, fmt.Errorf("dial TURN (tcp): %w", err1)
}
cleanupFns = append(cleanupFns, func() { _ = c.Close() })
turnConn = turn.NewSTUNConn(c)
wrappedC := &splitFirstWriteConn{Conn: c, splitAt: 6, delay: 20 * time.Millisecond}
turnConn = turn.NewSTUNConn(wrappedC)
}
// 3. Create TURN client and allocate relay
+52 -9
View File
@@ -4,9 +4,11 @@ package main
import (
"crypto/rand"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"sync/atomic"
"golang.org/x/crypto/chacha20"
)
@@ -16,6 +18,31 @@ const (
wrapKeyLen = 32
)
// Nonce layout: [4B session prefix | 8B atomic counter, big-endian].
// Session prefix is randomised once at process start; counter monotonically
// increments per-packet. This eliminates the per-packet crypto/rand syscall
// (which on Linux is a getrandom() round-trip ~hundreds of ns) while keeping
// (key, nonce) pairs unique across 2^64 packets per session and 2^32 sessions
// per key. Wire format is byte-identical to the previous random-nonce scheme,
// so server-side decryption is unchanged.
var (
nonceSessionPrefix [4]byte
nonceCounter atomic.Uint64
)
func init() {
// Best-effort: if rand.Read fails this early, the OS is in trouble and the
// binary is going to crash anyway during DTLS cert generation. Leaving the
// prefix zero would still keep nonces unique within this process.
_, _ = rand.Read(nonceSessionPrefix[:])
}
func fillWrapNonce(dst []byte) {
_ = dst[wrapNonceLen-1] // bounds-check hint
copy(dst[:4], nonceSessionPrefix[:])
binary.BigEndian.PutUint64(dst[4:wrapNonceLen], nonceCounter.Add(1))
}
func genWrapKeyHex() (string, error) {
key := make([]byte, wrapKeyLen)
if _, err := rand.Read(key); err != nil {
@@ -41,20 +68,36 @@ func decodeWrapKey(enabled bool, raw string) ([]byte, error) {
return key, nil
}
func wrapPacket(key, payload []byte) ([]byte, error) {
// wrapInto encrypts payload into dst using the shared scheme
// [12B nonce | ChaCha20-XOR(payload)]. dst must have capacity for
// wrapNonceLen+len(payload). Returns total bytes written. Hot-path callers
// should reuse a single dst buffer to avoid per-packet allocation.
func wrapInto(dst, key, payload []byte) (int, error) {
if len(key) != wrapKeyLen {
return nil, fmt.Errorf("wrap: key must be %d bytes (got %d)", wrapKeyLen, len(key))
return 0, fmt.Errorf("wrap: key must be %d bytes (got %d)", wrapKeyLen, len(key))
}
out := make([]byte, wrapNonceLen+len(payload))
if _, err := rand.Read(out[:wrapNonceLen]); err != nil {
return nil, fmt.Errorf("wrap: nonce gen: %w", err)
total := wrapNonceLen + len(payload)
if len(dst) < total {
return 0, errors.New("wrap: dst buffer too small")
}
cipher, err := chacha20.NewUnauthenticatedCipher(key, out[:wrapNonceLen])
fillWrapNonce(dst[:wrapNonceLen])
cipher, err := chacha20.NewUnauthenticatedCipher(key, dst[:wrapNonceLen])
if err != nil {
return nil, fmt.Errorf("wrap: cipher init: %w", err)
return 0, fmt.Errorf("wrap: cipher init: %w", err)
}
cipher.XORKeyStream(out[wrapNonceLen:], payload)
return out, nil
cipher.XORKeyStream(dst[wrapNonceLen:total], payload)
return total, nil
}
// wrapPacket allocates a fresh wire buffer. Retained for tests and control
// paths; hot-path code should call wrapInto with a reusable scratch buffer.
func wrapPacket(key, payload []byte) ([]byte, error) {
out := make([]byte, wrapNonceLen+len(payload))
n, err := wrapInto(out, key, payload)
if err != nil {
return nil, err
}
return out[:n], nil
}
func unwrapPacket(key, wire, dst []byte) (int, error) {