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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. // NewDefaultDialer build a new dialer which dials bypassing proxies
  46. // etc.
  47. //
  48. // The most default one you can imagine. But it has tunes TCP
  49. // connections and setups SO_REUSEPORT.
  50. func NewDefaultDialer(timeout time.Duration, bufferSize int) (Dialer, error) {
  51. switch {
  52. case timeout < 0:
  53. return nil, fmt.Errorf("timeout %v should be positive number", timeout)
  54. case bufferSize < 0:
  55. return nil, fmt.Errorf("buffer size %d should be positive number", bufferSize)
  56. }
  57. if timeout == 0 {
  58. timeout = DefaultTimeout
  59. }
  60. if bufferSize == 0 {
  61. bufferSize = DefaultBufferSize
  62. }
  63. return &defaultDialer{
  64. Dialer: net.Dialer{
  65. Timeout: timeout,
  66. Control: reuseport.Control,
  67. },
  68. bufferSize: bufferSize,
  69. }, nil
  70. }