-
-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathtailscale.go
More file actions
300 lines (251 loc) · 7.87 KB
/
tailscale.go
File metadata and controls
300 lines (251 loc) · 7.87 KB
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
//go:build tailscale
package main
import (
"context"
"crypto/rand"
"encoding/hex"
"fmt"
"log"
"net"
"os"
"path/filepath"
"strings"
"sync"
"tailscale.com/ipn/ipnstate"
"tailscale.com/tsnet"
)
// TailscaleManager encapsulates tsnet.Server lifecycle management
type TailscaleManager struct {
server *tsnet.Server
config *configuration
started bool
funnelEnabled bool // Current Funnel state
tsListener net.Listener // Current Tailscale listener
mu sync.Mutex // Protect concurrent access
ready chan struct{} // Closed when Tailscale is ready (for async startup)
startErr error // Error from background startup
}
// NewTailscaleManager creates a new TailscaleManager with the given configuration
func NewTailscaleManager(cfg *configuration) *TailscaleManager {
return &TailscaleManager{
config: cfg,
}
}
// generateRandomSuffix creates a short random hex string for ephemeral hostnames
func generateRandomSuffix() string {
b := make([]byte, 3) // 3 bytes = 6 hex chars
rand.Read(b)
return hex.EncodeToString(b)
}
// Start initializes the Tailscale server and returns a listener
func (tm *TailscaleManager) Start(ctx context.Context) (net.Listener, error) {
// Create state directory with proper permissions
if err := tm.ensureStateDir(); err != nil {
return nil, fmt.Errorf("failed to create state directory: %w", err)
}
// Determine hostname - add random suffix for ephemeral nodes
hostname := tm.config.TailscaleHostname
if tm.config.TailscaleEphemeral {
hostname = fmt.Sprintf("%s-%s", hostname, generateRandomSuffix())
}
// Create and configure tsnet.Server
tm.server = &tsnet.Server{
Hostname: hostname,
Dir: tm.config.TailscaleStateDir,
}
// Configure auth key for headless operation
if tm.config.TailscaleAuthKey != "" {
tm.server.AuthKey = tm.config.TailscaleAuthKey
}
// Configure ephemeral mode
if tm.config.TailscaleEphemeral {
tm.server.Ephemeral = true
}
// Configure logging
if !tm.config.TailscaleVerbose {
tm.server.Logf = func(string, ...any) {}
}
// Wait for Tailscale network to be ready
log.Println("Waiting for Tailscale network to be ready...")
status, err := tm.server.Up(ctx)
if err != nil {
return nil, fmt.Errorf("failed to start Tailscale: %w", err)
}
tm.started = true
// Log connection information
tm.logConnectionInfo(status)
// Create the appropriate listener
listener, err := tm.createListener()
if err != nil {
return nil, err
}
tm.mu.Lock()
tm.tsListener = listener
tm.funnelEnabled = tm.config.TailscaleFunnel
tm.mu.Unlock()
return listener, nil
}
// ensureStateDir creates the state directory with proper permissions
func (tm *TailscaleManager) ensureStateDir() error {
dir := tm.config.TailscaleStateDir
if dir == "" {
return fmt.Errorf("state directory not configured")
}
// Create parent directories if needed
parentDir := filepath.Dir(dir)
if err := os.MkdirAll(parentDir, 0700); err != nil {
return fmt.Errorf("failed to create parent directory %s: %w", parentDir, err)
}
// Create state directory
if err := os.MkdirAll(dir, 0700); err != nil {
return fmt.Errorf("failed to create state directory %s: %w", dir, err)
}
return nil
}
// logConnectionInfo logs the Tailscale connection information
func (tm *TailscaleManager) logConnectionInfo(status *ipnstate.Status) {
if status == nil || status.Self == nil {
return
}
log.Printf("Tailscale connected as: %s", tm.server.Hostname)
// Log all Tailscale IPs
for _, ip := range status.Self.TailscaleIPs {
log.Printf("Tailscale IP: %s", ip)
}
// Log the MagicDNS name if available
dnsName := status.Self.DNSName
if dnsName != "" {
log.Printf("Tailscale DNS name: %s", dnsName)
}
// Log the access URL (strip trailing dot, format port properly)
cleanDNS := strings.TrimSuffix(dnsName, ".")
portNum := strings.TrimPrefix(tm.config.TailscalePort, ":")
if tm.config.TailscaleFunnel {
log.Printf("Funnel URL: https://%s:%s", cleanDNS, portNum)
} else if tm.config.TailscaleUseTLS {
log.Printf("Access URL: https://%s:%s", cleanDNS, portNum)
} else {
log.Printf("Access URL: http://%s:%s", cleanDNS, portNum)
}
}
// createListener creates the appropriate listener based on configuration
func (tm *TailscaleManager) createListener() (net.Listener, error) {
addr := tm.config.TailscalePort
if tm.config.TailscaleFunnel {
// Funnel provides public internet access with TLS
log.Println("Starting Tailscale Funnel listener...")
return tm.server.ListenFunnel("tcp", addr)
}
if tm.config.TailscaleUseTLS {
// Use Tailscale's automatic TLS certificates
log.Println("Starting Tailscale TLS listener...")
return tm.server.ListenTLS("tcp", addr)
}
// Plain listener (Tailscale still encrypts via WireGuard)
log.Println("Starting Tailscale listener (WireGuard encrypted)...")
return tm.server.Listen("tcp", addr)
}
// Close shuts down the Tailscale server gracefully
func (tm *TailscaleManager) Close() error {
if tm.server != nil && tm.started {
log.Println("Shutting down Tailscale server...")
return tm.server.Close()
}
return nil
}
// UseTLS returns whether the caller should apply TLS
// When using Tailscale, never apply additional TLS:
// - If TailscaleUseTLS=true, tsnet handles TLS via ListenTLS()
// - If TailscaleUseTLS=false, WireGuard encrypts, no TLS needed
func (tm *TailscaleManager) UseTLS() bool {
return false
}
// GetFunnelInfo returns current funnel status and URL
func (tm *TailscaleManager) GetFunnelInfo() (enabled bool, url string, err error) {
tm.mu.Lock()
defer tm.mu.Unlock()
if !tm.started || tm.server == nil {
return false, "", nil
}
lc, err := tm.server.LocalClient()
if err != nil {
return false, "", err
}
status, err := lc.Status(context.Background())
if err != nil {
return false, "", err
}
if status == nil || status.Self == nil {
return false, "", nil
}
dnsName := strings.TrimSuffix(status.Self.DNSName, ".")
// Extract port number from TailscalePort (e.g., ":8443" -> "8443")
portNum := strings.TrimPrefix(tm.config.TailscalePort, ":")
url = fmt.Sprintf("https://%s:%s", dnsName, portNum)
return tm.funnelEnabled, url, nil
}
// ToggleFunnel enables or disables Funnel, returning new listener
func (tm *TailscaleManager) ToggleFunnel(enable bool) (net.Listener, error) {
tm.mu.Lock()
defer tm.mu.Unlock()
if !tm.started || tm.server == nil {
return nil, fmt.Errorf("Tailscale not started")
}
// Close existing Tailscale listener
if tm.tsListener != nil {
tm.tsListener.Close()
}
// Create new listener
addr := tm.config.TailscalePort
var newListener net.Listener
var err error
if enable {
log.Println("Enabling Tailscale Funnel...")
newListener, err = tm.server.ListenFunnel("tcp", addr)
} else {
log.Println("Disabling Tailscale Funnel...")
newListener, err = tm.server.Listen("tcp", addr)
}
if err != nil {
return nil, err
}
tm.tsListener = newListener
tm.funnelEnabled = enable
return newListener, nil
}
// GetListener returns current Tailscale listener
func (tm *TailscaleManager) GetListener() net.Listener {
tm.mu.Lock()
defer tm.mu.Unlock()
return tm.tsListener
}
// StartAsync begins Tailscale initialization in background (non-blocking)
func (tm *TailscaleManager) StartAsync(ctx context.Context) {
tm.mu.Lock()
tm.ready = make(chan struct{})
tm.mu.Unlock()
go func() {
listener, err := tm.Start(ctx)
tm.mu.Lock()
if err != nil {
tm.startErr = err
log.Printf("Tailscale startup failed: %v", err)
} else {
log.Printf("Tailscale ready: %v", listener.Addr())
}
tm.mu.Unlock()
close(tm.ready)
}()
}
// Ready returns a channel that's closed when Tailscale startup completes (success or failure)
func (tm *TailscaleManager) Ready() <-chan struct{} {
tm.mu.Lock()
defer tm.mu.Unlock()
return tm.ready
}
// IsReady returns true if Tailscale has started successfully
func (tm *TailscaleManager) IsReady() bool {
tm.mu.Lock()
defer tm.mu.Unlock()
return tm.started && tm.startErr == nil
}