-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexporter.go
More file actions
373 lines (316 loc) · 7.56 KB
/
exporter.go
File metadata and controls
373 lines (316 loc) · 7.56 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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
package main
import (
"bufio"
"context"
"fmt"
"io"
"log"
"net"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"tailscale.com/tsnet"
)
// ExporterManager manages port exports over tsnet
type ExporterManager struct {
config *Config
server *tsnet.Server
mu sync.Mutex
exporters map[int]*portExporter // port -> exporter
ctx context.Context
cancel context.CancelFunc
}
type portExporter struct {
port int
listener net.Listener
refcount int
ctx context.Context
cancel context.CancelFunc
wg sync.WaitGroup
}
// NewExporterManager creates a new exporter manager
func NewExporterManager(config *Config, server *tsnet.Server) *ExporterManager {
ctx, cancel := context.WithCancel(context.Background())
return &ExporterManager{
config: config,
server: server,
exporters: make(map[int]*portExporter),
ctx: ctx,
cancel: cancel,
}
}
// StartControlSocket starts the Unix socket control server
func (em *ExporterManager) StartControlSocket(socketPath string) error {
// Remove existing socket if it exists
os.Remove(socketPath)
// Ensure directory exists
dir := filepath.Dir(socketPath)
if err := os.MkdirAll(dir, 0700); err != nil {
return fmt.Errorf("failed to create control socket directory: %w", err)
}
// Create Unix domain socket listener
listener, err := net.Listen("unix", socketPath)
if err != nil {
return fmt.Errorf("failed to create control socket: %w", err)
}
// Set permissions
if err := os.Chmod(socketPath, 0600); err != nil {
listener.Close()
return fmt.Errorf("failed to set socket permissions: %w", err)
}
if em.config.Verbose {
log.Printf("Control socket listening on %s", socketPath)
}
// Accept connections in background
go func() {
defer listener.Close()
for {
select {
case <-em.ctx.Done():
return
default:
}
conn, err := listener.Accept()
if err != nil {
if em.ctx.Err() != nil {
return
}
if em.config.Verbose {
log.Printf("Control socket accept error: %v", err)
}
continue
}
go em.handleControlConnection(conn)
}
}()
return nil
}
func (em *ExporterManager) handleControlConnection(conn net.Conn) {
defer conn.Close()
scanner := bufio.NewScanner(conn)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "" {
continue
}
parts := strings.Fields(line)
if len(parts) < 3 {
if em.config.Verbose {
log.Printf("Invalid control message: %s", line)
}
continue
}
cmd := parts[0]
// family := parts[1] // tcp4 or tcp6
portStr := parts[2]
port, err := strconv.Atoi(portStr)
if err != nil {
if em.config.Verbose {
log.Printf("Invalid port in control message: %s", portStr)
}
continue
}
switch cmd {
case "LISTEN":
em.handleListen(port)
case "CLOSE":
em.handleClose(port)
default:
if em.config.Verbose {
log.Printf("Unknown control command: %s", cmd)
}
}
}
}
func (em *ExporterManager) handleListen(port int) {
em.mu.Lock()
defer em.mu.Unlock()
// Check if port is allowed
if !em.isPortAllowed(port) {
if em.config.Verbose {
log.Printf("Port %d not allowed by export policy", port)
}
return
}
// Check if already exported
if exp, exists := em.exporters[port]; exists {
exp.refcount++
if em.config.Verbose {
log.Printf("Port %d already exported, refcount now %d", port, exp.refcount)
}
return
}
// Check max exports
if len(em.exporters) >= em.config.ExportMax {
if em.config.Verbose {
log.Printf("Cannot export port %d: max exports (%d) reached", port, em.config.ExportMax)
}
return
}
// Create new exporter
if err := em.startExporter(port); err != nil {
log.Printf("Failed to export port %d: %v", port, err)
}
}
func (em *ExporterManager) handleClose(port int) {
em.mu.Lock()
defer em.mu.Unlock()
exp, exists := em.exporters[port]
if !exists {
return
}
exp.refcount--
if em.config.Verbose {
log.Printf("Port %d refcount decreased to %d", port, exp.refcount)
}
if exp.refcount <= 0 {
em.stopExporter(port)
}
}
func (em *ExporterManager) startExporter(port int) error {
// Listen on tailnet
listener, err := em.server.Listen("tcp", fmt.Sprintf(":%d", port))
if err != nil {
return fmt.Errorf("failed to listen on tailnet port %d: %w", port, err)
}
ctx, cancel := context.WithCancel(em.ctx)
exp := &portExporter{
port: port,
listener: listener,
refcount: 1,
ctx: ctx,
cancel: cancel,
}
em.exporters[port] = exp
if em.config.Verbose {
log.Printf("Exporting port %d on tailnet", port)
}
// Start accept loop
exp.wg.Add(1)
go func() {
defer exp.wg.Done()
em.acceptLoop(exp)
}()
return nil
}
func (em *ExporterManager) stopExporter(port int) {
exp, exists := em.exporters[port]
if !exists {
return
}
if em.config.Verbose {
log.Printf("Stopping export of port %d", port)
}
exp.cancel()
exp.listener.Close()
delete(em.exporters, port)
// Wait for accept loop to finish
go exp.wg.Wait()
}
func (em *ExporterManager) acceptLoop(exp *portExporter) {
for {
conn, err := exp.listener.Accept()
if err != nil {
if exp.ctx.Err() != nil {
return
}
if em.config.Verbose {
log.Printf("Accept error on port %d: %v", exp.port, err)
}
continue
}
go em.forwardConnection(exp.ctx, conn, exp.port)
}
}
func (em *ExporterManager) forwardConnection(ctx context.Context, tsConn net.Conn, port int) {
defer tsConn.Close()
// Try IPv4 loopback first
localConn, err := net.Dial("tcp", fmt.Sprintf("127.0.0.1:%d", port))
if err != nil {
// Try IPv6 loopback
localConn, err = net.Dial("tcp", fmt.Sprintf("[::1]:%d", port))
if err != nil {
if em.config.Verbose {
log.Printf("Failed to connect to local port %d: %v", port, err)
}
return
}
}
defer localConn.Close()
if em.config.Verbose {
log.Printf("Forwarding connection to local port %d", port)
}
// Bidirectional copy with proper half-close handling
var wg sync.WaitGroup
wg.Add(2)
// Helper to close write side of connection if supported
closeWrite := func(conn net.Conn) {
type closeWriter interface {
CloseWrite() error
}
if cw, ok := conn.(closeWriter); ok {
cw.CloseWrite()
}
}
go func() {
defer wg.Done()
io.Copy(localConn, tsConn)
closeWrite(localConn)
}()
go func() {
defer wg.Done()
io.Copy(tsConn, localConn)
closeWrite(tsConn)
}()
wg.Wait()
}
func (em *ExporterManager) isPortAllowed(port int) bool {
// Check deny list first
if em.config.ExportDenyPorts != "" {
if em.matchesPortSpec(port, em.config.ExportDenyPorts) {
return false
}
}
// Check allow list (if specified)
if em.config.ExportAllowPorts != "" {
return em.matchesPortSpec(port, em.config.ExportAllowPorts)
}
// No allow list specified, allow by default (subject to deny list)
return true
}
func (em *ExporterManager) matchesPortSpec(port int, spec string) bool {
parts := strings.Split(spec, ",")
for _, part := range parts {
part = strings.TrimSpace(part)
// Check for range
if strings.Contains(part, "-") {
rangeParts := strings.Split(part, "-")
if len(rangeParts) != 2 {
continue
}
start, err1 := strconv.Atoi(strings.TrimSpace(rangeParts[0]))
end, err2 := strconv.Atoi(strings.TrimSpace(rangeParts[1]))
if err1 == nil && err2 == nil && port >= start && port <= end {
return true
}
} else {
// Single port
p, err := strconv.Atoi(part)
if err == nil && p == port {
return true
}
}
}
return false
}
// Stop stops all exporters and the control socket
func (em *ExporterManager) Stop() {
em.cancel()
em.mu.Lock()
defer em.mu.Unlock()
for port := range em.exporters {
em.stopExporter(port)
}
}