Skip to content

Commit

Permalink
new: add turn server relay
Browse files Browse the repository at this point in the history
  • Loading branch information
Your Name committed Nov 17, 2023
1 parent bec6c24 commit 45dedd1
Show file tree
Hide file tree
Showing 12 changed files with 72 additions and 79 deletions.
4 changes: 3 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -104,4 +104,6 @@ require (
lukechampine.com/blake3 v1.2.1 // indirect
)

replace github.com/sagernet/sing-box/outbound/hiddify => ./outbound/hiddify
replace github.com/sagernet/sing-box/outbound/houtbound => ./outbound/houtbound

replace github.com/sagernet/sing-box/option => ./option
8 changes: 8 additions & 0 deletions option/h_turn_udp_proxy.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package option

type TurnRelayOptions struct {
ServerOptions
Username string `json:"username,omitempty"`
Password string `json:"password,omitempty"`
Realm string `json:"realm,omitempty"`
}
2 changes: 1 addition & 1 deletion option/hysteria.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
package option

type HysteriaInboundOptions struct {
ListenOptions
Up string `json:"up,omitempty"`
Expand Down Expand Up @@ -36,4 +35,5 @@ type HysteriaOutboundOptions struct {
DisableMTUDiscovery bool `json:"disable_mtu_discovery,omitempty"`
Network NetworkList `json:"network,omitempty"`
TLS *OutboundTLSOptions `json:"tls,omitempty"`
TurnRelay *TurnRelayOptions`json:"turn_relay,omitempty"`
}
2 changes: 1 addition & 1 deletion option/hysteria2.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,5 +32,5 @@ type Hysteria2OutboundOptions struct {
Network NetworkList `json:"network,omitempty"`
TLS *OutboundTLSOptions `json:"tls,omitempty"`
BrutalDebug bool `json:"brutal_debug,omitempty"`
Bale bool `json:"bale,omitempty"`
TurnRelay *TurnRelayOptions`json:"turn_relay,omitempty"`
}
2 changes: 1 addition & 1 deletion option/tuic.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,5 @@ type TUICOutboundOptions struct {
Heartbeat Duration `json:"heartbeat,omitempty"`
Network NetworkList `json:"network,omitempty"`
TLS *OutboundTLSOptions `json:"tls,omitempty"`
Bale bool `json:"bale,omitempty"`
TurnRelay *TurnRelayOptions`json:"turn_relay,omitempty"`
}
4 changes: 2 additions & 2 deletions option/wireguard.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package option

import "net/netip"

import "net/netip"
type WireGuardOutboundOptions struct {
DialerOptions
SystemInterface bool `json:"system_interface,omitempty"`
Expand All @@ -16,6 +15,7 @@ type WireGuardOutboundOptions struct {
Workers int `json:"workers,omitempty"`
MTU uint32 `json:"mtu,omitempty"`
Network NetworkList `json:"network,omitempty"`
TurnRelay *TurnRelayOptions`json:"turn_relay,omitempty"`
}

type WireGuardPeer struct {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package hiddify
package houtbound

import (
"log"
Expand Down
60 changes: 29 additions & 31 deletions outbound/hiddify/bale.go → outbound/houtbound/turn_udp_proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,63 +10,66 @@
// |___/
//
// Package main implements a TURN client with support for TCP
package hiddify
package houtbound

import (
"fmt"
"github.com/pion/logging"
"github.com/pion/turn/v3"
"log"
"net"
"strings"
"time"
"math/rand"

"github.com/sagernet/sing-box/option"
)

type Bale struct {
Host string
Port uint16
RelayPort uint16
Forwarder *Forwarder
type CommonTurnRelayOptions struct {
option.ServerOptions
*option.TurnRelayOptions
}


func genString(serverOptions option.ServerOptions) (string) {
return fmt.Sprintf("%s:%d", serverOptions.Server, serverOptions.ServerPort)
}
func ApplyBale(udp_host string,udp_port uint16)(*Bale,error) {
server:=fmt.Sprintf("%s:%d", udp_host, udp_port)
host := "meet-turn.bale.sh"
port := 443
user := "balelivekit=GygZPHQSgAV7L5L8"

func ApplyTurnRelay(option CommonTurnRelayOptions)(*Forwarder) {
if option.TurnRelayOptions == nil {
return nil
}
targetServerAddr := genString(option.ServerOptions) // fmt.Sprintf("%s:%d", option.ServerOptions.Server, option.ServerOptions.ServerPort)
// Dial TURN Server
turnServerAddr := fmt.Sprintf("%s:%d", host, port)
turnServerAddr := genString(option.TurnRelayOptions.ServerOptions) //fmt.Sprintf("%s:%d", option.TurnRelay.Server, option.TurnRelay.Port)
conn, err := net.Dial("udp", turnServerAddr)
if err != nil {
log.Panicf("Failed to connect to TURN server: %s", err)
return nil
}

cred := strings.SplitN(user, "=", 2)

// Start a new TURN Client and wrap our net.Conn in a STUNConn
// This allows us to simulate datagram based communication over a net.Conn
cfg := &turn.ClientConfig{
STUNServerAddr: turnServerAddr,
TURNServerAddr: turnServerAddr,
Conn: turn.NewSTUNConn(conn),
Username: cred[0],
Password: cred[1],
Realm: "bale.ai",
Username: option.TurnRelayOptions.Username,
Password: option.TurnRelayOptions.Password,
Realm: option.TurnRelayOptions.Realm,
LoggerFactory: logging.NewDefaultLoggerFactory(),
}

client, err := turn.NewClient(cfg)
if err != nil {
log.Panicf("Failed to create TURN client: %s", err)
return nil
}
defer client.Close()

// Start listening on the conn provided.
err = client.Listen()
if err != nil {
log.Panicf("Failed to listen: %s", err)
return nil
}

// Allocate a relay socket on the TURN server. On success, it
Expand All @@ -75,6 +78,7 @@ func ApplyBale(udp_host string,udp_port uint16)(*Bale,error) {
relayConn, err := client.Allocate()
if err != nil {
log.Panicf("Failed to allocate: %s", err)
return nil
}
defer func() {
if closeErr := relayConn.Close(); closeErr != nil {
Expand All @@ -84,27 +88,21 @@ func ApplyBale(udp_host string,udp_port uint16)(*Bale,error) {
rnd_port,err:=getRandomPort(10000,30000)
if err!=nil{
log.Panicf("Failed to get random port: %s", err)
return nil,err
return nil
}
// The relayConn's local address is actually the transport
// address assigned on the TURN server.
log.Printf("relayed-address=%s", relayConn.LocalAddr().String())

// Forward(src, dst). It's asynchronous.
forwarder, err := Forward(fmt.Sprint("127.0.0.1:%d",rnd_port), server, relayConn, DefaultTimeout)
forwarder, err := Forward(fmt.Sprint("127.0.0.1:%d",rnd_port), targetServerAddr, relayConn, DefaultTimeout)

Check failure on line 98 in outbound/houtbound/turn_udp_proxy.go

View workflow job for this annotation

GitHub Actions / Debug build

fmt.Sprint call has possible Printf formatting directive %d
if err != nil {
return nil,err
return nil
}
forwarder.Run()
return &Bale{
Host:udp_host,
Port:udp_port,
RelayPort:rnd_port,
Forwarder:forwarder,
},nil
}
func (f *Bale) Close() {
f.Forwarder.Close()
option.Server="127.0.0.1"
option.ServerPort=rnd_port
return forwarder
}


Expand Down
4 changes: 4 additions & 0 deletions outbound/hysteria.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
E "github.com/sagernet/sing/common/exceptions"
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
"github.com/sagernet/sing-box/outbound/houtbound"
)

var (
Expand All @@ -30,13 +31,15 @@ var (
type Hysteria struct {
myOutboundAdapter
client *hysteria.Client
hforwarder *houtbound.Forwarder
}

func NewHysteria(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.HysteriaOutboundOptions) (*Hysteria, error) {
options.UDPFragmentDefault = true
if options.TLS == nil || !options.TLS.Enabled {
return nil, C.ErrTLSRequired
}
hforwarder := houtbound.ApplyTurnRelay(houtbound.CommonTurnRelayOptions{ServerOptions: options.ServerOptions,TurnRelayOptions: options.TurnRelay})
tlsConfig, err := tls.NewClient(ctx, options.Server, common.PtrValueOrDefault(options.TLS))
if err != nil {
return nil, err
Expand Down Expand Up @@ -98,6 +101,7 @@ func NewHysteria(ctx context.Context, router adapter.Router, logger log.ContextL
dependencies: withDialerDependency(options.DialerOptions),
},
client: client,
hforwarder: hforwarder,
}, nil
}

Expand Down
24 changes: 7 additions & 17 deletions outbound/hysteria2.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import (
E "github.com/sagernet/sing/common/exceptions"
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
"github.com/sagernet/sing-box/outbound/hiddify"
"github.com/sagernet/sing-box/outbound/houtbound"
)

var (
Expand All @@ -31,26 +31,16 @@ var (
type Hysteria2 struct {
myOutboundAdapter
client *hysteria2.Client
bale *hiddify.Bale
hforwarder *houtbound.Forwarder
}

func NewHysteria2(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.Hysteria2OutboundOptions) (*Hysteria2, error) {
options.UDPFragmentDefault = true
if options.TLS == nil || !options.TLS.Enabled {
return nil, C.ErrTLSRequired
}
var bale *hiddify.Bale
if options.Bale {
var err2 error
bale,err2 = hiddify.ApplyBale(options.Server, options.ServerPort)
if err2 == nil {
options.Server=bale.Host
options.ServerPort=bale.RelayPort
options.Server="127.0.0.1"
}else{
return nil, err2
}
}
hforwarder := houtbound.ApplyTurnRelay(houtbound.CommonTurnRelayOptions{ServerOptions: options.ServerOptions,TurnRelayOptions: options.TurnRelay})

tlsConfig, err := tls.NewClient(ctx, options.Server, common.PtrValueOrDefault(options.TLS))
if err != nil {
return nil, err
Expand Down Expand Up @@ -98,7 +88,7 @@ func NewHysteria2(ctx context.Context, router adapter.Router, logger log.Context
dependencies: withDialerDependency(options.DialerOptions),
},
client: client,
bale: bale,
hforwarder: hforwarder,
}, nil
}

Expand Down Expand Up @@ -136,8 +126,8 @@ func (h *Hysteria2) InterfaceUpdated() error {
}

func (h *Hysteria2) Close() error {
if h.bale != nil {
h.bale.Close()
if h.hforwarder != nil {
h.hforwarder.Close()
}
return h.client.CloseWithError(os.ErrClosed)
}
31 changes: 7 additions & 24 deletions outbound/tuic.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ import (
"github.com/sagernet/sing/common/uot"

"github.com/gofrs/uuid/v5"
"github.com/sagernet/sing-box/outbound/hiddify"
"fmt"

"github.com/sagernet/sing-box/outbound/houtbound"
)

var (
Expand All @@ -36,32 +36,15 @@ type TUIC struct {
myOutboundAdapter
client *tuic.Client
udpStream bool
bale *hiddify.Bale
hforwarder *houtbound.Forwarder
}

func NewTUIC(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.TUICOutboundOptions) (*TUIC, error) {
options.UDPFragmentDefault = true
if options.TLS == nil || !options.TLS.Enabled {
return nil, C.ErrTLSRequired
}
var bale *hiddify.Bale
fmt.Println("===========================")
logger.Debug("bale=======")
if options.Bale {
var err2 error
fmt.Println("original tuic %+v",options)
// bale,err2 = hiddify.ApplyBale(options.Server, options.ServerPort)
bale=&hiddify.Bale{Host:"1.1.1.1",Port:443,RelayPort:1000}
err2=nil
if err2 == nil {
options.Server="127.0.0.1"
options.ServerPort=bale.RelayPort

fmt.Println("Starting tuic with bale in %+v",options)
}else{
return nil, err2
}
}
hforwarder := houtbound.ApplyTurnRelay(houtbound.CommonTurnRelayOptions{ServerOptions: options.ServerOptions,TurnRelayOptions: options.TurnRelay})
tlsConfig, err := tls.NewClient(ctx, options.Server, common.PtrValueOrDefault(options.TLS))
if err != nil {
return nil, err
Expand Down Expand Up @@ -109,7 +92,7 @@ func NewTUIC(ctx context.Context, router adapter.Router, logger log.ContextLogge
},
client: client,
udpStream: options.UDPOverStream,
bale: bale,
hforwarder: hforwarder,
}, nil
}

Expand Down Expand Up @@ -171,8 +154,8 @@ func (h *TUIC) InterfaceUpdated() {
}

func (h *TUIC) Close() error {
if h.bale != nil {
h.bale.Close()
if h.hforwarder != nil {
h.hforwarder.Close()
}
return h.client.CloseWithError(os.ErrClosed)
}
8 changes: 8 additions & 0 deletions outbound/wireguard.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@

//go:build with_wireguard

package outbound
Expand All @@ -23,6 +24,7 @@ import (
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
"github.com/sagernet/wireguard-go/device"
"github.com/sagernet/sing-box/outbound/houtbound"
)

var (
Expand All @@ -35,9 +37,11 @@ type WireGuard struct {
bind *wireguard.ClientBind
device *device.Device
tunDevice wireguard.Device
hforwarder *houtbound.Forwarder
}

func NewWireGuard(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.WireGuardOutboundOptions) (*WireGuard, error) {
hforwarder := houtbound.ApplyTurnRelay(houtbound.CommonTurnRelayOptions{ServerOptions: options.ServerOptions,TurnRelayOptions: options.TurnRelay})
outbound := &WireGuard{
myOutboundAdapter: myOutboundAdapter{
protocol: C.TypeWireGuard,
Expand All @@ -47,6 +51,7 @@ func NewWireGuard(ctx context.Context, router adapter.Router, logger log.Context
tag: tag,
dependencies: withDialerDependency(options.DialerOptions),
},
hforwarder: hforwarder,
}
var reserved [3]uint8
if len(options.Reserved) > 0 {
Expand Down Expand Up @@ -239,6 +244,9 @@ func (w *WireGuard) Start() error {
}

func (w *WireGuard) Close() error {
if w.hforwarder != nil {
w.hforwarder.Close()
}
if w.device != nil {
w.device.Close()
}
Expand Down

0 comments on commit 45dedd1

Please sign in to comment.