github.com/xtls/xray-core@v1.8.12-0.20240518155711-3168d27b0bdb/common/singbridge/dialer.go (about) 1 package singbridge 2 3 import ( 4 "context" 5 "os" 6 7 M "github.com/sagernet/sing/common/metadata" 8 N "github.com/sagernet/sing/common/network" 9 "github.com/xtls/xray-core/common/net" 10 "github.com/xtls/xray-core/common/net/cnc" 11 "github.com/xtls/xray-core/common/session" 12 "github.com/xtls/xray-core/proxy" 13 "github.com/xtls/xray-core/transport" 14 "github.com/xtls/xray-core/transport/internet" 15 "github.com/xtls/xray-core/transport/pipe" 16 ) 17 18 var _ N.Dialer = (*XrayDialer)(nil) 19 20 type XrayDialer struct { 21 internet.Dialer 22 } 23 24 func NewDialer(dialer internet.Dialer) *XrayDialer { 25 return &XrayDialer{dialer} 26 } 27 28 func (d *XrayDialer) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) { 29 return d.Dialer.Dial(ctx, ToDestination(destination, ToNetwork(network))) 30 } 31 32 func (d *XrayDialer) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) { 33 return nil, os.ErrInvalid 34 } 35 36 type XrayOutboundDialer struct { 37 outbound proxy.Outbound 38 dialer internet.Dialer 39 } 40 41 func NewOutboundDialer(outbound proxy.Outbound, dialer internet.Dialer) *XrayOutboundDialer { 42 return &XrayOutboundDialer{outbound, dialer} 43 } 44 45 func (d *XrayOutboundDialer) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) { 46 outbounds := session.OutboundsFromContext(ctx) 47 if len(outbounds) == 0 { 48 outbounds = []*session.Outbound{{}} 49 ctx = session.ContextWithOutbounds(ctx, outbounds) 50 } 51 ob := outbounds[len(outbounds) - 1] 52 ob.Target = ToDestination(destination, ToNetwork(network)) 53 54 opts := []pipe.Option{pipe.WithSizeLimit(64 * 1024)} 55 uplinkReader, uplinkWriter := pipe.New(opts...) 56 downlinkReader, downlinkWriter := pipe.New(opts...) 57 conn := cnc.NewConnection(cnc.ConnectionInputMulti(downlinkWriter), cnc.ConnectionOutputMulti(uplinkReader)) 58 go d.outbound.Process(ctx, &transport.Link{Reader: downlinkReader, Writer: uplinkWriter}, d.dialer) 59 return conn, nil 60 } 61 62 func (d *XrayOutboundDialer) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) { 63 return nil, os.ErrInvalid 64 }