summaryrefslogtreecommitdiffhomepage
path: root/ipn/fake_test.go
blob: 4f6c9273b46e16681b5afbac7dffab7c8fc3d5de (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
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package ipn

import (
	"time"

	"tailscale.com/ipn/ipnstate"
	"tailscale.com/tailcfg"
	"tailscale.com/types/netmap"
)

type FakeBackend struct {
	serverURL string
	notify    func(n Notify)
	live      bool
}

func (b *FakeBackend) Start(opts Options) error {
	b.serverURL = opts.Prefs.ControlURLOrDefault()
	if b.notify == nil {
		panic("FakeBackend.Start: SetNotifyCallback not called")
	}
	nl := NeedsLogin
	if b.notify != nil {
		b.notify(Notify{Prefs: opts.Prefs})
		b.notify(Notify{State: &nl})
	}
	return nil
}

func (b *FakeBackend) SetNotifyCallback(notify func(Notify)) {
	if notify == nil {
		panic("FakeBackend.SetNotifyCallback: notify is nil")
	}
	b.notify = notify
}

func (b *FakeBackend) newState(s State) {
	if b.notify != nil {
		b.notify(Notify{State: &s})
	}
	if s == Running {
		b.live = true
	} else {
		b.live = false
	}
}

func (b *FakeBackend) StartLoginInteractive() {
	u := b.serverURL + "/this/is/fake"
	if b.notify != nil {
		b.notify(Notify{BrowseToURL: &u})
	}
	b.login()
}

func (b *FakeBackend) Login(token *tailcfg.Oauth2Token) {
	b.login()
}

func (b *FakeBackend) login() {
	b.newState(NeedsMachineAuth)
	b.newState(Stopped)
	// TODO(apenwarr): Fill in a more interesting netmap here.
	if b.notify != nil {
		b.notify(Notify{NetMap: &netmap.NetworkMap{}})
	}
	b.newState(Starting)
	// TODO(apenwarr): Fill in a more interesting status.
	if b.notify != nil {
		b.notify(Notify{Engine: &EngineStatus{}})
	}
	b.newState(Running)
}

func (b *FakeBackend) Logout() {
	b.newState(NeedsLogin)
}

func (b *FakeBackend) SetPrefs(new *Prefs) {
	if new == nil {
		panic("FakeBackend.SetPrefs got nil prefs")
	}

	if b.notify != nil {
		b.notify(Notify{Prefs: new.Clone()})
	}
	if new.WantRunning && !b.live {
		b.newState(Starting)
		b.newState(Running)
	} else if !new.WantRunning && b.live {
		b.newState(Stopped)
	}
}

func (b *FakeBackend) RequestEngineStatus() {
	if b.notify != nil {
		b.notify(Notify{Engine: &EngineStatus{}})
	}
}

func (b *FakeBackend) FakeExpireAfter(x time.Duration) {
	if b.notify != nil {
		b.notify(Notify{NetMap: &netmap.NetworkMap{}})
	}
}

func (b *FakeBackend) Ping(ip string, useTSMP bool) {
	if b.notify != nil {
		b.notify(Notify{PingResult: &ipnstate.PingResult{}})
	}
}