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
|
/* SPDX-License-Identifier: MIT
*
* Copyright (C) 2019 WireGuard LLC. All Rights Reserved.
*/
package ui
import (
"fmt"
"github.com/lxn/walk"
"golang.zx2c4.com/wireguard/windows/service"
)
type TunnelTracker struct {
activeTunnel *service.Tunnel
activeTunnelChanged walk.EventPublisher
tunnelChangeCB *service.TunnelChangeCallback
inTransition bool
}
func (tt *TunnelTracker) ActiveTunnel() *service.Tunnel {
return tt.activeTunnel
}
func (tt *TunnelTracker) ActivateTunnel(tunnel *service.Tunnel) error {
if tunnel == tt.activeTunnel {
return nil
}
if err := tt.DeactivateTunnel(); err != nil {
return fmt.Errorf("ActivateTunnel: Failed to deactivate tunnel '%s': %v", tunnel.Name, err)
}
if err := tunnel.Start(); err != nil {
return fmt.Errorf("ActivateTunnel: Failed to start tunnel '%s': %v", tunnel.Name, err)
}
return nil
}
func (tt *TunnelTracker) DeactivateTunnel() error {
if tt.activeTunnel == nil {
return nil
}
state, err := tt.activeTunnel.State()
if err != nil {
return fmt.Errorf("DeactivateTunnel: Failed to retrieve state for tunnel %s: %v", tt.activeTunnel.Name, err)
}
if state == service.TunnelStarted {
if err := tt.activeTunnel.Stop(); err != nil {
return fmt.Errorf("DeactivateTunnel: Failed to stop tunnel '%s': %v", tt.activeTunnel.Name, err)
}
}
if state == service.TunnelStarted || state == service.TunnelStopping {
if err := tt.activeTunnel.WaitForStop(); err != nil {
return fmt.Errorf("DeactivateTunnel: Failed to wait for tunnel '%s' to stop: %v", tt.activeTunnel.Name, err)
}
}
return nil
}
func (tt *TunnelTracker) ActiveTunnelChanged() *walk.Event {
return tt.activeTunnelChanged.Event()
}
func (tt *TunnelTracker) InTransition() bool {
return tt.inTransition
}
func (tt *TunnelTracker) SetTunnelState(tunnel *service.Tunnel, state service.TunnelState, err error) {
if err != nil {
tt.inTransition = false
}
switch state {
case service.TunnelStarted:
tt.inTransition = false
tt.activeTunnel = tunnel
case service.TunnelStarting, service.TunnelStopping:
tt.inTransition = true
case service.TunnelStopped:
if tt.activeTunnel != nil && tt.activeTunnel.Name == tunnel.Name {
tt.inTransition = false
}
tt.activeTunnel = nil
default:
return
}
tt.activeTunnelChanged.Publish()
}
|