github.com/sagernet/sing-box@v1.9.0-rc.20/inbound/hysteria.go (about)

     1  //go:build with_quic
     2  
     3  package inbound
     4  
     5  import (
     6  	"context"
     7  	"net"
     8  	"time"
     9  
    10  	"github.com/sagernet/sing-box/adapter"
    11  	"github.com/sagernet/sing-box/common/humanize"
    12  	"github.com/sagernet/sing-box/common/tls"
    13  	C "github.com/sagernet/sing-box/constant"
    14  	"github.com/sagernet/sing-box/log"
    15  	"github.com/sagernet/sing-box/option"
    16  	"github.com/sagernet/sing-quic/hysteria"
    17  	"github.com/sagernet/sing/common"
    18  	"github.com/sagernet/sing/common/auth"
    19  	E "github.com/sagernet/sing/common/exceptions"
    20  	N "github.com/sagernet/sing/common/network"
    21  )
    22  
    23  var _ adapter.Inbound = (*Hysteria)(nil)
    24  
    25  type Hysteria struct {
    26  	myInboundAdapter
    27  	tlsConfig    tls.ServerConfig
    28  	service      *hysteria.Service[int]
    29  	userNameList []string
    30  }
    31  
    32  func NewHysteria(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.HysteriaInboundOptions) (*Hysteria, error) {
    33  	options.UDPFragmentDefault = true
    34  	if options.TLS == nil || !options.TLS.Enabled {
    35  		return nil, C.ErrTLSRequired
    36  	}
    37  	tlsConfig, err := tls.NewServer(ctx, logger, common.PtrValueOrDefault(options.TLS))
    38  	if err != nil {
    39  		return nil, err
    40  	}
    41  	inbound := &Hysteria{
    42  		myInboundAdapter: myInboundAdapter{
    43  			protocol:      C.TypeHysteria,
    44  			network:       []string{N.NetworkUDP},
    45  			ctx:           ctx,
    46  			router:        router,
    47  			logger:        logger,
    48  			tag:           tag,
    49  			listenOptions: options.ListenOptions,
    50  		},
    51  		tlsConfig: tlsConfig,
    52  	}
    53  	var sendBps, receiveBps uint64
    54  	if len(options.Up) > 0 {
    55  		sendBps, err = humanize.ParseBytes(options.Up)
    56  		if err != nil {
    57  			return nil, E.Cause(err, "invalid up speed format: ", options.Up)
    58  		}
    59  	} else {
    60  		sendBps = uint64(options.UpMbps) * hysteria.MbpsToBps
    61  	}
    62  	if len(options.Down) > 0 {
    63  		receiveBps, err = humanize.ParseBytes(options.Down)
    64  		if receiveBps == 0 {
    65  			return nil, E.New("invalid down speed format: ", options.Down)
    66  		}
    67  	} else {
    68  		receiveBps = uint64(options.DownMbps) * hysteria.MbpsToBps
    69  	}
    70  	var udpTimeout time.Duration
    71  	if options.UDPTimeout != 0 {
    72  		udpTimeout = time.Duration(options.UDPTimeout)
    73  	} else {
    74  		udpTimeout = C.UDPTimeout
    75  	}
    76  	service, err := hysteria.NewService[int](hysteria.ServiceOptions{
    77  		Context:       ctx,
    78  		Logger:        logger,
    79  		SendBPS:       sendBps,
    80  		ReceiveBPS:    receiveBps,
    81  		XPlusPassword: options.Obfs,
    82  		TLSConfig:     tlsConfig,
    83  		UDPTimeout:    udpTimeout,
    84  		Handler:       adapter.NewUpstreamHandler(adapter.InboundContext{}, inbound.newConnection, inbound.newPacketConnection, nil),
    85  
    86  		// Legacy options
    87  
    88  		ConnReceiveWindow:   options.ReceiveWindowConn,
    89  		StreamReceiveWindow: options.ReceiveWindowClient,
    90  		MaxIncomingStreams:  int64(options.MaxConnClient),
    91  		DisableMTUDiscovery: options.DisableMTUDiscovery,
    92  	})
    93  	if err != nil {
    94  		return nil, err
    95  	}
    96  	userList := make([]int, 0, len(options.Users))
    97  	userNameList := make([]string, 0, len(options.Users))
    98  	userPasswordList := make([]string, 0, len(options.Users))
    99  	for index, user := range options.Users {
   100  		userList = append(userList, index)
   101  		userNameList = append(userNameList, user.Name)
   102  		var password string
   103  		if user.AuthString != "" {
   104  			password = user.AuthString
   105  		} else {
   106  			password = string(user.Auth)
   107  		}
   108  		userPasswordList = append(userPasswordList, password)
   109  	}
   110  	service.UpdateUsers(userList, userPasswordList)
   111  	inbound.service = service
   112  	inbound.userNameList = userNameList
   113  	return inbound, nil
   114  }
   115  
   116  func (h *Hysteria) newConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
   117  	ctx = log.ContextWithNewID(ctx)
   118  	metadata = h.createMetadata(conn, metadata)
   119  	h.logger.InfoContext(ctx, "inbound connection from ", metadata.Source)
   120  	userID, _ := auth.UserFromContext[int](ctx)
   121  	if userName := h.userNameList[userID]; userName != "" {
   122  		metadata.User = userName
   123  		h.logger.InfoContext(ctx, "[", userName, "] inbound connection to ", metadata.Destination)
   124  	} else {
   125  		h.logger.InfoContext(ctx, "inbound connection to ", metadata.Destination)
   126  	}
   127  	return h.router.RouteConnection(ctx, conn, metadata)
   128  }
   129  
   130  func (h *Hysteria) newPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error {
   131  	ctx = log.ContextWithNewID(ctx)
   132  	metadata = h.createPacketMetadata(conn, metadata)
   133  	h.logger.InfoContext(ctx, "inbound packet connection from ", metadata.Source)
   134  	userID, _ := auth.UserFromContext[int](ctx)
   135  	if userName := h.userNameList[userID]; userName != "" {
   136  		metadata.User = userName
   137  		h.logger.InfoContext(ctx, "[", userName, "] inbound packet connection to ", metadata.Destination)
   138  	} else {
   139  		h.logger.InfoContext(ctx, "inbound packet connection to ", metadata.Destination)
   140  	}
   141  	return h.router.RoutePacketConnection(ctx, conn, metadata)
   142  }
   143  
   144  func (h *Hysteria) Start() error {
   145  	if h.tlsConfig != nil {
   146  		err := h.tlsConfig.Start()
   147  		if err != nil {
   148  			return err
   149  		}
   150  	}
   151  	packetConn, err := h.myInboundAdapter.ListenUDP()
   152  	if err != nil {
   153  		return err
   154  	}
   155  	return h.service.Start(packetConn)
   156  }
   157  
   158  func (h *Hysteria) Close() error {
   159  	return common.Close(
   160  		&h.myInboundAdapter,
   161  		h.tlsConfig,
   162  		common.PtrOrNil(h.service),
   163  	)
   164  }