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.

conn.go 1.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package tls
  2. import (
  3. "bufio"
  4. "bytes"
  5. "github.com/9seconds/mtg/v2/essentials"
  6. )
  7. const (
  8. SizeRecordType = 1
  9. SizeVersion = 2
  10. SizeSize = 2
  11. SizeHeader = SizeRecordType + SizeVersion + SizeSize
  12. MaxRecordSize = 16384
  13. MaxRecordPayloadSize = MaxRecordSize - SizeHeader
  14. DefaultBufferSize = 4096
  15. TypeChangeCipherSpec = 0x14
  16. TypeHandshake = 0x16
  17. TypeApplicationData = 0x17
  18. )
  19. var (
  20. // TLS 1.2 is used for both TLS 1.2 and 1.3
  21. TLSVersion = [SizeVersion]byte{3, 3}
  22. )
  23. // Conn presents an established TLS 1.3 connection, after handshake
  24. type Conn struct {
  25. essentials.Conn
  26. p *connPayload
  27. }
  28. type connPayload struct {
  29. readBuf bytes.Buffer
  30. writeBuf bytes.Buffer
  31. connBuffered *bufio.Reader
  32. read bool
  33. write bool
  34. }
  35. func (c Conn) Write(p []byte) (int, error) {
  36. if !c.p.write {
  37. return c.Conn.Write(p)
  38. }
  39. return len(p), WriteRecord(c.Conn, p)
  40. }
  41. func (c Conn) Read(p []byte) (int, error) {
  42. if !c.p.read {
  43. return c.Conn.Read(p)
  44. }
  45. for {
  46. if n, err := c.p.readBuf.Read(p); err == nil {
  47. return n, nil
  48. }
  49. recordType, _, err := ReadRecord(c.p.connBuffered, &c.p.readBuf)
  50. if err != nil {
  51. return 0, err
  52. }
  53. if recordType != TypeApplicationData {
  54. c.p.readBuf.Reset()
  55. }
  56. }
  57. }
  58. func New(conn essentials.Conn, read, write bool) Conn {
  59. newConn := Conn{
  60. Conn: conn,
  61. p: &connPayload{
  62. connBuffered: bufio.NewReaderSize(conn, DefaultBufferSize),
  63. read: read,
  64. write: write,
  65. },
  66. }
  67. newConn.p.readBuf.Grow(DefaultBufferSize)
  68. newConn.p.writeBuf.Grow(DefaultBufferSize)
  69. return newConn
  70. }