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.

network.go 3.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. package network
  2. import (
  3. "context"
  4. "fmt"
  5. "math/rand"
  6. "net"
  7. "net/http"
  8. "sync"
  9. "time"
  10. "github.com/9seconds/mtg/v2/mtglib"
  11. doh "github.com/babolivier/go-doh-client"
  12. )
  13. type networkHTTPTransport struct {
  14. userAgent string
  15. next http.RoundTripper
  16. }
  17. func (n networkHTTPTransport) RoundTrip(req *http.Request) (*http.Response, error) {
  18. req.Header.Set("User-Agent", n.userAgent)
  19. return n.next.RoundTrip(req)
  20. }
  21. type network struct {
  22. dialer Dialer
  23. dns doh.Resolver
  24. idleTimeout time.Duration
  25. httpTimeout time.Duration
  26. userAgent string
  27. }
  28. func (n *network) Dial(protocol, address string) (net.Conn, error) {
  29. return n.DialContext(context.Background(), protocol, address)
  30. }
  31. func (n *network) DialContext(ctx context.Context, protocol, address string) (net.Conn, error) {
  32. host, port, _ := net.SplitHostPort(address)
  33. ips, err := n.dnsResolve(protocol, host)
  34. if err != nil {
  35. return nil, fmt.Errorf("cannot resolve dns names: %w", err)
  36. }
  37. if len(ips) > 1 {
  38. rand.Shuffle(len(ips), func(i, j int) {
  39. ips[i], ips[j] = ips[j], ips[i]
  40. })
  41. }
  42. var conn net.Conn
  43. for _, v := range ips {
  44. conn, err = n.dialer.DialContext(ctx, protocol, net.JoinHostPort(v, port))
  45. if err == nil {
  46. return conn, nil
  47. }
  48. }
  49. return nil, fmt.Errorf("cannot dial to %s:%s: %w", protocol, address, err)
  50. }
  51. func (n *network) MakeHTTPClient(dialFunc func(ctx context.Context,
  52. network, address string) (net.Conn, error)) *http.Client {
  53. if dialFunc == nil {
  54. dialFunc = n.DialContext
  55. }
  56. return makeHTTPClient(n.userAgent, n.httpTimeout, dialFunc)
  57. }
  58. func (n *network) IdleTimeout() time.Duration {
  59. return n.idleTimeout
  60. }
  61. func (n *network) TCPBufferSize() int {
  62. return n.dialer.TCPBufferSize()
  63. }
  64. func (n *network) dnsResolve(protocol, address string) ([]string, error) {
  65. if net.ParseIP(address) != nil {
  66. return []string{address}, nil
  67. }
  68. ips := []string{}
  69. wg := &sync.WaitGroup{}
  70. mutex := &sync.Mutex{}
  71. switch protocol {
  72. case "tcp", "tcp4":
  73. wg.Add(1)
  74. go func() {
  75. defer wg.Done()
  76. if recs, _, err := n.dns.LookupA(address); err == nil {
  77. mutex.Lock()
  78. defer mutex.Unlock()
  79. for _, v := range recs {
  80. ips = append(ips, v.IP4)
  81. }
  82. }
  83. }()
  84. }
  85. switch protocol {
  86. case "tcp", "tcp6":
  87. wg.Add(1)
  88. go func() {
  89. defer wg.Done()
  90. if recs, _, err := n.dns.LookupAAAA(address); err == nil {
  91. mutex.Lock()
  92. defer mutex.Unlock()
  93. for _, v := range recs {
  94. ips = append(ips, v.IP6)
  95. }
  96. }
  97. }()
  98. }
  99. wg.Wait()
  100. if len(ips) == 0 {
  101. return nil, fmt.Errorf("cannot find any ips for %s:%s", protocol, address)
  102. }
  103. return ips, nil
  104. }
  105. func NewNetwork(dialer Dialer,
  106. userAgent, dohHostname string,
  107. httpTimeout, idleTimeout time.Duration) (mtglib.Network, error) {
  108. switch {
  109. case httpTimeout < 0:
  110. return nil, fmt.Errorf("timeout should be positive number %s", httpTimeout)
  111. case httpTimeout == 0:
  112. httpTimeout = DefaultHTTPTimeout
  113. }
  114. switch {
  115. case idleTimeout < 0:
  116. return nil, fmt.Errorf("timeout should be positive number %s", idleTimeout)
  117. case idleTimeout == 0:
  118. idleTimeout = DefaultIdleTimeout
  119. }
  120. if net.ParseIP(dohHostname) == nil {
  121. return nil, fmt.Errorf("hostname %s should be IP address", dohHostname)
  122. }
  123. return &network{
  124. dialer: dialer,
  125. idleTimeout: idleTimeout,
  126. httpTimeout: httpTimeout,
  127. userAgent: userAgent,
  128. dns: doh.Resolver{
  129. Host: dohHostname,
  130. Class: doh.IN,
  131. HTTPClient: makeHTTPClient(userAgent, DNSTimeout, dialer.DialContext),
  132. },
  133. }, nil
  134. }
  135. func makeHTTPClient(userAgent string,
  136. timeout time.Duration,
  137. dialFunc func(ctx context.Context, network, address string) (net.Conn, error)) *http.Client {
  138. return &http.Client{
  139. Timeout: timeout,
  140. Transport: networkHTTPTransport{
  141. userAgent: userAgent,
  142. next: &http.Transport{
  143. DialContext: dialFunc,
  144. },
  145. },
  146. }
  147. }