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

network.go 3.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  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. httpTimeout time.Duration
  25. userAgent string
  26. }
  27. func (n *network) Dial(protocol, address string) (net.Conn, error) {
  28. return n.DialContext(context.Background(), protocol, address)
  29. }
  30. func (n *network) DialContext(ctx context.Context, protocol, address string) (net.Conn, error) {
  31. host, port, _ := net.SplitHostPort(address)
  32. ips, err := n.dnsResolve(protocol, host)
  33. if err != nil {
  34. return nil, fmt.Errorf("cannot resolve dns names: %w", err)
  35. }
  36. if len(ips) > 1 {
  37. rand.Shuffle(len(ips), func(i, j int) {
  38. ips[i], ips[j] = ips[j], ips[i]
  39. })
  40. }
  41. var conn net.Conn
  42. for _, v := range ips {
  43. conn, err = n.dialer.DialContext(ctx, protocol, net.JoinHostPort(v, port))
  44. if err == nil {
  45. return conn, nil
  46. }
  47. }
  48. return nil, fmt.Errorf("cannot dial to %s:%s: %w", protocol, address, err)
  49. }
  50. func (n *network) MakeHTTPClient(dialFunc func(ctx context.Context,
  51. network, address string) (net.Conn, error)) *http.Client {
  52. if dialFunc == nil {
  53. dialFunc = n.DialContext
  54. }
  55. return makeHTTPClient(n.userAgent, n.httpTimeout, dialFunc)
  56. }
  57. func (n *network) dnsResolve(protocol, address string) ([]string, error) {
  58. if net.ParseIP(address) != nil {
  59. return []string{address}, nil
  60. }
  61. ips := []string{}
  62. wg := &sync.WaitGroup{}
  63. mutex := &sync.Mutex{}
  64. switch protocol {
  65. case "tcp", "tcp4":
  66. wg.Add(1)
  67. go func() {
  68. defer wg.Done()
  69. if recs, _, err := n.dns.LookupA(address); err == nil {
  70. mutex.Lock()
  71. defer mutex.Unlock()
  72. for _, v := range recs {
  73. ips = append(ips, v.IP4)
  74. }
  75. }
  76. }()
  77. }
  78. switch protocol {
  79. case "tcp", "tcp6":
  80. wg.Add(1)
  81. go func() {
  82. defer wg.Done()
  83. if recs, _, err := n.dns.LookupAAAA(address); err == nil {
  84. mutex.Lock()
  85. defer mutex.Unlock()
  86. for _, v := range recs {
  87. ips = append(ips, v.IP6)
  88. }
  89. }
  90. }()
  91. }
  92. wg.Wait()
  93. if len(ips) == 0 {
  94. return nil, fmt.Errorf("cannot find any ips for %s:%s", protocol, address)
  95. }
  96. return ips, nil
  97. }
  98. func NewNetwork(dialer Dialer,
  99. userAgent, dohHostname string,
  100. httpTimeout time.Duration) (mtglib.Network, error) {
  101. switch {
  102. case httpTimeout < 0:
  103. return nil, fmt.Errorf("timeout should be positive number %s", httpTimeout)
  104. case httpTimeout == 0:
  105. httpTimeout = DefaultHTTPTimeout
  106. }
  107. if net.ParseIP(dohHostname) == nil {
  108. return nil, fmt.Errorf("hostname %s should be IP address", dohHostname)
  109. }
  110. return &network{
  111. dialer: dialer,
  112. httpTimeout: httpTimeout,
  113. userAgent: userAgent,
  114. dns: doh.Resolver{
  115. Host: dohHostname,
  116. Class: doh.IN,
  117. HTTPClient: makeHTTPClient(userAgent, DNSTimeout, dialer.DialContext),
  118. },
  119. }, nil
  120. }
  121. func makeHTTPClient(userAgent string,
  122. timeout time.Duration,
  123. dialFunc func(ctx context.Context, network, address string) (net.Conn, error)) *http.Client {
  124. return &http.Client{
  125. Timeout: timeout,
  126. Transport: networkHTTPTransport{
  127. userAgent: userAgent,
  128. next: &http.Transport{
  129. DialContext: dialFunc,
  130. },
  131. },
  132. }
  133. }