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
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

conns.go 1.7KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package mtglib
  2. import (
  3. "bytes"
  4. "context"
  5. "fmt"
  6. "io"
  7. "net"
  8. "github.com/9seconds/mtg/v2/essentials"
  9. "github.com/pires/go-proxyproto"
  10. )
  11. type connTraffic struct {
  12. essentials.Conn
  13. streamID string
  14. stream EventStream
  15. ctx context.Context
  16. }
  17. func (c connTraffic) Read(b []byte) (int, error) {
  18. n, err := c.Conn.Read(b)
  19. if n > 0 {
  20. c.stream.Send(c.ctx, NewEventTraffic(c.streamID, uint(n), true))
  21. }
  22. return n, err //nolint: wrapcheck
  23. }
  24. func (c connTraffic) Write(b []byte) (int, error) {
  25. n, err := c.Conn.Write(b)
  26. if n > 0 {
  27. c.stream.Send(c.ctx, NewEventTraffic(c.streamID, uint(n), false))
  28. }
  29. return n, err //nolint: wrapcheck
  30. }
  31. type connRewind struct {
  32. essentials.Conn
  33. buf bytes.Buffer
  34. active io.Reader
  35. }
  36. func (c *connRewind) Read(p []byte) (int, error) {
  37. return c.active.Read(p)
  38. }
  39. func (c *connRewind) Rewind() {
  40. c.active = io.MultiReader(&c.buf, c.Conn)
  41. }
  42. func newConnRewind(conn essentials.Conn) *connRewind {
  43. rv := &connRewind{
  44. Conn: conn,
  45. }
  46. rv.active = io.TeeReader(conn, &rv.buf)
  47. return rv
  48. }
  49. type connProxyProtocol struct {
  50. essentials.Conn
  51. sourceAddr net.Addr
  52. headersWritten bool
  53. }
  54. func (c *connProxyProtocol) Write(p []byte) (int, error) {
  55. if !c.headersWritten {
  56. headers := proxyproto.HeaderProxyFromAddrs(2, c.sourceAddr, c.RemoteAddr())
  57. toSend, err := headers.Format()
  58. if err != nil {
  59. panic(err)
  60. }
  61. if _, err := c.Conn.Write(toSend); err != nil {
  62. return 0, fmt.Errorf("cannot send proxy protocol header: %w", err)
  63. }
  64. c.headersWritten = true
  65. }
  66. return c.Conn.Write(p)
  67. }
  68. func newConnProxyProtocol(source, target essentials.Conn) *connProxyProtocol {
  69. return &connProxyProtocol{
  70. Conn: target,
  71. sourceAddr: source.RemoteAddr(),
  72. }
  73. }