inbound_multi.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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. var metadata M.Metadata
  138. if inbound.Source.IsValid() {
  139. metadata.Source = M.ParseSocksaddr(inbound.Source.NetAddr())
  140. }
  141. ctx = session.ContextWithDispatcher(ctx, dispatcher)
  142. if network == net.Network_TCP {
  143. return singbridge.ReturnError(i.service.NewConnection(ctx, connection, metadata))
  144. } else {
  145. reader := buf.NewReader(connection)
  146. pc := &natPacketConn{connection}
  147. for {
  148. mb, err := reader.ReadMultiBuffer()
  149. if err != nil {
  150. buf.ReleaseMulti(mb)
  151. return singbridge.ReturnError(err)
  152. }
  153. for _, buffer := range mb {
  154. packet := B.As(buffer.Bytes()).ToOwned()
  155. err = i.service.NewPacket(ctx, pc, packet, metadata)
  156. if err != nil {
  157. packet.Release()
  158. buf.ReleaseMulti(mb)
  159. return err
  160. }
  161. buffer.Release()
  162. }
  163. }
  164. }
  165. }
  166. func (i *MultiUserInbound) NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error {
  167. inbound := session.InboundFromContext(ctx)
  168. userInt, _ := A.UserFromContext[int](ctx)
  169. user := i.users[userInt]
  170. inbound.User = &protocol.MemoryUser{
  171. Email: user.Email,
  172. Level: uint32(user.Level),
  173. }
  174. ctx = log.ContextWithAccessMessage(ctx, &log.AccessMessage{
  175. From: metadata.Source,
  176. To: metadata.Destination,
  177. Status: log.AccessAccepted,
  178. Email: user.Email,
  179. })
  180. newError("tunnelling request to tcp:", metadata.Destination).WriteToLog(session.ExportIDToError(ctx))
  181. dispatcher := session.DispatcherFromContext(ctx)
  182. destination := singbridge.ToDestination(metadata.Destination, net.Network_TCP)
  183. if !destination.IsValid() {
  184. return newError("invalid destination")
  185. }
  186. link, err := dispatcher.Dispatch(ctx, destination)
  187. if err != nil {
  188. return err
  189. }
  190. return singbridge.CopyConn(ctx, conn, link, conn)
  191. }
  192. func (i *MultiUserInbound) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata M.Metadata) error {
  193. inbound := session.InboundFromContext(ctx)
  194. userInt, _ := A.UserFromContext[int](ctx)
  195. user := i.users[userInt]
  196. inbound.User = &protocol.MemoryUser{
  197. Email: user.Email,
  198. Level: uint32(user.Level),
  199. }
  200. ctx = log.ContextWithAccessMessage(ctx, &log.AccessMessage{
  201. From: metadata.Source,
  202. To: metadata.Destination,
  203. Status: log.AccessAccepted,
  204. Email: user.Email,
  205. })
  206. newError("tunnelling request to udp:", metadata.Destination).WriteToLog(session.ExportIDToError(ctx))
  207. dispatcher := session.DispatcherFromContext(ctx)
  208. destination := singbridge.ToDestination(metadata.Destination, net.Network_UDP)
  209. link, err := dispatcher.Dispatch(ctx, destination)
  210. if err != nil {
  211. return err
  212. }
  213. outConn := &singbridge.PacketConnWrapper{
  214. Reader: link.Reader,
  215. Writer: link.Writer,
  216. Dest: destination,
  217. }
  218. return bufio.CopyPacketConn(ctx, conn, outConn)
  219. }
  220. func (i *MultiUserInbound) NewError(ctx context.Context, err error) {
  221. if E.IsClosed(err) {
  222. return
  223. }
  224. newError(err).AtWarning().WriteToLog()
  225. }