inbound_relay.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. package shadowsocks_2022
  2. import (
  3. "context"
  4. "strconv"
  5. "strings"
  6. "github.com/sagernet/sing-shadowsocks/shadowaead_2022"
  7. C "github.com/sagernet/sing/common"
  8. A "github.com/sagernet/sing/common/auth"
  9. B "github.com/sagernet/sing/common/buf"
  10. "github.com/sagernet/sing/common/bufio"
  11. E "github.com/sagernet/sing/common/exceptions"
  12. M "github.com/sagernet/sing/common/metadata"
  13. N "github.com/sagernet/sing/common/network"
  14. "github.com/xtls/xray-core/common"
  15. "github.com/xtls/xray-core/common/buf"
  16. "github.com/xtls/xray-core/common/log"
  17. "github.com/xtls/xray-core/common/net"
  18. "github.com/xtls/xray-core/common/protocol"
  19. "github.com/xtls/xray-core/common/session"
  20. "github.com/xtls/xray-core/common/uuid"
  21. "github.com/xtls/xray-core/features/routing"
  22. "github.com/xtls/xray-core/transport/internet/stat"
  23. )
  24. func init() {
  25. common.Must(common.RegisterConfig((*RelayServerConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  26. return NewRelayServer(ctx, config.(*RelayServerConfig))
  27. }))
  28. }
  29. type RelayInbound struct {
  30. networks []net.Network
  31. destinations []*RelayDestination
  32. service *shadowaead_2022.RelayService[int]
  33. }
  34. func NewRelayServer(ctx context.Context, config *RelayServerConfig) (*RelayInbound, error) {
  35. networks := config.Network
  36. if len(networks) == 0 {
  37. networks = []net.Network{
  38. net.Network_TCP,
  39. net.Network_UDP,
  40. }
  41. }
  42. inbound := &RelayInbound{
  43. networks: networks,
  44. destinations: config.Destinations,
  45. }
  46. if !C.Contains(shadowaead_2022.List, config.Method) || !strings.Contains(config.Method, "aes") {
  47. return nil, newError("unsupported method ", config.Method)
  48. }
  49. service, err := shadowaead_2022.NewRelayServiceWithPassword[int](config.Method, config.Key, 500, inbound)
  50. if err != nil {
  51. return nil, newError("create service").Base(err)
  52. }
  53. for i, destination := range config.Destinations {
  54. if destination.Email == "" {
  55. u := uuid.New()
  56. destination.Email = "unnamed-destination-" + strconv.Itoa(i) + "-" + u.String()
  57. }
  58. }
  59. err = service.UpdateUsersWithPasswords(
  60. C.MapIndexed(config.Destinations, func(index int, it *RelayDestination) int { return index }),
  61. C.Map(config.Destinations, func(it *RelayDestination) string { return it.Key }),
  62. C.Map(config.Destinations, func(it *RelayDestination) M.Socksaddr {
  63. return toSocksaddr(net.Destination{
  64. Address: it.Address.AsAddress(),
  65. Port: net.Port(it.Port),
  66. })
  67. }),
  68. )
  69. if err != nil {
  70. return nil, newError("create service").Base(err)
  71. }
  72. inbound.service = service
  73. return inbound, nil
  74. }
  75. func (i *RelayInbound) Network() []net.Network {
  76. return i.networks
  77. }
  78. func (i *RelayInbound) Process(ctx context.Context, network net.Network, connection stat.Connection, dispatcher routing.Dispatcher) error {
  79. inbound := session.InboundFromContext(ctx)
  80. var metadata M.Metadata
  81. if inbound.Source.IsValid() {
  82. metadata.Source = M.ParseSocksaddr(inbound.Source.NetAddr())
  83. }
  84. ctx = session.ContextWithDispatcher(ctx, dispatcher)
  85. if network == net.Network_TCP {
  86. return returnError(i.service.NewConnection(ctx, connection, metadata))
  87. } else {
  88. reader := buf.NewReader(connection)
  89. pc := &natPacketConn{connection}
  90. for {
  91. mb, err := reader.ReadMultiBuffer()
  92. if err != nil {
  93. buf.ReleaseMulti(mb)
  94. return returnError(err)
  95. }
  96. for _, buffer := range mb {
  97. packet := B.As(buffer.Bytes()).ToOwned()
  98. err = i.service.NewPacket(ctx, pc, packet, metadata)
  99. if err != nil {
  100. packet.Release()
  101. buf.ReleaseMulti(mb)
  102. return err
  103. }
  104. buffer.Release()
  105. }
  106. }
  107. }
  108. }
  109. func (i *RelayInbound) NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error {
  110. inbound := session.InboundFromContext(ctx)
  111. userInt, _ := A.UserFromContext[int](ctx)
  112. user := i.destinations[userInt]
  113. inbound.User = &protocol.MemoryUser{
  114. Email: user.Email,
  115. Level: uint32(user.Level),
  116. }
  117. ctx = log.ContextWithAccessMessage(ctx, &log.AccessMessage{
  118. From: metadata.Source,
  119. To: metadata.Destination,
  120. Status: log.AccessAccepted,
  121. Email: user.Email,
  122. })
  123. newError("tunnelling request to tcp:", metadata.Destination).WriteToLog(session.ExportIDToError(ctx))
  124. dispatcher := session.DispatcherFromContext(ctx)
  125. link, err := dispatcher.Dispatch(ctx, toDestination(metadata.Destination, net.Network_TCP))
  126. if err != nil {
  127. return err
  128. }
  129. outConn := &pipeConnWrapper{
  130. &buf.BufferedReader{Reader: link.Reader},
  131. link.Writer,
  132. conn,
  133. }
  134. return bufio.CopyConn(ctx, conn, outConn)
  135. }
  136. func (i *RelayInbound) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata M.Metadata) error {
  137. inbound := session.InboundFromContext(ctx)
  138. userInt, _ := A.UserFromContext[int](ctx)
  139. user := i.destinations[userInt]
  140. inbound.User = &protocol.MemoryUser{
  141. Email: user.Email,
  142. Level: uint32(user.Level),
  143. }
  144. ctx = log.ContextWithAccessMessage(ctx, &log.AccessMessage{
  145. From: metadata.Source,
  146. To: metadata.Destination,
  147. Status: log.AccessAccepted,
  148. Email: user.Email,
  149. })
  150. newError("tunnelling request to udp:", metadata.Destination).WriteToLog(session.ExportIDToError(ctx))
  151. dispatcher := session.DispatcherFromContext(ctx)
  152. destination := toDestination(metadata.Destination, net.Network_UDP)
  153. link, err := dispatcher.Dispatch(ctx, destination)
  154. if err != nil {
  155. return err
  156. }
  157. outConn := &packetConnWrapper{
  158. Reader: link.Reader,
  159. Writer: link.Writer,
  160. Dest: destination,
  161. }
  162. return bufio.CopyPacketConn(ctx, conn, outConn)
  163. }
  164. func (i *RelayInbound) NewError(ctx context.Context, err error) {
  165. if E.IsClosed(err) {
  166. return
  167. }
  168. newError(err).AtWarning().WriteToLog()
  169. }