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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package telegram
  2. import (
  3. "errors"
  4. "math/rand"
  5. "net"
  6. "go.uber.org/zap"
  7. "github.com/9seconds/mtg/conntypes"
  8. "github.com/9seconds/mtg/utils"
  9. "github.com/9seconds/mtg/wrappers/stream"
  10. )
  11. type baseTelegram struct {
  12. dialer net.Dialer
  13. logger *zap.SugaredLogger
  14. secret []byte
  15. v4DefaultDC conntypes.DC
  16. v6DefaultDC conntypes.DC
  17. v4Addresses map[conntypes.DC][]string
  18. v6Addresses map[conntypes.DC][]string
  19. }
  20. func (b *baseTelegram) Secret() []byte {
  21. return b.secret
  22. }
  23. func (b *baseTelegram) dial(dc conntypes.DC,
  24. protocol conntypes.ConnectionProtocol) (conntypes.StreamReadWriteCloser, error) {
  25. addresses := make([]string, 0, 2)
  26. if protocol&conntypes.ConnectionProtocolIPv6 != 0 {
  27. addresses = append(addresses, b.chooseAddress(b.v6Addresses, dc, b.v6DefaultDC))
  28. }
  29. if protocol&conntypes.ConnectionProtocolIPv4 != 0 {
  30. addresses = append(addresses, b.chooseAddress(b.v4Addresses, dc, b.v4DefaultDC))
  31. }
  32. for _, addr := range addresses {
  33. conn, err := b.dialer.Dial("tcp", addr)
  34. if err != nil {
  35. b.logger.Infow("Cannot dial to Telegram", "address", addr, "error", err)
  36. continue
  37. }
  38. if err := utils.InitTCP(conn); err != nil {
  39. b.logger.Infow("Cannot initialize TCP socket", "address", addr, "error", err)
  40. continue
  41. }
  42. return stream.NewTelegramConn(dc, conn), nil
  43. }
  44. return nil, errors.New("cannot dial to the chosen DC")
  45. }
  46. func (b *baseTelegram) chooseAddress(addresses map[conntypes.DC][]string,
  47. dc, defaultDC conntypes.DC) string {
  48. addrs, ok := addresses[dc]
  49. if !ok {
  50. addrs = addresses[defaultDC]
  51. }
  52. switch {
  53. case len(addrs) == 1:
  54. return addrs[0]
  55. case len(addrs) > 1:
  56. return addrs[rand.Intn(len(addrs))]
  57. }
  58. return ""
  59. }