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.

connection.go 1.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package hub
  2. import (
  3. "fmt"
  4. "math/rand"
  5. "sync"
  6. "github.com/9seconds/mtg/conntypes"
  7. "github.com/9seconds/mtg/mtproto"
  8. "github.com/9seconds/mtg/protocol"
  9. )
  10. type connectionID int
  11. type connection struct {
  12. conn conntypes.PacketReadWriteCloser
  13. mutex sync.RWMutex
  14. id connectionID
  15. hub *connectionHub
  16. pending uint
  17. closing bool
  18. }
  19. func (c *connection) Write(packet conntypes.Packet) error {
  20. c.mutex.Lock()
  21. defer c.mutex.Unlock()
  22. err := c.conn.Write(packet)
  23. if err != nil {
  24. // if we tried to write into a socket and it was broken, it is
  25. // a time to reconsider the prescence of this socket at all.
  26. //
  27. // probably we need to remove it completely because it seems
  28. // that connection is broken.
  29. c.pending = 0
  30. }
  31. return err
  32. }
  33. func (c *connection) Read() (conntypes.Packet, error) {
  34. packet, err := c.conn.Read()
  35. c.mutex.Lock()
  36. if err != nil {
  37. c.pending--
  38. } else {
  39. c.pending = 0
  40. }
  41. c.mutex.Unlock()
  42. return packet, err
  43. }
  44. func (c *connection) Stats() (bool, uint) {
  45. c.mutex.RLock()
  46. defer c.mutex.RUnlock()
  47. return c.closing, c.pending
  48. }
  49. func (c *connection) Close() error {
  50. c.mutex.Lock()
  51. defer c.mutex.Unlock()
  52. c.closing = true
  53. return c.conn.Close()
  54. }
  55. func (c *connection) run() {
  56. for {
  57. packet, err := c.conn.Read()
  58. if err != nil {
  59. c.Close()
  60. c.hub.brokenSocketsChan <- c.id
  61. c.hub = nil
  62. return
  63. }
  64. // TODO
  65. if channel, ok := Registry.getChannel(conntypes.ConnID{}); ok {
  66. go channel.write(packet) // nolint: errcheck
  67. }
  68. }
  69. }
  70. func newConnection(hub *connectionHub, req *protocol.TelegramRequest) (*connection, error) {
  71. conn, err := mtproto.TelegramProtocol(req)
  72. if err != nil {
  73. return nil, fmt.Errorf("cannot create a new connection: %w", err)
  74. }
  75. rv := &connection{
  76. conn: conn,
  77. hub: hub,
  78. id: connectionID(rand.Int()),
  79. }
  80. go rv.run()
  81. return rv, nil
  82. }