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.1KB

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