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.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package stream
  2. import (
  3. "context"
  4. "fmt"
  5. "net"
  6. "time"
  7. "go.uber.org/zap"
  8. "mtg/conntypes"
  9. )
  10. type wrapperCtx struct {
  11. parent conntypes.StreamReadWriteCloser
  12. ctx context.Context
  13. cancel context.CancelFunc
  14. }
  15. func (w *wrapperCtx) WriteTimeout(p []byte, timeout time.Duration) (int, error) {
  16. select {
  17. case <-w.ctx.Done():
  18. w.Close()
  19. return 0, fmt.Errorf("cannot write because context was closed: %w", w.ctx.Err())
  20. default:
  21. return w.parent.WriteTimeout(p, timeout)
  22. }
  23. }
  24. func (w *wrapperCtx) Write(p []byte) (int, error) {
  25. select {
  26. case <-w.ctx.Done():
  27. w.Close()
  28. return 0, fmt.Errorf("cannot write because context was closed: %w", w.ctx.Err())
  29. default:
  30. return w.parent.Write(p)
  31. }
  32. }
  33. func (w *wrapperCtx) ReadTimeout(p []byte, timeout time.Duration) (int, error) {
  34. select {
  35. case <-w.ctx.Done():
  36. w.Close()
  37. return 0, fmt.Errorf("cannot write because context was closed: %w", w.ctx.Err())
  38. default:
  39. return w.parent.ReadTimeout(p, timeout)
  40. }
  41. }
  42. func (w *wrapperCtx) Read(p []byte) (int, error) {
  43. select {
  44. case <-w.ctx.Done():
  45. w.Close()
  46. return 0, fmt.Errorf("cannot write because context was closed: %w", w.ctx.Err())
  47. default:
  48. return w.parent.Read(p)
  49. }
  50. }
  51. func (w *wrapperCtx) Close() error {
  52. w.cancel()
  53. return w.parent.Close()
  54. }
  55. func (w *wrapperCtx) Conn() net.Conn {
  56. return w.parent.Conn()
  57. }
  58. func (w *wrapperCtx) Logger() *zap.SugaredLogger {
  59. return w.parent.Logger().Named("ctx")
  60. }
  61. func (w *wrapperCtx) LocalAddr() *net.TCPAddr {
  62. return w.parent.LocalAddr()
  63. }
  64. func (w *wrapperCtx) RemoteAddr() *net.TCPAddr {
  65. return w.parent.RemoteAddr()
  66. }
  67. func NewCtx(ctx context.Context,
  68. cancel context.CancelFunc,
  69. parent conntypes.StreamReadWriteCloser) conntypes.StreamReadWriteCloser {
  70. return &wrapperCtx{
  71. parent: parent,
  72. ctx: ctx,
  73. cancel: cancel,
  74. }
  75. }