summaryrefslogtreecommitdiff
path: root/pkg/standalone/bonafide/eip_service.go
blob: c097e8a730d07a0bcfb901e262fac1bc9d549759 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
package bonafide

import (
	"encoding/json"
	"fmt"
	"io"
	"log"
	"math/rand"
	"sort"
	"strconv"
	"strings"
	"time"

	"0xacab.org/leap/bitmask-vpn/pkg/config"
)

const (
	eip1API = config.APIURL + "1/config/eip-service.json"
	eip3API = config.APIURL + "3/config/eip-service.json"
)

type eipService struct {
	Gateways             []gatewayV3
	Locations            map[string]location
	OpenvpnConfiguration openvpnConfig `json:"openvpn_configuration"`
	defaultGateway       string
}

type eipServiceV1 struct {
	Gateways             []gatewayV1
	Locations            map[string]location
	OpenvpnConfiguration openvpnConfig `json:"openvpn_configuration"`
}

type location struct {
	CountryCode string
	Hemisphere  string
	Name        string
	Timezone    string
}

type gatewayV1 struct {
	Capabilities struct {
		Ports     []string
		Protocols []string
	}
	Host      string
	IPAddress string `json:"ip_address"`
	Location  string
}

type gatewayV3 struct {
	Capabilities struct {
		Transport []transportV3
	}
	Host      string
	IPAddress string `json:"ip_address"`
	Location  string
}

type transportV3 struct {
	Type      string
	Protocols []string
	Ports     []string
	Options   map[string]string
}

func (b *Bonafide) fetchEipJSON() error {
	resp, err := b.client.Post(eip3API, "", nil)
	for err != nil {
		log.Printf("Error fetching eip v3 json: %v", err)
		time.Sleep(retryFetchJSONSeconds * time.Second)
		resp, err = b.client.Post(eip3API, "", nil)
	}
	defer resp.Body.Close()

	switch resp.StatusCode {
	case 200:
		b.eip, err = decodeEIP3(resp.Body)
	case 404:
		buf := make([]byte, 128)
		resp.Body.Read(buf)
		log.Printf("Error fetching eip v3 json: %s", buf)
		resp, err = b.client.Post(eip1API, "", nil)
		if err != nil {
			return err
		}
		defer resp.Body.Close()
		if resp.StatusCode != 200 {
			return fmt.Errorf("get eip json has failed with status: %s", resp.Status)
		}

		b.eip, err = decodeEIP1(resp.Body)
	default:
		return fmt.Errorf("get eip json has failed with status: %s", resp.Status)
	}
	if err != nil {
		return err
	}

	b.sortGateways()
	return nil
}

func decodeEIP3(body io.Reader) (*eipService, error) {
	var eip eipService
	decoder := json.NewDecoder(body)
	err := decoder.Decode(&eip)
	return &eip, err
}

func decodeEIP1(body io.Reader) (*eipService, error) {
	var eip1 eipServiceV1
	decoder := json.NewDecoder(body)
	err := decoder.Decode(&eip1)
	if err != nil {
		log.Printf("Error fetching eip v1 json: %v", err)
		return nil, err
	}

	eip3 := eipService{
		Gateways:             make([]gatewayV3, len(eip1.Gateways)),
		Locations:            eip1.Locations,
		OpenvpnConfiguration: eip1.OpenvpnConfiguration,
	}
	for _, g := range eip1.Gateways {
		gateway := gatewayV3{
			Host:      g.Host,
			IPAddress: g.IPAddress,
			Location:  g.Location,
		}
		gateway.Capabilities.Transport = []transportV3{
			transportV3{
				Type:      "openvpn",
				Ports:     g.Capabilities.Ports,
				Protocols: g.Capabilities.Protocols,
			},
		}
		eip3.Gateways = append(eip3.Gateways, gateway)
	}
	return &eip3, nil
}

func (eip eipService) getGateways(transport string) []Gateway {
	gws := []Gateway{}
	for _, g := range eip.Gateways {
		for _, t := range g.Capabilities.Transport {
			if t.Type != transport {
				continue
			}

			gateway := Gateway{
				Host:      g.Host,
				IPAddress: g.IPAddress,
				Location:  g.Location,
				Ports:     t.Ports,
				Protocols: t.Protocols,
				Options:   t.Options,
			}
			gws = append(gws, gateway)
		}
	}
	return gws
}

func (eip *eipService) setDefaultGateway(name string) {
	eip.defaultGateway = name
}

func (eip eipService) getOpenvpnArgs() []string {
	args := []string{}
	for arg, value := range eip.OpenvpnConfiguration {
		switch v := value.(type) {
		case string:
			args = append(args, "--"+arg)
			args = append(args, strings.Split(v, " ")...)
		case bool:
			if v {
				args = append(args, "--"+arg)
			}
		default:
			log.Printf("Unknown openvpn argument type: %s - %v", arg, value)
		}
	}
	return args
}

func (eip *eipService) sortGatewaysByGeolocation(geolocatedGateways []string) {
	gws := make([]gatewayV3, len(eip.Gateways))

	if eip.defaultGateway != "" {
		for _, gw := range eip.Gateways {
			if gw.Location == eip.defaultGateway {
				gws = append(gws, gw)
				break
			}
		}
	}
	for _, host := range geolocatedGateways {
		for _, gw := range eip.Gateways {
			if gw.Host == host {
				gws = append(gws, gw)
			}
		}
	}
	eip.Gateways = gws
}

type gatewayDistance struct {
	gateway  gatewayV3
	distance int
}

func (eip *eipService) sortGatewaysByTimezone(tzOffsetHours int) {
	gws := []gatewayDistance{}

	for _, gw := range eip.Gateways {
		distance := 13
		if gw.Location == eip.defaultGateway {
			distance = -1
		} else {
			gwOffset, err := strconv.Atoi(eip.Locations[gw.Location].Timezone)
			if err != nil {
				log.Printf("Error sorting gateways: %v", err)
			} else {
				distance = tzDistance(tzOffsetHours, gwOffset)
			}
		}
		gws = append(gws, gatewayDistance{gw, distance})
	}
	rand.Seed(time.Now().UnixNano())
	cmp := func(i, j int) bool {
		if gws[i].distance == gws[j].distance {
			return rand.Intn(2) == 1
		}
		return gws[i].distance < gws[j].distance
	}
	sort.Slice(gws, cmp)

	for i, gw := range gws {
		eip.Gateways[i] = gw.gateway
	}
}

func tzDistance(offset1, offset2 int) int {
	abs := func(x int) int {
		if x < 0 {
			return -x
		}
		return x
	}
	distance := abs(offset1 - offset2)
	if distance > 12 {
		distance = 24 - distance
	}
	return distance
}