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
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

stream_context.go 1.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package mtglib
  2. import (
  3. "context"
  4. "crypto/rand"
  5. "encoding/base64"
  6. "net"
  7. "time"
  8. "github.com/9seconds/mtg/v2/essentials"
  9. )
  10. type streamContext struct {
  11. ctx context.Context
  12. ctxCancel context.CancelFunc
  13. clientConn essentials.Conn
  14. telegramConn essentials.Conn
  15. streamID string
  16. dc int
  17. logger Logger
  18. }
  19. func (s *streamContext) Deadline() (time.Time, bool) {
  20. return s.ctx.Deadline()
  21. }
  22. func (s *streamContext) Done() <-chan struct{} {
  23. return s.ctx.Done()
  24. }
  25. func (s *streamContext) Err() error {
  26. return s.ctx.Err() // nolint: wrapcheck
  27. }
  28. func (s *streamContext) Value(key interface{}) interface{} {
  29. return s.ctx.Value(key)
  30. }
  31. func (s *streamContext) Close() {
  32. s.ctxCancel()
  33. if s.clientConn != nil {
  34. s.clientConn.Close()
  35. }
  36. if s.telegramConn != nil {
  37. s.telegramConn.Close()
  38. }
  39. }
  40. func (s *streamContext) ClientIP() net.IP {
  41. return s.clientConn.RemoteAddr().(*net.TCPAddr).IP // nolint: forcetypeassert
  42. }
  43. func newStreamContext(ctx context.Context, logger Logger, clientConn essentials.Conn) *streamContext {
  44. connIDBytes := make([]byte, ConnectionIDBytesLength)
  45. if _, err := rand.Read(connIDBytes); err != nil {
  46. panic(err)
  47. }
  48. ctx, cancel := context.WithCancel(ctx)
  49. streamCtx := &streamContext{
  50. ctx: ctx,
  51. ctxCancel: cancel,
  52. clientConn: clientConn,
  53. streamID: base64.RawURLEncoding.EncodeToString(connIDBytes),
  54. }
  55. streamCtx.logger = logger.
  56. BindStr("stream-id", streamCtx.streamID).
  57. BindStr("client-ip", streamCtx.ClientIP().String())
  58. return streamCtx
  59. }