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 символов.

default.go 2.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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, ok := conn.(*net.TCPConn)
  27. if !ok {
  28. panic("conn type is not tcp")
  29. }
  30. if err := tcpConn.SetNoDelay(true); err != nil {
  31. conn.Close()
  32. return nil, fmt.Errorf("cannot set TCP_NO_DELAY: %w", err)
  33. }
  34. if err := tcpConn.SetReadBuffer(d.bufferSize); err != nil {
  35. tcpConn.Close()
  36. return nil, fmt.Errorf("cannot set read buffer size: %w", err)
  37. }
  38. if err := tcpConn.SetWriteBuffer(d.bufferSize); err != nil {
  39. tcpConn.Close()
  40. return nil, fmt.Errorf("cannot set write buffer size: %w", err)
  41. }
  42. if err := tcpConn.SetKeepAlive(true); err != nil {
  43. tcpConn.Close()
  44. return nil, fmt.Errorf("cannot enable keep-alive: %w", err)
  45. }
  46. return tcpConn, nil
  47. }
  48. // NewDefaultDialer build a new dialer which dials bypassing proxies
  49. // etc.
  50. //
  51. // The most default one you can imagine. But it has tunes TCP
  52. // connections and setups SO_REUSEPORT.
  53. func NewDefaultDialer(timeout time.Duration, bufferSize int) (Dialer, error) {
  54. switch {
  55. case timeout < 0:
  56. return nil, fmt.Errorf("timeout %v should be positive number", timeout)
  57. case bufferSize < 0:
  58. return nil, fmt.Errorf("buffer size %d should be positive number", bufferSize)
  59. }
  60. if timeout == 0 {
  61. timeout = DefaultTimeout
  62. }
  63. if bufferSize == 0 {
  64. bufferSize = DefaultBufferSize
  65. }
  66. return &defaultDialer{
  67. Dialer: net.Dialer{
  68. Timeout: timeout,
  69. Control: reuseport.Control,
  70. },
  71. bufferSize: bufferSize,
  72. }, nil
  73. }