inbound.go 6.3 KB

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