From 483e45d68aeefeb1e6ff369831568d41138b8727 Mon Sep 17 00:00:00 2001 From: samosvalishe Date: Wed, 20 May 2026 11:52:27 +0300 Subject: [PATCH] =?UTF-8?q?refactor(kcptun):=20=D0=BF=D0=B5=D1=80=D0=B5?= =?UTF-8?q?=D0=B4=D0=B0=D0=B2=D0=B0=D1=82=D1=8C=20Profile/FEC=20=D1=8F?= =?UTF-8?q?=D0=B2=D0=BD=D0=BE=20=D1=87=D0=B5=D1=80=D0=B5=D0=B7=20config=20?= =?UTF-8?q?=D0=B2=D0=BC=D0=B5=D1=81=D1=82=D0=BE=20process-wide=20env?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cmd/vk-turn-client/main.go | 14 +- cmd/vk-turn-server/main.go | 2 +- internal/config/config.go | 18 ++ internal/proxy/tcpfwd/tcpfwd.go | 16 +- internal/proxy/tcpfwdserver/tcpfwdserver.go | 4 +- internal/transport/kcptun/kcptun.go | 197 ++++++++------------ 6 files changed, 114 insertions(+), 137 deletions(-) diff --git a/cmd/vk-turn-client/main.go b/cmd/vk-turn-client/main.go index 3c55eff..73a353c 100644 --- a/cmd/vk-turn-client/main.go +++ b/cmd/vk-turn-client/main.go @@ -111,12 +111,14 @@ func main() { BondHandler: bondH.Handle, } vlessParams := &tcpfwd.Params{ - Host: cfg.TURN.Host, - Port: cfg.TURN.Port, - Link: cfg.VK.Link, - UDP: cfg.TURN.UDP, - WrapKey: cfg.Obf.WrapKey, - GetCreds: tcpfwd.GetCredsFunc(vkAuth.GetCredentials), + Host: cfg.TURN.Host, + Port: cfg.TURN.Port, + Link: cfg.VK.Link, + UDP: cfg.TURN.UDP, + WrapKey: cfg.Obf.WrapKey, + GetCreds: tcpfwd.GetCredsFunc(vkAuth.GetCredentials), + KCPProfile: cfg.KCP.Profile, + KCPFEC: cfg.KCP.FEC, } if err := tcpfwd.Run(ctx, vlessDeps, vlessParams, peer, cfg.Proxy.Listen, cfg.TURN.N, cfg.Proxy.Mode == config.ProxyModeTCPFwdBond); err != nil { logger.Errorf("tcpfwd: %v", err) diff --git a/cmd/vk-turn-server/main.go b/cmd/vk-turn-server/main.go index 8bc6516..8a26f55 100644 --- a/cmd/vk-turn-server/main.go +++ b/cmd/vk-turn-server/main.go @@ -147,7 +147,7 @@ func handleAccepted(ctx context.Context, logger logx.Logger, registry *bondserve logger.Debugf("Handshake done") if cfg.Proxy.Mode == config.ProxyModeTCPFwd { - tcpfwdserver.Handle(ctx, logger, registry, dtlsConn, cfg.Proxy.Connect) + tcpfwdserver.Handle(ctx, logger, registry, dtlsConn, cfg.Proxy.Connect, cfg.KCP.Profile, cfg.KCP.FEC) } else { udpserver.Handle(ctx, logger, conn, cfg.Proxy.Connect) } diff --git a/internal/config/config.go b/internal/config/config.go index 83331ea..50792b4 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -15,6 +15,7 @@ import ( "io" "strings" + "github.com/cacggghp/vk-turn-proxy/internal/transport/kcptun" "github.com/cacggghp/vk-turn-proxy/internal/wire/srtpmimicry" ) @@ -77,6 +78,13 @@ type LogOpts struct { Debug bool // -debug } +// KCPOpts groups KCP tunnel options. Both sides of a tunnel must agree on +// Profile and FEC; values currently come from VK_TURN_KCP_* env vars. +type KCPOpts struct { + Profile kcptun.Profile + FEC kcptun.FEC +} + // Client holds parsed and validated client CLI options. type Client struct { TURN TURNOpts @@ -85,6 +93,7 @@ type Client struct { VK VKOpts DNS DNSOpts Log LogOpts + KCP KCPOpts } // Server holds parsed and validated server CLI options. @@ -92,6 +101,7 @@ type Server struct { Obf ObfOpts Proxy ProxyOpts Log LogOpts + KCP KCPOpts } // ParseClient parses args (excluding program name) into a Client. @@ -150,6 +160,10 @@ func ParseClient(args []string, errOut io.Writer) (*Client, error) { Log: LogOpts{ Debug: *debugFlag, }, + KCP: KCPOpts{ + Profile: kcptun.LoadProfileFromEnv(), + FEC: kcptun.LoadFECFromEnv(), + }, } switch c.DNS.Mode { @@ -225,6 +239,10 @@ func ParseServer(args []string, errOut io.Writer) (*Server, error) { Log: LogOpts{ Debug: *debugFlag, }, + KCP: KCPOpts{ + Profile: kcptun.LoadProfileFromEnv(), + FEC: kcptun.LoadFECFromEnv(), + }, } if s.Obf.GenWrapKey { diff --git a/internal/proxy/tcpfwd/tcpfwd.go b/internal/proxy/tcpfwd/tcpfwd.go index 400234b..e701ae7 100644 --- a/internal/proxy/tcpfwd/tcpfwd.go +++ b/internal/proxy/tcpfwd/tcpfwd.go @@ -24,12 +24,14 @@ type GetCredsFunc = common.GetCredsFunc // Params is the per-pool TURN/wrap configuration. type Params struct { - Host string - Port string - Link string - UDP bool - WrapKey []byte - GetCreds GetCredsFunc + Host string + Port string + Link string + UDP bool + WrapKey []byte + GetCreds GetCredsFunc + KCPProfile kcptun.Profile + KCPFEC kcptun.FEC } // BondHandler stripes one accepted TCP connection across all currently-live @@ -254,7 +256,7 @@ func createSmuxSession(ctx context.Context, deps *Deps, params *Params, peer *ne st := stats.New(deps.log().DebugEnabled()) go st.LogEvery(statsCtx, deps.log().Debugf, fmt.Sprintf("[session %d] VLESS", id), "to-turn", "from-turn") - kcpSess, err := kcptun.NewKCPOverDTLS(&stats.CountingConn{Conn: dtlsConn, Stats: st}, false) + kcpSess, err := kcptun.NewKCPOverDTLS(&stats.CountingConn{Conn: dtlsConn, Stats: st}, false, params.KCPProfile, params.KCPFEC) if err != nil { cleanup() return nil, nil, fmt.Errorf("KCP session: %w", err) diff --git a/internal/proxy/tcpfwdserver/tcpfwdserver.go b/internal/proxy/tcpfwdserver/tcpfwdserver.go index 6e3591e..0eed048 100644 --- a/internal/proxy/tcpfwdserver/tcpfwdserver.go +++ b/internal/proxy/tcpfwdserver/tcpfwdserver.go @@ -22,7 +22,7 @@ import ( // Handle wraps dtlsConn in KCP+smux and forwards each accepted stream as a TCP // connection to connectAddr. Streams whose first 4 bytes match the bond magic // are handed off to registry. -func Handle(ctx context.Context, logger logx.Logger, registry *bondserver.Registry, dtlsConn net.Conn, connectAddr string) { +func Handle(ctx context.Context, logger logx.Logger, registry *bondserver.Registry, dtlsConn net.Conn, connectAddr string, kcpProfile kcptun.Profile, kcpFEC kcptun.FEC) { statsCtx, statsCancel := context.WithCancel(ctx) defer statsCancel() st := stats.New(logger.DebugEnabled()) @@ -34,7 +34,7 @@ func Handle(ctx context.Context, logger logx.Logger, registry *bondserver.Regist "from-client", ) - kcpSess, err := kcptun.NewKCPOverDTLS(&stats.CountingConn{Conn: dtlsConn, Stats: st}, true) + kcpSess, err := kcptun.NewKCPOverDTLS(&stats.CountingConn{Conn: dtlsConn, Stats: st}, true, kcpProfile, kcpFEC) if err != nil { logger.Errorf("tcpfwdserver: KCP session: %s", err) return diff --git a/internal/transport/kcptun/kcptun.go b/internal/transport/kcptun/kcptun.go index 20cf232..9b96ef0 100644 --- a/internal/transport/kcptun/kcptun.go +++ b/internal/transport/kcptun/kcptun.go @@ -5,99 +5,87 @@ import ( "os" "strconv" "strings" - "sync" "time" "github.com/xtaci/kcp-go/v5" "github.com/xtaci/smux" ) -var ( - kcpProfileOnce sync.Once - cachedKCPProfile kcpProfile - - fecOnce sync.Once - cachedFECData int - cachedFECParity int -) - -type kcpProfile struct { - nodelay int - interval int - resend int - nc int - sndWnd int - rcvWnd int - mtu int - ackNoDelay bool +// Profile holds the tunable KCP parameters. Both sides of a tunnel must agree. +type Profile struct { + NoDelay int + Interval int + Resend int + NC int + SndWnd int + RcvWnd int + MTU int + ACKNoDelay bool } -func selectedKCPProfile() kcpProfile { - kcpProfileOnce.Do(func() { - cachedKCPProfile = loadKCPProfile() - }) - return cachedKCPProfile +// FEC controls KCP forward-error-correction shards. Zero values disable FEC. +type FEC struct { + Data int + Parity int } -func loadKCPProfile() kcpProfile { - profile := strings.ToLower(strings.TrimSpace(os.Getenv("VK_TURN_KCP_PROFILE"))) - var cfg kcpProfile - switch profile { - case "legacy", "fast": - cfg = kcpProfile{ - nodelay: 1, - interval: 10, - resend: 2, - nc: 1, - sndWnd: 4096, - rcvWnd: 4096, - mtu: 1280, - ackNoDelay: true, - } - case "cc", "balanced": - cfg = kcpProfile{ - nodelay: 1, - interval: 20, - resend: 2, - nc: 0, - sndWnd: 512, - rcvWnd: 512, - mtu: 1200, - ackNoDelay: true, - } - case "slow", "conservative": - cfg = kcpProfile{ - nodelay: 0, - interval: 40, - resend: 2, - nc: 0, - sndWnd: 256, - rcvWnd: 256, - mtu: 1150, - ackNoDelay: false, - } - default: - cfg = kcpProfile{ - nodelay: 1, - interval: 20, - resend: 2, - nc: 1, - sndWnd: 512, - rcvWnd: 512, - mtu: 1200, - ackNoDelay: true, - } +// DefaultProfile mirrors the historical balanced profile shipped with the proxy. +func DefaultProfile() Profile { + return Profile{ + NoDelay: 1, + Interval: 20, + Resend: 2, + NC: 1, + SndWnd: 512, + RcvWnd: 512, + MTU: 1200, + ACKNoDelay: true, } +} - cfg.nodelay = envInt("VK_TURN_KCP_NODELAY", cfg.nodelay) - cfg.interval = envInt("VK_TURN_KCP_INTERVAL", cfg.interval) - cfg.resend = envInt("VK_TURN_KCP_RESEND", cfg.resend) - cfg.nc = envInt("VK_TURN_KCP_NC", cfg.nc) - cfg.sndWnd = envInt("VK_TURN_KCP_SNDWND", cfg.sndWnd) - cfg.rcvWnd = envInt("VK_TURN_KCP_RCVWND", cfg.rcvWnd) - cfg.mtu = envInt("VK_TURN_KCP_MTU", cfg.mtu) - cfg.ackNoDelay = envBool("VK_TURN_KCP_ACK_NODELAY", cfg.ackNoDelay) - return cfg +// LoadProfileFromEnv reads VK_TURN_KCP_PROFILE and per-field VK_TURN_KCP_* +// overrides. Unknown profile name → DefaultProfile. +func LoadProfileFromEnv() Profile { + name := strings.ToLower(strings.TrimSpace(os.Getenv("VK_TURN_KCP_PROFILE"))) + var p Profile + switch name { + case "legacy", "fast": + p = Profile{NoDelay: 1, Interval: 10, Resend: 2, NC: 1, SndWnd: 4096, RcvWnd: 4096, MTU: 1280, ACKNoDelay: true} + case "cc", "balanced": + p = Profile{NoDelay: 1, Interval: 20, Resend: 2, NC: 0, SndWnd: 512, RcvWnd: 512, MTU: 1200, ACKNoDelay: true} + case "slow", "conservative": + p = Profile{NoDelay: 0, Interval: 40, Resend: 2, NC: 0, SndWnd: 256, RcvWnd: 256, MTU: 1150, ACKNoDelay: false} + default: + p = DefaultProfile() + } + p.NoDelay = envInt("VK_TURN_KCP_NODELAY", p.NoDelay) + p.Interval = envInt("VK_TURN_KCP_INTERVAL", p.Interval) + p.Resend = envInt("VK_TURN_KCP_RESEND", p.Resend) + p.NC = envInt("VK_TURN_KCP_NC", p.NC) + p.SndWnd = envInt("VK_TURN_KCP_SNDWND", p.SndWnd) + p.RcvWnd = envInt("VK_TURN_KCP_RCVWND", p.RcvWnd) + p.MTU = envInt("VK_TURN_KCP_MTU", p.MTU) + p.ACKNoDelay = envBool("VK_TURN_KCP_ACK_NODELAY", p.ACKNoDelay) + return p +} + +// LoadFECFromEnv parses VK_TURN_KCP_FEC as "data:parity" (e.g. "10:3"). +// Empty/invalid → disabled. +func LoadFECFromEnv() FEC { + raw := strings.TrimSpace(os.Getenv("VK_TURN_KCP_FEC")) + if raw == "" { + return FEC{} + } + parts := strings.SplitN(raw, ":", 2) + if len(parts) != 2 { + return FEC{} + } + d, err1 := strconv.Atoi(strings.TrimSpace(parts[0])) + p, err2 := strconv.Atoi(strings.TrimSpace(parts[1])) + if err1 != nil || err2 != nil || d <= 0 || p <= 0 { + return FEC{} + } + return FEC{Data: d, Parity: p} } func envInt(name string, fallback int) int { @@ -112,32 +100,6 @@ func envInt(name string, fallback int) int { return value } -// selectedFEC parses VK_TURN_KCP_FEC as "data:parity" (e.g. "10:3"). -// Returns 0,0 if unset/invalid (FEC disabled). Both sides must match. -func selectedFEC() (dataShards, parityShards int) { - fecOnce.Do(func() { - cachedFECData, cachedFECParity = loadFEC() - }) - return cachedFECData, cachedFECParity -} - -func loadFEC() (dataShards, parityShards int) { - raw := strings.TrimSpace(os.Getenv("VK_TURN_KCP_FEC")) - if raw == "" { - return 0, 0 - } - parts := strings.SplitN(raw, ":", 2) - if len(parts) != 2 { - return 0, 0 - } - d, err1 := strconv.Atoi(strings.TrimSpace(parts[0])) - p, err2 := strconv.Atoi(strings.TrimSpace(parts[1])) - if err1 != nil || err2 != nil || d <= 0 || p <= 0 { - return 0, 0 - } - return d, p -} - func envBool(name string, fallback bool) bool { raw := strings.ToLower(strings.TrimSpace(os.Getenv(name))) switch raw { @@ -191,7 +153,7 @@ func (d *DtlsPacketConn) SetWriteDeadline(t time.Time) error { // NewKCPOverDTLS creates a KCP session over a DTLS connection. // isServer: true for server-side (listener), false for client-side (dialer). -func NewKCPOverDTLS(dtlsConn net.Conn, isServer bool) (*kcp.UDPSession, error) { +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 @@ -201,14 +163,9 @@ func NewKCPOverDTLS(dtlsConn net.Conn, isServer bool) (*kcp.UDPSession, error) { var sess *kcp.UDPSession - dataShards, parityShards := selectedFEC() - if isServer { - // Server: listen on the PacketConn, accept one session, then drop the - // listener (it owns the PacketConn — the accepted session keeps using - // it via the shared kcp mux). var listener *kcp.Listener - listener, err = kcp.ServeConn(block, dataShards, parityShards, pc) + listener, err = kcp.ServeConn(block, fec.Data, fec.Parity, pc) if err != nil { return nil, err } @@ -222,18 +179,16 @@ func NewKCPOverDTLS(dtlsConn net.Conn, isServer bool) (*kcp.UDPSession, error) { return nil, err } } else { - // Client: dial through the PacketConn - sess, err = kcp.NewConn2(dtlsConn.RemoteAddr(), block, dataShards, parityShards, pc) + sess, err = kcp.NewConn2(dtlsConn.RemoteAddr(), block, fec.Data, fec.Parity, pc) if err != nil { return nil, err } } - profile := selectedKCPProfile() - sess.SetNoDelay(profile.nodelay, profile.interval, profile.resend, profile.nc) - sess.SetWindowSize(profile.sndWnd, profile.rcvWnd) - sess.SetMtu(profile.mtu) - sess.SetACKNoDelay(profile.ackNoDelay) + sess.SetNoDelay(profile.NoDelay, profile.Interval, profile.Resend, profile.NC) + sess.SetWindowSize(profile.SndWnd, profile.RcvWnd) + sess.SetMtu(profile.MTU) + sess.SetACKNoDelay(profile.ACKNoDelay) return sess, nil }