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

+271
View File
@@ -0,0 +1,271 @@
// 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 tcpfwd.SessionPool. Frame wire-format lives in
// internal/bond; this package wires the local TCP <-> lanes copy loops.
package bondclient
import (
"context"
"fmt"
"io"
"log"
"net"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/cacggghp/vk-turn-proxy/internal/logx"
"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"
)
// Deps groups host-process dependencies needed by the bond client.
type Deps struct {
Log logx.Logger
}
func (d *Deps) log() logx.Logger {
if d.Log == nil {
return logx.Nop()
}
return d.Log
}
// 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 *tcpfwd.PooledSession
stream *smux.Stream
mu sync.Mutex
dead atomic.Bool
}
// Handle stripes the local TCP connection across all live candidate sessions.
// 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)
defer cancel()
lanes := make([]*lane, 0, len(candidates))
laneIDs := make([]string, 0, len(candidates))
for i, ps := range candidates {
if ps.Sess.IsClosed() {
continue
}
stream, err := ps.Sess.OpenStream()
if err != nil {
log.Printf("[bond %d] session %d open stream error: %s", connID, ps.ID, err)
continue
}
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
}
ps.Opened.Add(1)
ps.Active.Add(1)
lanes = append(lanes, &lane{ps: ps, stream: stream})
laneIDs = append(laneIDs, strconv.Itoa(ps.ID))
}
if len(lanes) == 0 {
log.Printf("[bond %d] no usable lanes, rejecting TCP from %s", connID, tcpConn.RemoteAddr())
return
}
context.AfterFunc(ctx, func() {
now := time.Now()
if err := tcpConn.SetDeadline(now); err != nil {
h.Deps.log().Debugf("[bond %d] local TCP deadline error: %v", connID, err)
}
for _, l := range lanes {
if err := l.stream.SetDeadline(now); err != nil {
h.Deps.log().Debugf("[bond %d] session %d stream deadline error: %v", connID, l.ps.ID, err)
}
}
})
h.Deps.log().Debugf("[bond %d] TCP accept from=%s lanes=%d [%s]", connID, tcpConn.RemoteAddr(), len(lanes), strings.Join(laneIDs, ","))
defer func() {
for _, l := range lanes {
_ = l.stream.Close()
active := l.ps.Active.Add(-1)
closed := l.ps.Closed.Add(1)
h.Deps.log().Debugf("[bond %d] lane session %d close active=%d closed=%d totals: to-session=%s from-session=%s",
connID, l.ps.ID, active, closed,
stats.FormatByteCount(l.ps.ToSession.Load()), stats.FormatByteCount(l.ps.FromSession.Load()))
}
}()
recvCh := make(chan bondframe.Frame, 1024)
var readWG sync.WaitGroup
for _, l := range lanes {
readWG.Go(func() {
for {
f, err := bondframe.ReadFrame(l.stream)
if err != nil {
l.dead.Store(true)
select {
case <-ctx.Done():
default:
if err != io.EOF {
h.Deps.log().Debugf("[bond %d] session %d read frame error: %v", connID, l.ps.ID, err)
}
}
return
}
if f.Type == bondframe.FrameData {
l.ps.FromSession.Add(uint64(len(f.Data)))
}
select {
case recvCh <- f:
case <-ctx.Done():
return
}
}
})
}
go func() {
readWG.Wait()
close(recvCh)
}()
var wg sync.WaitGroup
wg.Go(func() {
h.copyTCPToBond(ctx, connID, tcpConn, lanes)
})
wg.Go(func() {
h.copyBondToTCP(ctx, connID, tcpConn, recvCh)
cancel()
})
wg.Wait()
}
func (h *Handler) copyTCPToBond(ctx context.Context, connID uint64, tcpConn net.Conn, lanes []*lane) {
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, bondframe.FrameData, seq, buf[:n], &laneIdx)
if writeErr != nil {
log.Printf("[bond %d] write data error: %v", connID, writeErr)
return
}
l.ps.ToSession.Add(uint64(n))
seq++
}
if err != nil {
if err != io.EOF {
h.Deps.log().Debugf("[bond %d] local TCP read finished with error: %v", connID, err)
}
for _, l := range lanes {
if l.dead.Load() {
continue
}
l.mu.Lock()
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)
}
}
h.Deps.log().Debugf("[bond %d] upload finished chunks=%d", connID, seq)
return
}
select {
case <-ctx.Done():
return
default:
}
}
}
func writeBondFrameToNextLane(ctx context.Context, lanes []*lane, typ byte, seq uint64, data []byte, laneIdx *uint64) (*lane, error) {
for range lanes {
idx := *laneIdx % uint64(len(lanes))
*laneIdx++
l := lanes[idx]
if l.dead.Load() {
continue
}
l.mu.Lock()
err := bondframe.WriteFrame(l.stream, typ, seq, data)
l.mu.Unlock()
if err == nil {
return l, nil
}
l.dead.Store(true)
if ctx.Err() != nil {
return nil, ctx.Err()
}
}
if ctx.Err() != nil {
return nil, ctx.Err()
}
return nil, fmt.Errorf("no live bond lanes")
}
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 {
bondframe.CloseWrite(tcpConn, h.Deps.log().Debugf)
h.Deps.log().Debugf("[bond %d] download finished chunks=%d", connID, expect)
return
}
select {
case <-ctx.Done():
return
case f, ok := <-recvCh:
if !ok {
return
}
switch f.Type {
case bondframe.FrameData:
if len(pending) >= 1024 {
log.Printf("[bond %d] pending map overflow (>1024), closing", connID)
return
}
pending[f.Seq] = f.Data
case bondframe.FrameFIN:
v := f.Seq
if finSeq == nil || v < *finSeq {
finSeq = &v
}
default:
log.Printf("[bond %d] unknown frame type %d", connID, f.Type)
return
}
for {
data, ok := pending[expect]
if !ok {
break
}
delete(pending, expect)
if len(data) > 0 {
if _, err := tcpConn.Write(data); err != nil {
log.Printf("[bond %d] local TCP write error: %v", connID, err)
return
}
}
expect++
}
}
}
}
+375
View File
@@ -0,0 +1,375 @@
// Package bondserver implements the server side of the bonded VLESS lane:
// a single backend TCP connection multiplexed across N smux streams that all
// share a ConnID. Frame wire-format lives in internal/bond; this package wires
// the backend TCP <-> lanes copy loops and the per-ConnID registry.
package bondserver
import (
"context"
"io"
"log"
"net"
"sync"
"time"
"github.com/cacggghp/vk-turn-proxy/internal/logx"
"github.com/cacggghp/vk-turn-proxy/internal/wire/bondframe"
"github.com/xtaci/smux"
)
// laneStream is the subset of *smux.Stream that serverLane needs. Defined as
// an interface so unit tests can inject in-memory pipes without spinning up a
// real smux session.
type laneStream interface {
io.Reader
io.Writer
SetDeadline(time.Time) error
}
// Deps groups host-process dependencies needed by the bond server.
type Deps struct {
Log logx.Logger
}
func (d *Deps) log() logx.Logger {
if d.Log == nil {
return logx.Nop()
}
return d.Log
}
// Registry deduplicates concurrent lanes that share a ConnID into a single
// backend TCP connection.
type Registry struct {
deps Deps
mu sync.Mutex
conns map[uint64]*serverConn
}
// NewRegistry creates an empty Registry.
func NewRegistry(deps Deps) *Registry {
return &Registry{deps: deps, conns: make(map[uint64]*serverConn)}
}
// HandleStreamAfterMagic accepts a smux stream whose first 4 magic bytes have
// 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) (bondframe.Hello, error) {
return bondframe.ReadHelloAfterMagic(rd, magic)
})
}
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)
}
}()
hello, err := readHello(stream)
if err != nil {
log.Printf("bond hello error: %v", err)
return
}
conn := r.get(ctx, hello.ConnID, connectAddr)
conn.addLane(&serverLane{
index: hello.LaneIndex,
stream: stream,
}, hello.LaneCount)
select {
case <-ctx.Done():
case <-conn.done:
}
}
func (r *Registry) get(ctx context.Context, id uint64, connectAddr string) *serverConn {
r.mu.Lock()
defer r.mu.Unlock()
if c := r.conns[id]; c != nil {
return c
}
connCtx, cancel := context.WithCancel(ctx)
c := &serverConn{
deps: &r.deps,
id: id,
connectAddr: connectAddr,
ctx: connCtx,
cancel: cancel,
done: make(chan struct{}),
ready: make(chan struct{}, 1),
recvCh: make(chan bondframe.Frame, 1024),
}
r.conns[id] = c
go func() {
<-c.done
r.mu.Lock()
if r.conns[id] == c {
delete(r.conns, id)
}
r.mu.Unlock()
}()
return c
}
type serverLane struct {
index uint16
stream laneStream
mu sync.Mutex
}
type serverConn struct {
deps *Deps
id uint64
connectAddr string
ctx context.Context
cancel context.CancelFunc
done chan struct{}
lanesMu sync.RWMutex
lanes []*serverLane
want uint16
ready chan struct{}
recvCh chan bondframe.Frame
once sync.Once
}
func (c *serverConn) addLane(l *serverLane, laneCount uint16) {
c.lanesMu.Lock()
if laneCount > c.want {
c.want = laneCount
}
c.lanes = append(c.lanes, l)
count := len(c.lanes)
c.lanesMu.Unlock()
c.deps.log().Debugf("[bond %d] lane %d attached (lanes=%d)", c.id, l.index, count)
select {
case c.ready <- struct{}{}:
default:
}
go c.readLane(l)
c.once.Do(func() {
go c.run()
})
}
func (c *serverConn) snapshotLanes() []*serverLane {
c.lanesMu.RLock()
defer c.lanesMu.RUnlock()
out := make([]*serverLane, len(c.lanes))
copy(out, c.lanes)
return out
}
func (c *serverConn) removeLane(l *serverLane) int {
c.lanesMu.Lock()
defer c.lanesMu.Unlock()
for i, lane := range c.lanes {
if lane == l {
c.lanes = append(c.lanes[:i], c.lanes[i+1:]...)
break
}
}
return len(c.lanes)
}
func (c *serverConn) waitForInitialLanes() {
timer := time.NewTimer(bondframe.LaneAttachTimeout)
defer timer.Stop()
for {
c.lanesMu.RLock()
count := len(c.lanes)
want := int(c.want)
c.lanesMu.RUnlock()
if want <= 0 || count >= want {
return
}
select {
case <-c.ctx.Done():
return
case <-c.ready:
case <-timer.C:
c.deps.log().Debugf("[bond %d] starting with %d/%d lanes after attach timeout", c.id, count, want)
return
}
}
}
func (c *serverConn) readLane(l *serverLane) {
for {
f, err := bondframe.ReadFrame(l.stream)
if err != nil {
left := c.removeLane(l)
select {
case <-c.ctx.Done():
default:
if err != io.EOF {
c.deps.log().Debugf("[bond %d] lane %d read error: %v (lanes=%d)", c.id, l.index, err, left)
}
if left == 0 {
c.cancel()
}
}
return
}
select {
case c.recvCh <- f:
case <-c.ctx.Done():
return
}
}
}
func (c *serverConn) run() {
defer close(c.done)
defer c.cancel()
c.waitForInitialLanes()
backendConn, err := net.DialTimeout("tcp", c.connectAddr, 10*time.Second)
if err != nil {
log.Printf("[bond %d] backend dial error: %s", c.id, err)
return
}
defer func() {
if err := backendConn.Close(); err != nil {
log.Printf("[bond %d] failed to close backend connection: %v", c.id, err)
}
}()
context.AfterFunc(c.ctx, func() {
now := time.Now()
if err := backendConn.SetDeadline(now); err != nil {
log.Printf("[bond %d] backend deadline error: %v", c.id, err)
}
for _, lane := range c.snapshotLanes() {
if err := lane.stream.SetDeadline(now); err != nil {
log.Printf("[bond %d] lane %d deadline error: %v", c.id, lane.index, err)
}
}
})
c.deps.log().Debugf("[bond %d] backend connected", c.id)
var wg sync.WaitGroup
wg.Go(func() {
c.copyBondToBackend(backendConn)
})
wg.Go(func() {
defer c.cancel()
c.copyBackendToBond(backendConn)
})
wg.Wait()
}
func (c *serverConn) copyBondToBackend(backendConn net.Conn) {
pending := make(map[uint64][]byte)
var expect uint64
var finSeq *uint64
for {
if finSeq != nil && expect == *finSeq {
bondframe.CloseWrite(backendConn, c.deps.log().Debugf)
c.deps.log().Debugf("[bond %d] upload to backend finished chunks=%d", c.id, expect)
return
}
select {
case <-c.ctx.Done():
return
case f := <-c.recvCh:
switch f.Type {
case bondframe.FrameData:
pending[f.Seq] = f.Data
case bondframe.FrameFIN:
v := f.Seq
if finSeq == nil || v < *finSeq {
finSeq = &v
}
default:
log.Printf("[bond %d] unknown frame type %d", c.id, f.Type)
return
}
for {
data, ok := pending[expect]
if !ok {
break
}
delete(pending, expect)
if len(data) > 0 {
if _, err := backendConn.Write(data); err != nil {
log.Printf("[bond %d] backend write error: %v", c.id, err)
return
}
}
expect++
}
}
}
}
func (c *serverConn) copyBackendToBond(backendConn net.Conn) {
buf := make([]byte, bondframe.MaxChunk)
var seq uint64
var laneIdx uint64
for {
n, err := backendConn.Read(buf)
if n > 0 {
data := make([]byte, n)
copy(data, buf[:n])
if writeErr := c.writeToNextLane(bondframe.FrameData, seq, data, &laneIdx); writeErr != nil {
log.Printf("[bond %d] lane write data error: %v", c.id, writeErr)
return
}
seq++
}
if err != nil {
lanes := c.snapshotLanes()
for _, lane := range lanes {
lane.mu.Lock()
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)
}
}
c.deps.log().Debugf("[bond %d] download from backend finished chunks=%d", c.id, seq)
return
}
select {
case <-c.ctx.Done():
return
default:
}
}
}
func (c *serverConn) writeToNextLane(typ byte, seq uint64, data []byte, laneIdx *uint64) error {
for {
lanes := c.snapshotLanes()
for range lanes {
lane := lanes[*laneIdx%uint64(len(lanes))]
*laneIdx++
lane.mu.Lock()
err := bondframe.WriteFrame(lane.stream, typ, seq, data)
lane.mu.Unlock()
if err == nil {
return nil
}
left := c.removeLane(lane)
log.Printf("[bond %d] lane %d write error: %v (lanes=%d)", c.id, lane.index, err, left)
if left == 0 {
return err
}
}
select {
case <-c.ctx.Done():
return c.ctx.Err()
case <-time.After(10 * time.Millisecond):
}
}
}
@@ -0,0 +1,273 @@
package bondserver
import (
"bytes"
"context"
"errors"
"io"
"net"
"sync"
"testing"
"time"
"github.com/cacggghp/vk-turn-proxy/internal/wire/bondframe"
)
// fakeStream implements laneStream over an in-memory ring; reads block when
// empty, writes go to a sink. SetDeadline is a no-op (tests cancel via ctx).
type fakeStream struct {
mu sync.Mutex
sink bytes.Buffer
writeFn func(p []byte) (int, error) // optional override
}
func newFakeStream() *fakeStream { return &fakeStream{} }
func (f *fakeStream) Read([]byte) (int, error) { return 0, io.EOF }
func (f *fakeStream) Write(p []byte) (int, error) {
if f.writeFn != nil {
return f.writeFn(p)
}
f.mu.Lock()
defer f.mu.Unlock()
return f.sink.Write(p)
}
func (f *fakeStream) SetDeadline(time.Time) error { return nil }
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 []bondframe.Frame
for {
fr, err := bondframe.ReadFrame(buf)
if err != nil {
if err == io.EOF {
return out
}
t.Fatalf("unexpected read err: %v", err)
}
out = append(out, fr)
}
}
func newTestConn(t *testing.T) *serverConn {
t.Helper()
deps := &Deps{}
ctx, cancel := context.WithCancel(t.Context())
t.Cleanup(cancel)
return &serverConn{
deps: deps,
id: 42,
ctx: ctx,
cancel: cancel,
done: make(chan struct{}),
ready: make(chan struct{}, 1),
recvCh: make(chan bondframe.Frame, 1024),
}
}
// TestCopyBondToBackendReorder pushes data frames out-of-seq + FIN and verifies
// backend receives bytes in seq order, then write side is closed.
func TestCopyBondToBackendReorder(t *testing.T) {
c := newTestConn(t)
backendA, backendB := net.Pipe()
defer backendA.Close()
defer backendB.Close()
collected := make(chan []byte, 1)
go func() {
var buf bytes.Buffer
_, err := io.Copy(&buf, backendB)
_ = err
collected <- buf.Bytes()
}()
done := make(chan struct{})
go func() {
c.copyBondToBackend(backendA)
_ = backendA.Close()
close(done)
}()
// out-of-order: seq 2, 0, FIN(3), 1
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:
case <-time.After(2 * time.Second):
t.Fatal("copyBondToBackend did not return after FIN")
}
got := <-collected
if string(got) != "ABC" {
t.Fatalf("backend got %q want %q", got, "ABC")
}
}
// TestCopyBondToBackendPendingDrains exercises the pending map: many gap
// frames buffered, then the missing one arrives and drains the whole run.
func TestCopyBondToBackendPendingDrains(t *testing.T) {
c := newTestConn(t)
backendA, backendB := net.Pipe()
defer backendA.Close()
defer backendB.Close()
collected := make(chan []byte, 1)
go func() {
var buf bytes.Buffer
_, err := io.Copy(&buf, backendB)
_ = err
collected <- buf.Bytes()
}()
done := make(chan struct{})
go func() {
c.copyBondToBackend(backendA)
_ = backendA.Close()
close(done)
}()
const N = 64
// push seq 1..N-1 first (all pending), then seq 0 to unlock the run.
for i := range N {
if i == 0 {
continue
}
c.recvCh <- bondframe.Frame{Type: bondframe.FrameData, Seq: uint64(i), Data: []byte{byte(i)}}
}
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:
case <-time.After(2 * time.Second):
t.Fatal("copyBondToBackend did not return after FIN")
}
got := <-collected
if len(got) != N {
t.Fatalf("backend got %d bytes want %d", len(got), N)
}
for i := range N {
if got[i] != byte(i) {
t.Fatalf("byte %d = %d want %d", i, got[i], i)
}
}
}
// TestWriteToNextLaneRoundRobin verifies frames rotate across lanes by index.
func TestWriteToNextLaneRoundRobin(t *testing.T) {
c := newTestConn(t)
l0 := &serverLane{index: 0, stream: newFakeStream()}
l1 := &serverLane{index: 1, stream: newFakeStream()}
l2 := &serverLane{index: 2, stream: newFakeStream()}
c.lanes = []*serverLane{l0, l1, l2}
var idx uint64
for seq := range 6 {
if err := c.writeToNextLane(bondframe.FrameData, uint64(seq), []byte{byte(seq)}, &idx); err != nil {
t.Fatalf("write seq %d: %v", seq, err)
}
}
for i, lane := range []*serverLane{l0, l1, l2} {
fs, ok := lane.stream.(*fakeStream)
if !ok {
t.Fatalf("lane %d stream not fakeStream", i)
}
frames := fs.writtenFrames(t)
if len(frames) != 2 {
t.Fatalf("lane %d got %d frames want 2", i, len(frames))
}
// lane i should hold seqs i and i+3
if frames[0].Seq != uint64(i) || frames[1].Seq != uint64(i+3) {
t.Fatalf("lane %d seqs %d,%d want %d,%d", i, frames[0].Seq, frames[1].Seq, i, i+3)
}
}
}
// TestWriteToNextLaneChurn drops a failing lane and continues on survivors.
func TestWriteToNextLaneChurn(t *testing.T) {
c := newTestConn(t)
good := newFakeStream()
bad := newFakeStream()
bad.writeFn = func(p []byte) (int, error) { return 0, errors.New("boom") }
l0 := &serverLane{index: 0, stream: bad}
l1 := &serverLane{index: 1, stream: good}
c.lanes = []*serverLane{l0, l1}
var idx uint64
for seq := range 4 {
if err := c.writeToNextLane(bondframe.FrameData, uint64(seq), []byte{byte(seq)}, &idx); err != nil {
t.Fatalf("seq %d: %v", seq, err)
}
}
// bad lane should be removed after first attempt.
if got := len(c.snapshotLanes()); got != 1 {
t.Fatalf("lanes after churn = %d want 1", got)
}
frames := good.writtenFrames(t)
if len(frames) != 4 {
t.Fatalf("survivor got %d frames want 4", len(frames))
}
for i, f := range frames {
if f.Seq != uint64(i) {
t.Fatalf("frame %d seq=%d want %d", i, f.Seq, i)
}
}
}
// TestWriteToNextLaneAllFail returns the underlying error when no lane survives.
func TestWriteToNextLaneAllFail(t *testing.T) {
c := newTestConn(t)
mk := func(idx uint16) *serverLane {
s := newFakeStream()
s.writeFn = func(p []byte) (int, error) { return 0, errors.New("boom") }
return &serverLane{index: idx, stream: s}
}
c.lanes = []*serverLane{mk(0), mk(1)}
var idx uint64
err := c.writeToNextLane(bondframe.FrameData, 0, []byte("x"), &idx)
if err == nil {
t.Fatal("expected error when all lanes fail")
}
if got := len(c.snapshotLanes()); got != 0 {
t.Fatalf("lanes after all-fail = %d want 0", got)
}
}
// TestRegistryGetDedup ensures concurrent get() calls for the same ConnID
// share one serverConn, and that completion removes it from the registry.
func TestRegistryGetDedup(t *testing.T) {
r := NewRegistry(Deps{})
ctx := t.Context()
c1 := r.get(ctx, 7, "127.0.0.1:1")
c2 := r.get(ctx, 7, "127.0.0.1:1")
if c1 != c2 {
t.Fatal("expected same conn for same id")
}
close(c1.done)
// give the cleanup goroutine a chance to run
deadline := time.Now().Add(time.Second)
for time.Now().Before(deadline) {
r.mu.Lock()
_, ok := r.conns[7]
r.mu.Unlock()
if !ok {
return
}
time.Sleep(5 * time.Millisecond)
}
t.Fatal("registry did not drop conn after done")
}
@@ -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)