break!: выпил tcp-режим туннеля
убраны флаги -mode и -bond: остался только udp-релей для wireguard. удалены tcpfwd, tcpfwdserver, bondclient, bondserver, bondframe, kcptun, wire/relay; proxy/common переехал в udprelay/dial. BREAKING CHANGE: флаги -mode и -bond удалены; конфиги и ссылки freeturn:// с tcp-режимом больше не принимаются.
This commit is contained in:
1 parent
648c55415b
commit
74241de764
53 files changed
+105
-2547
No files matched your search
@@ -43,14 +43,6 @@ func ClientArgs(c *Client) []string {
|
||||
if c.TURN.TransportUDP != def.TURN.TransportUDP {
|
||||
add("-transport", TransportUDP)
|
||||
}
|
||||
switch c.Proxy.Mode {
|
||||
case ProxyModeTCPFwd:
|
||||
add("-mode", ModeTCP)
|
||||
case ProxyModeTCPFwdBond:
|
||||
add("-mode", ModeTCP)
|
||||
args = append(args, "-bond")
|
||||
case ProxyModeUDP:
|
||||
}
|
||||
if c.Obf.Enabled() {
|
||||
add("-obf-profile", string(c.Obf.Profile))
|
||||
add("-obf-key", hex.EncodeToString(c.Obf.Key))
|
||||
|
||||
@@ -15,7 +15,6 @@ func TestClientArgsRoundTrip(t *testing.T) {
|
||||
args []string
|
||||
}{
|
||||
{"minimal", validClientArgs()},
|
||||
{"tcp bond", append(validClientArgs(), "-mode", "tcp", "-bond")},
|
||||
{"udp transport", append(validClientArgs(), "-transport", "udp")},
|
||||
{"obf", append(validClientArgs(), "-obf-profile", "rtpopus3", "-obf-key", testObfKey)},
|
||||
{"obf timing", append(validClientArgs(), "-obf-profile", "rtpopus", "-obf-key", testObfKey, "-obf-timing", "20ms")},
|
||||
|
||||
@@ -6,7 +6,6 @@ import (
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/transport/kcptun"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/uri"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/wire/rtpopus"
|
||||
)
|
||||
@@ -40,15 +39,13 @@ func ParseClient(args []string, errOut io.Writer) (*Client, error) {
|
||||
}
|
||||
fs.StringVar(&r.Turn, "turn", r.Turn, "IP TURN-сервера; override creds провайдера")
|
||||
fs.StringVar(&r.Port, "port", r.Port, "порт TURN-сервера; override creds провайдера")
|
||||
fs.StringVar(&r.Listen, "listen", r.Listen, "локальный ip:port для WireGuard/Xray клиента")
|
||||
fs.StringVar(&r.Listen, "listen", r.Listen, "локальный ip:port для WireGuard-клиента")
|
||||
fs.StringVar(&r.Provider, "provider", r.Provider, "источник TURN-creds: vk")
|
||||
fs.StringVar(&r.Link, "link", r.Link, "(устарел) одна ссылка VK Calls, используйте -links")
|
||||
fs.StringVar(&r.Links, "links", r.Links, "ссылки VK Calls через запятую: https://vk.ru/call/join/...,https://vk.ru/call/join/...")
|
||||
fs.StringVar(&r.Peer, "peer", r.Peer, "адрес сервера на VPS, host:port; обязательно")
|
||||
fs.IntVar(&r.N, "n", r.N, "число параллельных TURN-потоков")
|
||||
fs.StringVar(&r.Transport, "transport", r.Transport, "транспорт до TURN-реле: tcp | udp")
|
||||
fs.StringVar(&r.Mode, "mode", r.Mode, "режим туннеля: udp (WireGuard) | tcp (Xray/sing-box)")
|
||||
fs.BoolVar(&r.Bond, "bond", r.Bond, "страйпинг TCP по smux-сессиям; только с -mode tcp")
|
||||
fs.StringVar(&r.ObfProfile, "obf-profile", r.ObfProfile, "wire-профиль обфускации: none | rtpopus | rtpopus2 | rtpopus3; должен совпадать с сервером")
|
||||
fs.StringVar(&r.ObfKey, "obf-key", r.ObfKey, "ключ для -obf-profile != none: 32 байта hex (64 символа)")
|
||||
fs.BoolVar(&r.GenObfKey, "gen-obf-key", r.GenObfKey, "напечатать новый -obf-key и выйти")
|
||||
@@ -97,8 +94,7 @@ func ParseServer(args []string, errOut io.Writer) (*Server, error) {
|
||||
fs.SetOutput(errOut)
|
||||
}
|
||||
listen := fs.String("listen", def.Proxy.Listen, "локальный адрес прослушивания ip:port")
|
||||
connect := fs.String("connect", "", "локальный бэкенд host:port; обязательно: WG 127.0.0.1:51820 | Xray 127.0.0.1:443")
|
||||
mode := fs.String("mode", DefaultMode, "режим туннеля: udp (WireGuard) | tcp (Xray/sing-box; bond авто)")
|
||||
connect := fs.String("connect", "", "локальный бэкенд host:port; обязательно: WG 127.0.0.1:51820")
|
||||
obfProfile := fs.String("obf-profile", string(def.Obf.Profile), "wire-профиль обфускации: none | rtpopus | rtpopus2 | rtpopus3; должен совпадать с клиентом")
|
||||
obfKey := fs.String("obf-key", "", "ключ для -obf-profile != none: 32 байта hex (64 символа)")
|
||||
genObfKey := fs.Bool("gen-obf-key", false, "напечатать новый -obf-key и выйти")
|
||||
@@ -110,12 +106,6 @@ func ParseServer(args []string, errOut io.Writer) (*Server, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
switch *mode {
|
||||
case ModeUDP, ModeTCP:
|
||||
default:
|
||||
return nil, fmt.Errorf("invalid -mode value %q: must be %s | %s", *mode, ModeUDP, ModeTCP)
|
||||
}
|
||||
|
||||
s := &Server{
|
||||
Obf: ObfOpts{
|
||||
Profile: ObfProfile(*obfProfile),
|
||||
@@ -123,15 +113,10 @@ func ParseServer(args []string, errOut io.Writer) (*Server, error) {
|
||||
Timing: *obfTiming,
|
||||
},
|
||||
Proxy: ProxyOpts{
|
||||
Mode: serverProxyMode(*mode),
|
||||
Listen: *listen,
|
||||
Connect: *connect,
|
||||
},
|
||||
Log: LogOpts{Debug: *debug},
|
||||
KCP: KCPOpts{
|
||||
Profile: kcptun.DefaultProfile(),
|
||||
FEC: kcptun.FEC{},
|
||||
},
|
||||
Log: LogOpts{Debug: *debug},
|
||||
ClientsFile: *clientsFile,
|
||||
}
|
||||
|
||||
|
||||
@@ -4,19 +4,9 @@ package config
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/transport/kcptun"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/tunnel"
|
||||
)
|
||||
|
||||
// ProxyMode задаёт тип прикладного трафика в TURN-туннеле.
|
||||
type ProxyMode string
|
||||
|
||||
const (
|
||||
ProxyModeUDP ProxyMode = "udp" // -mode udp (default): UDP-релей пакетов (WireGuard)
|
||||
ProxyModeTCPFwd ProxyMode = "tcpfwd" // -mode tcp: TCP-форвардер через smux
|
||||
ProxyModeTCPFwdBond ProxyMode = "tcpfwd-bond" // -mode tcp -bond: bond TCP по N smux-сессиям
|
||||
)
|
||||
|
||||
type TURNOpts struct {
|
||||
Host string
|
||||
Port string
|
||||
@@ -44,7 +34,6 @@ type ObfOpts struct {
|
||||
func (o ObfOpts) Enabled() bool { return o.Profile != ObfProfileNone }
|
||||
|
||||
type ProxyOpts struct {
|
||||
Mode ProxyMode
|
||||
Listen string
|
||||
Connect string
|
||||
Peer string
|
||||
@@ -81,11 +70,6 @@ type LogOpts struct {
|
||||
Debug bool
|
||||
}
|
||||
|
||||
type KCPOpts struct {
|
||||
Profile kcptun.Profile
|
||||
FEC kcptun.FEC
|
||||
}
|
||||
|
||||
// TunnelOpts - параметры встроенного WireGuard/AmneziaWG userspace-туннеля.
|
||||
type TunnelOpts struct {
|
||||
Mode tunnel.Mode
|
||||
@@ -103,7 +87,6 @@ type Client struct {
|
||||
VK VKOpts
|
||||
DNS DNSOpts
|
||||
Log LogOpts
|
||||
KCP KCPOpts
|
||||
Tunnel TunnelOpts
|
||||
ClientID string
|
||||
SubURL string
|
||||
@@ -114,6 +97,5 @@ type Server struct {
|
||||
Obf ObfOpts
|
||||
Proxy ProxyOpts
|
||||
Log LogOpts
|
||||
KCP KCPOpts
|
||||
ClientsFile string
|
||||
}
|
||||
@@ -51,9 +51,6 @@ func TestParseClient_Defaults(t *testing.T) {
|
||||
if c.Obf.Enabled() {
|
||||
t.Errorf("Obf.Enabled() should be false when profile=none")
|
||||
}
|
||||
if c.Proxy.Mode != ProxyModeUDP {
|
||||
t.Errorf("Proxy.Mode default: %q (expected udp)", c.Proxy.Mode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseClient_VKLinkStrip(t *testing.T) {
|
||||
@@ -144,14 +141,6 @@ func TestParseClient_PlatformInvalid(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseClient_BondWithoutTCPMode(t *testing.T) {
|
||||
args := append(validClientArgs(), "-bond")
|
||||
_, err := ParseClient(args, io.Discard)
|
||||
if err == nil || !strings.Contains(err.Error(), "-bond requires -mode tcp") {
|
||||
t.Errorf("expected bond error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseClient_ObfMissingKey(t *testing.T) {
|
||||
args := append(validClientArgs(), "-obf-profile", "rtpopus")
|
||||
_, err := ParseClient(args, io.Discard)
|
||||
@@ -193,14 +182,6 @@ func TestParseClient_ObfTimingRequiresObf(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseClient_ObfTimingRejectsTCP(t *testing.T) {
|
||||
args := append(validClientArgs(), "-mode", "tcp", "-obf-profile", "rtpopus3", "-obf-key", testObfKey, "-obf-timing", "20ms")
|
||||
_, err := ParseClient(args, io.Discard)
|
||||
if err == nil || !strings.Contains(err.Error(), "-obf-timing") {
|
||||
t.Errorf("expected obf-timing/mode error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseClient_ObfTimingValid(t *testing.T) {
|
||||
args := append(validClientArgs(), "-obf-profile", "rtpopus3", "-obf-key", testObfKey, "-obf-timing", "20ms")
|
||||
c, err := ParseClient(args, io.Discard)
|
||||
@@ -212,14 +193,6 @@ func TestParseClient_ObfTimingValid(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseServer_ObfTimingRejectsTCP(t *testing.T) {
|
||||
args := []string{"-connect", "127.0.0.1:51820", "-mode", "tcp", "-obf-profile", "rtpopus3", "-obf-key", testObfKey, "-obf-timing", "10ms"}
|
||||
_, err := ParseServer(args, io.Discard)
|
||||
if err == nil || !strings.Contains(err.Error(), "-obf-timing") {
|
||||
t.Errorf("expected obf-timing/mode error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseClient_StreamsPerCredNonPositive(t *testing.T) {
|
||||
args := append(validClientArgs(), "-streams-per-cred", "0")
|
||||
_, err := ParseClient(args, io.Discard)
|
||||
@@ -276,31 +249,6 @@ func TestParseClient_HelpReturnsErrHelp(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseClient_ProxyMode(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
args []string
|
||||
want ProxyMode
|
||||
}{
|
||||
{"default-udp", nil, ProxyModeUDP},
|
||||
{"tcp", []string{"-mode", "tcp"}, ProxyModeTCPFwd},
|
||||
{"tcp-bond", []string{"-mode", "tcp", "-bond"}, ProxyModeTCPFwdBond},
|
||||
{"default-udp-no-bond", nil, ProxyModeUDP},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
args := append(validClientArgs(), tc.args...)
|
||||
c, err := ParseClient(args, io.Discard)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c.Proxy.Mode != tc.want {
|
||||
t.Errorf("Proxy.Mode = %q, want %q", c.Proxy.Mode, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseServer_Defaults(t *testing.T) {
|
||||
s, err := ParseServer([]string{"-connect", "backend:1234"}, io.Discard)
|
||||
if err != nil {
|
||||
@@ -312,9 +260,6 @@ func TestParseServer_Defaults(t *testing.T) {
|
||||
if s.Proxy.Connect != "backend:1234" {
|
||||
t.Errorf("Proxy.Connect: %q", s.Proxy.Connect)
|
||||
}
|
||||
if s.Proxy.Mode != ProxyModeUDP {
|
||||
t.Errorf("Proxy.Mode default: %q", s.Proxy.Mode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseServer_MissingConnect(t *testing.T) {
|
||||
@@ -368,12 +313,9 @@ func TestParseServer_GenObfKeySkipsConnectCheck(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseServer_ProxyMode(t *testing.T) {
|
||||
s, err := ParseServer([]string{"-connect", "x:1", "-mode", "tcp"}, io.Discard)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s.Proxy.Mode != ProxyModeTCPFwd {
|
||||
t.Errorf("Proxy.Mode = %q, want tcpfwd", s.Proxy.Mode)
|
||||
func TestParseServer_RejectsRemovedModeFlag(t *testing.T) {
|
||||
_, err := ParseServer([]string{"-connect", "x:1", "-mode", "tcp"}, io.Discard)
|
||||
if err == nil {
|
||||
t.Error("expected error on removed -mode flag")
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,10 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/transport/kcptun"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/tunnel"
|
||||
)
|
||||
import "github.com/samosvalishe/free-turn-proxy/internal/tunnel"
|
||||
|
||||
const (
|
||||
TransportTCP = "tcp"
|
||||
TransportUDP = "udp"
|
||||
|
||||
ModeUDP = "udp"
|
||||
ModeTCP = "tcp"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -24,7 +18,6 @@ const (
|
||||
DefaultStreams = 10
|
||||
DefaultStreamsPerCred = 10
|
||||
DefaultTransport = TransportTCP
|
||||
DefaultMode = ModeUDP
|
||||
DefaultDNSMode = DNSModeAuto
|
||||
DefaultProvider = ProviderVK
|
||||
DefaultPlatform = PlatformDesktop
|
||||
@@ -40,7 +33,6 @@ func defaultRaw() raw {
|
||||
N: DefaultStreams,
|
||||
StreamsPerCred: DefaultStreamsPerCred,
|
||||
Transport: DefaultTransport,
|
||||
Mode: DefaultMode,
|
||||
ObfProfile: string(DefaultObfProfile),
|
||||
Platform: string(DefaultPlatform),
|
||||
DNSMode: DefaultDNSMode,
|
||||
@@ -63,7 +55,6 @@ func Defaults() Client {
|
||||
func ServerDefaults() Server {
|
||||
return Server{
|
||||
Obf: ObfOpts{Profile: DefaultObfProfile},
|
||||
Proxy: ProxyOpts{Mode: ProxyModeUDP, Listen: DefaultServerListen},
|
||||
KCP: KCPOpts{Profile: kcptun.DefaultProfile()},
|
||||
Proxy: ProxyOpts{Listen: DefaultServerListen},
|
||||
}
|
||||
}
|
||||
@@ -17,9 +17,6 @@ func TestDefaultsAssemble(t *testing.T) {
|
||||
if d.TURN.TransportUDP {
|
||||
t.Error("TransportUDP must be false for default -transport tcp")
|
||||
}
|
||||
if d.Proxy.Mode != ProxyModeUDP {
|
||||
t.Errorf("Mode = %q, want %q", d.Proxy.Mode, ProxyModeUDP)
|
||||
}
|
||||
if d.DNS.Mode != DefaultDNSMode || d.VK.Platform != DefaultPlatform {
|
||||
t.Errorf("DNS.Mode = %q, Platform = %q", d.DNS.Mode, d.VK.Platform)
|
||||
}
|
||||
@@ -49,7 +46,7 @@ func TestServerDefaults(t *testing.T) {
|
||||
if d.Proxy.Listen != DefaultServerListen {
|
||||
t.Errorf("Listen = %q, want %q", d.Proxy.Listen, DefaultServerListen)
|
||||
}
|
||||
if d.Proxy.Mode != ProxyModeUDP || d.Obf.Enabled() {
|
||||
if d.Obf.Enabled() {
|
||||
t.Errorf("unexpected server defaults: %+v", d)
|
||||
}
|
||||
}
|
||||
@@ -61,7 +58,6 @@ func TestParseServerDefaultsMatchServerDefaults(t *testing.T) {
|
||||
}
|
||||
want := ServerDefaults()
|
||||
want.Proxy.Connect = parsed.Proxy.Connect
|
||||
want.KCP = parsed.KCP
|
||||
|
||||
if !reflect.DeepEqual(*parsed, want) {
|
||||
t.Errorf("ParseServer defaults differ from ServerDefaults():\n got %+v\nwant %+v", *parsed, want)
|
||||
|
||||
@@ -42,8 +42,6 @@ type turnJSON struct {
|
||||
}
|
||||
|
||||
type proxyJSON struct {
|
||||
Mode string `json:"mode"`
|
||||
Bond bool `json:"bond"`
|
||||
Listen string `json:"listen"`
|
||||
}
|
||||
|
||||
@@ -131,11 +129,7 @@ func defaultClientJSON() ClientJSON {
|
||||
Host: r.Turn,
|
||||
Port: r.Port,
|
||||
},
|
||||
Proxy: proxyJSON{
|
||||
Mode: r.Mode,
|
||||
Bond: r.Bond,
|
||||
Listen: r.Listen,
|
||||
},
|
||||
Proxy: proxyJSON{Listen: r.Listen},
|
||||
VK: vkJSON{
|
||||
StreamsPerCred: r.StreamsPerCred,
|
||||
ManualCaptcha: r.ManualCaptcha,
|
||||
@@ -169,8 +163,6 @@ func (j ClientJSON) toRaw() raw {
|
||||
N: j.TURN.N,
|
||||
StreamsPerCred: j.VK.StreamsPerCred,
|
||||
Transport: j.TURN.Transport,
|
||||
Mode: j.Proxy.Mode,
|
||||
Bond: j.Proxy.Bond,
|
||||
|
||||
ObfProfile: j.Obf.Profile,
|
||||
ObfKey: j.Obf.Key,
|
||||
|
||||
@@ -32,7 +32,7 @@ func TestParseClientJSONAppliesFields(t *testing.T) {
|
||||
"peer": "5.6.7.8:56000",
|
||||
"clientId": "abc",
|
||||
"turn": {"n": 3, "transport": "udp"},
|
||||
"proxy": {"mode": "tcp", "bond": true, "listen": "127.0.0.1:1080"},
|
||||
"proxy": {"listen": "127.0.0.1:1080"},
|
||||
"vk": {"links": ["A", "B"], "streamsPerCred": 4, "manualCaptcha": true, "platform": "mobile"},
|
||||
"obf": {"profile": "rtpopus3", "key": "` + testObfKey + `"},
|
||||
"dns": {"mode": "doh", "servers": ["1.1.1.1", "8.8.8.8"]},
|
||||
@@ -46,7 +46,7 @@ func TestParseClientJSONAppliesFields(t *testing.T) {
|
||||
if c.TURN.N != 3 || !c.TURN.TransportUDP {
|
||||
t.Errorf("TURN = %+v", c.TURN)
|
||||
}
|
||||
if c.Proxy.Mode != ProxyModeTCPFwdBond || c.Proxy.Listen != "127.0.0.1:1080" {
|
||||
if c.Proxy.Listen != "127.0.0.1:1080" {
|
||||
t.Errorf("Proxy = %+v", c.Proxy)
|
||||
}
|
||||
if len(c.VK.Links) != 2 || c.VK.Platform != PlatformMobile || !c.VK.ManualCaptcha {
|
||||
@@ -64,8 +64,8 @@ func TestParseClientJSONAppliesFields(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestParseClientJSONRunsValidate(t *testing.T) {
|
||||
in := `{"peer":"1.2.3.4:5000","vk":{"links":["A"]},"proxy":{"mode":"tcp"},` +
|
||||
`"obf":{"profile":"rtpopus3","key":"` + testObfKey + `","timingMs":20}}`
|
||||
in := `{"peer":"1.2.3.4:5000","vk":{"links":["A"]},` +
|
||||
`"obf":{"profile":"none","timingMs":20}}`
|
||||
_, err := ParseClientJSON([]byte(in), "")
|
||||
if err == nil || !strings.Contains(err.Error(), "-obf-timing") {
|
||||
t.Fatalf("ParseClientJSON() error = %v, want obf-timing rule", err)
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/transport/kcptun"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/tunnel"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/uri"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/wire/rtpopus"
|
||||
@@ -26,8 +24,6 @@ type raw struct {
|
||||
N int
|
||||
StreamsPerCred int
|
||||
Transport string
|
||||
Mode string
|
||||
Bond bool
|
||||
|
||||
ObfProfile string
|
||||
ObfKey string
|
||||
@@ -58,12 +54,6 @@ func (r *raw) applyURI(u *uri.Config) {
|
||||
if u.Transport != "" {
|
||||
r.Transport = u.Transport
|
||||
}
|
||||
if u.Mode != "" {
|
||||
r.Mode = u.Mode
|
||||
}
|
||||
if u.Bond {
|
||||
r.Bond = true
|
||||
}
|
||||
if u.N > 0 {
|
||||
r.N = u.N
|
||||
}
|
||||
@@ -102,15 +92,6 @@ func assemble(r raw) (*Client, error) {
|
||||
default:
|
||||
return nil, fmt.Errorf("invalid -transport value %q: must be %s | %s", r.Transport, TransportTCP, TransportUDP)
|
||||
}
|
||||
switch r.Mode {
|
||||
case ModeUDP, ModeTCP:
|
||||
default:
|
||||
return nil, fmt.Errorf("invalid -mode value %q: must be %s | %s", r.Mode, ModeUDP, ModeTCP)
|
||||
}
|
||||
if r.Bond && r.Mode != ModeTCP {
|
||||
return nil, errors.New("-bond requires -mode tcp")
|
||||
}
|
||||
|
||||
n := r.N
|
||||
if n <= 0 {
|
||||
n = DefaultStreams
|
||||
@@ -137,7 +118,6 @@ func assemble(r raw) (*Client, error) {
|
||||
Timing: r.ObfTiming,
|
||||
},
|
||||
Proxy: ProxyOpts{
|
||||
Mode: clientProxyMode(r.Mode, r.Bond),
|
||||
Listen: r.Listen,
|
||||
Peer: r.Peer,
|
||||
},
|
||||
@@ -150,10 +130,6 @@ func assemble(r raw) (*Client, error) {
|
||||
},
|
||||
DNS: DNSOpts{Mode: r.DNSMode},
|
||||
Log: LogOpts{Debug: r.Debug},
|
||||
KCP: KCPOpts{
|
||||
Profile: kcptun.DefaultProfile(),
|
||||
FEC: kcptun.FEC{},
|
||||
},
|
||||
Tunnel: TunnelOpts{
|
||||
Mode: tunnel.Mode(r.TunnelMode),
|
||||
Config: r.TunnelConfig,
|
||||
@@ -209,21 +185,3 @@ func normalizeVKLinks(links, link string) []string {
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func clientProxyMode(mode string, bond bool) ProxyMode {
|
||||
switch {
|
||||
case mode == ModeTCP && bond:
|
||||
return ProxyModeTCPFwdBond
|
||||
case mode == ModeTCP:
|
||||
return ProxyModeTCPFwd
|
||||
default:
|
||||
return ProxyModeUDP
|
||||
}
|
||||
}
|
||||
|
||||
func serverProxyMode(mode string) ProxyMode {
|
||||
if mode == ModeTCP {
|
||||
return ProxyModeTCPFwd
|
||||
}
|
||||
return ProxyModeUDP
|
||||
}
|
||||
@@ -41,8 +41,6 @@ func TestAssembleRejectsRawEnums(t *testing.T) {
|
||||
want string
|
||||
}{
|
||||
{"transport", func(r *raw) { r.Transport = "sctp" }, "invalid -transport"},
|
||||
{"mode", func(r *raw) { r.Mode = "quic" }, "invalid -mode"},
|
||||
{"bond without tcp", func(r *raw) { r.Bond = true }, "-bond requires"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
@@ -80,15 +78,13 @@ func TestApplyURIOverridesOnlyPresentFields(t *testing.T) {
|
||||
r.applyURI(&uri.Config{
|
||||
Peer: "uri-peer:2",
|
||||
Transport: TransportUDP,
|
||||
Mode: ModeTCP,
|
||||
Bond: true,
|
||||
N: 7,
|
||||
})
|
||||
|
||||
if r.Peer != "uri-peer:2" {
|
||||
t.Errorf("Peer = %q, want URI value", r.Peer)
|
||||
}
|
||||
if r.Transport != TransportUDP || r.Mode != ModeTCP || !r.Bond || r.N != 7 {
|
||||
if r.Transport != TransportUDP || r.N != 7 {
|
||||
t.Errorf("URI fields not applied: %+v", r)
|
||||
}
|
||||
if r.ClientID != "flag-id" || r.Links != "https://vk.ru/call/join/FROMFLAG" {
|
||||
@@ -100,12 +96,10 @@ func TestApplyURIIgnoresZeroValues(t *testing.T) {
|
||||
r := defaultRaw()
|
||||
r.N = 5
|
||||
r.StreamsPerCred = 3
|
||||
r.Bond = true
|
||||
r.Mode = ModeTCP
|
||||
|
||||
r.applyURI(&uri.Config{})
|
||||
|
||||
if r.N != 5 || r.StreamsPerCred != 3 || !r.Bond || r.Mode != ModeTCP {
|
||||
if r.N != 5 || r.StreamsPerCred != 3 {
|
||||
t.Errorf("empty URI must not reset fields: %+v", r)
|
||||
}
|
||||
}
|
||||
@@ -43,14 +43,13 @@ func Validate(c *Client) error {
|
||||
if err := validateObfProfile(c.Obf.Profile); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateTunnel(c.Tunnel, c.Proxy.Mode); err != nil {
|
||||
if err := validateTunnel(c.Tunnel); err != nil {
|
||||
return err
|
||||
}
|
||||
return validateObfTiming(c.Obf, c.Proxy.Mode)
|
||||
return validateObfTiming(c.Obf)
|
||||
}
|
||||
|
||||
// validateTunnel проверяет параметры userspace-туннеля (доступен только в mode udp).
|
||||
func validateTunnel(t TunnelOpts, mode ProxyMode) error {
|
||||
func validateTunnel(t TunnelOpts) error {
|
||||
if t.Mode != "" && !t.Mode.Valid() {
|
||||
return fmt.Errorf("invalid tunnel mode %q: must be %s | %s | %s",
|
||||
t.Mode, tunnel.ModeNone, tunnel.ModeWG, tunnel.ModeAWG)
|
||||
@@ -58,9 +57,6 @@ func validateTunnel(t TunnelOpts, mode ProxyMode) error {
|
||||
if !t.Enabled() {
|
||||
return nil
|
||||
}
|
||||
if mode != ProxyModeUDP {
|
||||
return errors.New("tunnel requires proxy mode udp")
|
||||
}
|
||||
if strings.TrimSpace(t.Config) == "" {
|
||||
return errors.New("tunnel config is required")
|
||||
}
|
||||
@@ -80,20 +76,16 @@ func ValidateServer(s *Server) error {
|
||||
if err := validateObfProfile(s.Obf.Profile); err != nil {
|
||||
return err
|
||||
}
|
||||
return validateObfTiming(s.Obf, s.Proxy.Mode)
|
||||
return validateObfTiming(s.Obf)
|
||||
}
|
||||
|
||||
// validateObfTiming проверяет pacing (только для режима udp с включенной обфускацией).
|
||||
func validateObfTiming(o ObfOpts, mode ProxyMode) error {
|
||||
func validateObfTiming(o ObfOpts) error {
|
||||
if o.Timing <= 0 {
|
||||
return nil
|
||||
}
|
||||
if !o.Enabled() {
|
||||
return errors.New("-obf-timing requires -obf-profile != none")
|
||||
}
|
||||
if mode != ProxyModeUDP {
|
||||
return errors.New("-obf-timing supported only with -mode udp")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -33,11 +33,6 @@ func TestValidateRejects(t *testing.T) {
|
||||
{"dns mode", func(c *Client) { c.DNS.Mode = "bogus" }, "invalid -dns-mode"},
|
||||
{"obf profile", func(c *Client) { c.Obf.Profile = "bogus" }, "invalid -obf-profile"},
|
||||
{"timing without obf", func(c *Client) { c.Obf.Timing = time.Second }, "-obf-timing"},
|
||||
{"timing with tcp", func(c *Client) {
|
||||
c.Obf.Profile = ObfProfileRTPOpus3
|
||||
c.Obf.Timing = time.Second
|
||||
c.Proxy.Mode = ProxyModeTCPFwd
|
||||
}, "-obf-timing"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
package netconn
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// BiCopy выполняет двунаправленное копирование между c1 и c2 с закрытием по первому завершению.
|
||||
func BiCopy(ctx context.Context, c1, c2 net.Conn, errf func(format string, v ...any)) (int64, int64) {
|
||||
ctx2, cancel := context.WithCancel(ctx)
|
||||
context.AfterFunc(ctx2, func() {
|
||||
now := time.Now()
|
||||
if err := c1.SetDeadline(now); err != nil && errf != nil {
|
||||
errf("BiCopy: c1 SetDeadline: %v", err)
|
||||
}
|
||||
if err := c2.SetDeadline(now); err != nil && errf != nil {
|
||||
errf("BiCopy: c2 SetDeadline: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
var wg sync.WaitGroup
|
||||
var c1FromC2, c2FromC1 int64
|
||||
wg.Go(func() {
|
||||
defer cancel()
|
||||
n, err := io.Copy(c1, c2)
|
||||
c1FromC2 = n
|
||||
if err != nil && errf != nil {
|
||||
errf("BiCopy: c1<-c2: %v", err)
|
||||
}
|
||||
})
|
||||
wg.Go(func() {
|
||||
defer cancel()
|
||||
n, err := io.Copy(c2, c1)
|
||||
c2FromC1 = n
|
||||
if err != nil && errf != nil {
|
||||
errf("BiCopy: c2<-c1: %v", err)
|
||||
}
|
||||
})
|
||||
wg.Wait()
|
||||
|
||||
if err := c1.SetDeadline(time.Time{}); err != nil && errf != nil {
|
||||
errf("BiCopy: c1 clear deadline: %v", err)
|
||||
}
|
||||
if err := c2.SetDeadline(time.Time{}); err != nil && errf != nil {
|
||||
errf("BiCopy: c2 clear deadline: %v", err)
|
||||
}
|
||||
return c1FromC2, c2FromC1
|
||||
}
|
||||
@@ -757,17 +757,35 @@ func SafeURL(raw string) string {
|
||||
return out
|
||||
}
|
||||
|
||||
func captchaFormSummary(values [][2]string) string {
|
||||
func captchaDomainFromRedirectURI(redirectURI string) string {
|
||||
u, err := neturl.Parse(redirectURI)
|
||||
if err != nil {
|
||||
return captchaDomain
|
||||
}
|
||||
domain := strings.TrimSpace(u.Query().Get("domain"))
|
||||
if domain == "" {
|
||||
return captchaDomain
|
||||
}
|
||||
return domain
|
||||
}
|
||||
|
||||
// Ключи сортируются: логи двух прогонов должны диффиться построчно.
|
||||
func captchaFormSummary(values neturl.Values) string {
|
||||
if len(values) == 0 {
|
||||
return "none"
|
||||
}
|
||||
parts := make([]string, 0, len(values))
|
||||
for _, kv := range values {
|
||||
switch kv[0] {
|
||||
keys := make([]string, 0, len(values))
|
||||
for k := range values {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
parts := make([]string, 0, len(keys))
|
||||
for _, k := range keys {
|
||||
switch k {
|
||||
case "session_token", "browser_fp", "hash", "answer", "debug_info", "device", "settings_key", "captcha_settings":
|
||||
parts = append(parts, fmt.Sprintf("%s:%d", kv[0], len(kv[1])))
|
||||
parts = append(parts, fmt.Sprintf("%s:%d", k, len(values.Get(k))))
|
||||
default:
|
||||
parts = append(parts, kv[0])
|
||||
parts = append(parts, k)
|
||||
}
|
||||
}
|
||||
return strings.Join(parts, ",")
|
||||
|
||||
@@ -30,9 +30,8 @@ func NewStore(streamsPerCache int) *Store {
|
||||
}
|
||||
|
||||
// CacheID группирует потоки в блоки по streamsPerCache: потоки 1..streamsPerCache
|
||||
// делят один кэш реквизитов, streamsPerCache+1.. - следующий. streamID 1-based
|
||||
// (единый базис udprelay и tcpfwd); первый поток блока инициирует fetch к VK,
|
||||
// остальные переиспользуют тёплый кэш.
|
||||
// делят один кэш реквизитов, streamsPerCache+1.. - следующий. streamID 1-based;
|
||||
// первый поток блока инициирует fetch к VK, остальные переиспользуют тёплый кэш.
|
||||
func (s *Store) CacheID(streamID int) int {
|
||||
if streamID < 1 {
|
||||
return 0
|
||||
|
||||
@@ -1,237 +0,0 @@
|
||||
// Package bondclient реализует клиентскую сторону агрегации нескольких smux-потоков в одно TCP-соединение.
|
||||
package bondclient
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/logx"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/proxy/tcpfwd"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/stats"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/wire/bondframe"
|
||||
"github.com/xtaci/smux"
|
||||
)
|
||||
|
||||
type Deps struct {
|
||||
Log logx.Logger
|
||||
}
|
||||
|
||||
func (d *Deps) log() logx.Logger {
|
||||
if d.Log == nil {
|
||||
return logx.Nop()
|
||||
}
|
||||
return d.Log
|
||||
}
|
||||
|
||||
type Handler struct {
|
||||
Deps Deps
|
||||
}
|
||||
|
||||
type lane struct {
|
||||
ps *tcpfwd.PooledSession
|
||||
stream *smux.Stream
|
||||
mu sync.Mutex
|
||||
dead atomic.Bool
|
||||
}
|
||||
|
||||
// Handle распределяет трафик принятого TCP-соединения по доступным smux-сессиям.
|
||||
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()
|
||||
|
||||
type pending struct {
|
||||
ps *tcpfwd.PooledSession
|
||||
stream *smux.Stream
|
||||
}
|
||||
opened := make([]pending, 0, len(candidates))
|
||||
for _, ps := range candidates {
|
||||
if ps.Sess.IsClosed() {
|
||||
continue
|
||||
}
|
||||
stream, err := ps.Sess.OpenStream()
|
||||
if err != nil {
|
||||
h.Deps.log().Errorf("[bond %d] session %d open stream error: %s", connID, ps.ID, err)
|
||||
continue
|
||||
}
|
||||
opened = append(opened, pending{ps: ps, stream: stream})
|
||||
}
|
||||
|
||||
if len(opened) > math.MaxUint16 {
|
||||
opened = opened[:math.MaxUint16]
|
||||
}
|
||||
lanes := make([]*lane, 0, len(opened))
|
||||
laneIDs := make([]string, 0, len(opened))
|
||||
laneCount := uint16(len(opened)) //nolint:gosec // bounded above by MaxUint16
|
||||
for i, p := range opened {
|
||||
if err := bondframe.WriteHello(p.stream, connID, uint16(i), laneCount); err != nil { //nolint:gosec // i < laneCount <= MaxUint16
|
||||
h.Deps.log().Errorf("[bond %d] session %d hello error: %s", connID, p.ps.ID, err)
|
||||
_ = p.stream.Close()
|
||||
continue
|
||||
}
|
||||
p.ps.Opened.Add(1)
|
||||
p.ps.Active.Add(1)
|
||||
lanes = append(lanes, &lane{ps: p.ps, stream: p.stream})
|
||||
laneIDs = append(laneIDs, strconv.Itoa(p.ps.ID))
|
||||
}
|
||||
|
||||
if len(lanes) == 0 {
|
||||
h.Deps.log().Errorf("[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 !errors.Is(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 {
|
||||
h.Deps.log().Errorf("[bond %d] write data error: %v", connID, writeErr)
|
||||
return
|
||||
}
|
||||
l.ps.ToSession.Add(uint64(n))
|
||||
seq++
|
||||
}
|
||||
if err != nil {
|
||||
if !errors.Is(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 {
|
||||
h.Deps.log().Errorf("[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:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// writeBondFrameToNextLane пишет фрейм в следующий активный lane в порядке round-robin.
|
||||
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) {
|
||||
chunks := bondframe.Reorder(ctx, tcpConn, recvCh, bondframe.ReorderHooks{
|
||||
OnOverflow: func(_ int) {
|
||||
h.Deps.log().Errorf("[bond %d] pending map overflow (>%d), closing", connID, bondframe.PendingCap)
|
||||
},
|
||||
OnUnknownType: func(typ byte) { h.Deps.log().Errorf("[bond %d] unknown frame type %d", connID, typ) },
|
||||
OnWriteError: func(err error) { h.Deps.log().Errorf("[bond %d] local TCP write error: %v", connID, err) },
|
||||
OnCloseWrite: h.Deps.log().Debugf,
|
||||
})
|
||||
h.Deps.log().Debugf("[bond %d] download finished chunks=%d", connID, chunks)
|
||||
}
|
||||
@@ -1,338 +0,0 @@
|
||||
// Package bondserver реализует серверное демультиплексирование bonded VLESS lane в TCP-соединение к backend.
|
||||
package bondserver
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/logx"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/wire/bondframe"
|
||||
"github.com/xtaci/smux"
|
||||
)
|
||||
|
||||
type laneStream interface {
|
||||
io.Reader
|
||||
io.Writer
|
||||
SetDeadline(time.Time) error
|
||||
}
|
||||
|
||||
type Deps struct {
|
||||
Log logx.Logger
|
||||
}
|
||||
|
||||
func (d *Deps) log() logx.Logger {
|
||||
if d.Log == nil {
|
||||
return logx.Nop()
|
||||
}
|
||||
return d.Log
|
||||
}
|
||||
|
||||
// Registry дедуплицирует потоки с одинаковым ConnID в единое TCP-соединение.
|
||||
type Registry struct {
|
||||
deps Deps
|
||||
|
||||
mu sync.Mutex
|
||||
conns map[uint64]*serverConn
|
||||
}
|
||||
|
||||
func NewRegistry(deps Deps) *Registry {
|
||||
return &Registry{deps: deps, conns: make(map[uint64]*serverConn)}
|
||||
}
|
||||
|
||||
// HandleStreamAfterMagic регистрирует поток после чтения префикса magic-байтов.
|
||||
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 && !errors.Is(err, smux.ErrGoAway) {
|
||||
r.deps.log().Errorf("bondserver: close smux stream: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
hello, err := readHello(stream)
|
||||
if err != nil {
|
||||
r.deps.log().Errorf("bondserver: bond hello: %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:
|
||||
}
|
||||
|
||||
c.once.Do(func() {
|
||||
go c.run()
|
||||
})
|
||||
go c.readLane(l)
|
||||
}
|
||||
|
||||
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 !errors.Is(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.Dialer{Timeout: 10 * time.Second}).DialContext(c.ctx, "tcp", c.connectAddr)
|
||||
if err != nil {
|
||||
c.deps.log().Errorf("[bond %d] backend dial: %s", c.id, err)
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
if err := backendConn.Close(); err != nil {
|
||||
c.deps.log().Errorf("[bond %d] close backend connection: %v", c.id, err)
|
||||
}
|
||||
}()
|
||||
context.AfterFunc(c.ctx, func() {
|
||||
now := time.Now()
|
||||
if err := backendConn.SetDeadline(now); err != nil {
|
||||
c.deps.log().Errorf("[bond %d] backend deadline: %v", c.id, err)
|
||||
}
|
||||
for _, lane := range c.snapshotLanes() {
|
||||
if err := lane.stream.SetDeadline(now); err != nil {
|
||||
c.deps.log().Errorf("[bond %d] lane %d deadline: %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) {
|
||||
chunks := bondframe.Reorder(c.ctx, backendConn, c.recvCh, bondframe.ReorderHooks{
|
||||
OnOverflow: func(_ int) {
|
||||
c.deps.log().Errorf("[bond %d] pending map overflow (>%d), closing", c.id, bondframe.PendingCap)
|
||||
},
|
||||
OnUnknownType: func(typ byte) { c.deps.log().Errorf("[bond %d] unknown frame type %d", c.id, typ) },
|
||||
OnWriteError: func(err error) { c.deps.log().Errorf("[bond %d] backend write error: %v", c.id, err) },
|
||||
OnCloseWrite: c.deps.log().Debugf,
|
||||
})
|
||||
c.deps.log().Debugf("[bond %d] upload to backend finished chunks=%d", c.id, chunks)
|
||||
}
|
||||
|
||||
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 {
|
||||
if writeErr := c.writeToNextLane(seq, buf[:n], &laneIdx); writeErr != nil {
|
||||
c.deps.log().Errorf("[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 {
|
||||
c.deps.log().Errorf("[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(seq uint64, data []byte, laneIdx *uint64) error {
|
||||
lanes := c.snapshotLanes()
|
||||
for {
|
||||
if len(lanes) == 0 {
|
||||
select {
|
||||
case <-c.ctx.Done():
|
||||
return c.ctx.Err()
|
||||
case <-time.After(10 * time.Millisecond):
|
||||
}
|
||||
lanes = c.snapshotLanes()
|
||||
continue
|
||||
}
|
||||
written := false
|
||||
for range lanes {
|
||||
lane := lanes[*laneIdx%uint64(len(lanes))]
|
||||
*laneIdx++
|
||||
lane.mu.Lock()
|
||||
err := bondframe.WriteFrame(lane.stream, bondframe.FrameData, seq, data)
|
||||
lane.mu.Unlock()
|
||||
if err == nil {
|
||||
written = true
|
||||
break
|
||||
}
|
||||
left := c.removeLane(lane)
|
||||
c.deps.log().Errorf("[bond %d] lane %d write error: %v (lanes=%d)", c.id, lane.index, err, left)
|
||||
if left == 0 {
|
||||
c.cancel()
|
||||
return err
|
||||
}
|
||||
}
|
||||
if written {
|
||||
return nil
|
||||
}
|
||||
lanes = c.snapshotLanes()
|
||||
}
|
||||
}
|
||||
@@ -1,272 +0,0 @@
|
||||
package bondserver
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samosvalishe/free-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 (*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 (*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() //nolint:errcheck
|
||||
defer backendB.Close() //nolint:errcheck
|
||||
|
||||
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() //nolint:errcheck
|
||||
defer backendB.Close() //nolint:errcheck
|
||||
|
||||
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(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(_ []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(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(_ []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(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)
|
||||
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,120 +0,0 @@
|
||||
// Package tcpfwd реализует VLESS-режим: пересылка TCP через пул TURN-туннелированных
|
||||
// smux-сессий. Каждое принятое TCP-соединение открывается как smux-поток
|
||||
// (round-robin по сессиям) или, с bond, распределяется по всем активным сессиям.
|
||||
//
|
||||
// SessionPool/PooledSession экспортированы, чтобы bond-клиент (internal/proxy/bondclient)
|
||||
// мог распределять одно TCP-соединение по нескольким сессиям.
|
||||
package tcpfwd
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/xtaci/smux"
|
||||
)
|
||||
|
||||
// PooledSession - одна TURN+DTLS+KCP+smux сессия. Поля экспортированы для
|
||||
// per-lane трафика в bondclient; атомики изменять только через их методы.
|
||||
type PooledSession struct {
|
||||
ID int
|
||||
Sess *smux.Session
|
||||
Active atomic.Int32
|
||||
Opened atomic.Uint64
|
||||
Closed atomic.Uint64
|
||||
ToSession atomic.Uint64
|
||||
FromSession atomic.Uint64
|
||||
}
|
||||
|
||||
// SessionPool - конкурентно-безопасный round-robin пул активных smux-сессий.
|
||||
type SessionPool struct {
|
||||
mu sync.RWMutex
|
||||
sessions []*PooledSession
|
||||
counter atomic.Uint64
|
||||
connCounter atomic.Uint64
|
||||
|
||||
// active - зеркало числа живых сессий для watchdog/UI. nil, если не просили.
|
||||
active *atomic.Int32
|
||||
|
||||
readyOnce sync.Once
|
||||
ready chan struct{}
|
||||
}
|
||||
|
||||
// publishActive обновляет внешнее зеркало. Вызывать под p.mu.
|
||||
func (p *SessionPool) publishActive() {
|
||||
if p.active != nil {
|
||||
p.active.Store(int32(len(p.sessions))) //nolint:gosec // сессий десятки, int32 не переполнить
|
||||
}
|
||||
}
|
||||
|
||||
func (p *SessionPool) Ready() <-chan struct{} {
|
||||
p.mu.Lock()
|
||||
if p.ready == nil {
|
||||
p.ready = make(chan struct{})
|
||||
}
|
||||
ch := p.ready
|
||||
p.mu.Unlock()
|
||||
return ch
|
||||
}
|
||||
|
||||
func (p *SessionPool) Add(id int, s *smux.Session) *PooledSession {
|
||||
ps := &PooledSession{ID: id, Sess: s}
|
||||
p.mu.Lock()
|
||||
p.sessions = append(p.sessions, ps)
|
||||
p.publishActive()
|
||||
if p.ready == nil {
|
||||
p.ready = make(chan struct{})
|
||||
}
|
||||
ready := p.ready
|
||||
p.mu.Unlock()
|
||||
p.readyOnce.Do(func() { close(ready) })
|
||||
return ps
|
||||
}
|
||||
|
||||
// Remove no-op если ps не найден.
|
||||
func (p *SessionPool) Remove(ps *PooledSession) {
|
||||
p.mu.Lock()
|
||||
for i, sess := range p.sessions {
|
||||
if sess == ps {
|
||||
p.sessions = append(p.sessions[:i], p.sessions[i+1:]...)
|
||||
break
|
||||
}
|
||||
}
|
||||
p.publishActive()
|
||||
p.mu.Unlock()
|
||||
}
|
||||
|
||||
// Pick - nil если пул пуст.
|
||||
func (p *SessionPool) Pick() *PooledSession {
|
||||
p.mu.RLock()
|
||||
defer p.mu.RUnlock()
|
||||
n := len(p.sessions)
|
||||
if n == 0 {
|
||||
return nil
|
||||
}
|
||||
idx := (p.counter.Add(1) - 1) % uint64(n)
|
||||
return p.sessions[idx]
|
||||
}
|
||||
|
||||
func (p *SessionPool) NextConnID() uint64 {
|
||||
return p.connCounter.Add(1)
|
||||
}
|
||||
|
||||
// Snapshot - копия незакрытых сессий.
|
||||
func (p *SessionPool) Snapshot() []*PooledSession {
|
||||
p.mu.RLock()
|
||||
defer p.mu.RUnlock()
|
||||
out := make([]*PooledSession, 0, len(p.sessions))
|
||||
for _, ps := range p.sessions {
|
||||
if !ps.Sess.IsClosed() {
|
||||
out = append(out, ps)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Count включает только что закрытые сессии; для live-only используй Snapshot.
|
||||
func (p *SessionPool) Count() int {
|
||||
p.mu.RLock()
|
||||
defer p.mu.RUnlock()
|
||||
return len(p.sessions)
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
package tcpfwd
|
||||
|
||||
import (
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Зеркало активных сессий - единственный источник "сколько каналов поднято" для
|
||||
// watchdog и UI в tcp-режиме: раньше счётчик оставался нулевым и сессию убивал
|
||||
// таймаут подключения.
|
||||
func TestSessionPoolMirrorsActiveCount(t *testing.T) {
|
||||
var active atomic.Int32
|
||||
pool := &SessionPool{active: &active}
|
||||
|
||||
first := pool.Add(1, nil)
|
||||
if got := active.Load(); got != 1 {
|
||||
t.Fatalf("active = %d, want 1", got)
|
||||
}
|
||||
|
||||
second := pool.Add(2, nil)
|
||||
if got := active.Load(); got != 2 {
|
||||
t.Fatalf("active = %d, want 2", got)
|
||||
}
|
||||
|
||||
pool.Remove(first)
|
||||
if got := active.Load(); got != 1 {
|
||||
t.Fatalf("active after remove = %d, want 1", got)
|
||||
}
|
||||
|
||||
pool.Remove(second)
|
||||
if got := active.Load(); got != 0 {
|
||||
t.Fatalf("active after drain = %d, want 0", got)
|
||||
}
|
||||
if pool.Count() != 0 {
|
||||
t.Fatalf("Count() = %d, want 0", pool.Count())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionPoolWithoutMirror(t *testing.T) {
|
||||
pool := &SessionPool{}
|
||||
ps := pool.Add(1, nil)
|
||||
pool.Remove(ps)
|
||||
if pool.Count() != 0 {
|
||||
t.Fatalf("Count() = %d, want 0", pool.Count())
|
||||
}
|
||||
}
|
||||
@@ -1,296 +0,0 @@
|
||||
package tcpfwd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/client/ish"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/clientsdb"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/logx"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/netconn"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/proxy/common"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/stats"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/transport/dtlsdial"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/transport/kcptun"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/wire"
|
||||
"github.com/xtaci/smux"
|
||||
)
|
||||
|
||||
type GetCredsFunc = common.GetCredsFunc
|
||||
|
||||
// Params содержит конфигурацию параметров TURN/obf/KCP для пула сессий.
|
||||
type Params struct {
|
||||
Host string
|
||||
Port string
|
||||
TransportUDP bool
|
||||
Profile string
|
||||
ObfKey []byte
|
||||
GetCreds GetCredsFunc
|
||||
KCPProfile kcptun.Profile
|
||||
KCPFEC kcptun.FEC
|
||||
ClientID string
|
||||
TrafficStats *stats.Stats
|
||||
}
|
||||
|
||||
// BondHandler распределяет TCP-соединение по нескольким активным сессиям пула.
|
||||
type BondHandler func(ctx context.Context, tcpConn net.Conn, connID uint64, lanes []*PooledSession)
|
||||
|
||||
// Deps определяет внешние зависимости для цикла tcpfwd.
|
||||
type Deps struct {
|
||||
DTLSDialer *dtlsdial.Dialer
|
||||
Log logx.Logger
|
||||
BondHandler BondHandler
|
||||
ConnectedStreams *atomic.Int32
|
||||
OnTURNServer func(ip net.IP)
|
||||
}
|
||||
|
||||
func (d *Deps) log() logx.Logger {
|
||||
if d.Log == nil {
|
||||
return logx.Nop()
|
||||
}
|
||||
return d.Log
|
||||
}
|
||||
|
||||
// Run запускает пул сессий, принимает локальные TCP-соединения и проксирует их через smux.
|
||||
func Run(ctx context.Context, deps *Deps, params *Params, peer *net.UDPAddr, listenAddr string, numSessions int, useBond bool) error {
|
||||
pool := &SessionPool{active: deps.ConnectedStreams}
|
||||
|
||||
var wgMaint sync.WaitGroup
|
||||
for i := range numSessions {
|
||||
id := i + 1
|
||||
stagger := time.Duration(i) * 300 * time.Millisecond
|
||||
wgMaint.Go(func() {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-time.After(stagger):
|
||||
}
|
||||
maintainSession(ctx, deps, params, peer, id, pool)
|
||||
})
|
||||
}
|
||||
|
||||
deps.log().Infof("TCP mode: waiting for sessions to connect (total: %d)...", numSessions)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
wgMaint.Wait()
|
||||
return nil
|
||||
case <-pool.Ready():
|
||||
}
|
||||
|
||||
listener, err := (&net.ListenConfig{}).Listen(ctx, "tcp", listenAddr)
|
||||
if err != nil {
|
||||
wgMaint.Wait()
|
||||
return fmt.Errorf("tcpfwd listen %s: %w", listenAddr, err)
|
||||
}
|
||||
|
||||
wrappedListener, err := ish.WrapListener(listener)
|
||||
if err != nil {
|
||||
deps.log().Warnf("failed to wrap listener: %v", err)
|
||||
wrappedListener = listener
|
||||
}
|
||||
|
||||
context.AfterFunc(ctx, func() { _ = wrappedListener.Close() })
|
||||
if useBond {
|
||||
deps.log().Infof("TCP bond mode: listening on %s (striping each TCP connection across active sessions)", listenAddr)
|
||||
} else {
|
||||
deps.log().Infof("TCP mode: listening on %s (round-robin across %d sessions)", listenAddr, numSessions)
|
||||
}
|
||||
|
||||
var wgConn sync.WaitGroup
|
||||
for {
|
||||
tcpConn, err := wrappedListener.Accept()
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
wgConn.Wait()
|
||||
wgMaint.Wait()
|
||||
return nil //nolint:nilerr // ctx cancel = clean shutdown, not an error
|
||||
}
|
||||
deps.log().Errorf("TCP accept error: %s", err)
|
||||
continue
|
||||
}
|
||||
|
||||
if useBond {
|
||||
if deps.BondHandler == nil {
|
||||
deps.log().Errorf("bond requested but no BondHandler set, rejecting")
|
||||
_ = tcpConn.Close()
|
||||
continue
|
||||
}
|
||||
connID := (uint64(time.Now().UnixNano()) << 16) ^ pool.NextConnID()
|
||||
lanes := pool.Snapshot()
|
||||
if len(lanes) == 0 {
|
||||
deps.log().Errorf("No active sessions, rejecting connection")
|
||||
_ = tcpConn.Close()
|
||||
continue
|
||||
}
|
||||
|
||||
tc, cid, lns := tcpConn, connID, lanes
|
||||
wgConn.Go(func() {
|
||||
deps.BondHandler(ctx, tc, cid, lns)
|
||||
})
|
||||
continue
|
||||
}
|
||||
|
||||
ps := pool.Pick()
|
||||
if ps == nil || ps.Sess.IsClosed() {
|
||||
deps.log().Errorf("No active sessions, rejecting connection")
|
||||
_ = tcpConn.Close()
|
||||
continue
|
||||
}
|
||||
|
||||
connID := pool.NextConnID()
|
||||
opened := ps.Opened.Add(1)
|
||||
active := ps.Active.Add(1)
|
||||
deps.log().Debugf("[session %d] TCP accept #%d from=%s active=%d opened=%d pool=%d",
|
||||
ps.ID, connID, tcpConn.RemoteAddr(), active, opened, pool.Count())
|
||||
|
||||
tc, sessRef, cid := tcpConn, ps, connID
|
||||
wgConn.Go(func() {
|
||||
defer func() { _ = tc.Close() }()
|
||||
defer func() {
|
||||
active := sessRef.Active.Add(-1)
|
||||
closed := sessRef.Closed.Add(1)
|
||||
deps.log().Debugf("[session %d] TCP close #%d active=%d closed=%d totals: to-session=%s from-session=%s",
|
||||
sessRef.ID, cid, active, closed,
|
||||
stats.FormatByteCount(sessRef.ToSession.Load()), stats.FormatByteCount(sessRef.FromSession.Load()))
|
||||
}()
|
||||
|
||||
stream, err := sessRef.Sess.OpenStream()
|
||||
if err != nil {
|
||||
deps.log().Errorf("[session %d] smux open stream error for TCP #%d: %s", sessRef.ID, cid, err)
|
||||
return
|
||||
}
|
||||
defer func() { _ = stream.Close() }()
|
||||
errf := func(format string, v ...any) {
|
||||
if deps.log().DebugEnabled() {
|
||||
deps.log().Errorf(format, v...)
|
||||
}
|
||||
}
|
||||
fromSession, toSession := netconn.BiCopy(ctx, tc, stream, errf)
|
||||
fromU, toU := nonNegUint64(fromSession), nonNegUint64(toSession)
|
||||
sessRef.FromSession.Add(fromU)
|
||||
sessRef.ToSession.Add(toU)
|
||||
deps.log().Debugf("[session %d] TCP done #%d local<-session=%s local->session=%s",
|
||||
sessRef.ID, cid, stats.FormatByteCount(fromU), stats.FormatByteCount(toU))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// maintainSession поддерживает одну сессию TURN+DTLS+KCP+smux в активном состоянии.
|
||||
func maintainSession(ctx context.Context, deps *Deps, params *Params, peer *net.UDPAddr, id int, pool *SessionPool) {
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
default:
|
||||
}
|
||||
|
||||
smuxSess, cleanup, err := createSmuxSession(ctx, deps, params, peer, id)
|
||||
if err != nil {
|
||||
deps.log().Errorf("[session %d] setup error: %s, retrying...", id, err)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-time.After(3 * time.Second):
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
ps := pool.Add(id, smuxSess)
|
||||
deps.log().Infof("[session %d] connected (active: %d)", id, pool.Count())
|
||||
|
||||
for !smuxSess.IsClosed() {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
pool.Remove(ps)
|
||||
cleanup()
|
||||
return
|
||||
case <-time.After(1 * time.Second):
|
||||
}
|
||||
}
|
||||
|
||||
pool.Remove(ps)
|
||||
cleanup()
|
||||
deps.log().Infof("[session %d] disconnected (active: %d), reconnecting...", id, pool.Count())
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-time.After(2 * time.Second):
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// createSmuxSession поднимает стек TURN+DTLS+KCP+smux и возвращает сессию smux.
|
||||
func createSmuxSession(ctx context.Context, deps *Deps, params *Params, peer *net.UDPAddr, id int) (*smux.Session, func(), error) {
|
||||
var cleanupFns []func()
|
||||
cleanup := func() {
|
||||
for i := len(cleanupFns) - 1; i >= 0; i-- {
|
||||
cleanupFns[i]()
|
||||
}
|
||||
}
|
||||
|
||||
stream, err := common.DialTURN(ctx, params.Host, params.Port, params.TransportUDP, peer, id, params.GetCreds)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
cleanupFns = append(cleanupFns, func() { _ = stream.Close() })
|
||||
relayConn := stream.Relay
|
||||
deps.log().Debugf("[session %d] TURN server IP: %s", id, stream.ServerUDPAddr.IP)
|
||||
if deps.OnTURNServer != nil {
|
||||
deps.OnTURNServer(stream.ServerUDPAddr.IP)
|
||||
}
|
||||
deps.log().Debugf("relayed-address=%s", relayConn.LocalAddr().String())
|
||||
|
||||
obfConn, err := common.NewClientObf(params.Profile, params.ObfKey)
|
||||
if err != nil {
|
||||
cleanup()
|
||||
return nil, nil, fmt.Errorf("obf init: %w", err)
|
||||
}
|
||||
dtlsPC := &wire.RelayPacketConn{Relay: relayConn, Peer: peer, Codec: obfConn}
|
||||
dtlsConn, err := deps.DTLSDialer.Dial(ctx, dtlsPC, peer)
|
||||
if err != nil {
|
||||
cleanup()
|
||||
return nil, nil, fmt.Errorf("DTLS handshake: %w", err)
|
||||
}
|
||||
cleanupFns = append(cleanupFns, func() { _ = dtlsConn.Close() })
|
||||
deps.log().Debugf("DTLS connection established")
|
||||
|
||||
if werr := clientsdb.WriteClientID(dtlsConn, params.ClientID); werr != nil {
|
||||
cleanup()
|
||||
return nil, nil, fmt.Errorf("send client ID: %w", werr)
|
||||
}
|
||||
|
||||
var countedConn net.Conn = dtlsConn
|
||||
if params.TrafficStats != nil {
|
||||
countedConn = &stats.CountingConn{Conn: countedConn, Stats: params.TrafficStats}
|
||||
}
|
||||
kcpSess, err := kcptun.NewKCPOverDTLS(countedConn, false, params.KCPProfile, params.KCPFEC)
|
||||
if err != nil {
|
||||
cleanup()
|
||||
return nil, nil, fmt.Errorf("KCP session: %w", err)
|
||||
}
|
||||
cleanupFns = append(cleanupFns, func() { _ = kcpSess.Close() })
|
||||
deps.log().Debugf("KCP session established")
|
||||
|
||||
smuxSess, err := smux.Client(kcpSess, kcptun.DefaultSmuxConfig())
|
||||
if err != nil {
|
||||
cleanup()
|
||||
return nil, nil, fmt.Errorf("smux client: %w", err)
|
||||
}
|
||||
cleanupFns = append(cleanupFns, func() { _ = smuxSess.Close() })
|
||||
deps.log().Debugf("smux session established")
|
||||
|
||||
return smuxSess, cleanup, nil
|
||||
}
|
||||
|
||||
// nonNegUint64 безопасно преобразует int64 в uint64.
|
||||
func nonNegUint64(n int64) uint64 {
|
||||
if n < 0 {
|
||||
return 0
|
||||
}
|
||||
return uint64(n)
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
// Package tcpfwdserver реализует серверную часть KCP+smux поверх DTLS с форвардингом в TCP backend.
|
||||
package tcpfwdserver
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/logx"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/netconn"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/proxy/bondserver"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/transport/kcptun"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/wire/bondframe"
|
||||
"github.com/xtaci/smux"
|
||||
)
|
||||
|
||||
// Handle принимает DTLS-соединение, инициализирует KCP+smux и пересылает входящие потоки в connectAddr.
|
||||
func Handle(ctx context.Context, logger logx.Logger, registry *bondserver.Registry, dtlsConn net.Conn, connectAddr string, kcpProfile kcptun.Profile, kcpFEC kcptun.FEC) {
|
||||
kcpSess, err := kcptun.NewKCPOverDTLS(dtlsConn, true, kcpProfile, kcpFEC)
|
||||
if err != nil {
|
||||
logger.Errorf("tcpfwdserver: KCP session: %s", err)
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
if closeErr := kcpSess.Close(); closeErr != nil {
|
||||
logger.Errorf("tcpfwdserver: close KCP session: %v", closeErr)
|
||||
}
|
||||
}()
|
||||
logger.Debugf("KCP session established (server)")
|
||||
|
||||
smuxSess, err := smux.Server(kcpSess, kcptun.DefaultSmuxConfig())
|
||||
if err != nil {
|
||||
logger.Errorf("tcpfwdserver: smux server: %s", err)
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
if err := smuxSess.Close(); err != nil {
|
||||
logger.Errorf("tcpfwdserver: close smux session: %v", err)
|
||||
}
|
||||
}()
|
||||
logger.Debugf("smux session established (server)")
|
||||
|
||||
var wg sync.WaitGroup
|
||||
for {
|
||||
stream, err := smuxSess.AcceptStream()
|
||||
if err != nil {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
default:
|
||||
logger.Errorf("tcpfwdserver: smux accept: %s", err)
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
s := stream
|
||||
wg.Go(func() {
|
||||
handleStream(ctx, logger, registry, s, connectAddr)
|
||||
})
|
||||
}
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func handleStream(ctx context.Context, logger logx.Logger, registry *bondserver.Registry, s *smux.Stream, connectAddr string) {
|
||||
var prefix [4]byte
|
||||
if _, err := io.ReadFull(s, prefix[:]); err != nil {
|
||||
if err != io.EOF && err != io.ErrUnexpectedEOF {
|
||||
logger.Errorf("tcpfwdserver: smux stream prefix read: %v", err)
|
||||
}
|
||||
_ = s.Close()
|
||||
return
|
||||
}
|
||||
if string(prefix[:]) == bondframe.Magic {
|
||||
logger.Debugf("auto-detected bond smux stream")
|
||||
registry.HandleStreamAfterMagic(ctx, s, connectAddr, prefix)
|
||||
return
|
||||
}
|
||||
|
||||
defer func() {
|
||||
if err := s.Close(); err != nil && err != smux.ErrGoAway {
|
||||
logger.Errorf("tcpfwdserver: close smux stream: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
backendConn, err := (&net.Dialer{Timeout: 10 * time.Second}).DialContext(ctx, "tcp", connectAddr)
|
||||
if err != nil {
|
||||
logger.Errorf("tcpfwdserver: backend dial: %s", err)
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
if err := backendConn.Close(); err != nil {
|
||||
logger.Errorf("tcpfwdserver: close backend connection: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
netconn.BiCopy(ctx, &prefixedConn{Conn: s, prefix: prefix[:]}, backendConn, logger.Debugf)
|
||||
}
|
||||
|
||||
// prefixedConn восстанавливает прочитанный префикс в поток байт.
|
||||
type prefixedConn struct {
|
||||
net.Conn
|
||||
prefix []byte
|
||||
}
|
||||
|
||||
func (c *prefixedConn) Read(p []byte) (int, error) {
|
||||
if len(c.prefix) > 0 {
|
||||
n := copy(p, c.prefix)
|
||||
c.prefix = c.prefix[n:]
|
||||
return n, nil
|
||||
}
|
||||
return c.Conn.Read(p)
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
// Package common содержит общие вспомогательные функции для udprelay и tcpfwd.
|
||||
package common
|
||||
package udprelay
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -8,7 +7,6 @@ import (
|
||||
"net"
|
||||
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/transport/turndial"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/wire"
|
||||
)
|
||||
|
||||
// GetCredsFunc разрешает TURN-реквизиты для streamID.
|
||||
@@ -43,8 +41,3 @@ func DialTURN(ctx context.Context, host, port string, udp bool, peer *net.UDPAdd
|
||||
}
|
||||
return nil, fmt.Errorf("all TURN candidates failed: %w", errors.Join(errs...))
|
||||
}
|
||||
|
||||
// NewClientObf возвращает клиентский wire.Codec для профиля obf.
|
||||
func NewClientObf(profile string, key []byte) (wire.Codec, error) {
|
||||
return wire.NewClientCodec(profile, key)
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package common
|
||||
package udprelay
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -12,9 +12,8 @@ import (
|
||||
"github.com/cbeuw/connutil"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/clientsdb"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/provider"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/proxy/common"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/randx"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/stats"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/wire"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/wire/shape"
|
||||
)
|
||||
|
||||
@@ -168,10 +167,6 @@ func oneDTLS(ctx context.Context, deps *Deps, params *Params, peer *net.UDPAddr,
|
||||
}
|
||||
}()
|
||||
|
||||
var countedConn net.Conn = dtlsConn
|
||||
if params.TrafficStats != nil {
|
||||
countedConn = &stats.CountingConn{Conn: countedConn, Stats: params.TrafficStats}
|
||||
}
|
||||
for {
|
||||
select {
|
||||
case <-dtlsctx.Done():
|
||||
@@ -179,7 +174,7 @@ func oneDTLS(ctx context.Context, deps *Deps, params *Params, peer *net.UDPAddr,
|
||||
case <-forwardDone:
|
||||
return errors.New("DTLS connection closed by remote peer")
|
||||
case pkt := <-inboundChan:
|
||||
_, err := countedConn.Write(pkt.Data[:pkt.N])
|
||||
_, err := dtlsConn.Write(pkt.Data[:pkt.N])
|
||||
packetPool.Put(pkt)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to forward packet to DTLS: %w", err)
|
||||
@@ -194,12 +189,10 @@ func oneTURN(ctx context.Context, deps *Deps, params *Params, peer *net.UDPAddr,
|
||||
c <- err
|
||||
}()
|
||||
|
||||
stream, derr := common.DialTURN(ctx, params.Host, params.Port, params.TransportUDP, peer, streamID, params.GetCreds)
|
||||
stream, derr := DialTURN(ctx, params.Host, params.Port, params.TransportUDP, peer, streamID, params.GetCreds)
|
||||
if derr != nil {
|
||||
if deps.Auth.IsAuthError(derr) && deps.Auth.HandleAuthError(streamID) {
|
||||
deps.log().Errorf("[STREAM %d] Fatal error fetching TURN credentials", streamID)
|
||||
err = provider.ErrFatalNoStreams
|
||||
return
|
||||
if deps.Auth.IsAuthError(derr) {
|
||||
deps.Auth.HandleAuthError(streamID)
|
||||
}
|
||||
err = fmt.Errorf("connect to TURN server: %w", derr)
|
||||
return
|
||||
@@ -231,8 +224,15 @@ func oneTURN(ctx context.Context, deps *Deps, params *Params, peer *net.UDPAddr,
|
||||
turnctx, turncancel := context.WithCancel(ctx)
|
||||
defer turncancel()
|
||||
|
||||
// без дедлайна relayConn.ReadFrom не проснётся на отмене turnctx - wg.Wait встанет намертво
|
||||
context.AfterFunc(turnctx, func() {
|
||||
if err := relayConn.SetDeadline(time.Now()); err != nil {
|
||||
deps.log().Errorf("[STREAM %d] Failed to set relay deadline: %s", streamID, err)
|
||||
}
|
||||
})
|
||||
|
||||
var internalPipeAddr atomic.Value
|
||||
obfConn, obfErr := common.NewClientObf(params.Profile, params.ObfKey)
|
||||
obfConn, obfErr := wire.NewClientCodec(params.Profile, params.ObfKey)
|
||||
if obfErr != nil {
|
||||
deps.log().Errorf("[STREAM %d] OBF init failed: %v", streamID, obfErr)
|
||||
return
|
||||
|
||||
@@ -10,14 +10,11 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/logx"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/proxy/common"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/stats"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/transport/dtlsdial"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/wake"
|
||||
)
|
||||
|
||||
type GetCredsFunc = common.GetCredsFunc
|
||||
|
||||
// AuthHandler определяет интерфейс взаимодействия с провайдером при ошибках авторизации.
|
||||
type AuthHandler interface {
|
||||
IsAuthError(err error) bool
|
||||
|
||||
@@ -15,8 +15,6 @@ import (
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/logx"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/provider"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/provider/vk"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/proxy/bondclient"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/proxy/tcpfwd"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/proxy/udprelay"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/routemgr"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/stats"
|
||||
@@ -45,7 +43,6 @@ const (
|
||||
defaultStatusInterval = 500 * time.Millisecond
|
||||
defaultRateInterval = time.Second
|
||||
defaultUDPHandshakeTimeout = 20 * time.Second
|
||||
defaultTCPHandshakeTimeout = 30 * time.Second
|
||||
defaultHandshakeConcurrency = 3
|
||||
|
||||
wakeTick = 5 * time.Second
|
||||
@@ -58,7 +55,6 @@ type Options struct {
|
||||
StatusInterval time.Duration
|
||||
RateInterval time.Duration
|
||||
UDPHandshakeTimeout time.Duration
|
||||
TCPHandshakeTimeout time.Duration
|
||||
HandshakeConcurrency int
|
||||
|
||||
Traffic bool
|
||||
@@ -74,9 +70,6 @@ func (o Options) withDefaults() Options {
|
||||
if o.UDPHandshakeTimeout <= 0 {
|
||||
o.UDPHandshakeTimeout = defaultUDPHandshakeTimeout
|
||||
}
|
||||
if o.TCPHandshakeTimeout <= 0 {
|
||||
o.TCPHandshakeTimeout = defaultTCPHandshakeTimeout
|
||||
}
|
||||
if o.HandshakeConcurrency <= 0 {
|
||||
o.HandshakeConcurrency = defaultHandshakeConcurrency
|
||||
}
|
||||
@@ -88,7 +81,7 @@ type Deps struct {
|
||||
Observer Observer
|
||||
Solver vk.ManualSolverFunc
|
||||
CaptchaActive func() bool
|
||||
// LocalPipe подменяет локальный UDP-сокет прямым каналом в памяти (только udp).
|
||||
// LocalPipe подменяет локальный UDP-сокет прямым каналом в памяти.
|
||||
LocalPipe net.PacketConn
|
||||
Options Options
|
||||
}
|
||||
@@ -324,34 +317,6 @@ func (s *Session) relay(ctx context.Context, prov provider.Provider, peer *net.U
|
||||
}
|
||||
}
|
||||
|
||||
if s.cfg.Proxy.Mode != config.ProxyModeUDP {
|
||||
dialer := &dtlsdial.Dialer{
|
||||
HandshakeTimeout: s.opts.TCPHandshakeTimeout,
|
||||
HandshakeSem: make(chan struct{}, s.opts.HandshakeConcurrency),
|
||||
}
|
||||
bond := &bondclient.Handler{Deps: bondclient.Deps{Log: log}}
|
||||
deps := &tcpfwd.Deps{
|
||||
DTLSDialer: dialer,
|
||||
Log: log,
|
||||
BondHandler: bond.Handle,
|
||||
ConnectedStreams: &s.connected,
|
||||
OnTURNServer: routeCallback,
|
||||
}
|
||||
params := &tcpfwd.Params{
|
||||
Host: s.cfg.TURN.Host,
|
||||
Port: s.cfg.TURN.Port,
|
||||
TransportUDP: s.cfg.TURN.TransportUDP,
|
||||
Profile: string(s.cfg.Obf.Profile),
|
||||
ObfKey: s.cfg.Obf.Key,
|
||||
GetCreds: tcpfwd.GetCredsFunc(getCreds),
|
||||
KCPProfile: s.cfg.KCP.Profile,
|
||||
KCPFEC: s.cfg.KCP.FEC,
|
||||
ClientID: s.cfg.ClientID,
|
||||
TrafficStats: s.trafficStats(),
|
||||
}
|
||||
return tcpfwd.Run(ctx, deps, params, peer, s.cfg.Proxy.Listen, s.total, s.cfg.Proxy.Mode == config.ProxyModeTCPFwdBond)
|
||||
}
|
||||
|
||||
local, err := s.localConn(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -3,7 +3,6 @@ package stats
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
@@ -58,32 +57,3 @@ func FormatBitsPerSecond(bytes uint64, interval time.Duration) string {
|
||||
}
|
||||
return fmt.Sprintf("%.0f bit/s", bps)
|
||||
}
|
||||
|
||||
// FormatByteCount форматирует количество байт в человекочитаемый вид (B, KiB, MiB).
|
||||
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 оборачивает net.Conn и учитывает прочитанные/записанные байты в Stats.
|
||||
type CountingConn struct {
|
||||
net.Conn
|
||||
Stats *Stats
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
@@ -33,27 +33,6 @@ func TestFormatBitsPerSecond(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
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()
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
|
||||
func TestParse(t *testing.T) {
|
||||
link1 := (&uri.Config{
|
||||
Version: 1, Provider: "vk", Peer: "1.1.1.1:56000", Mode: "tcp",
|
||||
Version: 1, Provider: "vk", Peer: "1.1.1.1:56000",
|
||||
}).String()
|
||||
link2 := (&uri.Config{
|
||||
Version: 1, Provider: "vk", Peer: "2.2.2.2:56000",
|
||||
@@ -50,7 +50,7 @@ func TestParse(t *testing.T) {
|
||||
if n1.IP != "1.1.1.1" {
|
||||
t.Errorf("Node[0].IP = %v, want 1.1.1.1", n1.IP)
|
||||
}
|
||||
if n1.URI.Provider != "vk" || n1.URI.Mode != "tcp" {
|
||||
if n1.URI.Provider != "vk" {
|
||||
t.Errorf("Node[0].URI = %+v", n1.URI)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,130 +0,0 @@
|
||||
package kcptun
|
||||
|
||||
import (
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/xtaci/kcp-go/v5"
|
||||
"github.com/xtaci/smux"
|
||||
)
|
||||
|
||||
// Profile задаёт параметры настройки KCP.
|
||||
type Profile struct {
|
||||
NoDelay int
|
||||
Interval int
|
||||
Resend int
|
||||
NC int
|
||||
SndWnd int
|
||||
RcvWnd int
|
||||
MTU int
|
||||
ACKNoDelay bool
|
||||
}
|
||||
|
||||
// FEC задаёт параметры Forward Error Correction (Data/Parity шарды).
|
||||
type FEC struct {
|
||||
Data int
|
||||
Parity int
|
||||
}
|
||||
|
||||
// DefaultProfile возвращает сбалансированный профиль KCP по умолчанию.
|
||||
func DefaultProfile() Profile {
|
||||
return Profile{
|
||||
NoDelay: 1,
|
||||
Interval: 20,
|
||||
Resend: 2,
|
||||
NC: 1,
|
||||
SndWnd: 512,
|
||||
RcvWnd: 512,
|
||||
MTU: 1200,
|
||||
ACKNoDelay: true,
|
||||
}
|
||||
}
|
||||
|
||||
// DtlsPacketConn адаптирует net.Conn (DTLS) к интерфейсу net.PacketConn для KCP.
|
||||
type DtlsPacketConn struct {
|
||||
conn net.Conn
|
||||
}
|
||||
|
||||
func NewDtlsPacketConn(conn net.Conn) *DtlsPacketConn {
|
||||
return &DtlsPacketConn{conn: conn}
|
||||
}
|
||||
|
||||
func (d *DtlsPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
||||
n, err := d.conn.Read(b)
|
||||
return n, d.conn.RemoteAddr(), err
|
||||
}
|
||||
|
||||
func (d *DtlsPacketConn) WriteTo(b []byte, _ net.Addr) (int, error) {
|
||||
return d.conn.Write(b)
|
||||
}
|
||||
|
||||
func (d *DtlsPacketConn) Close() error {
|
||||
return d.conn.Close()
|
||||
}
|
||||
|
||||
func (d *DtlsPacketConn) LocalAddr() net.Addr {
|
||||
return d.conn.LocalAddr()
|
||||
}
|
||||
|
||||
func (d *DtlsPacketConn) SetDeadline(t time.Time) error {
|
||||
return d.conn.SetDeadline(t)
|
||||
}
|
||||
|
||||
func (d *DtlsPacketConn) SetReadDeadline(t time.Time) error {
|
||||
return d.conn.SetReadDeadline(t)
|
||||
}
|
||||
|
||||
func (d *DtlsPacketConn) SetWriteDeadline(t time.Time) error {
|
||||
return d.conn.SetWriteDeadline(t)
|
||||
}
|
||||
|
||||
// NewKCPOverDTLS создаёт KCP-сессию поверх DTLS-соединения.
|
||||
func NewKCPOverDTLS(dtlsConn net.Conn, isServer bool, profile Profile, fec FEC) (*kcp.UDPSession, error) {
|
||||
pc := NewDtlsPacketConn(dtlsConn)
|
||||
|
||||
block, err := kcp.NewNoneBlockCrypt(nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var sess *kcp.UDPSession
|
||||
|
||||
if isServer {
|
||||
var listener *kcp.Listener
|
||||
listener, err = kcp.ServeConn(block, fec.Data, fec.Parity, pc)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = listener.SetDeadline(time.Now().Add(30 * time.Second)); err != nil {
|
||||
_ = listener.Close()
|
||||
return nil, err
|
||||
}
|
||||
sess, err = listener.AcceptKCP()
|
||||
if err != nil {
|
||||
_ = listener.Close()
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
sess, err = kcp.NewConn2(dtlsConn.RemoteAddr(), block, fec.Data, fec.Parity, pc)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
sess.SetNoDelay(profile.NoDelay, profile.Interval, profile.Resend, profile.NC)
|
||||
sess.SetWindowSize(profile.SndWnd, profile.RcvWnd)
|
||||
sess.SetMtu(profile.MTU)
|
||||
sess.SetACKNoDelay(profile.ACKNoDelay)
|
||||
|
||||
return sess, nil
|
||||
}
|
||||
|
||||
// DefaultSmuxConfig возвращает конфигурацию smux для туннелирования поверх TURN.
|
||||
func DefaultSmuxConfig() *smux.Config {
|
||||
cfg := smux.DefaultConfig()
|
||||
cfg.MaxReceiveBuffer = 4 * 1024 * 1024
|
||||
cfg.MaxStreamBuffer = 1 * 1024 * 1024
|
||||
cfg.KeepAliveInterval = 10 * time.Second
|
||||
cfg.KeepAliveTimeout = 30 * time.Second
|
||||
return cfg
|
||||
}
|
||||
@@ -17,8 +17,6 @@ type Config struct {
|
||||
Provider string
|
||||
Peer string
|
||||
Transport string
|
||||
Mode string
|
||||
Bond bool
|
||||
ObfProfile string
|
||||
ObfKey string
|
||||
N int
|
||||
@@ -37,8 +35,6 @@ type wire struct {
|
||||
Provider string `json:"provider"`
|
||||
Peer string `json:"peer"`
|
||||
Transport string `json:"transport,omitempty"`
|
||||
Mode string `json:"mode,omitempty"`
|
||||
Bond bool `json:"bond,omitempty"`
|
||||
Obf string `json:"obf,omitempty"`
|
||||
Key string `json:"key,omitempty"`
|
||||
N int `json:"n,omitempty"`
|
||||
@@ -85,8 +81,6 @@ func Parse(s string) (*Config, error) {
|
||||
Provider: w.Provider,
|
||||
Peer: w.Peer,
|
||||
Transport: w.Transport,
|
||||
Mode: w.Mode,
|
||||
Bond: w.Bond,
|
||||
ObfProfile: w.Obf,
|
||||
ObfKey: w.Key,
|
||||
N: w.N,
|
||||
@@ -107,8 +101,6 @@ func (c *Config) String() string {
|
||||
Provider: c.Provider,
|
||||
Peer: c.Peer,
|
||||
Transport: c.Transport,
|
||||
Mode: c.Mode,
|
||||
Bond: c.Bond,
|
||||
N: c.N,
|
||||
StreamsPerCred: c.StreamsPerCred,
|
||||
ClientID: c.ClientID,
|
||||
|
||||
@@ -17,8 +17,6 @@ func TestRoundTrip(t *testing.T) {
|
||||
Provider: "vk",
|
||||
Peer: "127.0.0.1:56000",
|
||||
Transport: "udp",
|
||||
Mode: "tcp",
|
||||
Bond: true,
|
||||
ObfProfile: "rtpopus",
|
||||
ObfKey: "d823fa",
|
||||
N: 16,
|
||||
@@ -45,7 +43,6 @@ func TestRoundTrip(t *testing.T) {
|
||||
Version: currentVersion,
|
||||
Provider: "vk",
|
||||
Peer: "1.2.3.4:56000",
|
||||
Mode: "udp",
|
||||
Comment: "Сервер РФ",
|
||||
},
|
||||
},
|
||||
|
||||
@@ -1,197 +0,0 @@
|
||||
// Package bondframe определяет протокол кадрирования multi-lane VLESS bond (Hello, Data, FIN фреймы).
|
||||
package bondframe
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"net"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
Version uint8 = 1
|
||||
Magic = "VLB1"
|
||||
|
||||
FrameData byte = 1
|
||||
FrameFIN byte = 2
|
||||
|
||||
MaxChunk = 16 * 1024
|
||||
|
||||
LaneAttachTimeout = 300 * time.Millisecond
|
||||
)
|
||||
|
||||
// Hello содержит заголовок рукопожатия отдельного lane.
|
||||
type Hello struct {
|
||||
ConnID uint64
|
||||
LaneIndex uint16
|
||||
LaneCount uint16
|
||||
}
|
||||
|
||||
// Frame представляет единичный фрейм данных или FIN с последовательным номером Seq.
|
||||
type Frame struct {
|
||||
Type byte
|
||||
Seq uint64
|
||||
Data []byte
|
||||
}
|
||||
|
||||
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 читает остаток заголовка Hello после проверки magic-байтов.
|
||||
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[:])
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
func WriteFrame(w io.Writer, typ byte, seq uint64, data []byte) error {
|
||||
if uint64(len(data)) > math.MaxUint32 {
|
||||
return fmt.Errorf("bondframe: data too large: %d", len(data))
|
||||
}
|
||||
var hdr [13]byte
|
||||
hdr[0] = typ
|
||||
binary.BigEndian.PutUint64(hdr[1:9], seq)
|
||||
binary.BigEndian.PutUint32(hdr[9:13], uint32(len(data))) //nolint:gosec // bounded above
|
||||
if _, err := w.Write(hdr[:]); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(data) == 0 {
|
||||
return nil
|
||||
}
|
||||
_, err := w.Write(data)
|
||||
return err
|
||||
}
|
||||
|
||||
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 > MaxChunk {
|
||||
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
|
||||
}
|
||||
|
||||
// PendingCap ограничивает максимальное число неупорядоченных фреймов в буфере.
|
||||
const PendingCap = 1024
|
||||
|
||||
// ReorderHooks задаёт колбэки для обработки ошибок и событий Reorder.
|
||||
type ReorderHooks struct {
|
||||
OnOverflow func(have int)
|
||||
OnUnknownType func(typ byte)
|
||||
OnWriteError func(err error)
|
||||
OnCloseWrite func(format string, v ...any)
|
||||
}
|
||||
|
||||
// Reorder переупорядочивает фреймы по возрастанию Seq и записывает полезную нагрузку в dst.
|
||||
func Reorder(ctx context.Context, dst net.Conn, recv <-chan Frame, h ReorderHooks) uint64 {
|
||||
pending := make(map[uint64][]byte)
|
||||
var expect uint64
|
||||
var finSeq *uint64
|
||||
|
||||
for {
|
||||
if finSeq != nil && expect == *finSeq {
|
||||
CloseWrite(dst, h.OnCloseWrite)
|
||||
return expect
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return expect
|
||||
case f, ok := <-recv:
|
||||
if !ok {
|
||||
return expect
|
||||
}
|
||||
switch f.Type {
|
||||
case FrameData:
|
||||
if len(pending) >= PendingCap {
|
||||
if h.OnOverflow != nil {
|
||||
h.OnOverflow(len(pending))
|
||||
}
|
||||
return expect
|
||||
}
|
||||
pending[f.Seq] = f.Data
|
||||
case FrameFIN:
|
||||
v := f.Seq
|
||||
if finSeq == nil || v < *finSeq {
|
||||
finSeq = &v
|
||||
}
|
||||
default:
|
||||
if h.OnUnknownType != nil {
|
||||
h.OnUnknownType(f.Type)
|
||||
}
|
||||
return expect
|
||||
}
|
||||
for {
|
||||
data, ok := pending[expect]
|
||||
if !ok {
|
||||
break
|
||||
}
|
||||
delete(pending, expect)
|
||||
if len(data) > 0 {
|
||||
if _, err := dst.Write(data); err != nil {
|
||||
if h.OnWriteError != nil {
|
||||
h.OnWriteError(err)
|
||||
}
|
||||
return expect
|
||||
}
|
||||
}
|
||||
expect++
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// CloseWrite закрывает канал записи conn, если соединение поддерживает half-close.
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,128 +0,0 @@
|
||||
package bondframe
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
package wire
|
||||
|
||||
import (
|
||||
"net"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var relayBufPool = sync.Pool{
|
||||
New: func() any {
|
||||
b := make([]byte, 1600+128)
|
||||
return &b
|
||||
},
|
||||
}
|
||||
|
||||
// RelayPacketConn адаптирует net.PacketConn релея с опциональным шифрованием/обфускацией.
|
||||
type RelayPacketConn struct {
|
||||
Relay net.PacketConn
|
||||
Peer net.Addr
|
||||
Codec Codec
|
||||
}
|
||||
|
||||
func (r *RelayPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
||||
if r.Codec == nil {
|
||||
return r.Relay.ReadFrom(b)
|
||||
}
|
||||
bp := relayBufPool.Get().(*[]byte) //nolint:errcheck // pool New always returns *[]byte
|
||||
buf := *bp
|
||||
need := r.Codec.MaxWire(len(b))
|
||||
if cap(buf) < need {
|
||||
buf = make([]byte, need)
|
||||
*bp = buf
|
||||
}
|
||||
defer relayBufPool.Put(bp)
|
||||
|
||||
n, addr, err := r.Relay.ReadFrom(buf[:cap(buf)])
|
||||
if err != nil {
|
||||
return 0, addr, err
|
||||
}
|
||||
m, err := r.Codec.Unwrap(buf[:n], b)
|
||||
if err != nil {
|
||||
return 0, addr, err
|
||||
}
|
||||
return m, addr, nil
|
||||
}
|
||||
|
||||
func (r *RelayPacketConn) WriteTo(b []byte, _ net.Addr) (int, error) {
|
||||
if r.Codec == nil {
|
||||
return r.Relay.WriteTo(b, r.Peer)
|
||||
}
|
||||
wireLen := r.Codec.MaxWire(len(b))
|
||||
|
||||
bp := relayBufPool.Get().(*[]byte) //nolint:errcheck // pool New always returns *[]byte
|
||||
out := *bp
|
||||
if cap(out) < wireLen {
|
||||
out = make([]byte, wireLen)
|
||||
*bp = out
|
||||
}
|
||||
out = out[:wireLen]
|
||||
defer relayBufPool.Put(bp)
|
||||
|
||||
n, err := r.Codec.WrapInto(out, b)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if _, err = r.Relay.WriteTo(out[:n], r.Peer); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return len(b), nil
|
||||
}
|
||||
|
||||
func (r *RelayPacketConn) Close() error { return r.Relay.Close() }
|
||||
func (r *RelayPacketConn) LocalAddr() net.Addr { return r.Relay.LocalAddr() }
|
||||
func (r *RelayPacketConn) SetDeadline(t time.Time) error { return r.Relay.SetDeadline(t) }
|
||||
func (r *RelayPacketConn) SetReadDeadline(t time.Time) error { return r.Relay.SetReadDeadline(t) }
|
||||
func (r *RelayPacketConn) SetWriteDeadline(t time.Time) error { return r.Relay.SetWriteDeadline(t) }
|
||||
@@ -53,7 +53,7 @@ func TestWrapIntoRoundTrip(t *testing.T) {
|
||||
cli, _ := NewConn(key, false)
|
||||
srv, _ := NewConn(key, true)
|
||||
|
||||
payload := []byte("xray tcp bytes over smux")
|
||||
payload := []byte("wireguard bytes over relay")
|
||||
dst := make([]byte, MaxWire(len(payload)))
|
||||
n, err := cli.WrapInto(dst, payload)
|
||||
if err != nil {
|
||||
|
||||
@@ -53,7 +53,7 @@ func TestWrapIntoRoundTrip(t *testing.T) {
|
||||
cli, _ := NewConn(key, false)
|
||||
srv, _ := NewConn(key, true)
|
||||
|
||||
payload := []byte("xray tcp bytes over smux")
|
||||
payload := []byte("wireguard bytes over relay")
|
||||
dst := make([]byte, MaxWire(len(payload)))
|
||||
n, err := cli.WrapInto(dst, payload)
|
||||
if err != nil {
|
||||
|
||||
Reference in new issue
Block a user