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.

mtproto_frame.go 4.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. package wrappers
  2. import (
  3. "bytes"
  4. "crypto/aes"
  5. "encoding/binary"
  6. "hash/crc32"
  7. "io"
  8. "io/ioutil"
  9. "net"
  10. "github.com/juju/errors"
  11. "go.uber.org/zap"
  12. )
  13. const (
  14. mtprotoFrameMinMessageLength = 12
  15. mtprotoFrameMaxMessageLength = 16777216
  16. )
  17. var mtprotoFramePadding = []byte{0x04, 0x00, 0x00, 0x00}
  18. // MTProtoFrame is a wrapper which converts written data to the MTProtoFrame.
  19. // The format of the frame:
  20. //
  21. // [ MSGLEN(4) | SEQNO(4) | MSG(...) | CRC32(4) | PADDING(4*x) ]
  22. //
  23. // MSGLEN is the length of the message + len of seqno and msglen.
  24. // SEQNO is the number of frame in the receive/send sequence. If client
  25. // sends a message with SeqNo 18, it has to receive message with SeqNo 18.
  26. // MSG is the data which has to be written
  27. // CRC32 is the CRC32 checksum of MSGLEN + SEQNO + MSG
  28. // PADDING is custom padding schema to complete frame length to such that
  29. // len(frame) % 16 == 0
  30. type MTProtoFrame struct {
  31. conn StreamReadWriteCloser
  32. logger *zap.SugaredLogger
  33. readSeqNo int32
  34. writeSeqNo int32
  35. }
  36. func (m *MTProtoFrame) Read() ([]byte, error) { // nolint: gocyclo
  37. buf := &bytes.Buffer{}
  38. sum := crc32.NewIEEE()
  39. writer := io.MultiWriter(buf, sum)
  40. for {
  41. buf.Reset()
  42. sum.Reset()
  43. if _, err := io.CopyN(writer, m.conn, 4); err != nil {
  44. return nil, errors.Annotate(err, "Cannot read frame padding")
  45. }
  46. if !bytes.Equal(buf.Bytes(), mtprotoFramePadding) {
  47. break
  48. }
  49. }
  50. messageLength := binary.LittleEndian.Uint32(buf.Bytes())
  51. m.logger.Debugw("Read MTProto frame",
  52. "messageLength", messageLength,
  53. "sequence_number", m.readSeqNo,
  54. )
  55. if messageLength%4 != 0 || messageLength < mtprotoFrameMinMessageLength ||
  56. messageLength > mtprotoFrameMaxMessageLength {
  57. return nil, errors.Errorf("Incorrect frame message length %d", messageLength)
  58. }
  59. buf.Reset()
  60. buf.Grow(int(messageLength) - 4 - 4)
  61. if _, err := io.CopyN(writer, m.conn, int64(messageLength)-4-4); err != nil {
  62. return nil, errors.Annotate(err, "Cannot read the message frame")
  63. }
  64. var seqNo int32
  65. binary.Read(buf, binary.LittleEndian, &seqNo) // nolint: errcheck
  66. if seqNo != m.readSeqNo {
  67. return nil, errors.Errorf("Unexpected sequence number %d (wait for %d)", seqNo, m.readSeqNo)
  68. }
  69. data, _ := ioutil.ReadAll(buf)
  70. buf.Reset()
  71. // write to buf, not to writer. This is because we are going to fetch
  72. // crc32 checksum.
  73. if _, err := io.CopyN(buf, m.conn, 4); err != nil {
  74. return nil, errors.Annotate(err, "Cannot read checksum")
  75. }
  76. checksum := binary.LittleEndian.Uint32(buf.Bytes())
  77. if checksum != sum.Sum32() {
  78. return nil, errors.Errorf("CRC32 checksum mismatch. Wait for %d, got %d", sum.Sum32(), checksum)
  79. }
  80. m.logger.Debugw("Read MTProto frame",
  81. "messageLength", messageLength,
  82. "sequence_number", m.readSeqNo,
  83. "dataLength", len(data),
  84. "checksum", checksum,
  85. )
  86. m.readSeqNo++
  87. return data, nil
  88. }
  89. func (m *MTProtoFrame) Write(p []byte) (int, error) {
  90. messageLength := 4 + 4 + len(p) + 4
  91. paddingLength := (aes.BlockSize - messageLength%aes.BlockSize) % aes.BlockSize
  92. buf := &bytes.Buffer{}
  93. buf.Grow(messageLength + paddingLength)
  94. binary.Write(buf, binary.LittleEndian, uint32(messageLength)) // nolint: errcheck
  95. binary.Write(buf, binary.LittleEndian, m.writeSeqNo) // nolint: errcheck
  96. buf.Write(p)
  97. checksum := crc32.ChecksumIEEE(buf.Bytes())
  98. binary.Write(buf, binary.LittleEndian, checksum) // nolint: errcheck
  99. buf.Write(bytes.Repeat(mtprotoFramePadding, paddingLength/4))
  100. m.logger.Debugw("Write MTProto frame",
  101. "length", len(p),
  102. "sequence_number", m.writeSeqNo,
  103. "crc32", checksum,
  104. "frame_length", buf.Len(),
  105. )
  106. m.writeSeqNo++
  107. _, err := m.conn.Write(buf.Bytes())
  108. return len(p), err
  109. }
  110. // Logger returns an instance of the logger for this wrapper.
  111. func (m *MTProtoFrame) Logger() *zap.SugaredLogger {
  112. return m.logger
  113. }
  114. // LocalAddr returns local address of the underlying net.Conn.
  115. func (m *MTProtoFrame) LocalAddr() *net.TCPAddr {
  116. return m.conn.LocalAddr()
  117. }
  118. // RemoteAddr returns remote address of the underlying net.Conn.
  119. func (m *MTProtoFrame) RemoteAddr() *net.TCPAddr {
  120. return m.conn.RemoteAddr()
  121. }
  122. // Close closes underlying net.Conn instance.
  123. func (m *MTProtoFrame) Close() error {
  124. return m.conn.Close()
  125. }
  126. // NewMTProtoFrame creates new PacketWrapper for underlying connection.
  127. func NewMTProtoFrame(conn StreamReadWriteCloser, seqNo int32) PacketReadWriteCloser {
  128. return &MTProtoFrame{
  129. conn: conn,
  130. logger: conn.Logger().Named("mtproto-frame"),
  131. readSeqNo: seqNo,
  132. writeSeqNo: seqNo,
  133. }
  134. }