跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

udp_proxy.go

196 行 · 5.0 KB历史下载
1package forwarder
2
3// Modified version of https://github.com/moby/moby/blob/master/cmd/docker-proxy/udp_proxy.go and
4// https://github.com/moby/vpnkit/blob/master/go/pkg/libproxy/udp_proxy.go
5
6import (
7 "encoding/binary"
8 "io"
9 "net"
10 "strings"
11 "sync"
12 "syscall"
13 "time"
14
15 log "github.com/sirupsen/logrus"
16)
17
18const (
19 // UDPConnTrackTimeout is the timeout used for UDP connection tracking
20 UDPConnTrackTimeout = 90 * time.Second
21 // UDPBufSize is the buffer size for the UDP proxy
22 UDPBufSize = 65507
23)
24
25// A net.Addr where the IP is split into two fields so you can use it as a key
26// in a map:
27type connTrackKey struct {
28 IPHigh uint64
29 IPLow uint64
30 Port int
31}
32
33func newConnTrackKey(addr *net.UDPAddr) *connTrackKey {
34 if len(addr.IP) == net.IPv4len {
35 return &connTrackKey{
36 IPHigh: 0,
37 IPLow: uint64(binary.BigEndian.Uint32(addr.IP)),
38 Port: addr.Port,
39 }
40 }
41 return &connTrackKey{
42 IPHigh: binary.BigEndian.Uint64(addr.IP[:8]),
43 IPLow: binary.BigEndian.Uint64(addr.IP[8:]),
44 Port: addr.Port,
45 }
46}
47
48type connTrackMap map[connTrackKey]net.Conn
49
50// UDPProxy is proxy for which handles UDP datagrams. It implements the Proxy
51// interface to handle UDP traffic forwarding between the frontend and backend
52// addresses.
53type UDPProxy struct {
54 listener udpConn
55 dialer func() (net.Conn, error)
56 connTrackTable connTrackMap
57 connTrackLock sync.Mutex
58}
59
60// NewUDPProxy creates a new UDPProxy.
61func NewUDPProxy(listener udpConn, dialer func() (net.Conn, error)) (*UDPProxy, error) {
62 return &UDPProxy{
63 listener: listener,
64 connTrackTable: make(connTrackMap),
65 dialer: dialer,
66 }, nil
67}
68
69func (proxy *UDPProxy) replyLoop(proxyConn net.Conn, clientAddr net.Addr, clientKey *connTrackKey) {
70 defer func() {
71 proxy.connTrackLock.Lock()
72 delete(proxy.connTrackTable, *clientKey)
73 proxy.connTrackLock.Unlock()
74 proxyConn.Close()
75 }()
76
77 readBuf := make([]byte, UDPBufSize)
78 for {
79 _ = proxyConn.SetReadDeadline(time.Now().Add(UDPConnTrackTimeout))
80 again:
81 read, err := proxyConn.Read(readBuf)
82 if read == 0 && err == nil {
83 // treat this condition same as EOF
84 return
85 }
86 if err != nil {
87 if err, ok := err.(*net.OpError); ok && err.Err == syscall.ECONNREFUSED {
88 // This will happen if the last write failed
89 // (e.g: nothing is actually listening on the
90 // proxied port on the container), ignore it
91 // and continue until UDPConnTrackTimeout
92 // expires:
93 goto again
94 }
95 return
96 }
97 for i := 0; i != read; {
98 written, err := proxy.listener.WriteTo(readBuf[i:read], clientAddr)
99 if err != nil {
100 return
101 }
102 i += written
103 }
104 }
105}
106
107// Run starts forwarding the traffic using UDP.
108func (proxy *UDPProxy) Run() {
109 readBuf := make([]byte, UDPBufSize)
110 for {
111 read, from, err := proxy.listener.ReadFrom(readBuf)
112 if err != nil {
113 // NOTE: Apparently ReadFrom doesn't return
114 // ECONNREFUSED like Read do (see comment in
115 // UDPProxy.replyLoop)
116 if !isClosedError(err) {
117 log.Debugf("Stopping udp proxy (%s)", err)
118 }
119 break
120 }
121
122 fromKey := newConnTrackKey(from.(*net.UDPAddr))
123 proxy.connTrackLock.Lock()
124 proxyConn, hit := proxy.connTrackTable[*fromKey]
125 if !hit {
126 proxyConn, err = proxy.dialer()
127 if err != nil {
128 log.Errorf("Can't proxy a datagram to udp: %s\n", err)
129 proxy.connTrackLock.Unlock()
130 continue
131 }
132 proxy.connTrackTable[*fromKey] = proxyConn
133 go proxy.replyLoop(proxyConn, from, fromKey)
134 }
135 proxy.connTrackLock.Unlock()
136 for i := 0; i != read; {
137 _ = proxyConn.SetReadDeadline(time.Now().Add(UDPConnTrackTimeout))
138 written, err := proxyConn.Write(readBuf[i:read])
139 if err != nil {
140 log.Errorf("Can't proxy a datagram to udp: %s\n", err)
141 break
142 }
143 i += written
144 }
145 }
146}
147
148// Close stops forwarding the traffic.
149func (proxy *UDPProxy) Close() error {
150 proxy.listener.Close()
151 proxy.connTrackLock.Lock()
152 defer proxy.connTrackLock.Unlock()
153 for _, conn := range proxy.connTrackTable {
154 conn.Close()
155 }
156 return nil
157}
158
159func isClosedError(err error) bool {
160 /* This comparison is ugly, but unfortunately, net.go doesn't export errClosing.
161 * See:
162 * http://golang.org/src/pkg/net/net.go
163 * https://code.google.com/p/go/issues/detail?id=4337
164 * https://groups.google.com/forum/#!msg/golang-nuts/0_aaCvBmOcM/SptmDyX1XJMJ
165 */
166 return strings.HasSuffix(err.Error(), "use of closed network connection")
167}
168
169type udpConn interface {
170 ReadFrom(b []byte) (int, net.Addr, error)
171 WriteTo(b []byte, addr net.Addr) (int, error)
172 SetReadDeadline(t time.Time) error
173 io.Closer
174}
175
176type autoStoppingListener struct {
177 underlying udpConn
178}
179
180func (l *autoStoppingListener) ReadFrom(b []byte) (int, net.Addr, error) {
181 _ = l.underlying.SetReadDeadline(time.Now().Add(UDPConnTrackTimeout))
182 return l.underlying.ReadFrom(b)
183}
184
185func (l *autoStoppingListener) WriteTo(b []byte, addr net.Addr) (int, error) {
186 _ = l.underlying.SetReadDeadline(time.Now().Add(UDPConnTrackTimeout))
187 return l.underlying.WriteTo(b, addr)
188}
189
190func (l *autoStoppingListener) SetReadDeadline(t time.Time) error {
191 return l.underlying.SetReadDeadline(t)
192}
193
194func (l *autoStoppingListener) Close() error {
195 return l.underlying.Close()
196}