This repository has been archived by the owner on Dec 25, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxy.go
82 lines (74 loc) · 2.05 KB
/
proxy.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
package proxy
import (
"encoding/binary"
"fmt"
"io"
"sync"
)
const (
lenBufSize = 2
tunMTU = 65535 // The maximum-allowed MTU for the tun interface.
tunName = "tun0"
DefaultPort = 1024
)
// TunToVsock forwards network packets from the tun device to our
// TCP-over-VSOCK connection. The function keeps on forwarding packets until we
// encounter an error or EOF. Errors (including EOF) are written to the given
// channel.
func TunToVsock(from io.ReadCloser, to io.WriteCloser, ch chan error, wg *sync.WaitGroup) {
defer to.Close()
defer wg.Done()
var (
err error
pktLenBuf = make([]byte, lenBufSize)
pktBuf = make([]byte, tunMTU)
)
for {
// Read a network packet from the tun interface.
nr, rerr := from.Read(pktBuf)
if nr > 0 {
// Forward the network packet to our TCP-over-VSOCK connection.
binary.BigEndian.PutUint16(pktLenBuf, uint16(nr))
if _, werr := to.Write(append(pktLenBuf, pktBuf[:nr]...)); werr != nil {
err = werr
break
}
}
if rerr != nil {
err = rerr
break
}
}
ch <- fmt.Errorf("stopped tun-to-vsock forwarding: %w", err)
}
// VsockToTun forwards network packets from our TCP-over-VSOCK connection to
// the tun interface. The function keeps on forwarding packets until we
// encounter an error or EOF. Errors (including EOF) are written to the given
// channel.
func VsockToTun(from io.ReadCloser, to io.WriteCloser, ch chan error, wg *sync.WaitGroup) {
defer to.Close()
defer wg.Done()
var (
err error
pktLen uint16
pktLenBuf = make([]byte, lenBufSize)
pktBuf = make([]byte, tunMTU)
)
for {
// Read the length prefix that tells us the size of the subsequent
// packet.
if _, err = io.ReadFull(from, pktLenBuf); err != nil {
break
}
pktLen = binary.BigEndian.Uint16(pktLenBuf)
// Read the packet.
if _, err = io.ReadFull(from, pktBuf[:pktLen]); err != nil {
break
}
// Forward the packet to the tun interface.
if _, err = to.Write(pktBuf[:pktLen]); err != nil {
break
}
}
ch <- fmt.Errorf("stopped vsock-to-tun forwarding: %w", err)
}