/
navigation.go
306 lines (270 loc) Β· 8.28 KB
/
navigation.go
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
package captain
import (
"context"
"errors"
"fmt"
"time"
"github.com/safing/portbase/log"
"github.com/safing/portbase/modules"
"github.com/safing/portmaster/service/intel"
"github.com/safing/portmaster/service/netenv"
"github.com/safing/portmaster/service/profile/endpoints"
"github.com/safing/portmaster/spn/access"
"github.com/safing/portmaster/spn/docks"
"github.com/safing/portmaster/spn/hub"
"github.com/safing/portmaster/spn/navigator"
"github.com/safing/portmaster/spn/terminal"
)
const stopCraneAfterBeingUnsuggestedFor = 6 * time.Hour
var (
// ErrAllHomeHubsExcluded is returned when all available home hubs were excluded.
ErrAllHomeHubsExcluded = errors.New("all home hubs are excluded")
// ErrReInitSPNSuggested is returned when no home hub can be found, even without rules.
ErrReInitSPNSuggested = errors.New("SPN re-init suggested")
)
func establishHomeHub(ctx context.Context) error {
// Get own IP.
locations, ok := netenv.GetInternetLocation()
if !ok || len(locations.All) == 0 {
return errors.New("failed to locate own device")
}
log.Debugf(
"spn/captain: looking for new home hub near %s and %s",
locations.BestV4(),
locations.BestV6(),
)
// Get own entity.
// Checking the entity against the entry policies is somewhat hit and miss
// anyway, as the device location is an approximation.
var myEntity *intel.Entity
if dl := locations.BestV4(); dl != nil && dl.IP != nil {
myEntity = (&intel.Entity{IP: dl.IP}).Init(0)
myEntity.FetchData(ctx)
} else if dl := locations.BestV6(); dl != nil && dl.IP != nil {
myEntity = (&intel.Entity{IP: dl.IP}).Init(0)
myEntity.FetchData(ctx)
}
// Get home hub policy for selecting the home hub.
homePolicy, err := getHomeHubPolicy()
if err != nil {
return err
}
// Build navigation options for searching for a home hub.
opts := &navigator.Options{
Home: &navigator.HomeHubOptions{
HubPolicies: []endpoints.Endpoints{homePolicy},
CheckHubPolicyWith: myEntity,
},
}
// Add requirement to only use Safing nodes when not using community nodes.
if !cfgOptionUseCommunityNodes() {
opts.Home.RequireVerifiedOwners = NonCommunityVerifiedOwners
}
// Require a trusted home node when the routing profile requires less than two hops.
routingProfile := navigator.GetRoutingProfile(cfgOptionRoutingAlgorithm())
if routingProfile.MinHops < 2 {
opts.Home.Regard = opts.Home.Regard.Add(navigator.StateTrusted)
}
// Find nearby hubs.
findCandidates:
candidates, err := navigator.Main.FindNearestHubs(
locations.BestV4().LocationOrNil(),
locations.BestV6().LocationOrNil(),
opts, navigator.HomeHub,
)
if err != nil {
switch {
case errors.Is(err, navigator.ErrEmptyMap):
// bootstrap to the network!
err := bootstrapWithUpdates()
if err != nil {
return err
}
goto findCandidates
case errors.Is(err, navigator.ErrAllPinsDisregarded):
if len(homePolicy) > 0 {
return ErrAllHomeHubsExcluded
}
return ErrReInitSPNSuggested
default:
return fmt.Errorf("failed to find nearby hubs: %w", err)
}
}
// Try connecting to a hub.
var tries int
var candidate *hub.Hub
for tries, candidate = range candidates {
err = connectToHomeHub(ctx, candidate)
if err != nil {
// Check if context is canceled.
if ctx.Err() != nil {
return ctx.Err()
}
// Check if the SPN protocol is stopping again.
if errors.Is(err, terminal.ErrStopping) {
return err
}
log.Warningf("spn/captain: failed to connect to %s as new home: %s", candidate, err)
} else {
log.Infof("spn/captain: established connection to %s as new home with %d failed tries", candidate, tries)
return nil
}
}
if err != nil {
return fmt.Errorf("failed to connect to a new home hub - tried %d hubs: %w", tries+1, err)
}
return errors.New("no home hub candidates available")
}
func connectToHomeHub(ctx context.Context, dst *hub.Hub) error {
// Create new context with timeout.
// The maximum timeout is a worst case safeguard.
// Keep in mind that multiple IPs and protocols may be tried in all configurations.
// Some servers will be (possibly on purpose) hard to reach.
ctx, cancel := context.WithTimeout(ctx, 5*time.Minute)
defer cancel()
// Set and clean up exceptions.
setExceptions(dst.Info.IPv4, dst.Info.IPv6)
defer setExceptions(nil, nil)
// Connect to hub.
crane, err := EstablishCrane(ctx, dst)
if err != nil {
return err
}
// Cleanup connection in case of failure.
var success bool
defer func() {
if !success {
crane.Stop(nil)
}
}()
// Query all gossip msgs on first connection.
gossipQuery, tErr := NewGossipQueryOp(crane.Controller)
if tErr != nil {
log.Warningf("spn/captain: failed to start initial gossip query: %s", tErr)
}
// Wait for gossip query to complete.
select {
case <-gossipQuery.ctx.Done():
case <-ctx.Done():
return context.Canceled
}
// Create communication terminal.
homeTerminal, initData, tErr := docks.NewLocalCraneTerminal(crane, nil, terminal.DefaultHomeHubTerminalOpts())
if tErr != nil {
return tErr.Wrap("failed to create home terminal")
}
tErr = crane.EstablishNewTerminal(homeTerminal, initData)
if tErr != nil {
return tErr.Wrap("failed to connect home terminal")
}
if !DisableAccount {
// Authenticate to home hub.
authOp, tErr := access.AuthorizeToTerminal(homeTerminal)
if tErr != nil {
return tErr.Wrap("failed to authorize")
}
select {
case tErr := <-authOp.Result:
if !tErr.Is(terminal.ErrExplicitAck) {
return tErr.Wrap("failed to authenticate to")
}
case <-time.After(3 * time.Second):
return terminal.ErrTimeout.With("waiting for auth to complete")
case <-ctx.Done():
return terminal.ErrStopping
}
}
// Set new home on map.
ok := navigator.Main.SetHome(dst.ID, homeTerminal)
if !ok {
return errors.New("failed to set home hub on map")
}
// Assign crane to home hub in order to query it later.
docks.AssignCrane(crane.ConnectedHub.ID, crane)
success = true
return nil
}
func optimizeNetwork(ctx context.Context, task *modules.Task) error {
if publicIdentity == nil {
return nil
}
optimize:
result, err := navigator.Main.Optimize(nil)
if err != nil {
if errors.Is(err, navigator.ErrEmptyMap) {
// bootstrap to the network!
err := bootstrapWithUpdates()
if err != nil {
return err
}
goto optimize
}
return err
}
// Create any new connections.
var createdConnections int
var attemptedConnections int
for _, connectTo := range result.SuggestedConnections {
// Skip duplicates.
if connectTo.Duplicate {
continue
}
// Check if connection already exists.
crane := docks.GetAssignedCrane(connectTo.Hub.ID)
if crane != nil {
// Update last suggested timestamp.
crane.NetState.UpdateLastSuggestedAt()
// Continue crane if stopping.
if crane.AbortStopping() {
log.Infof("spn/captain: optimization aborted retiring of %s, removed stopping mark", crane)
crane.NotifyUpdate()
}
// Create new connections if we have connects left.
} else if createdConnections < result.MaxConnect {
attemptedConnections++
crane, tErr := EstablishPublicLane(ctx, connectTo.Hub)
if !tErr.IsOK() {
log.Warningf("spn/captain: failed to establish lane to %s: %s", connectTo.Hub, tErr)
} else {
createdConnections++
crane.NetState.UpdateLastSuggestedAt()
log.Infof("spn/captain: established lane to %s", connectTo.Hub)
}
}
}
// Log optimization result.
if attemptedConnections > 0 {
log.Infof(
"spn/captain: created %d/%d new connections for %s optimization",
createdConnections,
attemptedConnections,
result.Purpose)
} else {
log.Infof(
"spn/captain: checked %d connections for %s optimization",
len(result.SuggestedConnections),
result.Purpose,
)
}
// Retire cranes if unsuggested for a while.
if result.StopOthers {
for _, crane := range docks.GetAllAssignedCranes() {
switch {
case crane.Stopped():
// Crane already stopped.
case crane.IsStopping():
// Crane is stopping, forcibly stop if mine and suggested.
if crane.IsMine() && crane.NetState.StopSuggested() {
crane.Stop(nil)
}
case crane.IsMine() && crane.NetState.StoppingSuggested():
// Mark as stopping if mine and suggested.
crane.MarkStopping()
case crane.NetState.RequestStoppingSuggested(stopCraneAfterBeingUnsuggestedFor):
// Mark as stopping requested.
crane.MarkStoppingRequested()
}
}
}
return nil
}