refactor: симметрия, вынос серверных хендлеров

- internal/proxy/udpserver: handleUDPConnection вынесен из server-main
- internal/proxy/tcpfwdserver: handleVLESSConnection + prefixedConn + pipeConn
  вынесены из server-main
- cmd/vk-turn-server/main.go: 396 → 134 строк, глобалы убраны
- internal/proxy/udprelay: добавлен entrypoint Run() симметрично tcpfwd.Run;
  Pool → packetPool (unexported); listener+fan-in вынесены из client-main
- cmd/vk-turn-client/main.go: 262 → 130 строк, package-глобалы убраны
- dtlsdial.Dialer: кеш self-signed сертификата на Dialer (sync.Once) вместо
  регенерации на каждый handshake
- captcha.solveCaptchaPoW: переиспользование буфера (вместо 10M конкатенаций
  строк), ctx-проверка каждые 1024 итерации (было 4096)

Тесты + lint проходят.
This commit is contained in:
samosvalishe committed 2026-05-19 21:53:13 +03:00
1 parent ed6825976a
commit 51bda46446
7 files changed
+465 -460

No files matched your search

+7 -2
View File
@@ -463,15 +463,20 @@ func solveCaptchaPoW(ctx context.Context, input string, difficulty int) string {
return ""
}
target := strings.Repeat("0", difficulty)
// ctx-check every 1024 iterations keeps cancel latency under a few ms
// even on weak ARM (was every 4096).
buf := make([]byte, 0, len(input)+20)
buf = append(buf, input...)
for nonce := 1; nonce <= 10_000_000; nonce++ {
if nonce%4096 == 0 {
if nonce&1023 == 0 {
select {
case <-ctx.Done():
return ""
default:
}
}
sum := sha256.Sum256([]byte(input + strconv.Itoa(nonce)))
buf = strconv.AppendInt(buf[:len(input)], int64(nonce), 10)
sum := sha256.Sum256(buf)
hashHex := hex.EncodeToString(sum[:])
if strings.HasPrefix(hashHex, target) {
return hashHex
+166
View File
@@ -0,0 +1,166 @@
// Package tcpfwdserver implements the server-side VLESS lane: KCP+smux over a
// DTLS connection, with each smux stream forwarded as a TCP connection to the
// backend (Xray/VLESS). Bond streams are auto-detected by their magic prefix
// and dispatched to a bondserver.Registry.
package tcpfwdserver
import (
"context"
"io"
"log"
"net"
"sync"
"time"
"github.com/cacggghp/vk-turn-proxy/internal/logx"
"github.com/cacggghp/vk-turn-proxy/internal/proxy/bondserver"
"github.com/cacggghp/vk-turn-proxy/internal/stats"
"github.com/cacggghp/vk-turn-proxy/internal/transport/kcptun"
"github.com/cacggghp/vk-turn-proxy/internal/wire/bondframe"
"github.com/xtaci/smux"
)
// 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) {
statsCtx, statsCancel := context.WithCancel(ctx)
defer statsCancel()
st := stats.New(logger.DebugEnabled())
go st.LogEvery(
statsCtx,
logger.Debugf,
"[VLESS "+dtlsConn.RemoteAddr().String()+"]",
"to-client",
"from-client",
)
kcpSess, err := kcptun.NewKCPOverDTLS(&stats.CountingConn{Conn: dtlsConn, Stats: st}, true)
if err != nil {
log.Printf("KCP session error: %s", err)
return
}
defer func() {
if closeErr := kcpSess.Close(); closeErr != nil {
log.Printf("failed to close KCP session: %v", closeErr)
}
}()
logger.Debugf("KCP session established (server)")
smuxSess, err := smux.Server(kcpSess, kcptun.DefaultSmuxConfig())
if err != nil {
log.Printf("smux server error: %s", err)
return
}
defer func() {
if err := smuxSess.Close(); err != nil {
log.Printf("failed to close smux session: %v", err)
}
}()
logger.Debugf("smux session established (server)")
var wg sync.WaitGroup
for {
stream, err := smuxSess.AcceptStream()
if err != nil {
select {
case <-ctx.Done():
default:
log.Printf("smux accept error: %s", err)
}
break
}
s := stream
wg.Go(func() {
handleStream(ctx, logger, registry, s, connectAddr)
})
}
wg.Wait()
}
func handleStream(ctx context.Context, logger logx.Logger, registry *bondserver.Registry, s *smux.Stream, connectAddr string) {
var prefix [4]byte
if _, err := io.ReadFull(s, prefix[:]); err != nil {
if err != io.EOF && err != io.ErrUnexpectedEOF {
log.Printf("smux stream prefix read error: %v", err)
}
_ = s.Close()
return
}
if string(prefix[:]) == bondframe.Magic {
logger.Debugf("auto-detected bond smux stream")
registry.HandleStreamAfterMagic(ctx, s, connectAddr, prefix)
return
}
defer func() {
if err := s.Close(); err != nil && err != smux.ErrGoAway {
log.Printf("failed to close smux stream: %v", err)
}
}()
backendConn, err := net.DialTimeout("tcp", connectAddr, 10*time.Second)
if err != nil {
log.Printf("backend dial error: %s", err)
return
}
defer func() {
if err := backendConn.Close(); err != nil {
log.Printf("failed to close backend connection: %v", err)
}
}()
pipeConn(ctx, logger, &prefixedConn{Conn: s, prefix: prefix[:]}, backendConn)
}
// prefixedConn re-injects the magic-peek prefix on the first reads so the
// backend sees the full original byte stream.
type prefixedConn struct {
net.Conn
prefix []byte
}
func (c *prefixedConn) Read(p []byte) (int, error) {
if len(c.prefix) > 0 {
n := copy(p, c.prefix)
c.prefix = c.prefix[n:]
return n, nil
}
return c.Conn.Read(p)
}
// pipeConn copies data bidirectionally between two connections.
func pipeConn(ctx context.Context, logger logx.Logger, c1, c2 net.Conn) {
ctx2, cancel := context.WithCancel(ctx)
defer cancel()
context.AfterFunc(ctx2, func() {
if err := c1.SetDeadline(time.Now()); err != nil {
logger.Debugf("pipeConn: failed to set deadline c1: %v", err)
}
if err := c2.SetDeadline(time.Now()); err != nil {
logger.Debugf("pipeConn: failed to set deadline c2: %v", err)
}
})
var wg sync.WaitGroup
wg.Go(func() {
if _, err := io.Copy(c1, c2); err != nil {
logger.Debugf("pipeConn: c1<-c2 copy error: %v", err)
}
})
wg.Go(func() {
if _, err := io.Copy(c2, c1); err != nil {
logger.Debugf("pipeConn: c2<-c1 copy error: %v", err)
}
})
wg.Wait()
if err := c1.SetDeadline(time.Time{}); err != nil {
logger.Debugf("pipeConn: failed to reset deadline c1: %v", err)
}
if err := c2.SetDeadline(time.Time{}); err != nil {
logger.Debugf("pipeConn: failed to reset deadline c2: %v", err)
}
}
+117 -10
View File
@@ -1,8 +1,7 @@
// 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.
// allocation back to a remote peer. Run is the entrypoint; it owns the local
// listener, the inbound dispatch fan-in, and the per-stream DTLS/TURN loops.
package udprelay
import (
@@ -32,9 +31,9 @@ type Packet struct {
N int
}
// Pool reuses Packet buffers across the inbound hot path. Buffer size matches
// the 2048-byte default the listener loop expects.
var Pool = sync.Pool{
// packetPool reuses Packet buffers across the inbound hot path. Buffer size
// matches the 2048-byte default the listener loop expects.
var packetPool = sync.Pool{
New: func() any { return &Packet{Data: make([]byte, 2048)} },
}
@@ -61,9 +60,9 @@ type Params struct {
GetCreds GetCredsFunc
}
// Deps groups everything the loops need from the host process. ActiveLocalPeer
// is read concurrently with the listener that writes it; ConnectedStreams is
// the live-stream counter the auth layer queries.
// Deps groups everything the loops need from the host process. The atomics
// are owned by Run and exposed here so DTLSLoop/TURNLoop can share them when
// called directly (Run wires them automatically).
type Deps struct {
DTLSDialer *dtlsdial.Dialer
Auth AuthHandler
@@ -80,6 +79,114 @@ func (d *Deps) log() logx.Logger {
return d.Log
}
// Run is the UDP-mode entrypoint. It binds listenAddr, fans inbound packets
// into a shared queue, and spawns numStreams pairs of (DTLSLoop, TURNLoop).
// connectedStreams is owned by the caller (vkauth reads it via StreamsAlive)
// and incremented/decremented by oneTURN.
// Returns after all stream loops exit (i.e. when ctx is cancelled).
func Run(ctx context.Context, dtlsDialer *dtlsdial.Dialer, auth AuthHandler, logger logx.Logger, connectedStreams *atomic.Int32, appCancel context.CancelFunc, params *Params, peer *net.UDPAddr, listenAddr string, numStreams int) {
listenConn, err := net.ListenPacket("udp", listenAddr)
if err != nil {
log.Panicf("Failed to listen: %s", err)
}
context.AfterFunc(ctx, func() {
if closeErr := listenConn.Close(); closeErr != nil {
log.Printf("Failed to close local connection: %s", closeErr)
}
})
if numStreams <= 0 {
numStreams = 1
}
var activeLocalPeer atomic.Value
deps := &Deps{
DTLSDialer: dtlsDialer,
Auth: auth,
Log: logger,
ActiveLocalPeer: &activeLocalPeer,
ConnectedStreams: connectedStreams,
AppCancel: appCancel,
}
inboundChan := make(chan *Packet, inboundQueueCap)
go runListener(ctx, listenConn, &activeLocalPeer, inboundChan)
wg := sync.WaitGroup{}
t := time.Tick(200 * time.Millisecond)
okchan := make(chan struct{})
connchan := make(chan net.PacketConn)
wg.Go(func() {
DTLSLoop(ctx, deps, peer, listenConn, inboundChan, connchan, okchan, 1)
})
wg.Go(func() {
TURNLoop(ctx, deps, params, peer, connchan, t, 1)
})
select {
case <-okchan:
case <-ctx.Done():
}
for i := 1; i < numStreams; i++ {
cchan := make(chan net.PacketConn)
streamID := i
wg.Go(func() {
DTLSLoop(ctx, deps, peer, listenConn, inboundChan, cchan, nil, streamID)
})
wg.Go(func() {
TURNLoop(ctx, deps, params, peer, cchan, t, streamID)
})
}
wg.Wait()
}
const inboundQueueCap = 2000
// runListener reads packets from listenConn, refreshes the active-peer cache,
// and posts each packet to inboundChan. Packets are dropped when the channel
// is full to keep the read loop wait-free.
func runListener(ctx context.Context, listenConn net.PacketConn, activeLocalPeer *atomic.Value, inboundChan chan<- *Packet) {
// 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 {
if ctx.Err() != nil {
return
}
pktIface := packetPool.Get()
pkt := pktIface.(*Packet) //nolint:errcheck // pool New always returns *Packet
nRead, addr, err := listenConn.ReadFrom(pkt.Data)
if err != nil {
return
}
if addr != lastAddr {
s := addr.String()
if s != lastAddrStr {
activeLocalPeer.Store(addr)
lastAddrStr = s
}
lastAddr = addr
}
pkt.N = nRead
select {
case inboundChan <- pkt:
default:
packetPool.Put(pkt)
}
}
}
// DTLSLoop keeps a single DTLS termination alive for streamID, restarting it
// on failure with a 10-30s backoff (skipped while a captcha lockout is active
// and the prior error was a deadline). connchan is fed a fresh AsyncPacketPipe
@@ -224,7 +331,7 @@ func oneDTLS(ctx context.Context, deps *Deps, peer *net.UDPAddr, listenConn net.
return
case pkt := <-inboundChan:
_, _ = dtlsConn.Write(pkt.Data[:pkt.N])
Pool.Put(pkt)
packetPool.Put(pkt)
}
}
})
+98
View File
@@ -0,0 +1,98 @@
// Package udpserver implements the server-side UDP relay: a DTLS-terminated
// stream is forwarded to a UDP backend (WireGuard) and vice-versa.
package udpserver
import (
"context"
"fmt"
"log"
"net"
"sync"
"time"
"github.com/cacggghp/vk-turn-proxy/internal/logx"
"github.com/cacggghp/vk-turn-proxy/internal/stats"
)
const (
udpRelayBufSize = 1600
udpIdleTimeout = 30 * time.Minute
)
// Handle forwards DTLS packets between conn and a UDP backend at connectAddr
// until either side closes. Blocks until both copy goroutines exit.
func Handle(ctx context.Context, logger logx.Logger, conn net.Conn, connectAddr string) {
serverConn, err := net.Dial("udp", connectAddr)
if err != nil {
log.Println(err)
return
}
defer func() {
if err = serverConn.Close(); err != nil {
log.Printf("failed to close outgoing connection: %s", err)
}
}()
ctx2, cancel := context.WithCancel(ctx)
defer cancel()
st := stats.New(logger.DebugEnabled())
go st.LogEvery(
ctx2,
logger.Debugf,
fmt.Sprintf("[DTLS %s]", conn.RemoteAddr()),
"dtls-to-backend",
"backend-to-dtls",
)
context.AfterFunc(ctx2, func() {
if err := conn.SetDeadline(time.Now()); err != nil {
log.Printf("failed to set incoming deadline: %s", err)
}
if err := serverConn.SetDeadline(time.Now()); err != nil {
log.Printf("failed to set outgoing deadline: %s", err)
}
})
var wg sync.WaitGroup
wg.Go(func() {
defer cancel()
copyOne(ctx2, conn, serverConn, st.AddTx)
})
wg.Go(func() {
defer cancel()
copyOne(ctx2, serverConn, conn, st.AddRx)
})
wg.Wait()
}
// copyOne reads from src and writes to dst until ctx fires or either side errors.
// Each read/write resets an idle timeout so a stuck side closes instead of hanging.
func copyOne(ctx context.Context, src, dst net.Conn, count func(int)) {
buf := make([]byte, udpRelayBufSize)
for {
select {
case <-ctx.Done():
return
default:
}
if err := src.SetReadDeadline(time.Now().Add(udpIdleTimeout)); err != nil {
log.Printf("Failed: %s", err)
return
}
n, err := src.Read(buf)
if err != nil {
log.Printf("Failed: %s", err)
return
}
if werr := dst.SetWriteDeadline(time.Now().Add(udpIdleTimeout)); werr != nil {
log.Printf("Failed: %s", werr)
return
}
written, werr := dst.Write(buf[:n])
count(written)
if werr != nil {
log.Printf("Failed: %s", werr)
return
}
}
}
+17 -6
View File
@@ -5,7 +5,9 @@ package dtlsdial
import (
"context"
"crypto/tls"
"net"
"sync"
"time"
"github.com/pion/dtls/v3"
@@ -19,16 +21,25 @@ type Dialer struct {
// HandshakeSem, if non-nil, gates concurrent handshakes (Dial blocks
// until a slot is available or ctx fires).
HandshakeSem chan struct{}
certOnce sync.Once
cert tls.Certificate
certErr error
}
// Dial generates a fresh self-signed cert, acquires the optional handshake
// slot, and performs a DTLS client handshake over pc to peer. On success
// returns the connected *dtls.Conn. Caller closes it.
// Dial acquires the optional handshake slot and performs a DTLS client
// handshake over pc to peer. On success returns the connected *dtls.Conn.
// Caller closes it. The self-signed cert is generated once per Dialer and
// reused across handshakes (DTLS is used here for obfuscation, not auth —
// see internal/transport/dtlsdial/doc.go).
func (d *Dialer) Dial(ctx context.Context, pc net.PacketConn, peer *net.UDPAddr) (*dtls.Conn, error) {
certificate, err := selfsign.GenerateSelfSigned()
if err != nil {
return nil, err
d.certOnce.Do(func() {
d.cert, d.certErr = selfsign.GenerateSelfSigned()
})
if d.certErr != nil {
return nil, d.certErr
}
certificate := d.cert
if d.HandshakeSem != nil {
select {
case d.HandshakeSem <- struct{}{}: