This repository has been archived by the owner on Oct 7, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathmain.go
145 lines (119 loc) · 2.44 KB
/
main.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
package main
import (
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net"
"os"
"sync"
"tailscale.com/client/tailscale"
"tailscale.com/tsnet"
)
type Binding struct {
From uint16 `json:"from"`
To string `json:"to"`
Tls bool `json:"tls"`
}
func loadBindings() ([]Binding, error) {
bindingsPath := os.Getenv("TS_SIDECAR_BINDINGS")
if bindingsPath == "" {
bindingsPath = "/etc/ts-sidecar/bindings.json"
}
bindingsFile, err := os.Open(bindingsPath)
if err != nil {
return nil, err
}
defer bindingsFile.Close()
d := json.NewDecoder(bindingsFile)
var bindings []Binding
if err := d.Decode(&bindings); err != nil {
return nil, err
}
if len(bindings) == 0 {
return nil, errors.New("bindings empty")
}
return bindings, nil
}
func newTsNetServer() tsnet.Server {
hostname := os.Getenv("TS_SIDECAR_NAME")
if hostname == "" {
panic("TS_SIDECAR_NAME env var not set")
}
stateDir := os.Getenv("TS_SIDECAR_STATEDIR")
if stateDir == "" {
stateDir = "./tsstate"
}
if err := os.MkdirAll(stateDir, 0o755); err != nil {
panic("failed to create default state directory")
}
return tsnet.Server{
Dir: stateDir,
Hostname: hostname,
}
}
func proxyBind(s *tsnet.Server, b *Binding) {
ln, err := s.Listen("tcp", fmt.Sprintf(":%d", b.From))
if err != nil {
log.Println(err)
return
}
if b.Tls {
ln = tls.NewListener(ln, &tls.Config{
GetCertificate: tailscale.GetCertificate,
})
}
log.Printf("started proxy bind from %d to %v (tls: %t)", b.From, b.To, b.Tls)
for {
conn, err := ln.Accept()
if err != nil {
log.Println(err)
continue
}
go func(left net.Conn) {
defer left.Close()
right, err := net.Dial("tcp", b.To)
if err != nil {
log.Println(err)
return
}
defer right.Close()
var wg sync.WaitGroup
proxyConn := func(a, b net.Conn) {
defer wg.Done()
_, err := io.Copy(a, b)
if err != nil {
log.Println(err)
return
}
}
wg.Add(2)
go proxyConn(right, left)
go proxyConn(left, right)
wg.Wait()
}(conn)
}
}
func main() {
// Apparently this envvar needs to be set for this to work!
err := os.Setenv("TAILSCALE_USE_WIP_CODE", "true")
if err != nil {
panic(err)
}
bindings, err := loadBindings()
if err != nil {
panic(err)
}
s := newTsNetServer()
var wg sync.WaitGroup
for _, binding := range bindings {
wg.Add(1)
go func(binding Binding) {
defer wg.Done()
proxyBind(&s, &binding)
}(binding)
}
wg.Wait()
}