inbound_multi.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. package shadowsocks_2022
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "strconv"
  6. "strings"
  7. "sync"
  8. "github.com/sagernet/sing-shadowsocks/shadowaead_2022"
  9. C "github.com/sagernet/sing/common"
  10. A "github.com/sagernet/sing/common/auth"
  11. B "github.com/sagernet/sing/common/buf"
  12. "github.com/sagernet/sing/common/bufio"
  13. E "github.com/sagernet/sing/common/exceptions"
  14. M "github.com/sagernet/sing/common/metadata"
  15. N "github.com/sagernet/sing/common/network"
  16. "github.com/xtls/xray-core/common"
  17. "github.com/xtls/xray-core/common/buf"
  18. "github.com/xtls/xray-core/common/log"
  19. "github.com/xtls/xray-core/common/net"
  20. "github.com/xtls/xray-core/common/protocol"
  21. "github.com/xtls/xray-core/common/session"
  22. "github.com/xtls/xray-core/common/singbridge"
  23. "github.com/xtls/xray-core/common/uuid"
  24. "github.com/xtls/xray-core/features/routing"
  25. "github.com/xtls/xray-core/transport/internet/stat"
  26. )
  27. func init() {
  28. common.Must(common.RegisterConfig((*MultiUserServerConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  29. return NewMultiServer(ctx, config.(*MultiUserServerConfig))
  30. }))
  31. }
  32. type MultiUserInbound struct {
  33. sync.Mutex
  34. networks []net.Network
  35. users []*User
  36. service *shadowaead_2022.MultiService[int]
  37. }
  38. func NewMultiServer(ctx context.Context, config *MultiUserServerConfig) (*MultiUserInbound, error) {
  39. networks := config.Network
  40. if len(networks) == 0 {
  41. networks = []net.Network{
  42. net.Network_TCP,
  43. net.Network_UDP,
  44. }
  45. }
  46. inbound := &MultiUserInbound{
  47. networks: networks,
  48. users: config.Users,
  49. }
  50. if config.Key == "" {
  51. return nil, newError("missing key")
  52. }
  53. psk, err := base64.StdEncoding.DecodeString(config.Key)
  54. if err != nil {
  55. return nil, newError("parse config").Base(err)
  56. }
  57. service, err := shadowaead_2022.NewMultiService[int](config.Method, psk, 500, inbound, nil)
  58. if err != nil {
  59. return nil, newError("create service").Base(err)
  60. }
  61. for i, user := range config.Users {
  62. if user.Email == "" {
  63. u := uuid.New()
  64. user.Email = "unnamed-user-" + strconv.Itoa(i) + "-" + u.String()
  65. }
  66. }
  67. err = service.UpdateUsersWithPasswords(
  68. C.MapIndexed(config.Users, func(index int, it *User) int { return index }),
  69. C.Map(config.Users, func(it *User) string { return it.Key }),
  70. )
  71. if err != nil {
  72. return nil, newError("create service").Base(err)
  73. }
  74. inbound.service = service
  75. return inbound, nil
  76. }
  77. // AddUser implements proxy.UserManager.AddUser().
  78. func (i *MultiUserInbound) AddUser(ctx context.Context, u *protocol.MemoryUser) error {
  79. i.Lock()
  80. defer i.Unlock()
  81. account := u.Account.(*MemoryAccount)
  82. if account.Email != "" {
  83. for idx := range i.users {
  84. if i.users[idx].Email == account.Email {
  85. return newError("User ", account.Email, " already exists.")
  86. }
  87. }
  88. }
  89. i.users = append(i.users, &User{
  90. Key: account.Key,
  91. Email: account.Email,
  92. Level: account.Level,
  93. })
  94. // sync to multi service
  95. // Considering implements shadowsocks2022 in xray-core may have better performance.
  96. i.service.UpdateUsersWithPasswords(
  97. C.MapIndexed(i.users, func(index int, it *User) int { return index }),
  98. C.Map(i.users, func(it *User) string { return it.Key }),
  99. )
  100. return nil
  101. }
  102. // RemoveUser implements proxy.UserManager.RemoveUser().
  103. func (i *MultiUserInbound) RemoveUser(ctx context.Context, email string) error {
  104. if email == "" {
  105. return newError("Email must not be empty.")
  106. }
  107. i.Lock()
  108. defer i.Unlock()
  109. idx := -1
  110. for ii, u := range i.users {
  111. if strings.EqualFold(u.Email, email) {
  112. idx = ii
  113. break
  114. }
  115. }
  116. if idx == -1 {
  117. return newError("User ", email, " not found.")
  118. }
  119. ulen := len(i.users)
  120. i.users[idx] = i.users[ulen-1]
  121. i.users[ulen-1] = nil
  122. i.users = i.users[:ulen-1]
  123. // sync to multi service
  124. // Considering implements shadowsocks2022 in xray-core may have better performance.
  125. i.service.UpdateUsersWithPasswords(
  126. C.MapIndexed(i.users, func(index int, it *User) int { return index }),
  127. C.Map(i.users, func(it *User) string { return it.Key }),
  128. )
  129. return nil
  130. }
  131. func (i *MultiUserInbound) Network() []net.Network {
  132. return i.networks
  133. }
  134. func (i *MultiUserInbound) Process(ctx context.Context, network net.Network, connection stat.Connection, dispatcher routing.Dispatcher) error {
  135. inbound := session.InboundFromContext(ctx)
  136. inbound.Name = "shadowsocks-2022-multi"
  137. inbound.CanSpliceCopy = 3
  138. var metadata M.Metadata
  139. if inbound.Source.IsValid() {
  140. metadata.Source = M.ParseSocksaddr(inbound.Source.NetAddr())
  141. }
  142. ctx = session.ContextWithDispatcher(ctx, dispatcher)
  143. if network == net.Network_TCP {
  144. return singbridge.ReturnError(i.service.NewConnection(ctx, connection, metadata))
  145. } else {
  146. reader := buf.NewReader(connection)
  147. pc := &natPacketConn{connection}
  148. for {
  149. mb, err := reader.ReadMultiBuffer()
  150. if err != nil {
  151. buf.ReleaseMulti(mb)
  152. return singbridge.ReturnError(err)
  153. }
  154. for _, buffer := range mb {
  155. packet := B.As(buffer.Bytes()).ToOwned()
  156. buffer.Release()
  157. err = i.service.NewPacket(ctx, pc, packet, metadata)
  158. if err != nil {
  159. packet.Release()
  160. buf.ReleaseMulti(mb)
  161. return err
  162. }
  163. }
  164. }
  165. }
  166. }
  167. func (i *MultiUserInbound) NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error {
  168. inbound := session.InboundFromContext(ctx)
  169. userInt, _ := A.UserFromContext[int](ctx)
  170. user := i.users[userInt]
  171. inbound.User = &protocol.MemoryUser{
  172. Email: user.Email,
  173. Level: uint32(user.Level),
  174. }
  175. ctx = log.ContextWithAccessMessage(ctx, &log.AccessMessage{
  176. From: metadata.Source,
  177. To: metadata.Destination,
  178. Status: log.AccessAccepted,
  179. Email: user.Email,
  180. })
  181. newError("tunnelling request to tcp:", metadata.Destination).WriteToLog(session.ExportIDToError(ctx))
  182. dispatcher := session.DispatcherFromContext(ctx)
  183. destination := singbridge.ToDestination(metadata.Destination, net.Network_TCP)
  184. if !destination.IsValid() {
  185. return newError("invalid destination")
  186. }
  187. link, err := dispatcher.Dispatch(ctx, destination)
  188. if err != nil {
  189. return err
  190. }
  191. return singbridge.CopyConn(ctx, conn, link, conn)
  192. }
  193. func (i *MultiUserInbound) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata M.Metadata) error {
  194. inbound := session.InboundFromContext(ctx)
  195. userInt, _ := A.UserFromContext[int](ctx)
  196. user := i.users[userInt]
  197. inbound.User = &protocol.MemoryUser{
  198. Email: user.Email,
  199. Level: uint32(user.Level),
  200. }
  201. ctx = log.ContextWithAccessMessage(ctx, &log.AccessMessage{
  202. From: metadata.Source,
  203. To: metadata.Destination,
  204. Status: log.AccessAccepted,
  205. Email: user.Email,
  206. })
  207. newError("tunnelling request to udp:", metadata.Destination).WriteToLog(session.ExportIDToError(ctx))
  208. dispatcher := session.DispatcherFromContext(ctx)
  209. destination := singbridge.ToDestination(metadata.Destination, net.Network_UDP)
  210. link, err := dispatcher.Dispatch(ctx, destination)
  211. if err != nil {
  212. return err
  213. }
  214. outConn := &singbridge.PacketConnWrapper{
  215. Reader: link.Reader,
  216. Writer: link.Writer,
  217. Dest: destination,
  218. }
  219. return bufio.CopyPacketConn(ctx, conn, outConn)
  220. }
  221. func (i *MultiUserInbound) NewError(ctx context.Context, err error) {
  222. if E.IsClosed(err) {
  223. return
  224. }
  225. newError(err).AtWarning().WriteToLog()
  226. }