github.com/sagernet/sing-box@v1.9.0-rc.20/common/mux/client.go (about) 1 package mux 2 3 import ( 4 "context" 5 "net" 6 7 "github.com/sagernet/sing-box/adapter" 8 C "github.com/sagernet/sing-box/constant" 9 "github.com/sagernet/sing-box/option" 10 "github.com/sagernet/sing-mux" 11 E "github.com/sagernet/sing/common/exceptions" 12 "github.com/sagernet/sing/common/logger" 13 M "github.com/sagernet/sing/common/metadata" 14 N "github.com/sagernet/sing/common/network" 15 ) 16 17 type Client = mux.Client 18 19 func NewClientWithOptions(dialer N.Dialer, logger logger.Logger, options option.OutboundMultiplexOptions) (*Client, error) { 20 if !options.Enabled { 21 return nil, nil 22 } 23 var brutalOptions mux.BrutalOptions 24 if options.Brutal != nil && options.Brutal.Enabled { 25 brutalOptions = mux.BrutalOptions{ 26 Enabled: true, 27 SendBPS: uint64(options.Brutal.UpMbps * C.MbpsToBps), 28 ReceiveBPS: uint64(options.Brutal.DownMbps * C.MbpsToBps), 29 } 30 if brutalOptions.SendBPS < mux.BrutalMinSpeedBPS { 31 return nil, E.New("brutal: invalid upload speed") 32 } 33 if brutalOptions.ReceiveBPS < mux.BrutalMinSpeedBPS { 34 return nil, E.New("brutal: invalid download speed") 35 } 36 } 37 return mux.NewClient(mux.Options{ 38 Dialer: &clientDialer{dialer}, 39 Logger: logger, 40 Protocol: options.Protocol, 41 MaxConnections: options.MaxConnections, 42 MinStreams: options.MinStreams, 43 MaxStreams: options.MaxStreams, 44 Padding: options.Padding, 45 Brutal: brutalOptions, 46 }) 47 } 48 49 type clientDialer struct { 50 N.Dialer 51 } 52 53 func (d *clientDialer) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) { 54 return d.Dialer.DialContext(adapter.OverrideContext(ctx), network, destination) 55 } 56 57 func (d *clientDialer) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) { 58 return d.Dialer.ListenPacket(adapter.OverrideContext(ctx), destination) 59 }