From ada0c746aa47266c07f3653b785b2a4b17d55d67 Mon Sep 17 00:00:00 2001 From: samosvalishe Date: Tue, 19 May 2026 00:29:47 +0300 Subject: [PATCH] =?UTF-8?q?refactor:=20=D0=B2=D1=8B=D0=BD=D0=B5=D1=81?= =?UTF-8?q?=D1=82=D0=B8=20stats,=20netadapt,=20bond=20=D0=B2=20internal/?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - internal/stats: throughputStats/countingConn/форматтеры, общие для клиента и сервера - internal/netadapt: DirectNet, ConnectedUDPConn, SplitFirstWriteConn - internal/bond: wire-кодек (Frame/Hello, Read/Write, CloseWrite) Убирает дублирование между client/main.go и server/main.go. Wire-формат и поведение CLI не изменены; round-trip кодека покрыт тестами. --- client/main.go | 386 +++-------------------------- internal/bond/frame.go | 133 ++++++++++ internal/bond/frame_test.go | 128 ++++++++++ internal/netadapt/netadapt.go | 150 +++++++++++ internal/netadapt/netadapt_test.go | 116 +++++++++ internal/stats/stats.go | 130 ++++++++++ internal/stats/stats_test.go | 86 +++++++ server/main.go | 268 +++----------------- 8 files changed, 817 insertions(+), 580 deletions(-) create mode 100644 internal/bond/frame.go create mode 100644 internal/bond/frame_test.go create mode 100644 internal/netadapt/netadapt.go create mode 100644 internal/netadapt/netadapt_test.go create mode 100644 internal/stats/stats.go create mode 100644 internal/stats/stats_test.go diff --git a/client/main.go b/client/main.go index 1ecb80c..510f6ac 100644 --- a/client/main.go +++ b/client/main.go @@ -6,7 +6,6 @@ package main import ( "bytes" "context" - "encoding/binary" "encoding/json" "flag" "fmt" @@ -32,29 +31,21 @@ import ( "github.com/cacggghp/vk-turn-proxy/client/internal/captcha" "github.com/cacggghp/vk-turn-proxy/client/internal/dnsdial" "github.com/cacggghp/vk-turn-proxy/client/internal/namegen" + "github.com/cacggghp/vk-turn-proxy/internal/bond" + "github.com/cacggghp/vk-turn-proxy/internal/netadapt" + "github.com/cacggghp/vk-turn-proxy/internal/stats" "github.com/cacggghp/vk-turn-proxy/tcputil" "github.com/cbeuw/connutil" "github.com/google/uuid" "github.com/pion/dtls/v3" "github.com/pion/dtls/v3/pkg/crypto/selfsign" "github.com/pion/logging" - "github.com/pion/transport/v4" "github.com/pion/turn/v5" "github.com/xtaci/smux" ) type getCredsFunc func(ctx context.Context, link string, streamID int) (string, string, string, error) -type directNet struct{} - -type directDialer struct { - *net.Dialer -} - -type directListenConfig struct { - *net.ListenConfig -} - // Global state trackers var ( activeLocalPeer atomic.Value @@ -114,196 +105,6 @@ var packetPool = sync.Pool{ New: func() any { return &UDPPacket{Data: make([]byte, 2048)} }, } -type throughputStats struct { - tx atomic.Uint64 - rx atomic.Uint64 -} - -func (s *throughputStats) addTx(n int) { - // 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 !isDebug || n <= 0 { - return - } - s.rx.Add(uint64(n)) -} - -func (s *throughputStats) logEvery(ctx context.Context, label, txName, rxName string) { - if !isDebug { - return - } - - ticker := time.NewTicker(5 * time.Second) - defer ticker.Stop() - - var prevTx, prevRx uint64 - for { - select { - case <-ctx.Done(): - return - case <-ticker.C: - tx := s.tx.Load() - rx := s.rx.Load() - deltaTx := tx - prevTx - deltaRx := rx - prevRx - prevTx = tx - prevRx = rx - - if deltaTx == 0 && deltaRx == 0 { - continue - } - - debugf( - "%s throughput: %s=%s %s=%s total_%s=%s total_%s=%s", - label, - txName, - formatBitsPerSecond(deltaTx, 5*time.Second), - rxName, - formatBitsPerSecond(deltaRx, 5*time.Second), - txName, - formatByteCount(tx), - rxName, - formatByteCount(rx), - ) - } - } -} - -func formatBitsPerSecond(bytes uint64, interval time.Duration) string { - if interval <= 0 { - interval = time.Second - } - - bps := float64(bytes*8) / interval.Seconds() - if bps >= 1_000_000 { - return fmt.Sprintf("%.2f Mbit/s", bps/1_000_000) - } - if bps >= 1_000 { - return fmt.Sprintf("%.1f kbit/s", bps/1_000) - } - return fmt.Sprintf("%.0f bit/s", bps) -} - -func formatByteCount(bytes uint64) string { - if bytes >= 1024*1024 { - return fmt.Sprintf("%.2f MiB", float64(bytes)/(1024*1024)) - } - if bytes >= 1024 { - return fmt.Sprintf("%.1f KiB", float64(bytes)/1024) - } - return fmt.Sprintf("%d B", bytes) -} - -type countingConn struct { - net.Conn - stats *throughputStats -} - -func (c *countingConn) Read(p []byte) (int, error) { - n, err := c.Conn.Read(p) - c.stats.addRx(n) - return n, err -} - -func (c *countingConn) Write(p []byte) (int, error) { - n, err := c.Conn.Write(p) - c.stats.addTx(n) - return n, err -} - -func newDirectNet() transport.Net { - return directNet{} -} - -func (directNet) ListenPacket(network string, address string) (net.PacketConn, error) { - return net.ListenPacket(network, address) -} - -func (directNet) ListenUDP(network string, locAddr *net.UDPAddr) (transport.UDPConn, error) { - return net.ListenUDP(network, locAddr) -} - -func (directNet) ListenTCP(network string, laddr *net.TCPAddr) (transport.TCPListener, error) { - listener, err := net.ListenTCP(network, laddr) - if err != nil { - return nil, err - } - - return directTCPListener{listener}, nil -} - -func (directNet) Dial(network, address string) (net.Conn, error) { - return net.Dial(network, address) -} - -func (directNet) DialUDP(network string, laddr, raddr *net.UDPAddr) (transport.UDPConn, error) { - return net.DialUDP(network, laddr, raddr) -} - -func (directNet) DialTCP(network string, laddr, raddr *net.TCPAddr) (transport.TCPConn, error) { - return net.DialTCP(network, laddr, raddr) -} - -func (directNet) ResolveIPAddr(network, address string) (*net.IPAddr, error) { - return net.ResolveIPAddr(network, address) -} - -func (directNet) ResolveUDPAddr(network, address string) (*net.UDPAddr, error) { - return net.ResolveUDPAddr(network, address) -} - -func (directNet) ResolveTCPAddr(network, address string) (*net.TCPAddr, error) { - return net.ResolveTCPAddr(network, address) -} - -func (directNet) Interfaces() ([]*transport.Interface, error) { - return nil, transport.ErrNotSupported -} - -func (directNet) InterfaceByIndex(index int) (*transport.Interface, error) { - return nil, fmt.Errorf("%w: index=%d", transport.ErrInterfaceNotFound, index) -} - -func (directNet) InterfaceByName(name string) (*transport.Interface, error) { - return nil, fmt.Errorf("%w: %s", transport.ErrInterfaceNotFound, name) -} - -func (directNet) CreateDialer(dialer *net.Dialer) transport.Dialer { - return directDialer{Dialer: dialer} -} - -func (directNet) CreateListenConfig(listenerConfig *net.ListenConfig) transport.ListenConfig { - return directListenConfig{ListenConfig: listenerConfig} -} - -func (d directDialer) Dial(network, address string) (net.Conn, error) { - return d.Dialer.Dial(network, address) -} - -func (d directListenConfig) Listen(ctx context.Context, network, address string) (net.Listener, error) { - return d.ListenConfig.Listen(ctx, network, address) -} - -func (d directListenConfig) ListenPacket(ctx context.Context, network, address string) (net.PacketConn, error) { - return d.ListenConfig.ListenPacket(ctx, network, address) -} - -type directTCPListener struct { - *net.TCPListener -} - -func (l directTCPListener) AcceptTCP() (transport.TCPConn, error) { - return l.TCPListener.AcceptTCP() -} - // region Helper: HTTP Headers Injection func getCustomNetDialer() net.Dialer { @@ -989,40 +790,6 @@ func oneDtlsConnection(ctx context.Context, peer *net.UDPAddr, listenConn net.Pa return nil } -type connectedUDPConn struct { - *net.UDPConn -} - -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 @@ -1078,7 +845,7 @@ func oneTurnConnection(ctx context.Context, turnParams *turnParams, peer *net.UD return } }() - turnConn = &connectedUDPConn{conn} + turnConn = &netadapt.ConnectedUDPConn{UDPConn: conn} } else { conn, err2 := d.DialContext(ctx1, "tcp", turnServerAddr) if err2 != nil { @@ -1091,7 +858,7 @@ func oneTurnConnection(ctx context.Context, turnParams *turnParams, peer *net.UD return } }() - wrappedConn := &splitFirstWriteConn{Conn: conn, splitAt: 6, delay: 20 * time.Millisecond} + wrappedConn := &netadapt.SplitFirstWriteConn{Conn: conn, SplitAt: 6, Delay: 20 * time.Millisecond} turnConn = turn.NewSTUNConn(wrappedConn) } var addrFamily turn.RequestedAddressFamily @@ -1105,7 +872,7 @@ func oneTurnConnection(ctx context.Context, turnParams *turnParams, peer *net.UD STUNServerAddr: turnServerAddr, TURNServerAddr: turnServerAddr, Conn: turnConn, - Net: newDirectNet(), + Net: netadapt.New(), Username: user, Password: pass, RequestedAddressFamily: addrFamily, @@ -1152,8 +919,8 @@ func oneTurnConnection(ctx context.Context, turnParams *turnParams, peer *net.UD wg := sync.WaitGroup{} turnctx, turncancel := context.WithCancel(ctx) - stats := &throughputStats{} - go stats.logEvery(turnctx, fmt.Sprintf("[STREAM %d] TURN", streamID), "to-turn", "from-turn") + st := stats.New(isDebug) + go st.LogEvery(turnctx, debugf, fmt.Sprintf("[STREAM %d] TURN", streamID), "to-turn", "from-turn") context.AfterFunc(turnctx, func() { if err := relayConn.SetDeadline(time.Now()); err != nil { @@ -1207,7 +974,7 @@ func oneTurnConnection(ctx context.Context, turnParams *turnParams, peer *net.UD } written, err1 := relayConn.WriteTo(out, peer) - stats.addTx(written) + st.AddTx(written) if err1 != nil { return } @@ -1242,7 +1009,7 @@ func oneTurnConnection(ctx context.Context, turnParams *turnParams, peer *net.UD } payload = plain[:m] } - stats.addRx(len(payload)) + st.AddRx(len(payload)) if _, err := conn2.WriteTo(payload, addr); err != nil { return } @@ -1604,22 +1371,6 @@ func (p *sessionPool) count() int { return len(p.sessions) } -const ( - bondVersion = 1 - bondMagic = "VLB1" - - bondFrameData byte = 1 - bondFrameFIN byte = 2 - - bondMaxChunk = 16 * 1024 -) - -type bondFrame struct { - typ byte - seq uint64 - data []byte -} - type bondClientLane struct { ps *pooledSession stream *smux.Stream @@ -1627,65 +1378,6 @@ type bondClientLane struct { dead atomic.Bool } -func writeBondHello(w io.Writer, connID uint64, laneIndex, laneCount uint16) error { - var hdr [17]byte - copy(hdr[0:4], bondMagic) - hdr[4] = bondVersion - binary.BigEndian.PutUint64(hdr[5:13], connID) - binary.BigEndian.PutUint16(hdr[13:15], laneIndex) - binary.BigEndian.PutUint16(hdr[15:17], laneCount) - _, err := w.Write(hdr[:]) - return err -} - -func writeBondFrame(w io.Writer, typ byte, seq uint64, data []byte) error { - var hdr [13]byte - hdr[0] = typ - binary.BigEndian.PutUint64(hdr[1:9], seq) - binary.BigEndian.PutUint32(hdr[9:13], uint32(len(data))) - if _, err := w.Write(hdr[:]); err != nil { - return err - } - if len(data) == 0 { - return nil - } - _, err := w.Write(data) - return err -} - -func readBondFrame(r io.Reader) (bondFrame, error) { - var hdr [13]byte - if _, err := io.ReadFull(r, hdr[:]); err != nil { - return bondFrame{}, err - } - size := binary.BigEndian.Uint32(hdr[9:13]) - if size > 4*1024*1024 { - return bondFrame{}, fmt.Errorf("bond frame too large: %d", size) - } - f := bondFrame{ - typ: hdr[0], - seq: binary.BigEndian.Uint64(hdr[1:9]), - } - if size > 0 { - f.data = make([]byte, size) - if _, err := io.ReadFull(r, f.data); err != nil { - return bondFrame{}, err - } - } - return f, nil -} - -func closeWrite(conn net.Conn) { - type closeWriter interface { - CloseWrite() error - } - if cw, ok := conn.(closeWriter); ok { - if err := cw.CloseWrite(); err != nil && isDebug { - log.Printf("CloseWrite failed: %v", err) - } - } -} - func handleBondedTCP(ctx context.Context, tcpConn net.Conn, connID uint64, candidates []*pooledSession) { defer func() { _ = tcpConn.Close() }() @@ -1703,7 +1395,7 @@ func handleBondedTCP(ctx context.Context, tcpConn net.Conn, connID uint64, candi log.Printf("[bond %d] session %d open stream error: %s", connID, ps.id, err) continue } - if err := writeBondHello(stream, connID, uint16(i), uint16(len(candidates))); err != nil { + if err := bond.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 @@ -1738,17 +1430,17 @@ func handleBondedTCP(ctx context.Context, tcpConn net.Conn, connID uint64, candi closed := lane.ps.closed.Add(1) debugf("[bond %d] lane session %d close active=%d closed=%d totals: to-session=%s from-session=%s", connID, lane.ps.id, active, closed, - formatByteCount(lane.ps.toSession.Load()), formatByteCount(lane.ps.fromSession.Load())) + stats.FormatByteCount(lane.ps.toSession.Load()), stats.FormatByteCount(lane.ps.fromSession.Load())) } }() - recvCh := make(chan bondFrame, 1024) + recvCh := make(chan bond.Frame, 1024) var readWG sync.WaitGroup for _, lane := range lanes { l := lane readWG.Go(func() { for { - f, err := readBondFrame(l.stream) + f, err := bond.ReadFrame(l.stream) if err != nil { l.dead.Store(true) select { @@ -1760,8 +1452,8 @@ func handleBondedTCP(ctx context.Context, tcpConn net.Conn, connID uint64, candi } return } - if f.typ == bondFrameData { - l.ps.fromSession.Add(uint64(len(f.data))) + if f.Type == bond.FrameData { + l.ps.fromSession.Add(uint64(len(f.Data))) } select { case recvCh <- f: @@ -1788,13 +1480,13 @@ func handleBondedTCP(ctx context.Context, tcpConn net.Conn, connID uint64, candi } func copyTCPToBond(ctx context.Context, connID uint64, tcpConn net.Conn, lanes []*bondClientLane) { - buf := make([]byte, bondMaxChunk) + buf := make([]byte, bond.MaxChunk) var seq uint64 var laneIdx uint64 for { n, err := tcpConn.Read(buf) if n > 0 { - lane, writeErr := writeBondFrameToNextLane(ctx, lanes, bondFrameData, seq, buf[:n], &laneIdx) + lane, writeErr := writeBondFrameToNextLane(ctx, lanes, bond.FrameData, seq, buf[:n], &laneIdx) if writeErr != nil { log.Printf("[bond %d] write data error: %v", connID, writeErr) return @@ -1811,7 +1503,7 @@ func copyTCPToBond(ctx context.Context, connID uint64, tcpConn net.Conn, lanes [ continue } lane.mu.Lock() - writeErr := writeBondFrame(lane.stream, bondFrameFIN, seq, nil) + writeErr := bond.WriteFrame(lane.stream, bond.FrameFIN, seq, nil) lane.mu.Unlock() if writeErr != nil && ctx.Err() == nil { log.Printf("[bond %d] session %d write FIN error: %v", connID, lane.ps.id, writeErr) @@ -1837,7 +1529,7 @@ func writeBondFrameToNextLane(ctx context.Context, lanes []*bondClientLane, typ continue } lane.mu.Lock() - err := writeBondFrame(lane.stream, typ, seq, data) + err := bond.WriteFrame(lane.stream, typ, seq, data) lane.mu.Unlock() if err == nil { return lane, nil @@ -1853,14 +1545,14 @@ func writeBondFrameToNextLane(ctx context.Context, lanes []*bondClientLane, typ return nil, fmt.Errorf("no live bond lanes") } -func copyBondToTCP(ctx context.Context, connID uint64, tcpConn net.Conn, recvCh <-chan bondFrame) { +func copyBondToTCP(ctx context.Context, connID uint64, tcpConn net.Conn, recvCh <-chan bond.Frame) { pending := make(map[uint64][]byte) var expect uint64 var finSeq *uint64 for { if finSeq != nil && expect == *finSeq { - closeWrite(tcpConn) + bond.CloseWrite(tcpConn, debugf) debugf("[bond %d] download finished chunks=%d", connID, expect) return } @@ -1872,20 +1564,20 @@ func copyBondToTCP(ctx context.Context, connID uint64, tcpConn net.Conn, recvCh if !ok { return } - switch f.typ { - case bondFrameData: + switch f.Type { + case bond.FrameData: if len(pending) >= 1024 { log.Printf("[bond %d] pending map overflow (>1024), closing", connID) return } - pending[f.seq] = f.data - case bondFrameFIN: - v := f.seq + pending[f.Seq] = f.Data + case bond.FrameFIN: + v := f.Seq if finSeq == nil || v < *finSeq { finSeq = &v } default: - log.Printf("[bond %d] unknown frame type %d", connID, f.typ) + log.Printf("[bond %d] unknown frame type %d", connID, f.Type) return } @@ -1908,7 +1600,7 @@ func copyBondToTCP(ctx context.Context, connID uint64, tcpConn net.Conn, recvCh } // runVLESSMode implements TCP forwarding with round-robin across N TURN sessions. -func runVLESSMode(ctx context.Context, tp *turnParams, peer *net.UDPAddr, listenAddr string, numSessions int, bond bool) { +func runVLESSMode(ctx context.Context, tp *turnParams, peer *net.UDPAddr, listenAddr string, numSessions int, useBond bool) { pool := &sessionPool{} // Start N session maintainers with staggered startup @@ -1950,7 +1642,7 @@ func runVLESSMode(ctx context.Context, tp *turnParams, peer *net.UDPAddr, listen } context.AfterFunc(ctx, func() { _ = wrappedListener.Close() }) - if bond { + if useBond { log.Printf("VLESS bond mode: listening on %s (striping each TCP connection across active sessions)", listenAddr) } else { log.Printf("VLESS mode: listening on %s (round-robin across %d sessions)", listenAddr, numSessions) @@ -1971,7 +1663,7 @@ func runVLESSMode(ctx context.Context, tp *turnParams, peer *net.UDPAddr, listen continue } - if bond { + if useBond { connID := (uint64(time.Now().UnixNano()) << 16) ^ pool.nextConnID() lanes := pool.snapshot() if len(lanes) == 0 { @@ -2008,7 +1700,7 @@ func runVLESSMode(ctx context.Context, tp *turnParams, peer *net.UDPAddr, listen closed := sessRef.closed.Add(1) debugf("[session %d] TCP close #%d active=%d closed=%d totals: to-session=%s from-session=%s", sessRef.id, cid, active, closed, - formatByteCount(sessRef.toSession.Load()), formatByteCount(sessRef.fromSession.Load())) + stats.FormatByteCount(sessRef.toSession.Load()), stats.FormatByteCount(sessRef.fromSession.Load())) }() stream, err := sessRef.sess.OpenStream() @@ -2021,7 +1713,7 @@ func runVLESSMode(ctx context.Context, tp *turnParams, peer *net.UDPAddr, listen sessRef.fromSession.Add(uint64(fromSession)) sessRef.toSession.Add(uint64(toSession)) debugf("[session %d] TCP done #%d local<-session=%s local->session=%s", - sessRef.id, cid, formatByteCount(uint64(fromSession)), formatByteCount(uint64(toSession))) + sessRef.id, cid, stats.FormatByteCount(uint64(fromSession)), stats.FormatByteCount(uint64(toSession))) }) } } @@ -2114,7 +1806,7 @@ func createSmuxSession(ctx context.Context, tp *turnParams, peer *net.UDPAddr, i return nil, nil, fmt.Errorf("dial TURN (udp): %w", err1) } cleanupFns = append(cleanupFns, func() { _ = c.Close() }) - turnConn = &connectedUDPConn{c} + turnConn = &netadapt.ConnectedUDPConn{UDPConn: c} } else { var d net.Dialer c, err1 := d.DialContext(ctx1, "tcp", turnServerAddr) @@ -2122,7 +1814,7 @@ 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() }) - wrappedC := &splitFirstWriteConn{Conn: c, splitAt: 6, delay: 20 * time.Millisecond} + wrappedC := &netadapt.SplitFirstWriteConn{Conn: c, SplitAt: 6, Delay: 20 * time.Millisecond} turnConn = turn.NewSTUNConn(wrappedC) } @@ -2137,7 +1829,7 @@ func createSmuxSession(ctx context.Context, tp *turnParams, peer *net.UDPAddr, i STUNServerAddr: turnServerAddr, TURNServerAddr: turnServerAddr, Conn: turnConn, - Net: newDirectNet(), + Net: netadapt.New(), Username: user, Password: pass, RequestedAddressFamily: addrFamily, @@ -2200,10 +1892,10 @@ func createSmuxSession(ctx context.Context, tp *turnParams, peer *net.UDPAddr, i // 5. Create KCP session over DTLS statsCtx, statsCancel := context.WithCancel(ctx) cleanupFns = append(cleanupFns, statsCancel) - stats := &throughputStats{} - go stats.logEvery(statsCtx, fmt.Sprintf("[session %d] VLESS", id), "to-turn", "from-turn") + st := stats.New(isDebug) + go st.LogEvery(statsCtx, debugf, fmt.Sprintf("[session %d] VLESS", id), "to-turn", "from-turn") - kcpSess, err := tcputil.NewKCPOverDTLS(&countingConn{Conn: dtlsConn, stats: stats}, false) + kcpSess, err := tcputil.NewKCPOverDTLS(&stats.CountingConn{Conn: dtlsConn, Stats: st}, false) if err != nil { cleanup() return nil, nil, fmt.Errorf("KCP session: %w", err) diff --git a/internal/bond/frame.go b/internal/bond/frame.go new file mode 100644 index 0000000..8ba7672 --- /dev/null +++ b/internal/bond/frame.go @@ -0,0 +1,133 @@ +// 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 + +import ( + "encoding/binary" + "fmt" + "io" + "net" + "time" +) + +const ( + Version uint8 = 1 + Magic = "VLB1" + + FrameData byte = 1 + FrameFIN byte = 2 + + MaxChunk = 16 * 1024 + + LaneAttachTimeout = 300 * time.Millisecond +) + +// Hello is the per-lane handshake header sent right after a smux stream opens. +type Hello struct { + ConnID uint64 + LaneIndex uint16 + LaneCount uint16 +} + +// Frame is a single bonded data or FIN unit, identified by Seq within a ConnID. +type Frame struct { + Type byte + Seq uint64 + Data []byte +} + +// WriteHello encodes and writes a Hello to w using the bond wire format. +func WriteHello(w io.Writer, connID uint64, laneIndex, laneCount uint16) error { + var hdr [17]byte + copy(hdr[0:4], Magic) + hdr[4] = Version + binary.BigEndian.PutUint64(hdr[5:13], connID) + binary.BigEndian.PutUint16(hdr[13:15], laneIndex) + binary.BigEndian.PutUint16(hdr[15:17], laneCount) + _, err := w.Write(hdr[:]) + return err +} + +// ReadHelloAfterMagic finishes reading a Hello whose first 4 magic bytes have +// already been consumed (server pre-peeks the magic to multiplex protocols). +func ReadHelloAfterMagic(r io.Reader, magic [4]byte) (Hello, error) { + var hdr [17]byte + copy(hdr[0:4], magic[:]) + if _, err := io.ReadFull(r, hdr[4:]); err != nil { + return Hello{}, err + } + return ParseHelloHeader(hdr[:]) +} + +// ParseHelloHeader decodes a 17-byte Hello header from hdr. +func ParseHelloHeader(hdr []byte) (Hello, error) { + if len(hdr) != 17 { + return Hello{}, fmt.Errorf("bad bond hello size: %d", len(hdr)) + } + if string(hdr[0:4]) != Magic { + return Hello{}, fmt.Errorf("bad bond magic") + } + if hdr[4] != Version { + return Hello{}, fmt.Errorf("unsupported bond version: %d", hdr[4]) + } + return Hello{ + ConnID: binary.BigEndian.Uint64(hdr[5:13]), + LaneIndex: binary.BigEndian.Uint16(hdr[13:15]), + LaneCount: binary.BigEndian.Uint16(hdr[15:17]), + }, nil +} + +// WriteFrame writes a single Frame to w (header + payload). +func WriteFrame(w io.Writer, typ byte, seq uint64, data []byte) error { + var hdr [13]byte + hdr[0] = typ + binary.BigEndian.PutUint64(hdr[1:9], seq) + binary.BigEndian.PutUint32(hdr[9:13], uint32(len(data))) + if _, err := w.Write(hdr[:]); err != nil { + return err + } + if len(data) == 0 { + return nil + } + _, err := w.Write(data) + return err +} + +// ReadFrame reads one Frame from r. Payloads over 4 MiB are rejected. +func ReadFrame(r io.Reader) (Frame, error) { + var hdr [13]byte + if _, err := io.ReadFull(r, hdr[:]); err != nil { + return Frame{}, err + } + size := binary.BigEndian.Uint32(hdr[9:13]) + if size > 4*1024*1024 { + return Frame{}, fmt.Errorf("bond frame too large: %d", size) + } + f := Frame{ + Type: hdr[0], + Seq: binary.BigEndian.Uint64(hdr[1:9]), + } + if size > 0 { + f.Data = make([]byte, size) + if _, err := io.ReadFull(r, f.Data); err != nil { + return Frame{}, err + } + } + return f, nil +} + +// CloseWrite half-closes the write side of conn if the underlying type +// supports it (TCPConn, smux.Stream, …); otherwise it is a no-op. errf is +// invoked with the error if CloseWrite fails; callers typically pass a +// debug-gated log func. +func CloseWrite(conn net.Conn, errf func(format string, v ...any)) { + type closeWriter interface { + CloseWrite() error + } + if cw, ok := conn.(closeWriter); ok { + if err := cw.CloseWrite(); err != nil && errf != nil { + errf("CloseWrite failed: %v", err) + } + } +} diff --git a/internal/bond/frame_test.go b/internal/bond/frame_test.go new file mode 100644 index 0000000..967066a --- /dev/null +++ b/internal/bond/frame_test.go @@ -0,0 +1,128 @@ +package bond + +import ( + "bytes" + "encoding/binary" + "io" + "testing" +) + +func TestHelloRoundTrip(t *testing.T) { + t.Parallel() + + var buf bytes.Buffer + if err := WriteHello(&buf, 0xCAFEBABEDEADBEEF, 3, 7); err != nil { + t.Fatalf("WriteHello: %v", err) + } + if buf.Len() != 17 { + t.Fatalf("hello size = %d, want 17", buf.Len()) + } + + var magic [4]byte + copy(magic[:], buf.Bytes()[:4]) + if string(magic[:]) != Magic { + t.Fatalf("magic = %q, want %q", magic, Magic) + } + + // Consume magic to simulate the server pre-peek path. + buf.Next(4) + got, err := ReadHelloAfterMagic(&buf, magic) + if err != nil { + t.Fatalf("ReadHelloAfterMagic: %v", err) + } + want := Hello{ConnID: 0xCAFEBABEDEADBEEF, LaneIndex: 3, LaneCount: 7} + if got != want { + t.Fatalf("hello = %+v, want %+v", got, want) + } +} + +func TestParseHelloHeader_BadInputs(t *testing.T) { + t.Parallel() + + if _, err := ParseHelloHeader(make([]byte, 16)); err == nil { + t.Errorf("short header should fail") + } + + bad := make([]byte, 17) + copy(bad[0:4], "XXXX") + if _, err := ParseHelloHeader(bad); err == nil { + t.Errorf("bad magic should fail") + } + + bad = make([]byte, 17) + copy(bad[0:4], Magic) + bad[4] = 99 + if _, err := ParseHelloHeader(bad); err == nil { + t.Errorf("unsupported version should fail") + } +} + +func TestFrameRoundTrip(t *testing.T) { + t.Parallel() + + cases := []Frame{ + {Type: FrameData, Seq: 0, Data: []byte("hello")}, + {Type: FrameData, Seq: 0xFFFFFFFFFFFFFFFF, Data: bytes.Repeat([]byte{0xAB}, 1500)}, + {Type: FrameFIN, Seq: 42, Data: nil}, + } + for _, want := range cases { + var buf bytes.Buffer + if err := WriteFrame(&buf, want.Type, want.Seq, want.Data); err != nil { + t.Fatalf("WriteFrame: %v", err) + } + got, err := ReadFrame(&buf) + if err != nil { + t.Fatalf("ReadFrame: %v", err) + } + if got.Type != want.Type || got.Seq != want.Seq || !bytes.Equal(got.Data, want.Data) { + t.Fatalf("frame = %+v, want %+v", got, want) + } + } +} + +func TestReadFrame_RejectsOversize(t *testing.T) { + t.Parallel() + + var buf bytes.Buffer + var hdr [13]byte + hdr[0] = FrameData + binary.BigEndian.PutUint32(hdr[9:13], 4*1024*1024+1) + buf.Write(hdr[:]) + if _, err := ReadFrame(&buf); err == nil { + t.Fatalf("oversize frame should be rejected") + } +} + +func TestReadFrame_TruncatedHeader(t *testing.T) { + t.Parallel() + + buf := bytes.NewReader([]byte{1, 2, 3}) + _, err := ReadFrame(buf) + if err == nil { + t.Fatalf("truncated header should fail") + } +} + +func TestReadFrame_TruncatedPayload(t *testing.T) { + t.Parallel() + + var buf bytes.Buffer + if err := WriteFrame(&buf, FrameData, 1, []byte("hello world")); err != nil { + t.Fatalf("WriteFrame: %v", err) + } + truncated := buf.Bytes()[:13+5] // header + 5 of 11 payload bytes + if _, err := ReadFrame(bytes.NewReader(truncated)); err == nil { + t.Fatalf("truncated payload should fail") + } +} + +// Sanity: ReadHelloAfterMagic surfaces underlying EOF, not a silent zero. +func TestReadHelloAfterMagic_EOF(t *testing.T) { + t.Parallel() + + var magic [4]byte + copy(magic[:], Magic) + if _, err := ReadHelloAfterMagic(bytes.NewReader(nil), magic); err == nil || err == io.ErrShortBuffer { + t.Fatalf("expected EOF-like error, got %v", err) + } +} diff --git a/internal/netadapt/netadapt.go b/internal/netadapt/netadapt.go new file mode 100644 index 0000000..c156d58 --- /dev/null +++ b/internal/netadapt/netadapt.go @@ -0,0 +1,150 @@ +// Package netadapt 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 + +import ( + "context" + "fmt" + "net" + "sync/atomic" + "time" + + "github.com/pion/transport/v4" +) + +// DirectNet implements transport.Net by delegating to the std net package. +type DirectNet struct{} + +// New returns a transport.Net that delegates to the standard net package. +func New() transport.Net { + return DirectNet{} +} + +type directDialer struct { + *net.Dialer +} + +type directListenConfig struct { + *net.ListenConfig +} + +type directTCPListener struct { + *net.TCPListener +} + +func (DirectNet) ListenPacket(network string, address string) (net.PacketConn, error) { + return net.ListenPacket(network, address) +} + +func (DirectNet) ListenUDP(network string, locAddr *net.UDPAddr) (transport.UDPConn, error) { + return net.ListenUDP(network, locAddr) +} + +func (DirectNet) ListenTCP(network string, laddr *net.TCPAddr) (transport.TCPListener, error) { + listener, err := net.ListenTCP(network, laddr) + if err != nil { + return nil, err + } + return directTCPListener{listener}, nil +} + +func (DirectNet) Dial(network, address string) (net.Conn, error) { + return net.Dial(network, address) +} + +func (DirectNet) DialUDP(network string, laddr, raddr *net.UDPAddr) (transport.UDPConn, error) { + return net.DialUDP(network, laddr, raddr) +} + +func (DirectNet) DialTCP(network string, laddr, raddr *net.TCPAddr) (transport.TCPConn, error) { + return net.DialTCP(network, laddr, raddr) +} + +func (DirectNet) ResolveIPAddr(network, address string) (*net.IPAddr, error) { + return net.ResolveIPAddr(network, address) +} + +func (DirectNet) ResolveUDPAddr(network, address string) (*net.UDPAddr, error) { + return net.ResolveUDPAddr(network, address) +} + +func (DirectNet) ResolveTCPAddr(network, address string) (*net.TCPAddr, error) { + return net.ResolveTCPAddr(network, address) +} + +func (DirectNet) Interfaces() ([]*transport.Interface, error) { + return nil, transport.ErrNotSupported +} + +func (DirectNet) InterfaceByIndex(index int) (*transport.Interface, error) { + return nil, fmt.Errorf("%w: index=%d", transport.ErrInterfaceNotFound, index) +} + +func (DirectNet) InterfaceByName(name string) (*transport.Interface, error) { + return nil, fmt.Errorf("%w: %s", transport.ErrInterfaceNotFound, name) +} + +func (DirectNet) CreateDialer(dialer *net.Dialer) transport.Dialer { + return directDialer{Dialer: dialer} +} + +func (DirectNet) CreateListenConfig(listenerConfig *net.ListenConfig) transport.ListenConfig { + return directListenConfig{ListenConfig: listenerConfig} +} + +func (d directDialer) Dial(network, address string) (net.Conn, error) { + return d.Dialer.Dial(network, address) +} + +func (d directListenConfig) Listen(ctx context.Context, network, address string) (net.Listener, error) { + return d.ListenConfig.Listen(ctx, network, address) +} + +func (d directListenConfig) ListenPacket(ctx context.Context, network, address string) (net.PacketConn, error) { + return d.ListenConfig.ListenPacket(ctx, network, address) +} + +func (l directTCPListener) AcceptTCP() (transport.TCPConn, error) { + return l.TCPListener.AcceptTCP() +} + +// ConnectedUDPConn lets a dialed (connected) *net.UDPConn satisfy +// net.PacketConn semantics: WriteTo ignores the destination since the kernel +// already has it from connect(). +type ConnectedUDPConn struct { + *net.UDPConn +} + +// WriteTo discards the addr (UDP is already connected) and writes p. +func (c *ConnectedUDPConn) WriteTo(p []byte, _ net.Addr) (int, error) { + return c.Write(p) +} + +// SplitFirstWriteConn wraps a TCP net.Conn and splits the very first Write +// into two segments (SplitAt bytes + remainder) with an optional Delay between +// them. This breaks DPI rules that match a fixed offset in the first segment +// without TCP reassembly (e.g. the STUN magic cookie at offset 4-7). +type SplitFirstWriteConn struct { + net.Conn + SplitAt int + Delay time.Duration + done atomic.Bool +} + +// Write performs the one-shot split on the first call, then forwards directly. +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) +} diff --git a/internal/netadapt/netadapt_test.go b/internal/netadapt/netadapt_test.go new file mode 100644 index 0000000..e9a60fb --- /dev/null +++ b/internal/netadapt/netadapt_test.go @@ -0,0 +1,116 @@ +package netadapt + +import ( + "bytes" + "net" + "sync" + "testing" + "time" +) + +// pipeRecorder is a net.Conn that records the slice handed to each Write. +type pipeRecorder struct { + net.Conn + mu sync.Mutex + writes [][]byte +} + +func (p *pipeRecorder) Write(b []byte) (int, error) { + p.mu.Lock() + cp := make([]byte, len(b)) + copy(cp, b) + p.writes = append(p.writes, cp) + p.mu.Unlock() + return len(b), nil +} + +func newRecorder() *pipeRecorder { + a, b := net.Pipe() + go func() { _ = b.Close() }() + _ = a + return &pipeRecorder{Conn: dummyConn{}} +} + +type dummyConn struct{ net.Conn } + +func (dummyConn) Close() error { return nil } +func (dummyConn) LocalAddr() net.Addr { return nil } +func (dummyConn) RemoteAddr() net.Addr { return nil } +func (dummyConn) SetDeadline(time.Time) error { return nil } +func (dummyConn) SetReadDeadline(time.Time) error { return nil } +func (dummyConn) SetWriteDeadline(time.Time) error { return nil } +func (dummyConn) Read(b []byte) (int, error) { return 0, nil } + +func TestSplitFirstWriteConn_SplitsFirstWrite(t *testing.T) { + t.Parallel() + + rec := newRecorder() + c := &SplitFirstWriteConn{Conn: rec, SplitAt: 6} + payload := []byte("ABCDEF01234567") + n, err := c.Write(payload) + if err != nil { + t.Fatalf("Write err: %v", err) + } + if n != len(payload) { + t.Fatalf("Write n=%d want %d", n, len(payload)) + } + if len(rec.writes) != 2 { + t.Fatalf("expected 2 underlying writes, got %d", len(rec.writes)) + } + if !bytes.Equal(rec.writes[0], payload[:6]) { + t.Fatalf("first segment = %q, want %q", rec.writes[0], payload[:6]) + } + if !bytes.Equal(rec.writes[1], payload[6:]) { + t.Fatalf("second segment = %q, want %q", rec.writes[1], payload[6:]) + } +} + +func TestSplitFirstWriteConn_SubsequentWritesPassThrough(t *testing.T) { + t.Parallel() + + rec := newRecorder() + c := &SplitFirstWriteConn{Conn: rec, SplitAt: 6} + if _, err := c.Write([]byte("ABCDEF01234567")); err != nil { + t.Fatalf("first Write: %v", err) + } + if _, err := c.Write([]byte("XYZXYZ")); err != nil { + t.Fatalf("second Write: %v", err) + } + if len(rec.writes) != 3 { + t.Fatalf("expected 3 underlying writes after second call (2+1), got %d", len(rec.writes)) + } + if !bytes.Equal(rec.writes[2], []byte("XYZXYZ")) { + t.Fatalf("third write = %q, want XYZXYZ", rec.writes[2]) + } +} + +func TestSplitFirstWriteConn_ShortFirstWriteNoSplit(t *testing.T) { + t.Parallel() + + rec := newRecorder() + c := &SplitFirstWriteConn{Conn: rec, SplitAt: 6} + if _, err := c.Write([]byte("ABC")); err != nil { // len < SplitAt + t.Fatalf("Write: %v", err) + } + if len(rec.writes) != 1 { + t.Fatalf("expected single underlying write, got %d", len(rec.writes)) + } + if !bytes.Equal(rec.writes[0], []byte("ABC")) { + t.Fatalf("write = %q, want ABC", rec.writes[0]) + } +} + +func TestSplitFirstWriteConn_DelayApplied(t *testing.T) { + t.Parallel() + + rec := newRecorder() + c := &SplitFirstWriteConn{Conn: rec, SplitAt: 4, Delay: 25 * time.Millisecond} + start := time.Now() + if _, err := c.Write([]byte("ABCDEFGH")); err != nil { + t.Fatalf("Write: %v", err) + } + elapsed := time.Since(start) + if elapsed < 20*time.Millisecond { + t.Fatalf("expected delay >= 20ms, got %v", elapsed) + } +} diff --git a/internal/stats/stats.go b/internal/stats/stats.go new file mode 100644 index 0000000..facb948 --- /dev/null +++ b/internal/stats/stats.go @@ -0,0 +1,130 @@ +// Package stats provides throughput counters and a counting net.Conn wrapper +// shared between the client and server binaries. +package stats + +import ( + "context" + "fmt" + "net" + "sync/atomic" + "time" +) + +// Stats tracks tx/rx byte counters. When Enabled is false, Add* are no-ops and +// LogEvery returns immediately, matching the original isDebug-gated behavior. +type Stats struct { + tx atomic.Uint64 + rx atomic.Uint64 + enabled bool +} + +// New returns a Stats with the given enabled flag. +func New(enabled bool) *Stats { + return &Stats{enabled: enabled} +} + +// AddTx records n bytes sent. +func (s *Stats) AddTx(n int) { + if !s.enabled || n <= 0 { + return + } + s.tx.Add(uint64(n)) +} + +// AddRx records n bytes received. +func (s *Stats) AddRx(n int) { + if !s.enabled || n <= 0 { + return + } + s.rx.Add(uint64(n)) +} + +// LogEvery emits a throughput summary every 5s via logf until ctx is canceled. +// No-op if Stats is disabled. +func (s *Stats) LogEvery(ctx context.Context, logf func(string, ...any), label, txName, rxName string) { + if !s.enabled { + return + } + + ticker := time.NewTicker(5 * time.Second) + defer ticker.Stop() + + var prevTx, prevRx uint64 + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + tx := s.tx.Load() + rx := s.rx.Load() + deltaTx := tx - prevTx + deltaRx := rx - prevRx + prevTx = tx + prevRx = rx + + if deltaTx == 0 && deltaRx == 0 { + continue + } + + logf( + "%s throughput: %s=%s %s=%s total_%s=%s total_%s=%s", + label, + txName, + FormatBitsPerSecond(deltaTx, 5*time.Second), + rxName, + FormatBitsPerSecond(deltaRx, 5*time.Second), + txName, + FormatByteCount(tx), + rxName, + FormatByteCount(rx), + ) + } + } +} + +// FormatBitsPerSecond renders a bandwidth value from a byte count and interval. +func FormatBitsPerSecond(bytes uint64, interval time.Duration) string { + if interval <= 0 { + interval = time.Second + } + + bps := float64(bytes*8) / interval.Seconds() + if bps >= 1_000_000 { + return fmt.Sprintf("%.2f Mbit/s", bps/1_000_000) + } + if bps >= 1_000 { + return fmt.Sprintf("%.1f kbit/s", bps/1_000) + } + return fmt.Sprintf("%.0f bit/s", bps) +} + +// FormatByteCount renders a human-readable byte count. +func FormatByteCount(bytes uint64) string { + if bytes >= 1024*1024 { + return fmt.Sprintf("%.2f MiB", float64(bytes)/(1024*1024)) + } + if bytes >= 1024 { + return fmt.Sprintf("%.1f KiB", float64(bytes)/1024) + } + return fmt.Sprintf("%d B", bytes) +} + +// CountingConn wraps a net.Conn and accumulates rx/tx byte counters in Stats. +type CountingConn struct { + net.Conn + Stats *Stats +} + +// Read reads from the underlying conn and updates rx counter. +func (c *CountingConn) Read(p []byte) (int, error) { + n, err := c.Conn.Read(p) + c.Stats.AddRx(n) + return n, err +} + +// Write writes to the underlying conn and updates tx counter. +func (c *CountingConn) Write(p []byte) (int, error) { + n, err := c.Conn.Write(p) + c.Stats.AddTx(n) + return n, err +} diff --git a/internal/stats/stats_test.go b/internal/stats/stats_test.go new file mode 100644 index 0000000..9154752 --- /dev/null +++ b/internal/stats/stats_test.go @@ -0,0 +1,86 @@ +package stats + +import ( + "strings" + "testing" + "time" +) + +func TestFormatBitsPerSecond(t *testing.T) { + t.Parallel() + + cases := []struct { + bytes uint64 + interval time.Duration + want string + }{ + {0, time.Second, "0 bit/s"}, + {125, time.Second, "1.0 kbit/s"}, // 1000 bit/s + {125_000, time.Second, "1.00 Mbit/s"}, // 1_000_000 bit/s + {50, time.Second, "400 bit/s"}, + {1_000_000, 5 * time.Second, "1.60 Mbit/s"}, + } + for _, c := range cases { + got := FormatBitsPerSecond(c.bytes, c.interval) + if got != c.want { + t.Errorf("FormatBitsPerSecond(%d, %s) = %q, want %q", c.bytes, c.interval, got, c.want) + } + } + + // interval <= 0 should not panic and should default to 1s. + if got := FormatBitsPerSecond(125, 0); !strings.Contains(got, "kbit/s") { + t.Errorf("zero interval fallback: got %q", got) + } +} + +func TestFormatByteCount(t *testing.T) { + t.Parallel() + + cases := []struct { + bytes uint64 + want string + }{ + {0, "0 B"}, + {1023, "1023 B"}, + {1024, "1.0 KiB"}, + {1024 * 1024, "1.00 MiB"}, + {2 * 1024 * 1024, "2.00 MiB"}, + } + for _, c := range cases { + got := FormatByteCount(c.bytes) + if got != c.want { + t.Errorf("FormatByteCount(%d) = %q, want %q", c.bytes, got, c.want) + } + } +} + +func TestStatsDisabledNoOp(t *testing.T) { + t.Parallel() + + s := New(false) + s.AddTx(1234) + s.AddRx(5678) + if got := s.tx.Load(); got != 0 { + t.Errorf("disabled AddTx leaked: tx=%d", got) + } + if got := s.rx.Load(); got != 0 { + t.Errorf("disabled AddRx leaked: rx=%d", got) + } +} + +func TestStatsEnabledAccumulates(t *testing.T) { + t.Parallel() + + s := New(true) + s.AddTx(100) + s.AddTx(50) + s.AddRx(7) + s.AddTx(-5) // negative: ignored + s.AddRx(0) // zero: ignored + if got := s.tx.Load(); got != 150 { + t.Errorf("tx=%d, want 150", got) + } + if got := s.rx.Load(); got != 7 { + t.Errorf("rx=%d, want 7", got) + } +} diff --git a/server/main.go b/server/main.go index 048b628..9e34e0e 100644 --- a/server/main.go +++ b/server/main.go @@ -3,7 +3,6 @@ package main import ( "context" "crypto/rand" - "encoding/binary" "encoding/hex" "flag" "fmt" @@ -13,10 +12,11 @@ import ( "os" "os/signal" "sync" - "sync/atomic" "syscall" "time" + "github.com/cacggghp/vk-turn-proxy/internal/bond" + "github.com/cacggghp/vk-turn-proxy/internal/stats" "github.com/cacggghp/vk-turn-proxy/tcputil" "github.com/pion/dtls/v3" "github.com/pion/dtls/v3/pkg/crypto/selfsign" @@ -172,206 +172,6 @@ func main() { } } -type throughputStats struct { - tx atomic.Uint64 - rx atomic.Uint64 -} - -func (s *throughputStats) addTx(n int) { - if !isDebug || n <= 0 { - return - } - s.tx.Add(uint64(n)) -} - -func (s *throughputStats) addRx(n int) { - if !isDebug || n <= 0 { - return - } - s.rx.Add(uint64(n)) -} - -func (s *throughputStats) logEvery(ctx context.Context, label, txName, rxName string) { - if !isDebug { - return - } - - ticker := time.NewTicker(5 * time.Second) - defer ticker.Stop() - - var prevTx, prevRx uint64 - for { - select { - case <-ctx.Done(): - return - case <-ticker.C: - tx := s.tx.Load() - rx := s.rx.Load() - deltaTx := tx - prevTx - deltaRx := rx - prevRx - prevTx = tx - prevRx = rx - - if deltaTx == 0 && deltaRx == 0 { - continue - } - - debugf( - "%s throughput: %s=%s %s=%s total_%s=%s total_%s=%s", - label, - txName, - formatBitsPerSecond(deltaTx, 5*time.Second), - rxName, - formatBitsPerSecond(deltaRx, 5*time.Second), - txName, - formatByteCount(tx), - rxName, - formatByteCount(rx), - ) - } - } -} - -func formatBitsPerSecond(bytes uint64, interval time.Duration) string { - if interval <= 0 { - interval = time.Second - } - - bps := float64(bytes*8) / interval.Seconds() - if bps >= 1_000_000 { - return fmt.Sprintf("%.2f Mbit/s", bps/1_000_000) - } - if bps >= 1_000 { - return fmt.Sprintf("%.1f kbit/s", bps/1_000) - } - return fmt.Sprintf("%.0f bit/s", bps) -} - -func formatByteCount(bytes uint64) string { - if bytes >= 1024*1024 { - return fmt.Sprintf("%.2f MiB", float64(bytes)/(1024*1024)) - } - if bytes >= 1024 { - return fmt.Sprintf("%.1f KiB", float64(bytes)/1024) - } - return fmt.Sprintf("%d B", bytes) -} - -type countingConn struct { - net.Conn - stats *throughputStats -} - -func (c *countingConn) Read(p []byte) (int, error) { - n, err := c.Conn.Read(p) - c.stats.addRx(n) - return n, err -} - -func (c *countingConn) Write(p []byte) (int, error) { - n, err := c.Conn.Write(p) - c.stats.addTx(n) - return n, err -} - -const ( - bondVersion = 1 - bondMagic = "VLB1" - - bondFrameData byte = 1 - bondFrameFIN byte = 2 - - bondMaxChunk = 16 * 1024 - - bondLaneAttachTimeout = 300 * time.Millisecond -) - -type bondHello struct { - connID uint64 - laneIndex uint16 - laneCount uint16 -} - -type bondFrame struct { - typ byte - seq uint64 - data []byte -} - -func readBondHelloAfterMagic(r io.Reader, magic [4]byte) (bondHello, error) { - var hdr [17]byte - copy(hdr[0:4], magic[:]) - if _, err := io.ReadFull(r, hdr[4:]); err != nil { - return bondHello{}, err - } - return parseBondHelloHeader(hdr[:]) -} - -func parseBondHelloHeader(hdr []byte) (bondHello, error) { - if len(hdr) != 17 { - return bondHello{}, fmt.Errorf("bad bond hello size: %d", len(hdr)) - } - if string(hdr[0:4]) != bondMagic { - return bondHello{}, fmt.Errorf("bad bond magic") - } - if hdr[4] != bondVersion { - return bondHello{}, fmt.Errorf("unsupported bond version: %d", hdr[4]) - } - return bondHello{ - connID: binary.BigEndian.Uint64(hdr[5:13]), - laneIndex: binary.BigEndian.Uint16(hdr[13:15]), - laneCount: binary.BigEndian.Uint16(hdr[15:17]), - }, nil -} - -func writeBondFrame(w io.Writer, typ byte, seq uint64, data []byte) error { - var hdr [13]byte - hdr[0] = typ - binary.BigEndian.PutUint64(hdr[1:9], seq) - binary.BigEndian.PutUint32(hdr[9:13], uint32(len(data))) - if _, err := w.Write(hdr[:]); err != nil { - return err - } - if len(data) == 0 { - return nil - } - _, err := w.Write(data) - return err -} - -func readBondFrame(r io.Reader) (bondFrame, error) { - var hdr [13]byte - if _, err := io.ReadFull(r, hdr[:]); err != nil { - return bondFrame{}, err - } - size := binary.BigEndian.Uint32(hdr[9:13]) - if size > 4*1024*1024 { - return bondFrame{}, fmt.Errorf("bond frame too large: %d", size) - } - f := bondFrame{ - typ: hdr[0], - seq: binary.BigEndian.Uint64(hdr[1:9]), - } - if size > 0 { - f.data = make([]byte, size) - if _, err := io.ReadFull(r, f.data); err != nil { - return bondFrame{}, err - } - } - return f, nil -} - -func closeWrite(conn net.Conn) { - type closeWriter interface { - CloseWrite() error - } - if cw, ok := conn.(closeWriter); ok { - if err := cw.CloseWrite(); err != nil { - debugf("CloseWrite failed: %v", err) - } - } -} - type bondServerLane struct { index uint16 stream *smux.Stream @@ -390,7 +190,7 @@ type bondServerConn struct { want uint16 ready chan struct{} - recvCh chan bondFrame + recvCh chan bond.Frame once sync.Once } @@ -415,7 +215,7 @@ func (r *bondRegistry) get(ctx context.Context, id uint64, connectAddr string) * cancel: cancel, done: make(chan struct{}), ready: make(chan struct{}, 1), - recvCh: make(chan bondFrame, 1024), + recvCh: make(chan bond.Frame, 1024), } r.conns[id] = c go func() { @@ -470,7 +270,7 @@ func (c *bondServerConn) removeLane(l *bondServerLane) int { } func (c *bondServerConn) waitForInitialLanes() { - timer := time.NewTimer(bondLaneAttachTimeout) + timer := time.NewTimer(bond.LaneAttachTimeout) defer timer.Stop() for { c.lanesMu.RLock() @@ -493,7 +293,7 @@ func (c *bondServerConn) waitForInitialLanes() { func (c *bondServerConn) readLane(l *bondServerLane) { for { - f, err := readBondFrame(l.stream) + f, err := bond.ReadFrame(l.stream) if err != nil { left := c.removeLane(l) select { @@ -563,7 +363,7 @@ func (c *bondServerConn) copyBondToBackend(backendConn net.Conn) { for { if finSeq != nil && expect == *finSeq { - closeWrite(backendConn) + bond.CloseWrite(backendConn, debugf) debugf("[bond %d] upload to backend finished chunks=%d", c.id, expect) return } @@ -572,16 +372,16 @@ func (c *bondServerConn) copyBondToBackend(backendConn net.Conn) { case <-c.ctx.Done(): return case f := <-c.recvCh: - switch f.typ { - case bondFrameData: - pending[f.seq] = f.data - case bondFrameFIN: - v := f.seq + switch f.Type { + case bond.FrameData: + pending[f.Seq] = f.Data + case bond.FrameFIN: + v := f.Seq if finSeq == nil || v < *finSeq { finSeq = &v } default: - log.Printf("[bond %d] unknown frame type %d", c.id, f.typ) + log.Printf("[bond %d] unknown frame type %d", c.id, f.Type) return } @@ -604,7 +404,7 @@ func (c *bondServerConn) copyBondToBackend(backendConn net.Conn) { } func (c *bondServerConn) copyBackendToBond(backendConn net.Conn) { - buf := make([]byte, bondMaxChunk) + buf := make([]byte, bond.MaxChunk) var seq uint64 var laneIdx uint64 for { @@ -612,7 +412,7 @@ func (c *bondServerConn) copyBackendToBond(backendConn net.Conn) { if n > 0 { data := make([]byte, n) copy(data, buf[:n]) - if writeErr := c.writeToNextLane(bondFrameData, seq, data, &laneIdx); writeErr != nil { + if writeErr := c.writeToNextLane(bond.FrameData, seq, data, &laneIdx); writeErr != nil { log.Printf("[bond %d] lane write data error: %v", c.id, writeErr) return } @@ -622,7 +422,7 @@ func (c *bondServerConn) copyBackendToBond(backendConn net.Conn) { lanes := c.snapshotLanes() for _, lane := range lanes { lane.mu.Lock() - writeErr := writeBondFrame(lane.stream, bondFrameFIN, seq, nil) + writeErr := bond.WriteFrame(lane.stream, bond.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) @@ -646,7 +446,7 @@ func (c *bondServerConn) writeToNextLane(typ byte, seq uint64, data []byte, lane lane := lanes[*laneIdx%uint64(len(lanes))] (*laneIdx)++ lane.mu.Lock() - err := writeBondFrame(lane.stream, typ, seq, data) + err := bond.WriteFrame(lane.stream, typ, seq, data) lane.mu.Unlock() if err == nil { return nil @@ -666,12 +466,12 @@ func (c *bondServerConn) writeToNextLane(typ byte, seq uint64, data []byte, lane } func handleBondServerStreamAfterMagic(ctx context.Context, stream *smux.Stream, connectAddr string, magic [4]byte) { - handleBondServerStreamWithHello(ctx, stream, connectAddr, func(r io.Reader) (bondHello, error) { - return readBondHelloAfterMagic(r, magic) + handleBondServerStreamWithHello(ctx, stream, connectAddr, func(r io.Reader) (bond.Hello, error) { + return bond.ReadHelloAfterMagic(r, magic) }) } -func handleBondServerStreamWithHello(ctx context.Context, stream *smux.Stream, connectAddr string, readHello func(io.Reader) (bondHello, error)) { +func handleBondServerStreamWithHello(ctx context.Context, stream *smux.Stream, connectAddr string, readHello func(io.Reader) (bond.Hello, error)) { defer func() { if err := stream.Close(); err != nil && err != smux.ErrGoAway { log.Printf("failed to close bond smux stream: %v", err) @@ -684,11 +484,11 @@ func handleBondServerStreamWithHello(ctx context.Context, stream *smux.Stream, c return } - conn := globalBondRegistry.get(ctx, hello.connID, connectAddr) + conn := globalBondRegistry.get(ctx, hello.ConnID, connectAddr) conn.addLane(&bondServerLane{ - index: hello.laneIndex, + index: hello.LaneIndex, stream: stream, - }, hello.laneCount) + }, hello.LaneCount) select { case <-ctx.Done(): @@ -725,9 +525,10 @@ func handleUDPConnection(ctx context.Context, conn net.Conn, connectAddr string) var wg sync.WaitGroup ctx2, cancel2 := context.WithCancel(ctx) - stats := &throughputStats{} - go stats.logEvery( + st := stats.New(isDebug) + go st.LogEvery( ctx2, + debugf, fmt.Sprintf("[DTLS %s]", conn.RemoteAddr()), "dtls-to-backend", "backend-to-dtls", @@ -765,7 +566,7 @@ func handleUDPConnection(ctx context.Context, conn net.Conn, connectAddr string) return } written, err1 := serverConn.Write(buf[:n]) - stats.addTx(written) + st.AddTx(written) if err1 != nil { log.Printf("Failed: %s", err1) return @@ -796,7 +597,7 @@ func handleUDPConnection(ctx context.Context, conn net.Conn, connectAddr string) return } written, err1 := conn.Write(buf[:n]) - stats.addRx(written) + st.AddRx(written) if err1 != nil { log.Printf("Failed: %s", err1) return @@ -808,19 +609,20 @@ func handleUDPConnection(ctx context.Context, conn net.Conn, connectAddr string) // handleVLESSConnection creates a KCP+smux session over DTLS and forwards // each smux stream as a TCP connection to the backend (Xray/VLESS). -func handleVLESSConnection(ctx context.Context, dtlsConn net.Conn, connectAddr string, bond bool) { +func handleVLESSConnection(ctx context.Context, dtlsConn net.Conn, connectAddr string, useBond bool) { // 1. Create KCP session over DTLS statsCtx, statsCancel := context.WithCancel(ctx) defer statsCancel() - stats := &throughputStats{} - go stats.logEvery( + st := stats.New(isDebug) + go st.LogEvery( statsCtx, + debugf, fmt.Sprintf("[VLESS %s]", dtlsConn.RemoteAddr()), "to-client", "from-client", ) - kcpSess, err := tcputil.NewKCPOverDTLS(&countingConn{Conn: dtlsConn, stats: stats}, true) + kcpSess, err := tcputil.NewKCPOverDTLS(&stats.CountingConn{Conn: dtlsConn, Stats: st}, true) if err != nil { log.Printf("KCP session error: %s", err) return @@ -868,12 +670,12 @@ func handleVLESSConnection(ctx context.Context, dtlsConn net.Conn, connectAddr s _ = s.Close() return } - if string(prefix[:]) == bondMagic { + if string(prefix[:]) == bond.Magic { debugf("auto-detected bond smux stream") handleBondServerStreamAfterMagic(ctx, s, connectAddr, prefix) return } - if bond { + if useBond { log.Printf("non-bond smux stream accepted while -vless-bond is enabled") }