refactor(layout): переименовать пакеты (split wire/transport/proxy)

internal/wrap → internal/wire/srtpmimicry; правки doc ("обфускация, не security").
internal/bond/{frame,client,server} → internal/wire/bondframe,
internal/proxy/bondclient, internal/proxy/bondserver.
internal/netadapt → internal/netconn.
internal/turnpipe → internal/transport/turndial; internal/dtlsdial →
internal/transport/dtlsdial.
tcputil → internal/transport/kcptun; selectedKCPProfile и selectedFEC теперь
кешируются через sync.Once (env читается один раз вместо per-connection).
internal/proxy/udp → internal/proxy/udprelay; internal/proxy/vless →
internal/proxy/tcpfwd. Флаг CLI -vless сохранён.
internal/ish → internal/client/ish; doc пакета расширен (iSH = Linux user-mode
эмулятор на iOS, только linux/386).

Чисто механическое переименование + обновление import-путей/идентификаторов.
Wire-формат, флаги CLI и поведение не изменены. go build + go test зелёные.
This commit is contained in:
samosvalishe committed 2026-05-19 20:42:46 +03:00
1 parent 7fd2d9594d
commit 1fb869b3e1
27 files changed
+178 -147

No files matched your search

+1 -1
View File
@@ -26,7 +26,7 @@ import (
"time"
"github.com/cacggghp/vk-turn-proxy/internal/client/browserprofile"
"github.com/cacggghp/vk-turn-proxy/internal/ish"
"github.com/cacggghp/vk-turn-proxy/internal/client/ish"
)
// Debug toggles verbose request/response logging for the proxied browser
File renamed without changes.
+15
View File
@@ -0,0 +1,15 @@
//go:build !(linux && 386)
// Package ish provides a TCP listener shim for iSH (https://ish.app), a
// Linux user-mode emulator that runs on iOS. iSH targets linux/386 and lacks
// modern accept4 / Go's epoll-based poller, so a sandbox-aware accept loop
// is needed there. On every other GOOS/GOARCH WrapListener is a no-op
// pass-through.
package ish
import "net"
// WrapListener returns ln unchanged on non-iSH platforms.
func WrapListener(ln net.Listener) (net.Listener, error) {
return ln, nil
}
+3 -3
View File
@@ -12,7 +12,7 @@ import (
"io"
"strings"
"github.com/cacggghp/vk-turn-proxy/internal/wrap"
"github.com/cacggghp/vk-turn-proxy/internal/wire/srtpmimicry"
)
// Mirrors of constants defined in internal/client/* packages, duplicated here
@@ -125,7 +125,7 @@ func ParseClient(args []string, errOut io.Writer) (*Client, error) {
if *vklink == "" {
return nil, errors.New("need vk-link")
}
key, err := wrap.DecodeKey(c.WrapMode, *wrapKeyHex)
key, err := srtpmimicry.DecodeKey(c.WrapMode, *wrapKeyHex)
if err != nil {
return nil, err
}
@@ -182,7 +182,7 @@ func ParseServer(args []string, errOut io.Writer) (*Server, error) {
if s.Connect == "" {
return nil, fmt.Errorf("server address is required")
}
key, err := wrap.DecodeKey(s.WrapMode, *wrapKeyHex)
key, err := srtpmimicry.DecodeKey(s.WrapMode, *wrapKeyHex)
if err != nil {
return nil, err
}
-13
View File
@@ -1,13 +0,0 @@
//go:build !(linux && 386)
// Package ish provides a TCP listener shim for the iSH iOS simulator on
// linux/386, which lacks modern accept4 and Go's epoll-based poller. On every
// other GOOS/GOARCH WrapListener is a no-op pass-through.
package ish
import "net"
// WrapListener returns ln unchanged on non-iSH platforms.
func WrapListener(ln net.Listener) (net.Listener, error) {
return ln, nil
}
@@ -1,8 +1,8 @@
// Package netadapt holds small net.Conn / transport.Net adapters used by both
// Package netconn holds small net.Conn / transport.Net adapters used by both
// client and server: a passthrough transport.Net (for pion turn),
// ConnectedUDPConn (Write-only WriteTo on a dialed UDPConn), and
// SplitFirstWriteConn (DPI evasion via first-segment split).
package netadapt
package netconn
import (
"context"
@@ -1,4 +1,4 @@
package netadapt
package netconn
import (
"bytes"
@@ -1,6 +1,6 @@
// Package bondclient implements the client side of the bonded VLESS lane:
// a single accepted TCP connection striped (round-robin) across all currently
// live smux sessions in a vless.SessionPool. Frame wire-format lives in
// live smux sessions in a tcpfwd.SessionPool. Frame wire-format lives in
// internal/bond; this package wires the local TCP <-> lanes copy loops.
package bondclient
@@ -16,10 +16,10 @@ import (
"sync/atomic"
"time"
"github.com/cacggghp/vk-turn-proxy/internal/bond"
"github.com/cacggghp/vk-turn-proxy/internal/logx"
"github.com/cacggghp/vk-turn-proxy/internal/proxy/vless"
"github.com/cacggghp/vk-turn-proxy/internal/proxy/tcpfwd"
"github.com/cacggghp/vk-turn-proxy/internal/stats"
"github.com/cacggghp/vk-turn-proxy/internal/wire/bondframe"
"github.com/xtaci/smux"
)
@@ -35,22 +35,22 @@ func (d *Deps) log() logx.Logger {
return d.Log
}
// Handler binds Deps and exposes Handle, matching the vless.BondHandler signature.
// Handler binds Deps and exposes Handle, matching the tcpfwd.BondHandler signature.
type Handler struct {
Deps Deps
}
// lane is one striped smux stream within a bonded TCP connection.
type lane struct {
ps *vless.PooledSession
ps *tcpfwd.PooledSession
stream *smux.Stream
mu sync.Mutex
dead atomic.Bool
}
// Handle stripes the local TCP connection across all live candidate sessions.
// Signature matches vless.BondHandler.
func (h *Handler) Handle(ctx context.Context, tcpConn net.Conn, connID uint64, candidates []*vless.PooledSession) {
// Signature matches tcpfwd.BondHandler.
func (h *Handler) Handle(ctx context.Context, tcpConn net.Conn, connID uint64, candidates []*tcpfwd.PooledSession) {
defer func() { _ = tcpConn.Close() }()
ctx, cancel := context.WithCancel(ctx)
@@ -67,7 +67,7 @@ func (h *Handler) Handle(ctx context.Context, tcpConn net.Conn, connID uint64, c
log.Printf("[bond %d] session %d open stream error: %s", connID, ps.ID, err)
continue
}
if err := bond.WriteHello(stream, connID, uint16(i), uint16(len(candidates))); err != nil {
if err := bondframe.WriteHello(stream, connID, uint16(i), uint16(len(candidates))); err != nil {
log.Printf("[bond %d] session %d hello error: %s", connID, ps.ID, err)
_ = stream.Close()
continue
@@ -106,12 +106,12 @@ func (h *Handler) Handle(ctx context.Context, tcpConn net.Conn, connID uint64, c
}
}()
recvCh := make(chan bond.Frame, 1024)
recvCh := make(chan bondframe.Frame, 1024)
var readWG sync.WaitGroup
for _, l := range lanes {
readWG.Go(func() {
for {
f, err := bond.ReadFrame(l.stream)
f, err := bondframe.ReadFrame(l.stream)
if err != nil {
l.dead.Store(true)
select {
@@ -123,7 +123,7 @@ func (h *Handler) Handle(ctx context.Context, tcpConn net.Conn, connID uint64, c
}
return
}
if f.Type == bond.FrameData {
if f.Type == bondframe.FrameData {
l.ps.FromSession.Add(uint64(len(f.Data)))
}
select {
@@ -151,13 +151,13 @@ func (h *Handler) Handle(ctx context.Context, tcpConn net.Conn, connID uint64, c
}
func (h *Handler) copyTCPToBond(ctx context.Context, connID uint64, tcpConn net.Conn, lanes []*lane) {
buf := make([]byte, bond.MaxChunk)
buf := make([]byte, bondframe.MaxChunk)
var seq uint64
var laneIdx uint64
for {
n, err := tcpConn.Read(buf)
if n > 0 {
l, writeErr := writeBondFrameToNextLane(ctx, lanes, bond.FrameData, seq, buf[:n], &laneIdx)
l, writeErr := writeBondFrameToNextLane(ctx, lanes, bondframe.FrameData, seq, buf[:n], &laneIdx)
if writeErr != nil {
log.Printf("[bond %d] write data error: %v", connID, writeErr)
return
@@ -174,7 +174,7 @@ func (h *Handler) copyTCPToBond(ctx context.Context, connID uint64, tcpConn net.
continue
}
l.mu.Lock()
writeErr := bond.WriteFrame(l.stream, bond.FrameFIN, seq, nil)
writeErr := bondframe.WriteFrame(l.stream, bondframe.FrameFIN, seq, nil)
l.mu.Unlock()
if writeErr != nil && ctx.Err() == nil {
log.Printf("[bond %d] session %d write FIN error: %v", connID, l.ps.ID, writeErr)
@@ -200,7 +200,7 @@ func writeBondFrameToNextLane(ctx context.Context, lanes []*lane, typ byte, seq
continue
}
l.mu.Lock()
err := bond.WriteFrame(l.stream, typ, seq, data)
err := bondframe.WriteFrame(l.stream, typ, seq, data)
l.mu.Unlock()
if err == nil {
return l, nil
@@ -216,14 +216,14 @@ func writeBondFrameToNextLane(ctx context.Context, lanes []*lane, typ byte, seq
return nil, fmt.Errorf("no live bond lanes")
}
func (h *Handler) copyBondToTCP(ctx context.Context, connID uint64, tcpConn net.Conn, recvCh <-chan bond.Frame) {
func (h *Handler) copyBondToTCP(ctx context.Context, connID uint64, tcpConn net.Conn, recvCh <-chan bondframe.Frame) {
pending := make(map[uint64][]byte)
var expect uint64
var finSeq *uint64
for {
if finSeq != nil && expect == *finSeq {
bond.CloseWrite(tcpConn, h.Deps.log().Debugf)
bondframe.CloseWrite(tcpConn, h.Deps.log().Debugf)
h.Deps.log().Debugf("[bond %d] download finished chunks=%d", connID, expect)
return
}
@@ -236,13 +236,13 @@ func (h *Handler) copyBondToTCP(ctx context.Context, connID uint64, tcpConn net.
return
}
switch f.Type {
case bond.FrameData:
case bondframe.FrameData:
if len(pending) >= 1024 {
log.Printf("[bond %d] pending map overflow (>1024), closing", connID)
return
}
pending[f.Seq] = f.Data
case bond.FrameFIN:
case bondframe.FrameFIN:
v := f.Seq
if finSeq == nil || v < *finSeq {
finSeq = &v
@@ -12,8 +12,8 @@ import (
"sync"
"time"
"github.com/cacggghp/vk-turn-proxy/internal/bond"
"github.com/cacggghp/vk-turn-proxy/internal/logx"
"github.com/cacggghp/vk-turn-proxy/internal/wire/bondframe"
"github.com/xtaci/smux"
)
@@ -56,12 +56,12 @@ func NewRegistry(deps Deps) *Registry {
// already been consumed (server-side multiplex pre-peek), reads the Hello,
// attaches as a lane, and blocks until the underlying bond connection is done.
func (r *Registry) HandleStreamAfterMagic(ctx context.Context, stream *smux.Stream, connectAddr string, magic [4]byte) {
r.handleStream(ctx, stream, connectAddr, func(rd io.Reader) (bond.Hello, error) {
return bond.ReadHelloAfterMagic(rd, magic)
r.handleStream(ctx, stream, connectAddr, func(rd io.Reader) (bondframe.Hello, error) {
return bondframe.ReadHelloAfterMagic(rd, magic)
})
}
func (r *Registry) handleStream(ctx context.Context, stream *smux.Stream, connectAddr string, readHello func(io.Reader) (bond.Hello, error)) {
func (r *Registry) handleStream(ctx context.Context, stream *smux.Stream, connectAddr string, readHello func(io.Reader) (bondframe.Hello, error)) {
defer func() {
if err := stream.Close(); err != nil && err != smux.ErrGoAway {
log.Printf("failed to close bond smux stream: %v", err)
@@ -101,7 +101,7 @@ func (r *Registry) get(ctx context.Context, id uint64, connectAddr string) *serv
cancel: cancel,
done: make(chan struct{}),
ready: make(chan struct{}, 1),
recvCh: make(chan bond.Frame, 1024),
recvCh: make(chan bondframe.Frame, 1024),
}
r.conns[id] = c
go func() {
@@ -134,7 +134,7 @@ type serverConn struct {
want uint16
ready chan struct{}
recvCh chan bond.Frame
recvCh chan bondframe.Frame
once sync.Once
}
@@ -179,7 +179,7 @@ func (c *serverConn) removeLane(l *serverLane) int {
}
func (c *serverConn) waitForInitialLanes() {
timer := time.NewTimer(bond.LaneAttachTimeout)
timer := time.NewTimer(bondframe.LaneAttachTimeout)
defer timer.Stop()
for {
c.lanesMu.RLock()
@@ -202,7 +202,7 @@ func (c *serverConn) waitForInitialLanes() {
func (c *serverConn) readLane(l *serverLane) {
for {
f, err := bond.ReadFrame(l.stream)
f, err := bondframe.ReadFrame(l.stream)
if err != nil {
left := c.removeLane(l)
select {
@@ -272,7 +272,7 @@ func (c *serverConn) copyBondToBackend(backendConn net.Conn) {
for {
if finSeq != nil && expect == *finSeq {
bond.CloseWrite(backendConn, c.deps.log().Debugf)
bondframe.CloseWrite(backendConn, c.deps.log().Debugf)
c.deps.log().Debugf("[bond %d] upload to backend finished chunks=%d", c.id, expect)
return
}
@@ -282,9 +282,9 @@ func (c *serverConn) copyBondToBackend(backendConn net.Conn) {
return
case f := <-c.recvCh:
switch f.Type {
case bond.FrameData:
case bondframe.FrameData:
pending[f.Seq] = f.Data
case bond.FrameFIN:
case bondframe.FrameFIN:
v := f.Seq
if finSeq == nil || v < *finSeq {
finSeq = &v
@@ -313,7 +313,7 @@ func (c *serverConn) copyBondToBackend(backendConn net.Conn) {
}
func (c *serverConn) copyBackendToBond(backendConn net.Conn) {
buf := make([]byte, bond.MaxChunk)
buf := make([]byte, bondframe.MaxChunk)
var seq uint64
var laneIdx uint64
for {
@@ -321,7 +321,7 @@ func (c *serverConn) copyBackendToBond(backendConn net.Conn) {
if n > 0 {
data := make([]byte, n)
copy(data, buf[:n])
if writeErr := c.writeToNextLane(bond.FrameData, seq, data, &laneIdx); writeErr != nil {
if writeErr := c.writeToNextLane(bondframe.FrameData, seq, data, &laneIdx); writeErr != nil {
log.Printf("[bond %d] lane write data error: %v", c.id, writeErr)
return
}
@@ -331,7 +331,7 @@ func (c *serverConn) copyBackendToBond(backendConn net.Conn) {
lanes := c.snapshotLanes()
for _, lane := range lanes {
lane.mu.Lock()
writeErr := bond.WriteFrame(lane.stream, bond.FrameFIN, seq, nil)
writeErr := bondframe.WriteFrame(lane.stream, bondframe.FrameFIN, seq, nil)
lane.mu.Unlock()
if writeErr != nil && c.ctx.Err() == nil {
log.Printf("[bond %d] lane %d write FIN error: %v", c.id, lane.index, writeErr)
@@ -355,7 +355,7 @@ func (c *serverConn) writeToNextLane(typ byte, seq uint64, data []byte, laneIdx
lane := lanes[*laneIdx%uint64(len(lanes))]
*laneIdx++
lane.mu.Lock()
err := bond.WriteFrame(lane.stream, typ, seq, data)
err := bondframe.WriteFrame(lane.stream, typ, seq, data)
lane.mu.Unlock()
if err == nil {
return nil
@@ -10,7 +10,7 @@ import (
"testing"
"time"
"github.com/cacggghp/vk-turn-proxy/internal/bond"
"github.com/cacggghp/vk-turn-proxy/internal/wire/bondframe"
)
// fakeStream implements laneStream over an in-memory ring; reads block when
@@ -36,14 +36,14 @@ func (f *fakeStream) Write(p []byte) (int, error) {
func (f *fakeStream) SetDeadline(time.Time) error { return nil }
func (f *fakeStream) writtenFrames(t *testing.T) []bond.Frame {
func (f *fakeStream) writtenFrames(t *testing.T) []bondframe.Frame {
t.Helper()
f.mu.Lock()
buf := bytes.NewReader(f.sink.Bytes())
f.mu.Unlock()
var out []bond.Frame
var out []bondframe.Frame
for {
fr, err := bond.ReadFrame(buf)
fr, err := bondframe.ReadFrame(buf)
if err != nil {
if err == io.EOF {
return out
@@ -66,7 +66,7 @@ func newTestConn(t *testing.T) *serverConn {
cancel: cancel,
done: make(chan struct{}),
ready: make(chan struct{}, 1),
recvCh: make(chan bond.Frame, 1024),
recvCh: make(chan bondframe.Frame, 1024),
}
}
@@ -94,10 +94,10 @@ func TestCopyBondToBackendReorder(t *testing.T) {
}()
// out-of-order: seq 2, 0, FIN(3), 1
c.recvCh <- bond.Frame{Type: bond.FrameData, Seq: 2, Data: []byte("C")}
c.recvCh <- bond.Frame{Type: bond.FrameData, Seq: 0, Data: []byte("A")}
c.recvCh <- bond.Frame{Type: bond.FrameFIN, Seq: 3}
c.recvCh <- bond.Frame{Type: bond.FrameData, Seq: 1, Data: []byte("B")}
c.recvCh <- bondframe.Frame{Type: bondframe.FrameData, Seq: 2, Data: []byte("C")}
c.recvCh <- bondframe.Frame{Type: bondframe.FrameData, Seq: 0, Data: []byte("A")}
c.recvCh <- bondframe.Frame{Type: bondframe.FrameFIN, Seq: 3}
c.recvCh <- bondframe.Frame{Type: bondframe.FrameData, Seq: 1, Data: []byte("B")}
select {
case <-done:
@@ -140,10 +140,10 @@ func TestCopyBondToBackendPendingDrains(t *testing.T) {
if i == 0 {
continue
}
c.recvCh <- bond.Frame{Type: bond.FrameData, Seq: uint64(i), Data: []byte{byte(i)}}
c.recvCh <- bondframe.Frame{Type: bondframe.FrameData, Seq: uint64(i), Data: []byte{byte(i)}}
}
c.recvCh <- bond.Frame{Type: bond.FrameData, Seq: 0, Data: []byte{0}}
c.recvCh <- bond.Frame{Type: bond.FrameFIN, Seq: uint64(N)}
c.recvCh <- bondframe.Frame{Type: bondframe.FrameData, Seq: 0, Data: []byte{0}}
c.recvCh <- bondframe.Frame{Type: bondframe.FrameFIN, Seq: uint64(N)}
select {
case <-done:
@@ -172,7 +172,7 @@ func TestWriteToNextLaneRoundRobin(t *testing.T) {
var idx uint64
for seq := range 6 {
if err := c.writeToNextLane(bond.FrameData, uint64(seq), []byte{byte(seq)}, &idx); err != nil {
if err := c.writeToNextLane(bondframe.FrameData, uint64(seq), []byte{byte(seq)}, &idx); err != nil {
t.Fatalf("write seq %d: %v", seq, err)
}
}
@@ -205,7 +205,7 @@ func TestWriteToNextLaneChurn(t *testing.T) {
var idx uint64
for seq := range 4 {
if err := c.writeToNextLane(bond.FrameData, uint64(seq), []byte{byte(seq)}, &idx); err != nil {
if err := c.writeToNextLane(bondframe.FrameData, uint64(seq), []byte{byte(seq)}, &idx); err != nil {
t.Fatalf("seq %d: %v", seq, err)
}
}
@@ -236,7 +236,7 @@ func TestWriteToNextLaneAllFail(t *testing.T) {
c.lanes = []*serverLane{mk(0), mk(1)}
var idx uint64
err := c.writeToNextLane(bond.FrameData, 0, []byte("x"), &idx)
err := c.writeToNextLane(bondframe.FrameData, 0, []byte("x"), &idx)
if err == nil {
t.Fatal("expected error when all lanes fail")
}
@@ -1,10 +1,10 @@
// Package vless implements VLESS mode: TCP forwarding over a pool of TURN-tunneled
// Package tcpfwd implements VLESS mode: TCP forwarding over a pool of TURN-tunneled
// smux sessions. Each accepted local TCP connection is opened as a smux stream
// (round-robin across sessions) or, with bond, striped across all live sessions.
//
// The package exposes SessionPool/PooledSession so that the bond client half
// (still living in main during refactor stage 4.2) can operate on them.
package vless
package tcpfwd
import (
"sync"
@@ -1,4 +1,4 @@
package vless
package tcpfwd
import (
"context"
@@ -9,13 +9,13 @@ import (
"sync"
"time"
"github.com/cacggghp/vk-turn-proxy/internal/dtlsdial"
"github.com/cacggghp/vk-turn-proxy/internal/ish"
"github.com/cacggghp/vk-turn-proxy/internal/client/ish"
"github.com/cacggghp/vk-turn-proxy/internal/logx"
"github.com/cacggghp/vk-turn-proxy/internal/stats"
"github.com/cacggghp/vk-turn-proxy/internal/turnpipe"
"github.com/cacggghp/vk-turn-proxy/internal/wrap"
"github.com/cacggghp/vk-turn-proxy/tcputil"
"github.com/cacggghp/vk-turn-proxy/internal/transport/dtlsdial"
"github.com/cacggghp/vk-turn-proxy/internal/transport/kcptun"
"github.com/cacggghp/vk-turn-proxy/internal/transport/turndial"
"github.com/cacggghp/vk-turn-proxy/internal/wire/srtpmimicry"
"github.com/xtaci/smux"
)
@@ -237,7 +237,7 @@ func createSmuxSession(ctx context.Context, deps *Deps, params *Params, peer *ne
return nil, nil, fmt.Errorf("get TURN creds: %w", err)
}
stream, err := turnpipe.Open(ctx, turnpipe.Config{
stream, err := turndial.Open(ctx, turndial.Config{
HostOverride: params.Host,
PortOverride: params.Port,
UDP: params.UDP,
@@ -250,15 +250,15 @@ func createSmuxSession(ctx context.Context, deps *Deps, params *Params, peer *ne
deps.log().Debugf("[session %d] TURN server IP: %s", id, stream.ServerUDPAddr.IP)
deps.log().Debugf("relayed-address=%s", relayConn.LocalAddr().String())
var relayWC *wrap.Conn
if len(params.WrapKey) == wrap.KeyLen {
relayWC, err = wrap.NewConn(params.WrapKey, false)
var relayWC *srtpmimicry.Conn
if len(params.WrapKey) == srtpmimicry.KeyLen {
relayWC, err = srtpmimicry.NewConn(params.WrapKey, false)
if err != nil {
cleanup()
return nil, nil, fmt.Errorf("wrap init: %w", err)
}
}
dtlsPC := &wrap.RelayPacketConn{Relay: relayConn, Peer: peer, Conn: relayWC}
dtlsPC := &srtpmimicry.RelayPacketConn{Relay: relayConn, Peer: peer, Conn: relayWC}
dtlsConn, err := deps.DTLSDialer.Dial(ctx, dtlsPC, peer)
if err != nil {
cleanup()
@@ -272,7 +272,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 := tcputil.NewKCPOverDTLS(&stats.CountingConn{Conn: dtlsConn, Stats: st}, false)
kcpSess, err := kcptun.NewKCPOverDTLS(&stats.CountingConn{Conn: dtlsConn, Stats: st}, false)
if err != nil {
cleanup()
return nil, nil, fmt.Errorf("KCP session: %w", err)
@@ -280,7 +280,7 @@ func createSmuxSession(ctx context.Context, deps *Deps, params *Params, peer *ne
cleanupFns = append(cleanupFns, func() { _ = kcpSess.Close() })
deps.log().Debugf("KCP session established")
smuxSess, err := smux.Client(kcpSess, tcputil.DefaultSmuxConfig())
smuxSess, err := smux.Client(kcpSess, kcptun.DefaultSmuxConfig())
if err != nil {
cleanup()
return nil, nil, fmt.Errorf("smux client: %w", err)
@@ -1,9 +1,9 @@
// Package udp implements the UDP-mode proxy loop: it terminates DTLS from a
// Package udprelay implements the UDP-mode proxy loop: it terminates DTLS from a
// local peer (WireGuard) and relays its packets through a per-stream TURN
// allocation back to a remote peer. It owns oneDtlsConnection /
// oneTurnConnection and their retry loops; wiring (flag parsing, listener,
// inbound dispatch) stays in main.
package udp
package udprelay
import (
"context"
@@ -16,11 +16,11 @@ import (
"sync/atomic"
"time"
"github.com/cacggghp/vk-turn-proxy/internal/dtlsdial"
"github.com/cacggghp/vk-turn-proxy/internal/logx"
"github.com/cacggghp/vk-turn-proxy/internal/stats"
"github.com/cacggghp/vk-turn-proxy/internal/turnpipe"
"github.com/cacggghp/vk-turn-proxy/internal/wrap"
"github.com/cacggghp/vk-turn-proxy/internal/transport/dtlsdial"
"github.com/cacggghp/vk-turn-proxy/internal/transport/turndial"
"github.com/cacggghp/vk-turn-proxy/internal/wire/srtpmimicry"
"github.com/cbeuw/connutil"
)
@@ -253,7 +253,7 @@ func oneTURN(ctx context.Context, deps *Deps, params *Params, peer *net.UDPAddr,
err = fmt.Errorf("failed to get TURN credentials: %s", err1)
return
}
stream, err1 := turnpipe.Open(ctx, turnpipe.Config{
stream, err1 := turndial.Open(ctx, turndial.Config{
HostOverride: params.Host,
PortOverride: params.Port,
UDP: params.UDP,
@@ -293,10 +293,10 @@ func oneTURN(ctx context.Context, deps *Deps, params *Params, peer *net.UDPAddr,
}
})
var internalPipeAddr atomic.Value
var wc *wrap.Conn
if len(params.WrapKey) == wrap.KeyLen {
var wc *srtpmimicry.Conn
if len(params.WrapKey) == srtpmimicry.KeyLen {
var wcErr error
wc, wcErr = wrap.NewConn(params.WrapKey, false)
wc, wcErr = srtpmimicry.NewConn(params.WrapKey, false)
if wcErr != nil {
log.Printf("[STREAM %d] WRAP init failed: %v", streamID, wcErr)
turncancel()
@@ -309,7 +309,7 @@ func oneTURN(ctx context.Context, deps *Deps, params *Params, peer *net.UDPAddr,
buf := make([]byte, 1600)
var wireBuf []byte
if wc != nil {
wireBuf = make([]byte, wrap.MaxWire(len(buf)))
wireBuf = make([]byte, srtpmimicry.MaxWire(len(buf)))
}
for {
if turnctx.Err() != nil {
@@ -347,7 +347,7 @@ func oneTURN(ctx context.Context, deps *Deps, params *Params, peer *net.UDPAddr,
defer turncancel()
readBufLen := 1600
if wc != nil {
readBufLen = wrap.MaxWire(1600)
readBufLen = srtpmimicry.MaxWire(1600)
}
buf := make([]byte, readBufLen)
plain := make([]byte, 1600)
File renamed without changes.
+245
View File
@@ -0,0 +1,245 @@
package kcptun
import (
"net"
"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
}
func selectedKCPProfile() kcpProfile {
kcpProfileOnce.Do(func() {
cachedKCPProfile = loadKCPProfile()
})
return cachedKCPProfile
}
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,
}
}
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
}
func envInt(name string, fallback int) int {
raw := strings.TrimSpace(os.Getenv(name))
if raw == "" {
return fallback
}
value, err := strconv.Atoi(raw)
if err != nil {
return fallback
}
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 {
case "1", "true", "yes", "on":
return true
case "0", "false", "no", "off":
return false
default:
return fallback
}
}
// DtlsPacketConn wraps a net.Conn (DTLS) as a net.PacketConn for KCP.
// Each DTLS Read/Write preserves message boundaries (datagram semantics).
type DtlsPacketConn struct {
conn net.Conn
}
func NewDtlsPacketConn(conn net.Conn) *DtlsPacketConn {
return &DtlsPacketConn{conn: conn}
}
func (d *DtlsPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
n, err := d.conn.Read(b)
return n, d.conn.RemoteAddr(), err
}
func (d *DtlsPacketConn) WriteTo(b []byte, _ net.Addr) (int, error) {
return d.conn.Write(b)
}
func (d *DtlsPacketConn) Close() error {
return d.conn.Close()
}
func (d *DtlsPacketConn) LocalAddr() net.Addr {
return d.conn.LocalAddr()
}
func (d *DtlsPacketConn) SetDeadline(t time.Time) error {
return d.conn.SetDeadline(t)
}
func (d *DtlsPacketConn) SetReadDeadline(t time.Time) error {
return d.conn.SetReadDeadline(t)
}
func (d *DtlsPacketConn) SetWriteDeadline(t time.Time) error {
return d.conn.SetWriteDeadline(t)
}
// 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) {
pc := NewDtlsPacketConn(dtlsConn)
block, err := kcp.NewNoneBlockCrypt(nil) // DTLS already encrypts
if err != nil {
return nil, err
}
var sess *kcp.UDPSession
dataShards, parityShards := selectedFEC()
if isServer {
// Server: listen on the PacketConn and accept one session
var listener *kcp.Listener
listener, err = kcp.ServeConn(block, dataShards, parityShards, pc)
if err != nil {
return nil, err
}
if err = listener.SetDeadline(time.Now().Add(30 * time.Second)); err != nil {
return nil, err
}
sess, err = listener.AcceptKCP()
if err != nil {
return nil, err
}
} else {
// Client: dial through the PacketConn
sess, err = kcp.NewConn2(dtlsConn.RemoteAddr(), block, dataShards, parityShards, 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)
return sess, nil
}
// DefaultSmuxConfig returns smux config tuned for TURN tunnel.
func DefaultSmuxConfig() *smux.Config {
cfg := smux.DefaultConfig()
cfg.MaxReceiveBuffer = 4 * 1024 * 1024
cfg.MaxStreamBuffer = 1 * 1024 * 1024
cfg.KeepAliveInterval = 10 * time.Second
cfg.KeepAliveTimeout = 30 * time.Second
return cfg
}
@@ -1,11 +1,11 @@
// Package turnpipe centralizes the TURN dial+allocate pipeline shared by
// Package turndial centralizes the TURN dial+allocate pipeline shared by
// the client UDP (oneTurnConnection) and VLESS (createSmuxSession) modes.
//
// One call to Open performs: parse target, apply host/port overrides,
// resolve UDP addr, dial UDP-or-TCP (with SplitFirstWriteConn over TCP),
// turn.NewClient, Listen, Allocate. Returns the relay PacketConn plus a
// Close that tears down the allocation, TURN client, and underlying conn.
package turnpipe
package turndial
import (
"context"
@@ -13,7 +13,7 @@ import (
"net"
"time"
"github.com/cacggghp/vk-turn-proxy/internal/netadapt"
"github.com/cacggghp/vk-turn-proxy/internal/netconn"
"github.com/pion/logging"
"github.com/pion/turn/v5"
)
@@ -86,7 +86,7 @@ func Open(ctx context.Context, cfg Config, peer *net.UDPAddr, user, pass, rawAdd
if derr != nil {
return nil, fmt.Errorf("dial TURN (udp): %w", derr)
}
turnConn = &netadapt.ConnectedUDPConn{UDPConn: c}
turnConn = &netconn.ConnectedUDPConn{UDPConn: c}
closeConn = c.Close
} else {
dctx, cancel := context.WithTimeout(ctx, dialTimeout)
@@ -96,7 +96,7 @@ func Open(ctx context.Context, cfg Config, peer *net.UDPAddr, user, pass, rawAdd
if derr != nil {
return nil, fmt.Errorf("dial TURN (tcp): %w", derr)
}
wrapped := &netadapt.SplitFirstWriteConn{Conn: c, SplitAt: 6, Delay: 20 * time.Millisecond}
wrapped := &netconn.SplitFirstWriteConn{Conn: c, SplitAt: 6, Delay: 20 * time.Millisecond}
turnConn = turn.NewSTUNConn(wrapped)
closeConn = c.Close
}
@@ -111,7 +111,7 @@ func Open(ctx context.Context, cfg Config, peer *net.UDPAddr, user, pass, rawAdd
STUNServerAddr: turnServerAddr,
TURNServerAddr: turnServerAddr,
Conn: turnConn,
Net: netadapt.New(),
Net: netconn.New(),
Username: user,
Password: pass,
RequestedAddressFamily: addrFamily,
@@ -1,4 +1,4 @@
package turnpipe
package turndial
import (
"context"
@@ -1,7 +1,7 @@
// Package bond 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 bond
package bondframe
import (
"encoding/binary"
@@ -1,4 +1,4 @@
package bond
package bondframe
import (
"bytes"
@@ -1,6 +1,6 @@
// SPDX-License-Identifier: MIT
package wrap
package srtpmimicry
import (
"errors"
@@ -1,6 +1,6 @@
// SPDX-License-Identifier: MIT
package wrap
package srtpmimicry
import (
"net"
@@ -1,8 +1,13 @@
// SPDX-License-Identifier: MIT
// Package wrap implements an SRTP-mimicry AEAD framing used to bypass
// Package srtpmimicry implements an SRTP-mimicry AEAD framing used to bypass
// the 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.
//
// Wire format:
//
// [12B RTP header | 12B explicit nonce | AEAD ciphertext | 16B tag]
@@ -20,7 +25,7 @@
// AAD = first 24 bytes (RTP header || nonce).
//
// Wire format is frozen — bit-exact compatibility with deployed peers is required.
package wrap
package srtpmimicry
import (
"crypto/cipher"
@@ -1,4 +1,4 @@
package wrap
package srtpmimicry
import (
"bytes"