github.com/sagernet/sing-box@v1.9.0-rc.20/common/mux/router.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/log" 10 "github.com/sagernet/sing-box/option" 11 "github.com/sagernet/sing-mux" 12 E "github.com/sagernet/sing/common/exceptions" 13 "github.com/sagernet/sing/common/logger" 14 N "github.com/sagernet/sing/common/network" 15 ) 16 17 type Router struct { 18 router adapter.ConnectionRouter 19 service *mux.Service 20 } 21 22 func NewRouterWithOptions(router adapter.ConnectionRouter, logger logger.ContextLogger, options option.InboundMultiplexOptions) (adapter.ConnectionRouter, error) { 23 if !options.Enabled { 24 return router, nil 25 } 26 var brutalOptions mux.BrutalOptions 27 if options.Brutal != nil && options.Brutal.Enabled { 28 brutalOptions = mux.BrutalOptions{ 29 Enabled: true, 30 SendBPS: uint64(options.Brutal.UpMbps * C.MbpsToBps), 31 ReceiveBPS: uint64(options.Brutal.DownMbps * C.MbpsToBps), 32 } 33 if brutalOptions.SendBPS < mux.BrutalMinSpeedBPS { 34 return nil, E.New("brutal: invalid upload speed") 35 } 36 if brutalOptions.ReceiveBPS < mux.BrutalMinSpeedBPS { 37 return nil, E.New("brutal: invalid download speed") 38 } 39 } 40 service, err := mux.NewService(mux.ServiceOptions{ 41 NewStreamContext: func(ctx context.Context, conn net.Conn) context.Context { 42 return log.ContextWithNewID(ctx) 43 }, 44 Logger: logger, 45 Handler: adapter.NewRouteContextHandler(router, logger), 46 Padding: options.Padding, 47 Brutal: brutalOptions, 48 }) 49 if err != nil { 50 return nil, err 51 } 52 return &Router{router, service}, nil 53 } 54 55 func (r *Router) RouteConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error { 56 if metadata.Destination == mux.Destination { 57 return r.service.NewConnection(adapter.WithContext(ctx, &metadata), conn, adapter.UpstreamMetadata(metadata)) 58 } else { 59 return r.router.RouteConnection(ctx, conn, metadata) 60 } 61 } 62 63 func (r *Router) RoutePacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error { 64 return r.router.RoutePacketConnection(ctx, conn, metadata) 65 }