github.com/moqsien/xraycore@v1.8.5/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/moqsien/xraycore/common/buf"
    10  	"github.com/moqsien/xraycore/common/errors"
    11  	"github.com/moqsien/xraycore/common/net"
    12  	"github.com/moqsien/xraycore/common/session"
    13  	"github.com/moqsien/xraycore/features/routing"
    14  	"github.com/moqsien/xraycore/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  }