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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package tls
  2. import (
  3. "bufio"
  4. "bytes"
  5. "github.com/dolonet/mtg-multi/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. // TLS 1.2 is used for both TLS 1.2 and 1.3
  20. var TLSVersion = [SizeVersion]byte{3, 3}
  21. // Conn presents an established TLS 1.3 connection, after handshake
  22. type Conn struct {
  23. essentials.Conn
  24. p *connPayload
  25. }
  26. type connPayload struct {
  27. readBuf bytes.Buffer
  28. connBuffered *bufio.Reader
  29. read bool
  30. write bool
  31. }
  32. func (c Conn) Write(p []byte) (int, error) {
  33. if !c.p.write {
  34. return c.Conn.Write(p)
  35. }
  36. return len(p), WriteRecord(c.Conn, p)
  37. }
  38. func (c Conn) Read(p []byte) (int, error) {
  39. if !c.p.read {
  40. return c.Conn.Read(p)
  41. }
  42. for {
  43. if n, err := c.p.readBuf.Read(p); err == nil {
  44. return n, nil
  45. }
  46. recordType, _, err := ReadRecord(c.p.connBuffered, &c.p.readBuf)
  47. if err != nil {
  48. return 0, err
  49. }
  50. if recordType != TypeApplicationData {
  51. c.p.readBuf.Reset()
  52. }
  53. }
  54. }
  55. func New(conn essentials.Conn, read, write bool) Conn {
  56. newConn := Conn{
  57. Conn: conn,
  58. p: &connPayload{
  59. connBuffered: bufio.NewReaderSize(conn, DefaultBufferSize),
  60. read: read,
  61. write: write,
  62. },
  63. }
  64. newConn.p.readBuf.Grow(DefaultBufferSize)
  65. return newConn
  66. }