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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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 connection struct {
  11. conn conntypes.PacketReadWriteCloser
  12. mutex sync.RWMutex
  13. shutdownOnce sync.Once
  14. hub *connectionHub
  15. id int
  16. pending uint
  17. done chan struct{}
  18. }
  19. func (c *connection) read() (conntypes.Packet, error) {
  20. packet, err := c.conn.Read()
  21. c.mutex.Lock()
  22. if err != nil {
  23. c.pending--
  24. } else {
  25. c.pending = 0
  26. }
  27. c.mutex.Unlock()
  28. return packet, err
  29. }
  30. func (c *connection) write(packet conntypes.Packet) error {
  31. err := c.conn.Write(packet)
  32. if err != nil {
  33. // if we tried to write into a socket and it was broken, it is
  34. // a time to reconsider the prescence of this socket at all.
  35. //
  36. // probably we need to remove it completely because it seems
  37. // that connection is broken.
  38. c.mutex.Lock()
  39. c.pending = 0
  40. c.mutex.Unlock()
  41. }
  42. return err
  43. }
  44. func (c *connection) shutdown() {
  45. c.shutdownOnce.Do(func() {
  46. close(c.done)
  47. c.hub.channelBrokenSockets <- c.id
  48. })
  49. }
  50. func (c *connection) closed() bool {
  51. select {
  52. case <-c.done:
  53. return true
  54. default:
  55. return false
  56. }
  57. }
  58. func (c *connection) idle() bool {
  59. c.mutex.RLock()
  60. defer c.mutex.RUnlock()
  61. return c.pending == 0
  62. }
  63. func (c *connection) run() {
  64. for {
  65. packet, err := c.read()
  66. if err != nil {
  67. c.shutdown()
  68. return
  69. }
  70. if channel, ok := Registry.getChannel(conntypes.ConnID{}); ok {
  71. go channel.write(packet) // nolint: errcheck
  72. }
  73. }
  74. }
  75. func newConnection(req *protocol.TelegramRequest, hub *connectionHub) (*connection, error) {
  76. conn, err := mtproto.TelegramProtocol(req)
  77. if err != nil {
  78. return nil, fmt.Errorf("cannot create a new connection: %w", err)
  79. }
  80. rv := &connection{
  81. conn: conn,
  82. hub: hub,
  83. id: rand.Int(),
  84. }
  85. go rv.run()
  86. return rv, nil
  87. }