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

+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")
}