hysteria2.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. //go:build with_quic
  2. package inbound
  3. import (
  4. "context"
  5. "net"
  6. "net/http"
  7. "net/http/httputil"
  8. "net/url"
  9. "github.com/sagernet/sing-box/adapter"
  10. "github.com/sagernet/sing-box/common/tls"
  11. C "github.com/sagernet/sing-box/constant"
  12. "github.com/sagernet/sing-box/log"
  13. "github.com/sagernet/sing-box/option"
  14. "github.com/sagernet/sing-quic/hysteria"
  15. "github.com/sagernet/sing-quic/hysteria2"
  16. "github.com/sagernet/sing/common"
  17. "github.com/sagernet/sing/common/auth"
  18. E "github.com/sagernet/sing/common/exceptions"
  19. N "github.com/sagernet/sing/common/network"
  20. )
  21. var _ adapter.Inbound = (*Hysteria2)(nil)
  22. type Hysteria2 struct {
  23. myInboundAdapter
  24. tlsConfig tls.ServerConfig
  25. service *hysteria2.Service[int]
  26. userNameList []string
  27. }
  28. func NewHysteria2(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.Hysteria2InboundOptions) (*Hysteria2, error) {
  29. options.UDPFragmentDefault = true
  30. if options.TLS == nil || !options.TLS.Enabled {
  31. return nil, C.ErrTLSRequired
  32. }
  33. tlsConfig, err := tls.NewServer(ctx, logger, common.PtrValueOrDefault(options.TLS))
  34. if err != nil {
  35. return nil, err
  36. }
  37. var salamanderPassword string
  38. if options.Obfs != nil {
  39. if options.Obfs.Password == "" {
  40. return nil, E.New("missing obfs password")
  41. }
  42. switch options.Obfs.Type {
  43. case hysteria2.ObfsTypeSalamander:
  44. salamanderPassword = options.Obfs.Password
  45. default:
  46. return nil, E.New("unknown obfs type: ", options.Obfs.Type)
  47. }
  48. }
  49. var masqueradeHandler http.Handler
  50. if options.Masquerade != "" {
  51. masqueradeURL, err := url.Parse(options.Masquerade)
  52. if err != nil {
  53. return nil, E.Cause(err, "parse masquerade URL")
  54. }
  55. switch masqueradeURL.Scheme {
  56. case "file":
  57. masqueradeHandler = http.FileServer(http.Dir(masqueradeURL.Path))
  58. case "http", "https":
  59. masqueradeHandler = &httputil.ReverseProxy{
  60. Rewrite: func(r *httputil.ProxyRequest) {
  61. r.SetURL(masqueradeURL)
  62. r.Out.Host = r.In.Host
  63. },
  64. ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) {
  65. w.WriteHeader(http.StatusBadGateway)
  66. },
  67. }
  68. default:
  69. return nil, E.New("unknown masquerade URL scheme: ", masqueradeURL.Scheme)
  70. }
  71. }
  72. inbound := &Hysteria2{
  73. myInboundAdapter: myInboundAdapter{
  74. protocol: C.TypeHysteria2,
  75. network: []string{N.NetworkUDP},
  76. ctx: ctx,
  77. router: router,
  78. logger: logger,
  79. tag: tag,
  80. listenOptions: options.ListenOptions,
  81. },
  82. tlsConfig: tlsConfig,
  83. }
  84. service, err := hysteria2.NewService[int](hysteria2.ServiceOptions{
  85. Context: ctx,
  86. Logger: logger,
  87. SendBPS: uint64(options.UpMbps * hysteria.MbpsToBps),
  88. ReceiveBPS: uint64(options.DownMbps * hysteria.MbpsToBps),
  89. SalamanderPassword: salamanderPassword,
  90. TLSConfig: tlsConfig,
  91. IgnoreClientBandwidth: options.IgnoreClientBandwidth,
  92. Handler: adapter.NewUpstreamHandler(adapter.InboundContext{}, inbound.newConnection, inbound.newPacketConnection, nil),
  93. MasqueradeHandler: masqueradeHandler,
  94. })
  95. if err != nil {
  96. return nil, err
  97. }
  98. userList := make([]int, 0, len(options.Users))
  99. userNameList := make([]string, 0, len(options.Users))
  100. userPasswordList := make([]string, 0, len(options.Users))
  101. for index, user := range options.Users {
  102. userList = append(userList, index)
  103. userNameList = append(userNameList, user.Name)
  104. userPasswordList = append(userPasswordList, user.Password)
  105. }
  106. service.UpdateUsers(userList, userPasswordList)
  107. inbound.service = service
  108. inbound.userNameList = userNameList
  109. return inbound, nil
  110. }
  111. func (h *Hysteria2) newConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
  112. ctx = log.ContextWithNewID(ctx)
  113. metadata = h.createMetadata(conn, metadata)
  114. userID, _ := auth.UserFromContext[int](ctx)
  115. if userName := h.userNameList[userID]; userName != "" {
  116. metadata.User = userName
  117. h.logger.InfoContext(ctx, "[", userName, "] inbound connection to ", metadata.Destination)
  118. } else {
  119. h.logger.InfoContext(ctx, "inbound connection to ", metadata.Destination)
  120. }
  121. return h.router.RouteConnection(ctx, conn, metadata)
  122. }
  123. func (h *Hysteria2) newPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error {
  124. ctx = log.ContextWithNewID(ctx)
  125. metadata = h.createPacketMetadata(conn, metadata)
  126. userID, _ := auth.UserFromContext[int](ctx)
  127. if userName := h.userNameList[userID]; userName != "" {
  128. metadata.User = userName
  129. h.logger.InfoContext(ctx, "[", userName, "] inbound packet connection to ", metadata.Destination)
  130. } else {
  131. h.logger.InfoContext(ctx, "inbound packet connection to ", metadata.Destination)
  132. }
  133. return h.router.RoutePacketConnection(ctx, conn, metadata)
  134. }
  135. func (h *Hysteria2) Start() error {
  136. if h.tlsConfig != nil {
  137. err := h.tlsConfig.Start()
  138. if err != nil {
  139. return err
  140. }
  141. }
  142. packetConn, err := h.myInboundAdapter.ListenUDP()
  143. if err != nil {
  144. return err
  145. }
  146. return h.service.Start(packetConn)
  147. }
  148. func (h *Hysteria2) Close() error {
  149. return common.Close(
  150. &h.myInboundAdapter,
  151. h.tlsConfig,
  152. common.PtrOrNil(h.service),
  153. )
  154. }