refactor(kcptun): передавать Profile/FEC явно через config вместо process-wide env

This commit is contained in:
samosvalishe committed 2026-05-20 11:52:27 +03:00
1 parent 9459e94066
commit 483e45d68a
6 files changed
+98 -121

No files matched your search

+2
View File
@@ -117,6 +117,8 @@ func main() {
UDP: cfg.TURN.UDP, UDP: cfg.TURN.UDP,
WrapKey: cfg.Obf.WrapKey, WrapKey: cfg.Obf.WrapKey,
GetCreds: tcpfwd.GetCredsFunc(vkAuth.GetCredentials), 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 { 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) logger.Errorf("tcpfwd: %v", err)
+1 -1
View File
@@ -147,7 +147,7 @@ func handleAccepted(ctx context.Context, logger logx.Logger, registry *bondserve
logger.Debugf("Handshake done") logger.Debugf("Handshake done")
if cfg.Proxy.Mode == config.ProxyModeTCPFwd { 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 { } else {
udpserver.Handle(ctx, logger, conn, cfg.Proxy.Connect) udpserver.Handle(ctx, logger, conn, cfg.Proxy.Connect)
} }
+18
View File
@@ -15,6 +15,7 @@ import (
"io" "io"
"strings" "strings"
"github.com/cacggghp/vk-turn-proxy/internal/transport/kcptun"
"github.com/cacggghp/vk-turn-proxy/internal/wire/srtpmimicry" "github.com/cacggghp/vk-turn-proxy/internal/wire/srtpmimicry"
) )
@@ -77,6 +78,13 @@ type LogOpts struct {
Debug bool // -debug 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. // Client holds parsed and validated client CLI options.
type Client struct { type Client struct {
TURN TURNOpts TURN TURNOpts
@@ -85,6 +93,7 @@ type Client struct {
VK VKOpts VK VKOpts
DNS DNSOpts DNS DNSOpts
Log LogOpts Log LogOpts
KCP KCPOpts
} }
// Server holds parsed and validated server CLI options. // Server holds parsed and validated server CLI options.
@@ -92,6 +101,7 @@ type Server struct {
Obf ObfOpts Obf ObfOpts
Proxy ProxyOpts Proxy ProxyOpts
Log LogOpts Log LogOpts
KCP KCPOpts
} }
// ParseClient parses args (excluding program name) into a Client. // ParseClient parses args (excluding program name) into a Client.
@@ -150,6 +160,10 @@ func ParseClient(args []string, errOut io.Writer) (*Client, error) {
Log: LogOpts{ Log: LogOpts{
Debug: *debugFlag, Debug: *debugFlag,
}, },
KCP: KCPOpts{
Profile: kcptun.LoadProfileFromEnv(),
FEC: kcptun.LoadFECFromEnv(),
},
} }
switch c.DNS.Mode { switch c.DNS.Mode {
@@ -225,6 +239,10 @@ func ParseServer(args []string, errOut io.Writer) (*Server, error) {
Log: LogOpts{ Log: LogOpts{
Debug: *debugFlag, Debug: *debugFlag,
}, },
KCP: KCPOpts{
Profile: kcptun.LoadProfileFromEnv(),
FEC: kcptun.LoadFECFromEnv(),
},
} }
if s.Obf.GenWrapKey { if s.Obf.GenWrapKey {
+3 -1
View File
@@ -30,6 +30,8 @@ type Params struct {
UDP bool UDP bool
WrapKey []byte WrapKey []byte
GetCreds GetCredsFunc GetCreds GetCredsFunc
KCPProfile kcptun.Profile
KCPFEC kcptun.FEC
} }
// BondHandler stripes one accepted TCP connection across all currently-live // 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()) st := stats.New(deps.log().DebugEnabled())
go st.LogEvery(statsCtx, deps.log().Debugf, fmt.Sprintf("[session %d] VLESS", id), "to-turn", "from-turn") 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 { if err != nil {
cleanup() cleanup()
return nil, nil, fmt.Errorf("KCP session: %w", err) return nil, nil, fmt.Errorf("KCP session: %w", err)
+2 -2
View File
@@ -22,7 +22,7 @@ import (
// Handle wraps dtlsConn in KCP+smux and forwards each accepted stream as a TCP // 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 // connection to connectAddr. Streams whose first 4 bytes match the bond magic
// are handed off to registry. // 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) statsCtx, statsCancel := context.WithCancel(ctx)
defer statsCancel() defer statsCancel()
st := stats.New(logger.DebugEnabled()) st := stats.New(logger.DebugEnabled())
@@ -34,7 +34,7 @@ func Handle(ctx context.Context, logger logx.Logger, registry *bondserver.Regist
"from-client", "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 { if err != nil {
logger.Errorf("tcpfwdserver: KCP session: %s", err) logger.Errorf("tcpfwdserver: KCP session: %s", err)
return return
+72 -117
View File
@@ -5,99 +5,87 @@ import (
"os" "os"
"strconv" "strconv"
"strings" "strings"
"sync"
"time" "time"
"github.com/xtaci/kcp-go/v5" "github.com/xtaci/kcp-go/v5"
"github.com/xtaci/smux" "github.com/xtaci/smux"
) )
var ( // Profile holds the tunable KCP parameters. Both sides of a tunnel must agree.
kcpProfileOnce sync.Once type Profile struct {
cachedKCPProfile kcpProfile NoDelay int
Interval int
fecOnce sync.Once Resend int
cachedFECData int NC int
cachedFECParity int SndWnd int
) RcvWnd int
MTU int
type kcpProfile struct { ACKNoDelay bool
nodelay int
interval int
resend int
nc int
sndWnd int
rcvWnd int
mtu int
ackNoDelay bool
} }
func selectedKCPProfile() kcpProfile { // FEC controls KCP forward-error-correction shards. Zero values disable FEC.
kcpProfileOnce.Do(func() { type FEC struct {
cachedKCPProfile = loadKCPProfile() Data int
}) Parity int
return cachedKCPProfile
} }
func loadKCPProfile() kcpProfile { // DefaultProfile mirrors the historical balanced profile shipped with the proxy.
profile := strings.ToLower(strings.TrimSpace(os.Getenv("VK_TURN_KCP_PROFILE"))) func DefaultProfile() Profile {
var cfg kcpProfile return Profile{
switch profile { NoDelay: 1,
Interval: 20,
Resend: 2,
NC: 1,
SndWnd: 512,
RcvWnd: 512,
MTU: 1200,
ACKNoDelay: true,
}
}
// 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": case "legacy", "fast":
cfg = kcpProfile{ p = Profile{NoDelay: 1, Interval: 10, Resend: 2, NC: 1, SndWnd: 4096, RcvWnd: 4096, MTU: 1280, ACKNoDelay: true}
nodelay: 1,
interval: 10,
resend: 2,
nc: 1,
sndWnd: 4096,
rcvWnd: 4096,
mtu: 1280,
ackNoDelay: true,
}
case "cc", "balanced": case "cc", "balanced":
cfg = kcpProfile{ p = Profile{NoDelay: 1, Interval: 20, Resend: 2, NC: 0, SndWnd: 512, RcvWnd: 512, MTU: 1200, ACKNoDelay: true}
nodelay: 1,
interval: 20,
resend: 2,
nc: 0,
sndWnd: 512,
rcvWnd: 512,
mtu: 1200,
ackNoDelay: true,
}
case "slow", "conservative": case "slow", "conservative":
cfg = kcpProfile{ p = Profile{NoDelay: 0, Interval: 40, Resend: 2, NC: 0, SndWnd: 256, RcvWnd: 256, MTU: 1150, ACKNoDelay: false}
nodelay: 0,
interval: 40,
resend: 2,
nc: 0,
sndWnd: 256,
rcvWnd: 256,
mtu: 1150,
ackNoDelay: false,
}
default: default:
cfg = kcpProfile{ p = DefaultProfile()
nodelay: 1,
interval: 20,
resend: 2,
nc: 1,
sndWnd: 512,
rcvWnd: 512,
mtu: 1200,
ackNoDelay: true,
}
} }
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
}
cfg.nodelay = envInt("VK_TURN_KCP_NODELAY", cfg.nodelay) // LoadFECFromEnv parses VK_TURN_KCP_FEC as "data:parity" (e.g. "10:3").
cfg.interval = envInt("VK_TURN_KCP_INTERVAL", cfg.interval) // Empty/invalid → disabled.
cfg.resend = envInt("VK_TURN_KCP_RESEND", cfg.resend) func LoadFECFromEnv() FEC {
cfg.nc = envInt("VK_TURN_KCP_NC", cfg.nc) raw := strings.TrimSpace(os.Getenv("VK_TURN_KCP_FEC"))
cfg.sndWnd = envInt("VK_TURN_KCP_SNDWND", cfg.sndWnd) if raw == "" {
cfg.rcvWnd = envInt("VK_TURN_KCP_RCVWND", cfg.rcvWnd) return FEC{}
cfg.mtu = envInt("VK_TURN_KCP_MTU", cfg.mtu) }
cfg.ackNoDelay = envBool("VK_TURN_KCP_ACK_NODELAY", cfg.ackNoDelay) parts := strings.SplitN(raw, ":", 2)
return cfg 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 { func envInt(name string, fallback int) int {
@@ -112,32 +100,6 @@ func envInt(name string, fallback int) int {
return value 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 { func envBool(name string, fallback bool) bool {
raw := strings.ToLower(strings.TrimSpace(os.Getenv(name))) raw := strings.ToLower(strings.TrimSpace(os.Getenv(name)))
switch raw { switch raw {
@@ -191,7 +153,7 @@ func (d *DtlsPacketConn) SetWriteDeadline(t time.Time) error {
// NewKCPOverDTLS creates a KCP session over a DTLS connection. // NewKCPOverDTLS creates a KCP session over a DTLS connection.
// isServer: true for server-side (listener), false for client-side (dialer). // 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) pc := NewDtlsPacketConn(dtlsConn)
block, err := kcp.NewNoneBlockCrypt(nil) // DTLS already encrypts 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 var sess *kcp.UDPSession
dataShards, parityShards := selectedFEC()
if isServer { 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 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 { if err != nil {
return nil, err return nil, err
} }
@@ -222,18 +179,16 @@ func NewKCPOverDTLS(dtlsConn net.Conn, isServer bool) (*kcp.UDPSession, error) {
return nil, err return nil, err
} }
} else { } else {
// Client: dial through the PacketConn sess, err = kcp.NewConn2(dtlsConn.RemoteAddr(), block, fec.Data, fec.Parity, pc)
sess, err = kcp.NewConn2(dtlsConn.RemoteAddr(), block, dataShards, parityShards, pc)
if err != nil { if err != nil {
return nil, err return nil, err
} }
} }
profile := selectedKCPProfile() sess.SetNoDelay(profile.NoDelay, profile.Interval, profile.Resend, profile.NC)
sess.SetNoDelay(profile.nodelay, profile.interval, profile.resend, profile.nc) sess.SetWindowSize(profile.SndWnd, profile.RcvWnd)
sess.SetWindowSize(profile.sndWnd, profile.rcvWnd) sess.SetMtu(profile.MTU)
sess.SetMtu(profile.mtu) sess.SetACKNoDelay(profile.ACKNoDelay)
sess.SetACKNoDelay(profile.ackNoDelay)
return sess, nil return sess, nil
} }