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.

load_balanced_socks5.go 1.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package network
  2. import (
  3. "context"
  4. "fmt"
  5. "math/rand"
  6. "net/url"
  7. "github.com/9seconds/mtg/v2/essentials"
  8. )
  9. type loadBalancedSocks5Dialer struct {
  10. dialers []Dialer
  11. }
  12. func (l loadBalancedSocks5Dialer) Dial(network, address string) (essentials.Conn, error) {
  13. return l.DialContext(context.Background(), network, address)
  14. }
  15. func (l loadBalancedSocks5Dialer) DialContext(ctx context.Context, network, address string) (essentials.Conn, error) {
  16. length := len(l.dialers)
  17. start := rand.Intn(length)
  18. moved := false
  19. for i := start; i != start || !moved; i = (i + 1) % length {
  20. moved = true
  21. if conn, err := l.dialers[i].DialContext(ctx, network, address); err == nil {
  22. return conn, nil
  23. }
  24. }
  25. return nil, ErrCannotDialWithAllProxies
  26. }
  27. // NewLoadBalancedSocks5Dialer builds a new load balancing SOCKS5 dialer.
  28. //
  29. // The main difference from one which is made by NewSocks5Dialer is that we
  30. // actually have a list of these proxies. When dial is requested, any proxy is
  31. // picked and used. If proxy fails for some reason, we try another one.
  32. //
  33. // So, it is mostly useful if you have some routes with proxies which are not
  34. // always online or having buggy network.
  35. func NewLoadBalancedSocks5Dialer(baseDialer Dialer, proxyURLs []*url.URL) (Dialer, error) {
  36. dialers := make([]Dialer, 0, len(proxyURLs))
  37. for _, u := range proxyURLs {
  38. dialer, err := NewSocks5Dialer(newProxyDialer(baseDialer, u), u)
  39. if err != nil {
  40. return nil, fmt.Errorf("cannot build dialer for %s: %w", u.String(), err)
  41. }
  42. dialers = append(dialers, dialer)
  43. }
  44. return loadBalancedSocks5Dialer{
  45. dialers: dialers,
  46. }, nil
  47. }