github.com/sagernet/sing-box@v1.9.0-rc.20/common/uot/router.go (about)

     1  package uot
     2  
     3  import (
     4  	"context"
     5  	"net"
     6  	"net/netip"
     7  
     8  	"github.com/sagernet/sing-box/adapter"
     9  	E "github.com/sagernet/sing/common/exceptions"
    10  	"github.com/sagernet/sing/common/logger"
    11  	M "github.com/sagernet/sing/common/metadata"
    12  	N "github.com/sagernet/sing/common/network"
    13  	"github.com/sagernet/sing/common/uot"
    14  )
    15  
    16  var _ adapter.ConnectionRouter = (*Router)(nil)
    17  
    18  type Router struct {
    19  	router adapter.ConnectionRouter
    20  	logger logger.ContextLogger
    21  }
    22  
    23  func NewRouter(router adapter.ConnectionRouter, logger logger.ContextLogger) *Router {
    24  	return &Router{router, logger}
    25  }
    26  
    27  func (r *Router) RouteConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
    28  	switch metadata.Destination.Fqdn {
    29  	case uot.MagicAddress:
    30  		request, err := uot.ReadRequest(conn)
    31  		if err != nil {
    32  			return E.Cause(err, "read UoT request")
    33  		}
    34  		if request.IsConnect {
    35  			r.logger.InfoContext(ctx, "inbound UoT connect connection to ", request.Destination)
    36  		} else {
    37  			r.logger.InfoContext(ctx, "inbound UoT connection to ", request.Destination)
    38  		}
    39  		metadata.Domain = metadata.Destination.Fqdn
    40  		metadata.Destination = request.Destination
    41  		return r.router.RoutePacketConnection(ctx, uot.NewConn(conn, *request), metadata)
    42  	case uot.LegacyMagicAddress:
    43  		r.logger.InfoContext(ctx, "inbound legacy UoT connection")
    44  		metadata.Domain = metadata.Destination.Fqdn
    45  		metadata.Destination = M.Socksaddr{Addr: netip.IPv4Unspecified()}
    46  		return r.RoutePacketConnection(ctx, uot.NewConn(conn, uot.Request{}), metadata)
    47  	}
    48  	return r.router.RouteConnection(ctx, conn, metadata)
    49  }
    50  
    51  func (r *Router) RoutePacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error {
    52  	return r.router.RoutePacketConnection(ctx, conn, metadata)
    53  }