server.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. package mtproto
  2. import (
  3. "context"
  4. "time"
  5. "v2ray.com/core"
  6. "v2ray.com/core/common"
  7. "v2ray.com/core/common/buf"
  8. "v2ray.com/core/common/compare"
  9. "v2ray.com/core/common/crypto"
  10. "v2ray.com/core/common/net"
  11. "v2ray.com/core/common/protocol"
  12. "v2ray.com/core/common/session"
  13. "v2ray.com/core/common/signal"
  14. "v2ray.com/core/common/task"
  15. "v2ray.com/core/features/policy"
  16. "v2ray.com/core/features/routing"
  17. "v2ray.com/core/transport/internet"
  18. )
  19. var (
  20. dcList = []net.Address{
  21. net.ParseAddress("149.154.175.50"),
  22. net.ParseAddress("149.154.167.51"),
  23. net.ParseAddress("149.154.175.100"),
  24. net.ParseAddress("149.154.167.91"),
  25. net.ParseAddress("149.154.171.5"),
  26. }
  27. )
  28. type Server struct {
  29. user *protocol.User
  30. account *Account
  31. policy policy.Manager
  32. }
  33. func NewServer(ctx context.Context, config *ServerConfig) (*Server, error) {
  34. if len(config.User) == 0 {
  35. return nil, newError("no user configured.")
  36. }
  37. user := config.User[0]
  38. rawAccount, err := config.User[0].GetTypedAccount()
  39. if err != nil {
  40. return nil, newError("invalid account").Base(err)
  41. }
  42. account, ok := rawAccount.(*Account)
  43. if !ok {
  44. return nil, newError("not a MTProto account")
  45. }
  46. v := core.MustFromContext(ctx)
  47. return &Server{
  48. user: user,
  49. account: account,
  50. policy: v.GetFeature(policy.ManagerType()).(policy.Manager),
  51. }, nil
  52. }
  53. func (s *Server) Network() []net.Network {
  54. return []net.Network{net.Network_TCP}
  55. }
  56. func isValidConnectionType(c [4]byte) bool {
  57. if compare.BytesAll(c[:], 0xef) {
  58. return true
  59. }
  60. if compare.BytesAll(c[:], 0xee) {
  61. return true
  62. }
  63. return false
  64. }
  65. func (s *Server) Process(ctx context.Context, network net.Network, conn internet.Connection, dispatcher routing.Dispatcher) error {
  66. sPolicy := s.policy.ForLevel(s.user.Level)
  67. if err := conn.SetDeadline(time.Now().Add(sPolicy.Timeouts.Handshake)); err != nil {
  68. newError("failed to set deadline").Base(err).WriteToLog(session.ExportIDToError(ctx))
  69. }
  70. auth, err := ReadAuthentication(conn)
  71. if err != nil {
  72. return newError("failed to read authentication header").Base(err)
  73. }
  74. defer putAuthenticationObject(auth)
  75. if err := conn.SetDeadline(time.Time{}); err != nil {
  76. newError("failed to clear deadline").Base(err).WriteToLog(session.ExportIDToError(ctx))
  77. }
  78. auth.ApplySecret(s.account.Secret)
  79. decryptor := crypto.NewAesCTRStream(auth.DecodingKey[:], auth.DecodingNonce[:])
  80. decryptor.XORKeyStream(auth.Header[:], auth.Header[:])
  81. ct := auth.ConnectionType()
  82. if !isValidConnectionType(ct) {
  83. return newError("invalid connection type: ", ct)
  84. }
  85. dcID := auth.DataCenterID()
  86. if dcID >= uint16(len(dcList)) {
  87. return newError("invalid datacenter id: ", dcID)
  88. }
  89. dest := net.Destination{
  90. Network: net.Network_TCP,
  91. Address: dcList[dcID],
  92. Port: net.Port(443),
  93. }
  94. ctx, cancel := context.WithCancel(ctx)
  95. timer := signal.CancelAfterInactivity(ctx, cancel, sPolicy.Timeouts.ConnectionIdle)
  96. ctx = policy.ContextWithBufferPolicy(ctx, sPolicy.Buffer)
  97. sc := SessionContext{
  98. ConnectionType: ct,
  99. DataCenterID: dcID,
  100. }
  101. ctx = ContextWithSessionContext(ctx, sc)
  102. link, err := dispatcher.Dispatch(ctx, dest)
  103. if err != nil {
  104. return newError("failed to dispatch request to: ", dest).Base(err)
  105. }
  106. request := func() error {
  107. defer timer.SetTimeout(sPolicy.Timeouts.DownlinkOnly)
  108. reader := buf.NewReader(crypto.NewCryptionReader(decryptor, conn))
  109. return buf.Copy(reader, link.Writer, buf.UpdateActivity(timer))
  110. }
  111. response := func() error {
  112. defer timer.SetTimeout(sPolicy.Timeouts.UplinkOnly)
  113. encryptor := crypto.NewAesCTRStream(auth.EncodingKey[:], auth.EncodingNonce[:])
  114. writer := buf.NewWriter(crypto.NewCryptionWriter(encryptor, conn))
  115. return buf.Copy(link.Reader, writer, buf.UpdateActivity(timer))
  116. }
  117. var responseDoneAndCloseWriter = task.OnSuccess(response, task.Close(link.Writer))
  118. if err := task.Run(ctx, request, responseDoneAndCloseWriter); err != nil {
  119. common.Interrupt(link.Reader)
  120. common.Interrupt(link.Writer)
  121. return newError("connection ends").Base(err)
  122. }
  123. return nil
  124. }
  125. func init() {
  126. common.Must(common.RegisterConfig((*ServerConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  127. return NewServer(ctx, config.(*ServerConfig))
  128. }))
  129. }