Highly-opinionated (ex-bullshit-free) MTPROTO proxy for Telegram. If you use v1.0 or upgrade broke you proxy, please read the chapter Version 2
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

server.go 4.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. package proxy
  2. import (
  3. "context"
  4. "io"
  5. "net"
  6. "strconv"
  7. "sync"
  8. "time"
  9. "github.com/9seconds/mtg/obfuscated2"
  10. "github.com/juju/errors"
  11. uuid "github.com/satori/go.uuid"
  12. "go.uber.org/zap"
  13. )
  14. const bufferSize = 4096
  15. type Server struct {
  16. ip net.IP
  17. port int
  18. secret []byte
  19. logger *zap.SugaredLogger
  20. lsock net.Listener
  21. ctx context.Context
  22. readTimeout time.Duration
  23. writeTimeout time.Duration
  24. stats *Stats
  25. ipv6 bool
  26. }
  27. func (s *Server) Serve() error {
  28. lsock, err := net.Listen("tcp", s.Addr())
  29. if err != nil {
  30. return errors.Annotate(err, "Cannot create listen socket")
  31. }
  32. for {
  33. if conn, err := lsock.Accept(); err != nil {
  34. s.logger.Warn("Cannot allocate incoming connection", "error", err)
  35. } else {
  36. go s.accept(conn)
  37. }
  38. }
  39. return nil
  40. }
  41. func (s *Server) Addr() string {
  42. return net.JoinHostPort(s.ip.String(), strconv.Itoa(s.port))
  43. }
  44. func (s *Server) accept(conn net.Conn) {
  45. defer conn.Close()
  46. defer s.stats.closeConnection()
  47. s.stats.newConnection()
  48. ctx, cancel := context.WithCancel(context.Background())
  49. socketID := s.makeSocketID()
  50. s.logger.Debugw("Client connected",
  51. "secret", s.secret,
  52. "addr", conn.RemoteAddr().String(),
  53. "socketid", socketID,
  54. )
  55. clientConn, dc, err := s.getClientStream(conn, ctx, cancel, socketID)
  56. if err != nil {
  57. s.logger.Warnw("Cannot initialize client connection",
  58. "secret", s.secret,
  59. "addr", conn.RemoteAddr().String(),
  60. "socketid", socketID,
  61. "error", err,
  62. )
  63. return
  64. }
  65. defer clientConn.Close()
  66. tgConn, err := s.getTelegramStream(dc, ctx, cancel, socketID)
  67. if err != nil {
  68. s.logger.Warnw("Cannot initialize Telegram connection",
  69. "socketid", socketID,
  70. "error", err,
  71. )
  72. return
  73. }
  74. defer tgConn.Close()
  75. wait := &sync.WaitGroup{}
  76. wait.Add(2)
  77. go s.pipe(wait, clientConn, tgConn)
  78. go s.pipe(wait, tgConn, clientConn)
  79. <-ctx.Done()
  80. wait.Wait()
  81. s.logger.Debugw("Client disconnected",
  82. "secret", s.secret,
  83. "addr", conn.RemoteAddr().String(),
  84. "socketid", socketID,
  85. )
  86. }
  87. func (s *Server) makeSocketID() string {
  88. return uuid.NewV4().String()
  89. }
  90. func (s *Server) getClientStream(conn net.Conn, ctx context.Context, cancel context.CancelFunc, socketID string) (io.ReadWriteCloser, int16, error) {
  91. wConn := newTimeoutReadWriteCloser(conn, s.readTimeout, s.writeTimeout)
  92. wConn = newTrafficReadWriteCloser(wConn, s.stats.addIncomingTraffic, s.stats.addOutgoingTraffic)
  93. frame, err := obfuscated2.ExtractFrame(wConn)
  94. if err != nil {
  95. return nil, 0, errors.Annotate(err, "Cannot create client stream")
  96. }
  97. obfs2, dc, err := obfuscated2.ParseObfuscated2ClientFrame(s.secret, frame)
  98. if err != nil {
  99. return nil, 0, errors.Annotate(err, "Cannot create client stream")
  100. }
  101. wConn = newLogReadWriteCloser(wConn, s.logger, socketID, "client")
  102. wConn = newCipherReadWriteCloser(wConn, obfs2)
  103. wConn = newCtxReadWriteCloser(wConn, ctx, cancel)
  104. return wConn, dc, nil
  105. }
  106. func (s *Server) getTelegramStream(dc int16, ctx context.Context, cancel context.CancelFunc, socketID string) (io.ReadWriteCloser, error) {
  107. socket, err := dialToTelegram(s.ipv6, dc, s.readTimeout)
  108. if err != nil {
  109. return nil, errors.Annotate(err, "Cannot dial")
  110. }
  111. wConn := newTimeoutReadWriteCloser(socket, s.readTimeout, s.writeTimeout)
  112. wConn = newTrafficReadWriteCloser(wConn, s.stats.addIncomingTraffic, s.stats.addOutgoingTraffic)
  113. obfs2, frame := obfuscated2.MakeTelegramObfuscated2Frame()
  114. if n, err := socket.Write(frame); err != nil || n != len(frame) {
  115. return nil, errors.Annotate(err, "Cannot write hadnshake frame")
  116. }
  117. wConn = newLogReadWriteCloser(wConn, s.logger, socketID, "telegram")
  118. wConn = newCipherReadWriteCloser(wConn, obfs2)
  119. wConn = newCtxReadWriteCloser(wConn, ctx, cancel)
  120. return wConn, nil
  121. }
  122. func (s *Server) pipe(wait *sync.WaitGroup, reader io.Reader, writer io.Writer) {
  123. defer wait.Done()
  124. io.Copy(writer, reader)
  125. }
  126. func NewServer(ip net.IP, port int, secret []byte, logger *zap.SugaredLogger,
  127. readTimeout, writeTimeout time.Duration, ipv6 bool, stat *Stats) *Server {
  128. return &Server{
  129. ip: ip,
  130. port: port,
  131. secret: secret,
  132. ctx: context.Background(),
  133. logger: logger,
  134. readTimeout: readTimeout,
  135. writeTimeout: writeTimeout,
  136. stats: stat,
  137. ipv6: ipv6,
  138. }
  139. }