Просмотр исходного кода

Implement IP preferences

tags/v1.0.3^2
9seconds 6 лет назад
Родитель
Сommit
720158f15c
1 измененных файлов: 26 добавлений и 11 удалений
  1. 26
    11
      telegram/base.go

+ 26
- 11
telegram/base.go Просмотреть файл

@@ -7,6 +7,7 @@ import (
7 7
 
8 8
 	"go.uber.org/zap"
9 9
 
10
+	"github.com/9seconds/mtg/config"
10 11
 	"github.com/9seconds/mtg/conntypes"
11 12
 	"github.com/9seconds/mtg/utils"
12 13
 	"github.com/9seconds/mtg/wrappers/stream"
@@ -29,17 +30,7 @@ func (b *baseTelegram) Secret() []byte {
29 30
 
30 31
 func (b *baseTelegram) dial(dc conntypes.DC,
31 32
 	protocol conntypes.ConnectionProtocol) (conntypes.StreamReadWriteCloser, error) {
32
-	addresses := make([]string, 0, 2)
33
-
34
-	if protocol&conntypes.ConnectionProtocolIPv6 != 0 {
35
-		addresses = append(addresses, b.chooseAddress(b.v6Addresses, dc, b.v6DefaultDC))
36
-	}
37
-
38
-	if protocol&conntypes.ConnectionProtocolIPv4 != 0 {
39
-		addresses = append(addresses, b.chooseAddress(b.v4Addresses, dc, b.v4DefaultDC))
40
-	}
41
-
42
-	for _, addr := range addresses {
33
+	for _, addr := range b.getAddresses(dc, protocol) {
43 34
 		conn, err := b.dialer.Dial("tcp", addr)
44 35
 		if err != nil {
45 36
 			b.logger.Infow("Cannot dial to Telegram", "address", addr, "error", err)
@@ -57,6 +48,30 @@ func (b *baseTelegram) dial(dc conntypes.DC,
57 48
 	return nil, errors.New("cannot dial to the chosen DC")
58 49
 }
59 50
 
51
+func (b *baseTelegram) getAddresses(dc conntypes.DC, protocol conntypes.ConnectionProtocol) []string {
52
+	addresses := make([]string, 0, 2)
53
+	protos := []conntypes.ConnectionProtocol{
54
+		conntypes.ConnectionProtocolIPv6,
55
+		conntypes.ConnectionProtocolIPv4,
56
+	}
57
+
58
+	if config.C.PreferIP == config.PreferIPv4 {
59
+		protos[0], protos[1] = protos[1], protos[0]
60
+	}
61
+
62
+	for _, proto := range protos {
63
+		switch {
64
+		case proto&protocol == 0:
65
+		case proto&conntypes.ConnectionProtocolIPv6 != 0:
66
+			addresses = append(addresses, b.chooseAddress(b.v6Addresses, dc, b.v6DefaultDC))
67
+		case proto&conntypes.ConnectionProtocolIPv4 != 0:
68
+			addresses = append(addresses, b.chooseAddress(b.v4Addresses, dc, b.v4DefaultDC))
69
+		}
70
+	}
71
+
72
+	return addresses
73
+}
74
+
60 75
 func (b *baseTelegram) chooseAddress(addresses map[conntypes.DC][]string,
61 76
 	dc, defaultDC conntypes.DC) string {
62 77
 	addrs, ok := addresses[dc]

Загрузка…
Отмена
Сохранить