forked from Diniboy1123/usque
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtunnel.go
More file actions
295 lines (264 loc) · 7.67 KB
/
tunnel.go
File metadata and controls
295 lines (264 loc) · 7.67 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
package api
import (
"context"
"crypto/tls"
"errors"
"fmt"
"io"
"log"
"net"
"sync"
"time"
connectip "github.com/Diniboy1123/connect-ip-go"
"github.com/Diniboy1123/usque/internal"
"github.com/songgao/water"
"golang.zx2c4.com/wireguard/tun"
)
// NetBuffer is a pool of byte slices with a fixed capacity.
// Helps to reduce memory allocations and improve performance.
// It uses a sync.Pool to manage the byte slices.
// The capacity of the byte slices is set when the pool is created.
type NetBuffer struct {
capacity int
buf sync.Pool
}
// Get returns a byte slice from the pool.
func (n *NetBuffer) Get() []byte {
return *(n.buf.Get().(*[]byte))
}
// Put places a byte slice back into the pool.
// It checks if the capacity of the byte slice matches the pool's capacity.
// If it doesn't match, the byte slice is not returned to the pool.
func (n *NetBuffer) Put(buf []byte) {
if cap(buf) != n.capacity {
return
}
n.buf.Put(&buf)
}
// NewNetBuffer creates a new NetBuffer with the specified capacity.
// The capacity must be greater than 0.
func NewNetBuffer(capacity int) *NetBuffer {
if capacity <= 0 {
panic("capacity must be greater than 0")
}
return &NetBuffer{
capacity: capacity,
buf: sync.Pool{
New: func() interface{} {
b := make([]byte, capacity)
return &b
},
},
}
}
// TunnelDevice abstracts a TUN device so that we can use the same tunnel-maintenance code
// regardless of the underlying implementation.
type TunnelDevice interface {
// ReadPacket reads a packet from the device (using the given mtu) and returns its contents.
ReadPacket(buf []byte) (int, error)
// WritePacket writes a packet to the device.
WritePacket(pkt []byte) error
}
// NetstackAdapter wraps a tun.Device (e.g. from netstack) to satisfy TunnelDevice.
type NetstackAdapter struct {
dev tun.Device
tunnelBufPool sync.Pool
tunnelSizesPool sync.Pool
}
func (n *NetstackAdapter) ReadPacket(buf []byte) (int, error) {
packetBufsPtr := n.tunnelBufPool.Get().(*[][]byte)
sizesPtr := n.tunnelSizesPool.Get().(*[]int)
defer func() {
(*packetBufsPtr)[0] = nil
n.tunnelBufPool.Put(packetBufsPtr)
n.tunnelSizesPool.Put(sizesPtr)
}()
(*packetBufsPtr)[0] = buf
(*sizesPtr)[0] = 0
_, err := n.dev.Read(*packetBufsPtr, *sizesPtr, 0)
if err != nil {
return 0, err
}
return (*sizesPtr)[0], nil
}
func (n *NetstackAdapter) WritePacket(pkt []byte) error {
// Write expects a slice of packet buffers.
_, err := n.dev.Write([][]byte{pkt}, 0)
return err
}
// NewNetstackAdapter creates a new NetstackAdapter.
func NewNetstackAdapter(dev tun.Device) TunnelDevice {
return &NetstackAdapter{
dev: dev,
tunnelBufPool: sync.Pool{
New: func() interface{} {
buf := make([][]byte, 1)
return &buf
},
},
tunnelSizesPool: sync.Pool{
New: func() interface{} {
sizes := make([]int, 1)
return &sizes
},
},
}
}
// WaterAdapter wraps a *water.Interface so it satisfies TunnelDevice.
type WaterAdapter struct {
iface *water.Interface
}
func (w *WaterAdapter) ReadPacket(buf []byte) (int, error) {
n, err := w.iface.Read(buf)
if err != nil {
return 0, err
}
return n, nil
}
func (w *WaterAdapter) WritePacket(pkt []byte) error {
_, err := w.iface.Write(pkt)
return err
}
// NewWaterAdapter creates a new WaterAdapter.
func NewWaterAdapter(iface *water.Interface) TunnelDevice {
return &WaterAdapter{iface: iface}
}
// MaintainTunnelConfig contains runtime settings for tunnel maintenance.
type MaintainTunnelConfig struct {
TLSConfig *tls.Config
KeepalivePeriod time.Duration
InitialPacketSize uint16
Endpoint net.Addr
Device TunnelDevice
MTU int
ReconnectDelay time.Duration
AlwaysReconnect bool
UseHTTP2 bool
}
// MaintainTunnel continuously connects to the MASQUE server, then starts two
// forwarding goroutines: one forwarding from the device to the IP connection (and handling
// any ICMP reply), and the other forwarding from the IP connection to the device.
// If an error occurs in either loop, the connection is closed and a reconnect is attempted.
//
// Parameters:
// - ctx: context.Context - The context for the connection.
// - cfg: MaintainTunnelConfig - Tunnel maintenance runtime configuration.
func MaintainTunnel(ctx context.Context, cfg MaintainTunnelConfig) {
if cfg.UseHTTP2 {
if _, ok := cfg.Endpoint.(*net.TCPAddr); !ok {
log.Fatalf("MaintainTunnel: HTTP/2 mode requires a *net.TCPAddr endpoint, got %T", cfg.Endpoint)
}
} else {
if _, ok := cfg.Endpoint.(*net.UDPAddr); !ok {
log.Fatalf("MaintainTunnel: HTTP/3 mode requires a *net.UDPAddr endpoint, got %T", cfg.Endpoint)
}
}
packetBufferPool := NewNetBuffer(cfg.MTU)
for {
if !cfg.AlwaysReconnect {
log.Println("Tunnel idle. Waiting for outbound activity before reconnecting...")
buf := packetBufferPool.Get()
n, err := cfg.Device.ReadPacket(buf)
if err != nil {
packetBufferPool.Put(buf)
log.Printf("Failed to read from TUN device while waiting for activity: %v", err)
time.Sleep(cfg.ReconnectDelay)
continue
}
packetBufferPool.Put(buf)
log.Printf("Detected outbound activity (%d bytes). Reconnecting...", n)
}
log.Printf("Establishing MASQUE connection to %s", cfg.Endpoint)
udpConn, tr, ipConn, rsp, err := ConnectTunnel(
ctx,
cfg.TLSConfig,
internal.DefaultQuicConfig(cfg.KeepalivePeriod, cfg.InitialPacketSize),
internal.ConnectURI,
cfg.Endpoint,
cfg.UseHTTP2,
)
if err != nil {
log.Printf("Failed to connect tunnel: %v", err)
time.Sleep(cfg.ReconnectDelay)
continue
}
if rsp.StatusCode != 200 {
log.Printf("Tunnel connection failed: %s", rsp.Status)
ipConn.Close()
if udpConn != nil {
udpConn.Close()
}
if tr != nil {
tr.Close()
}
time.Sleep(cfg.ReconnectDelay)
continue
}
log.Println("Connected to MASQUE server")
errChan := make(chan error, 2)
go func() {
for {
buf := packetBufferPool.Get()
n, err := cfg.Device.ReadPacket(buf)
if err != nil {
packetBufferPool.Put(buf)
errChan <- fmt.Errorf("failed to read from TUN device: %w", err)
return
}
icmp, err := ipConn.WritePacket(buf[:n])
if err != nil {
packetBufferPool.Put(buf)
if errors.As(err, new(*connectip.CloseError)) {
errChan <- fmt.Errorf("connection closed while writing to IP connection: %w", err)
return
}
log.Printf("Error writing to IP connection: %v, continuing...", err)
continue
}
packetBufferPool.Put(buf)
if len(icmp) > 0 {
if err := cfg.Device.WritePacket(icmp); err != nil {
if errors.As(err, new(*connectip.CloseError)) {
errChan <- fmt.Errorf("connection closed while writing ICMP to TUN device: %w", err)
return
}
log.Printf("Error writing ICMP to TUN device: %v, continuing...", err)
}
}
}
}()
go func() {
buf := packetBufferPool.Get()
defer packetBufferPool.Put(buf)
for {
n, err := ipConn.ReadPacket(buf, true)
if err != nil {
if errors.Is(err, io.EOF) {
errChan <- fmt.Errorf("connection closed while reading from IP connection: %w", err)
return
}
if errors.As(err, new(*connectip.CloseError)) {
errChan <- fmt.Errorf("connection closed while reading from IP connection: %w", err)
return
}
log.Printf("Error reading from IP connection: %v, continuing...", err)
continue
}
if err := cfg.Device.WritePacket(buf[:n]); err != nil {
errChan <- fmt.Errorf("failed to write to TUN device: %w", err)
return
}
}
}()
err = <-errChan
log.Printf("Tunnel connection lost: %v. Reconnecting...", err)
ipConn.Close()
if udpConn != nil {
udpConn.Close()
}
if tr != nil {
tr.Close()
}
time.Sleep(cfg.ReconnectDelay)
}
}