inbound.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  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 != nil && options.Masquerade.Type != "" {
  59. switch options.Masquerade.Type {
  60. case C.Hysterai2MasqueradeTypeFile:
  61. masqueradeHandler = http.FileServer(http.Dir(options.Masquerade.FileOptions.Directory))
  62. case C.Hysterai2MasqueradeTypeProxy:
  63. masqueradeURL, err := url.Parse(options.Masquerade.ProxyOptions.URL)
  64. if err != nil {
  65. return nil, E.Cause(err, "parse masquerade URL")
  66. }
  67. masqueradeHandler = &httputil.ReverseProxy{
  68. Rewrite: func(r *httputil.ProxyRequest) {
  69. r.SetURL(masqueradeURL)
  70. if !options.Masquerade.ProxyOptions.RewriteHost {
  71. r.Out.Host = r.In.Host
  72. }
  73. },
  74. ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) {
  75. w.WriteHeader(http.StatusBadGateway)
  76. },
  77. }
  78. case C.Hysterai2MasqueradeTypeString:
  79. masqueradeHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  80. if options.Masquerade.StringOptions.StatusCode != 0 {
  81. w.WriteHeader(options.Masquerade.StringOptions.StatusCode)
  82. }
  83. for key, values := range options.Masquerade.StringOptions.Headers {
  84. for _, value := range values {
  85. w.Header().Add(key, value)
  86. }
  87. }
  88. w.Write([]byte(options.Masquerade.StringOptions.Content))
  89. })
  90. default:
  91. return nil, E.New("unknown masquerade type: ", options.Masquerade.Type)
  92. }
  93. }
  94. inbound := &Inbound{
  95. Adapter: inbound.NewAdapter(C.TypeHysteria2, tag),
  96. router: router,
  97. logger: logger,
  98. listener: listener.New(listener.Options{
  99. Context: ctx,
  100. Logger: logger,
  101. Listen: options.ListenOptions,
  102. }),
  103. tlsConfig: tlsConfig,
  104. }
  105. var udpTimeout time.Duration
  106. if options.UDPTimeout != 0 {
  107. udpTimeout = time.Duration(options.UDPTimeout)
  108. } else {
  109. udpTimeout = C.UDPTimeout
  110. }
  111. service, err := hysteria2.NewService[int](hysteria2.ServiceOptions{
  112. Context: ctx,
  113. Logger: logger,
  114. BrutalDebug: options.BrutalDebug,
  115. SendBPS: uint64(options.UpMbps * hysteria.MbpsToBps),
  116. ReceiveBPS: uint64(options.DownMbps * hysteria.MbpsToBps),
  117. SalamanderPassword: salamanderPassword,
  118. TLSConfig: tlsConfig,
  119. IgnoreClientBandwidth: options.IgnoreClientBandwidth,
  120. UDPTimeout: udpTimeout,
  121. Handler: inbound,
  122. MasqueradeHandler: masqueradeHandler,
  123. })
  124. if err != nil {
  125. return nil, err
  126. }
  127. userList := make([]int, 0, len(options.Users))
  128. userNameList := make([]string, 0, len(options.Users))
  129. userPasswordList := make([]string, 0, len(options.Users))
  130. for index, user := range options.Users {
  131. userList = append(userList, index)
  132. userNameList = append(userNameList, user.Name)
  133. userPasswordList = append(userPasswordList, user.Password)
  134. }
  135. service.UpdateUsers(userList, userPasswordList)
  136. inbound.service = service
  137. inbound.userNameList = userNameList
  138. return inbound, nil
  139. }
  140. func (h *Inbound) NewConnectionEx(ctx context.Context, conn net.Conn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
  141. ctx = log.ContextWithNewID(ctx)
  142. var metadata adapter.InboundContext
  143. metadata.Inbound = h.Tag()
  144. metadata.InboundType = h.Type()
  145. //nolint:staticcheck
  146. metadata.InboundDetour = h.listener.ListenOptions().Detour
  147. //nolint:staticcheck
  148. metadata.InboundOptions = h.listener.ListenOptions().InboundOptions
  149. metadata.OriginDestination = h.listener.UDPAddr()
  150. metadata.Source = source
  151. metadata.Destination = destination
  152. h.logger.InfoContext(ctx, "inbound connection from ", metadata.Source)
  153. userID, _ := auth.UserFromContext[int](ctx)
  154. if userName := h.userNameList[userID]; userName != "" {
  155. metadata.User = userName
  156. h.logger.InfoContext(ctx, "[", userName, "] inbound connection to ", metadata.Destination)
  157. } else {
  158. h.logger.InfoContext(ctx, "inbound connection to ", metadata.Destination)
  159. }
  160. h.router.RouteConnectionEx(ctx, conn, metadata, onClose)
  161. }
  162. func (h *Inbound) NewPacketConnectionEx(ctx context.Context, conn N.PacketConn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
  163. ctx = log.ContextWithNewID(ctx)
  164. var metadata adapter.InboundContext
  165. metadata.Inbound = h.Tag()
  166. metadata.InboundType = h.Type()
  167. //nolint:staticcheck
  168. metadata.InboundDetour = h.listener.ListenOptions().Detour
  169. //nolint:staticcheck
  170. metadata.InboundOptions = h.listener.ListenOptions().InboundOptions
  171. metadata.OriginDestination = h.listener.UDPAddr()
  172. metadata.Source = source
  173. metadata.Destination = destination
  174. h.logger.InfoContext(ctx, "inbound packet connection from ", metadata.Source)
  175. userID, _ := auth.UserFromContext[int](ctx)
  176. if userName := h.userNameList[userID]; userName != "" {
  177. metadata.User = userName
  178. h.logger.InfoContext(ctx, "[", userName, "] inbound packet connection to ", metadata.Destination)
  179. } else {
  180. h.logger.InfoContext(ctx, "inbound packet connection to ", metadata.Destination)
  181. }
  182. h.router.RoutePacketConnectionEx(ctx, conn, metadata, onClose)
  183. }
  184. func (h *Inbound) Start(stage adapter.StartStage) error {
  185. if stage != adapter.StartStateStart {
  186. return nil
  187. }
  188. if h.tlsConfig != nil {
  189. err := h.tlsConfig.Start()
  190. if err != nil {
  191. return err
  192. }
  193. }
  194. packetConn, err := h.listener.ListenUDP()
  195. if err != nil {
  196. return err
  197. }
  198. return h.service.Start(packetConn)
  199. }
  200. func (h *Inbound) Close() error {
  201. return common.Close(
  202. h.listener,
  203. h.tlsConfig,
  204. common.PtrOrNil(h.service),
  205. )
  206. }