github.com/xmplusdev/xmcore@v1.8.11-0.20240412132628-5518b55526af/common/singbridge/handler.go (about) 1 package singbridge 2 3 import ( 4 "context" 5 "io" 6 7 M "github.com/sagernet/sing/common/metadata" 8 N "github.com/sagernet/sing/common/network" 9 "github.com/xmplusdev/xmcore/common/buf" 10 "github.com/xmplusdev/xmcore/common/errors" 11 "github.com/xmplusdev/xmcore/common/net" 12 "github.com/xmplusdev/xmcore/common/session" 13 "github.com/xmplusdev/xmcore/features/routing" 14 "github.com/xmplusdev/xmcore/transport" 15 ) 16 17 var ( 18 _ N.TCPConnectionHandler = (*Dispatcher)(nil) 19 _ N.UDPConnectionHandler = (*Dispatcher)(nil) 20 ) 21 22 type Dispatcher struct { 23 upstream routing.Dispatcher 24 newErrorFunc func(values ...any) *errors.Error 25 } 26 27 func NewDispatcher(dispatcher routing.Dispatcher, newErrorFunc func(values ...any) *errors.Error) *Dispatcher { 28 return &Dispatcher{ 29 upstream: dispatcher, 30 newErrorFunc: newErrorFunc, 31 } 32 } 33 34 func (d *Dispatcher) NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error { 35 xConn := NewConn(conn) 36 return d.upstream.DispatchLink(ctx, ToDestination(metadata.Destination, net.Network_TCP), &transport.Link{ 37 Reader: xConn, 38 Writer: xConn, 39 }) 40 } 41 42 func (d *Dispatcher) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata M.Metadata) error { 43 return d.upstream.DispatchLink(ctx, ToDestination(metadata.Destination, net.Network_UDP), &transport.Link{ 44 Reader: buf.NewPacketReader(conn.(io.Reader)), 45 Writer: buf.NewWriter(conn.(io.Writer)), 46 }) 47 } 48 49 func (d *Dispatcher) NewError(ctx context.Context, err error) { 50 d.newErrorFunc(err).WriteToLog(session.ExportIDToError(ctx)) 51 }