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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package network
  2. import (
  3. "context"
  4. "fmt"
  5. "net"
  6. "time"
  7. "github.com/libp2p/go-reuseport"
  8. )
  9. type defaultDialer struct {
  10. net.Dialer
  11. bufferSize int
  12. }
  13. func (d *defaultDialer) Dial(network, address string) (net.Conn, error) {
  14. return d.DialContext(context.Background(), network, address)
  15. }
  16. func (d *defaultDialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
  17. switch network {
  18. case "tcp", "tcp4", "tcp6": // nolint: goconst
  19. default:
  20. return nil, fmt.Errorf("unsupported network %s", network)
  21. }
  22. conn, err := d.Dialer.DialContext(ctx, network, address)
  23. if err != nil {
  24. return nil, fmt.Errorf("cannot dial to %s: %w", address, err)
  25. }
  26. tcpConn := conn.(*net.TCPConn)
  27. if err := tcpConn.SetNoDelay(true); err != nil {
  28. conn.Close()
  29. return nil, fmt.Errorf("cannot set TCP_NO_DELAY: %w", err)
  30. }
  31. if err := tcpConn.SetReadBuffer(d.bufferSize); err != nil {
  32. tcpConn.Close()
  33. return nil, fmt.Errorf("cannot set read buffer size: %w", err)
  34. }
  35. if err := tcpConn.SetWriteBuffer(d.bufferSize); err != nil {
  36. tcpConn.Close()
  37. return nil, fmt.Errorf("cannot set write buffer size: %w", err)
  38. }
  39. if err := tcpConn.SetKeepAlive(true); err != nil {
  40. tcpConn.Close()
  41. return nil, fmt.Errorf("cannot enable keep-alive: %w", err)
  42. }
  43. return tcpConn, nil
  44. }
  45. func (d *defaultDialer) TCPBufferSize() int {
  46. return d.bufferSize
  47. }
  48. func NewDefaultDialer(timeout time.Duration, bufferSize int) (Dialer, error) {
  49. switch {
  50. case timeout < 0:
  51. return nil, fmt.Errorf("timeout %v should be positive number", timeout)
  52. case bufferSize < 0:
  53. return nil, fmt.Errorf("buffer size %d should be positive number", bufferSize)
  54. }
  55. if timeout == 0 {
  56. timeout = DefaultTimeout
  57. }
  58. if bufferSize == 0 {
  59. bufferSize = DefaultBufferSize
  60. }
  61. return &defaultDialer{
  62. Dialer: net.Dialer{
  63. Timeout: timeout,
  64. Control: reuseport.Control,
  65. },
  66. bufferSize: bufferSize,
  67. }, nil
  68. }