hysteria2.go 5.4 KB

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