inbound_multi.go 7.8 KB

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