inbound.go 6.0 KB

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