跳到主要内容

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

浏览文件

switch.go

342 行 · 7.7 KB历史下载
1package tap
2
3import (
4 "bufio"
5 "context"
6 "errors"
7 "fmt"
8 "io"
9 "net"
10 "sync"
11 "sync/atomic"
12 "syscall"
13
14 "github.com/containers/gvisor-tap-vsock/pkg/notification"
15 "github.com/containers/gvisor-tap-vsock/pkg/types"
16 "github.com/google/gopacket"
17 "github.com/google/gopacket/layers"
18 log "github.com/sirupsen/logrus"
19 "gvisor.dev/gvisor/pkg/buffer"
20 "gvisor.dev/gvisor/pkg/tcpip"
21 "gvisor.dev/gvisor/pkg/tcpip/header"
22 "gvisor.dev/gvisor/pkg/tcpip/stack"
23)
24
25type VirtualDevice interface {
26 DeliverNetworkPacket(protocol tcpip.NetworkProtocolNumber, pkt *stack.PacketBuffer)
27 LinkAddress() tcpip.LinkAddress
28 IP() string
29}
30
31type NetworkSwitch interface {
32 DeliverNetworkPacket(protocol tcpip.NetworkProtocolNumber, pkt *stack.PacketBuffer)
33}
34
35type Switch struct {
36 droppedIPv6 func([]byte)
37
38 Sent uint64
39 Received uint64
40
41 debug bool
42
43 nextConnID int
44 conns map[int]protocolConn
45 connLock sync.Mutex
46
47 cam map[tcpip.LinkAddress]int
48 camLock sync.RWMutex
49
50 writeLock sync.Mutex
51
52 gateway VirtualDevice
53
54 notificationSender *notification.NotificationSender
55}
56
57func NewSwitch(debug bool) *Switch {
58 return &Switch{
59 debug: debug,
60 conns: make(map[int]protocolConn),
61 cam: make(map[tcpip.LinkAddress]int),
62 }
63}
64
65// SetDroppedIPv6 is configured before Accept, only for an IPv4-only stack.
66func (e *Switch) SetDroppedIPv6(observe func([]byte)) { e.droppedIPv6 = observe }
67
68func (e *Switch) CAM() map[string]int {
69 e.camLock.RLock()
70 defer e.camLock.RUnlock()
71 ret := make(map[string]int)
72 for address, port := range e.cam {
73 ret[address.String()] = port
74 }
75 return ret
76}
77
78func (e *Switch) Connect(ep VirtualDevice) {
79 e.gateway = ep
80}
81
82func (e *Switch) DeliverNetworkPacket(_ tcpip.NetworkProtocolNumber, pkt *stack.PacketBuffer) {
83 if err := e.tx(pkt); err != nil {
84 log.Error(err)
85 }
86}
87
88func (e *Switch) Accept(ctx context.Context, rawConn net.Conn, protocol types.Protocol) error {
89 conn := protocolConn{Conn: rawConn, protocolImpl: protocolImplementation(protocol)}
90 log.Debugf("new connection from %s to %s", conn.RemoteAddr().String(), conn.LocalAddr().String())
91 id, failed := e.connect(conn)
92 if failed {
93 log.Error("connection failed")
94 return conn.Close()
95
96 }
97
98 defer func() {
99 e.connLock.Lock()
100 defer e.connLock.Unlock()
101 e.disconnect(id, conn)
102 }()
103 if err := e.rx(ctx, id, conn); err != nil {
104 if ctx.Err() != nil {
105 // Closing the connection is how a program ends the switch.
106 return nil
107 }
108 err := fmt.Errorf("cannot receive packets from %s, disconnecting: %w", conn.RemoteAddr().String(), err)
109 log.Error(err)
110 return err
111 }
112 return nil
113}
114
115func (e *Switch) connect(conn protocolConn) (int, bool) {
116 e.connLock.Lock()
117 defer e.connLock.Unlock()
118
119 id := e.nextConnID
120 e.nextConnID++
121
122 e.conns[id] = conn
123 return id, false
124}
125
126func (e *Switch) tx(pkt *stack.PacketBuffer) error {
127 return e.txPkt(pkt)
128}
129
130func (e *Switch) txPkt(pkt *stack.PacketBuffer) error {
131 e.writeLock.Lock()
132 defer e.writeLock.Unlock()
133
134 e.connLock.Lock()
135 defer e.connLock.Unlock()
136
137 buf := pkt.ToView().AsSlice()
138 eth := header.Ethernet(buf)
139 dst := eth.DestinationAddress()
140 src := eth.SourceAddress()
141
142 size := pkt.Size()
143 if size < 0 {
144 return fmt.Errorf("packet size out of range")
145 }
146 if dst == header.EthernetBroadcastAddress {
147 e.camLock.RLock()
148 srcID, ok := e.cam[src]
149 if !ok {
150 srcID = -1
151 }
152 e.camLock.RUnlock()
153 for id, conn := range e.conns {
154 if id == srcID {
155 continue
156 }
157
158 err := e.txBuf(id, conn, buf)
159 if err != nil {
160 return err
161 }
162
163 atomic.AddUint64(&e.Sent, uint64(size))
164 }
165 } else {
166 e.camLock.RLock()
167 id, ok := e.cam[dst]
168 if !ok {
169 e.camLock.RUnlock()
170 return nil
171 }
172 e.camLock.RUnlock()
173 conn := e.conns[id]
174 err := e.txBuf(id, conn, buf)
175 if err != nil {
176 return err
177 }
178 atomic.AddUint64(&e.Sent, uint64(size))
179 }
180 return nil
181}
182
183func (e *Switch) txBuf(id int, conn protocolConn, buf []byte) error {
184 if conn.protocolImpl.Stream() {
185 size := conn.protocolImpl.(streamProtocol).Buf()
186 conn.protocolImpl.(streamProtocol).Write(size, len(buf))
187 buf = append(size, buf...)
188 }
189 for {
190 if _, err := conn.Write(buf); err != nil {
191 if errors.Is(err, syscall.ENOBUFS) {
192 // socket buffer can be full keep retrying sending the same data
193 // again until it works or we get a different error
194 // https://github.com/containers/gvisor-tap-vsock/issues/367
195 continue
196 }
197 e.disconnect(id, conn)
198 return err
199 }
200 return nil
201 }
202}
203
204func (e *Switch) disconnect(id int, conn net.Conn) {
205 e.camLock.Lock()
206 defer e.camLock.Unlock()
207
208 for address, targetConn := range e.cam {
209 if targetConn == id {
210 if e.notificationSender != nil {
211 e.notificationSender.Send(types.NotificationMessage{
212 NotificationType: types.ConnectionClosed,
213 MacAddress: address.String(),
214 })
215 }
216 delete(e.cam, address)
217 }
218 }
219 _ = conn.Close()
220 delete(e.conns, id)
221}
222
223func (e *Switch) rx(ctx context.Context, id int, conn protocolConn) error {
224 if conn.protocolImpl.Stream() {
225 return e.rxStream(ctx, id, conn, conn.protocolImpl.(streamProtocol))
226 }
227 return e.rxNonStream(ctx, id, conn)
228}
229
230func (e *Switch) rxNonStream(ctx context.Context, id int, conn net.Conn) error {
231 bufSize := 1024 * 128
232 buf := make([]byte, bufSize)
233loop:
234 for {
235 select {
236 case <-ctx.Done():
237 break loop
238 default:
239 // passthrough
240 }
241 n, err := conn.Read(buf)
242 if err != nil {
243 return fmt.Errorf("cannot read size from socket: %w", err)
244 }
245 e.rxBuf(ctx, id, buf[:n])
246 }
247 return nil
248}
249
250func (e *Switch) rxStream(ctx context.Context, id int, conn net.Conn, sProtocol streamProtocol) error {
251 reader := bufio.NewReader(conn)
252 sizeBuf := sProtocol.Buf()
253loop:
254 for {
255 select {
256 case <-ctx.Done():
257 break loop
258 default:
259 // passthrough
260 }
261 _, err := io.ReadFull(reader, sizeBuf)
262 if err != nil {
263 return fmt.Errorf("cannot read size from socket: %w", err)
264 }
265 size := sProtocol.Read(sizeBuf)
266
267 buf := make([]byte, size)
268 _, err = io.ReadFull(reader, buf)
269 if err != nil {
270 return fmt.Errorf("cannot read packet from socket: %w", err)
271 }
272 e.rxBuf(ctx, id, buf)
273 }
274 return nil
275}
276
277func (e *Switch) rxBuf(_ context.Context, id int, buf []byte) {
278 if e.debug {
279 packet := gopacket.NewPacket(buf, layers.LayerTypeEthernet, gopacket.Default)
280 log.Info(packet.String())
281 }
282
283 if len(buf) < header.EthernetMinimumSize {
284 return
285 }
286 eth := header.Ethernet(buf)
287 if e.droppedIPv6 != nil && eth.Type() == header.IPv6ProtocolNumber {
288 e.droppedIPv6(buf[header.EthernetMinimumSize:])
289 atomic.AddUint64(&e.Received, uint64(len(buf)))
290 return
291 }
292
293 e.camLock.Lock()
294 _, exists := e.cam[eth.SourceAddress()]
295 e.cam[eth.SourceAddress()] = id
296 e.camLock.Unlock()
297
298 if !exists && e.notificationSender != nil {
299 e.notificationSender.Send(types.NotificationMessage{
300 NotificationType: types.ConnectionEstablished,
301 MacAddress: eth.SourceAddress().String(),
302 })
303 }
304
305 if eth.DestinationAddress() != e.gateway.LinkAddress() {
306 pkt := stack.NewPacketBuffer(stack.PacketBufferOptions{
307 Payload: buffer.MakeWithData(buf),
308 })
309 if err := e.tx(pkt); err != nil {
310 log.Error(err)
311 }
312 pkt.DecRef()
313 }
314 if eth.DestinationAddress() == e.gateway.LinkAddress() || eth.DestinationAddress() == header.EthernetBroadcastAddress {
315 data := buffer.MakeWithData(buf)
316 data.TrimFront(header.EthernetMinimumSize)
317 pkt := stack.NewPacketBuffer(stack.PacketBufferOptions{
318 Payload: data,
319 })
320 e.gateway.DeliverNetworkPacket(eth.Type(), pkt)
321 pkt.DecRef()
322 }
323
324 atomic.AddUint64(&e.Received, uint64(len(buf)))
325}
326
327func protocolImplementation(protocol types.Protocol) protocol {
328 switch protocol {
329 case types.QemuProtocol:
330 return &qemuProtocol{}
331 case types.BessProtocol:
332 return &bessProtocol{}
333 case types.VfkitProtocol:
334 return &vfkitProtocol{}
335 default:
336 return &hyperkitProtocol{}
337 }
338}
339
340func (e *Switch) SetNotificationSender(notificationSender *notification.NotificationSender) {
341 e.notificationSender = notificationSender
342}