跳到主要内容

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

浏览文件

ports.go

394 行 · 9.5 KB历史下载
1package forwarder
2
3import (
4 "context"
5 "encoding/json"
6 "errors"
7 "fmt"
8 "io"
9 "net"
10 "net/http"
11 "net/url"
12 "os"
13 "sort"
14 "strconv"
15 "strings"
16 "sync"
17
18 "github.com/containers/gvisor-tap-vsock/pkg/sshclient"
19 "github.com/containers/gvisor-tap-vsock/pkg/types"
20 "github.com/inetaf/tcpproxy"
21 log "github.com/sirupsen/logrus"
22 "gvisor.dev/gvisor/pkg/tcpip"
23 "gvisor.dev/gvisor/pkg/tcpip/adapters/gonet"
24 "gvisor.dev/gvisor/pkg/tcpip/network/ipv4"
25 "gvisor.dev/gvisor/pkg/tcpip/stack"
26)
27
28type ProxyKey string
29
30type PortsForwarder struct {
31 stack *stack.Stack
32
33 proxiesLock sync.Mutex
34 proxies map[ProxyKey]proxy
35}
36
37type proxy struct {
38 Local string `json:"local"`
39 Remote string `json:"remote"`
40 Protocol string `json:"protocol"`
41 underlying io.Closer
42}
43
44type gonetDialer struct {
45 stack *stack.Stack
46}
47
48func (d *gonetDialer) DialContextTCP(ctx context.Context, addr string) (conn net.Conn, e error) {
49 address, err := tcpipAddress(1, addr)
50 if err != nil {
51 return nil, err
52 }
53
54 return gonet.DialContextTCP(ctx, d.stack, address, ipv4.ProtocolNumber)
55}
56
57type CloseWrapper func() error
58
59func (w CloseWrapper) Close() error {
60 return w()
61}
62
63func NewPortsForwarder(s *stack.Stack) *PortsForwarder {
64 return &PortsForwarder{
65 stack: s,
66 proxies: make(map[ProxyKey]proxy),
67 }
68}
69
70func (f *PortsForwarder) Expose(protocol types.TransportProtocol, local, remote string) error {
71 f.proxiesLock.Lock()
72 defer f.proxiesLock.Unlock()
73 if _, ok := f.proxies[key(protocol, local)]; ok {
74 return errors.New("proxy already running")
75 }
76
77 switch protocol {
78 case types.UNIX, types.NPIPE:
79 // parse URI for remote
80 remoteURI, err := url.Parse(remote)
81 if err != nil {
82 return fmt.Errorf("failed to parse remote uri :%s : %w", remote, err)
83 }
84
85 // build the address from remoteURI
86 remoteAddr := net.JoinHostPort(remoteURI.Hostname(), remoteURI.Port())
87
88 // dialFn opens remote connection for the proxy
89 var dialFn func(ctx context.Context, network, addr string) (conn net.Conn, e error)
90
91 var cleanup func()
92
93 // dialFn is set based on the protocol provided by remoteURI.Scheme
94 switch remoteURI.Scheme {
95 case "ssh-tunnel": // unix-to-unix proxy (over SSH)
96 // query string to map for the remoteURI contains ssh config info
97 remoteQuery := remoteURI.Query()
98
99 // key
100 sshkeypath := firstValueOrEmpty(remoteQuery["key"])
101 if sshkeypath == "" {
102 return fmt.Errorf("key not provided for unix-ssh connection")
103 }
104
105 // passphrase
106 passphrase := firstValueOrEmpty(remoteQuery["passphrase"])
107
108 // default ssh port if not set
109 if remoteURI.Port() == "" {
110 remoteURI.Host = net.JoinHostPort(remoteURI.Hostname(), "22")
111 }
112
113 // check the remoteURI path provided for nonsense
114 if remoteURI.Path == "" || remoteURI.Path == "/" {
115 return fmt.Errorf("remote uri must contain a path to a socket file")
116 }
117
118 // captured and used by dialFn
119 var sshForward *sshclient.SSHForward
120 var connLock sync.Mutex
121
122 dialFn = func(ctx context.Context, _, _ string) (net.Conn, error) {
123 connLock.Lock()
124 defer connLock.Unlock()
125
126 if sshForward == nil {
127 client, err := sshclient.CreateSSHForwardPassphrase(ctx, &url.URL{}, remoteURI, sshkeypath, passphrase, &gonetDialer{f.stack})
128 if err != nil {
129 return nil, err
130 }
131 sshForward = client
132 }
133
134 return sshForward.Tunnel(ctx)
135 }
136
137 cleanup = func() {
138 if sshForward != nil {
139 sshForward.Close()
140 }
141 }
142
143 case "tcp": // unix-to-tcp proxy
144 // build address
145 address, err := tcpipAddress(1, remoteAddr)
146 if err != nil {
147 return err
148 }
149
150 dialFn = func(ctx context.Context, _, _ string) (conn net.Conn, e error) {
151 return gonet.DialContextTCP(ctx, f.stack, address, ipv4.ProtocolNumber)
152 }
153
154 default:
155 return fmt.Errorf("remote protocol for unix forwarder is not implemented: %s", remoteURI.Scheme)
156 }
157
158 // build the tcp proxy
159 var p tcpproxy.Proxy
160 switch protocol {
161 case types.UNIX:
162 p.ListenFunc = func(_, socketPath string) (net.Listener, error) {
163 // remove existing socket file
164 if err := os.Remove(socketPath); err != nil && !os.IsNotExist(err) {
165 return nil, err
166 }
167 return net.Listen("unix", socketPath) // override tcp to use unix socket
168 }
169 case types.NPIPE:
170 p.ListenFunc = func(_, socketPath string) (net.Listener, error) {
171 npipeURI, err := url.Parse(socketPath)
172 if err != nil {
173 return nil, err
174 }
175 return sshclient.ListenNpipe(npipeURI)
176 }
177 }
178 p.AddRoute(local, &tcpproxy.DialProxy{
179 Addr: remoteAddr,
180 DialContext: dialFn,
181 })
182 if err := p.Start(); err != nil {
183 return err
184 }
185 go func() {
186 if err := p.Wait(); err != nil {
187 log.Error(err)
188 }
189 }()
190 f.proxies[key(protocol, local)] = proxy{
191 Protocol: string(protocol),
192 Local: local,
193 Remote: remote,
194 underlying: CloseWrapper(func() error {
195 if cleanup != nil {
196 cleanup()
197 }
198 return p.Close()
199 }),
200 }
201 case types.UDP:
202 address, err := tcpipAddress(1, remote)
203 if err != nil {
204 return err
205 }
206
207 addr, err := net.ResolveUDPAddr("udp", local)
208 if err != nil {
209 return err
210 }
211 listener, err := net.ListenUDP("udp", addr)
212 if err != nil {
213 return err
214 }
215 p, err := NewUDPProxy(listener, func() (net.Conn, error) {
216 return gonet.DialUDP(f.stack, nil, &address, ipv4.ProtocolNumber)
217 })
218 if err != nil {
219 return err
220 }
221 go p.Run()
222 f.proxies[key(protocol, local)] = proxy{
223 Protocol: "udp",
224 Local: local,
225 Remote: remote,
226 underlying: p,
227 }
228 case types.TCP:
229 address, err := tcpipAddress(1, remote)
230 if err != nil {
231 return err
232 }
233
234 var p tcpproxy.Proxy
235 p.AddRoute(local, &tcpproxy.DialProxy{
236 Addr: remote,
237 DialContext: func(ctx context.Context, _, _ string) (conn net.Conn, e error) {
238 return gonet.DialContextTCP(ctx, f.stack, address, ipv4.ProtocolNumber)
239 },
240 })
241 if err := p.Start(); err != nil {
242 return err
243 }
244 go func() {
245 if err := p.Wait(); err != nil {
246 log.Error(err)
247 }
248 }()
249 f.proxies[key(protocol, local)] = proxy{
250 Protocol: "tcp",
251 Local: local,
252 Remote: remote,
253 underlying: &p,
254 }
255 default:
256 return fmt.Errorf("unknown protocol %s", protocol)
257 }
258 return nil
259}
260
261func key(protocol types.TransportProtocol, local string) ProxyKey {
262 return ProxyKey(fmt.Sprintf("%s/%s", protocol, local))
263}
264
265func (f *PortsForwarder) Unexpose(protocol types.TransportProtocol, local string) error {
266 f.proxiesLock.Lock()
267 defer f.proxiesLock.Unlock()
268 proxy, ok := f.proxies[key(protocol, local)]
269 if !ok {
270 return errors.New("proxy not found")
271 }
272 delete(f.proxies, key(protocol, local))
273 return proxy.underlying.Close()
274}
275
276func (f *PortsForwarder) Mux() http.Handler {
277 mux := http.NewServeMux()
278 mux.HandleFunc("/all", func(w http.ResponseWriter, _ *http.Request) {
279 f.proxiesLock.Lock()
280 defer f.proxiesLock.Unlock()
281 ret := make([]proxy, 0)
282 for _, proxy := range f.proxies {
283 ret = append(ret, proxy)
284 }
285 sort.Slice(ret, func(i, j int) bool {
286 if ret[i].Local == ret[j].Local {
287 return ret[i].Protocol < ret[j].Protocol
288 }
289 return ret[i].Local < ret[j].Local
290 })
291 _ = json.NewEncoder(w).Encode(ret)
292 })
293 mux.HandleFunc("/expose", func(w http.ResponseWriter, r *http.Request) {
294 if r.Method != http.MethodPost {
295 http.Error(w, "post only", http.StatusBadRequest)
296 return
297 }
298 var req types.ExposeRequest
299 if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
300 http.Error(w, err.Error(), http.StatusBadRequest)
301 return
302 }
303 if req.Protocol == "" {
304 req.Protocol = types.TCP
305 }
306
307 // contains unparsed remote field
308 remoteAddr := req.Remote
309
310 // TCP and UDP rely on remote() to preparse the remote field
311 if req.Protocol != types.UNIX && req.Protocol != types.NPIPE {
312 var err error
313 remoteAddr, err = remote(req, r.RemoteAddr)
314 if err != nil {
315 http.Error(w, err.Error(), http.StatusBadRequest)
316 return
317 }
318 }
319
320 if err := f.Expose(req.Protocol, req.Local, remoteAddr); err != nil {
321 http.Error(w, err.Error(), http.StatusInternalServerError)
322 return
323 }
324 w.WriteHeader(http.StatusOK)
325 })
326 mux.HandleFunc("/unexpose", func(w http.ResponseWriter, r *http.Request) {
327 if r.Method != http.MethodPost {
328 http.Error(w, "post only", http.StatusBadRequest)
329 return
330 }
331 var req types.UnexposeRequest
332 if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
333 http.Error(w, err.Error(), http.StatusBadRequest)
334 return
335 }
336 if req.Protocol == "" {
337 req.Protocol = types.TCP
338 }
339 if err := f.Unexpose(req.Protocol, req.Local); err != nil {
340 http.Error(w, err.Error(), http.StatusInternalServerError)
341 return
342 }
343 w.WriteHeader(http.StatusOK)
344 })
345 return mux
346}
347
348// if the request doesn't have an IP in the remote field, use the IP from the incoming http request.
349func remote(req types.ExposeRequest, ip string) (string, error) {
350 remoteIP, _, err := net.SplitHostPort(req.Remote)
351 if err != nil {
352 return "", err
353 }
354 if remoteIP == "" {
355 host, _, err := net.SplitHostPort(ip)
356 if err != nil {
357 return "", err
358 }
359 return fmt.Sprintf("%s%s", host, req.Remote), nil
360 }
361 return req.Remote, nil
362}
363
364// helper function for parsed URL query strings
365func firstValueOrEmpty(x []string) string {
366 if len(x) > 0 {
367 return x[0]
368 }
369 return ""
370}
371
372// helper function to build tcpip address
373func tcpipAddress(nicID tcpip.NICID, remote string) (address tcpip.FullAddress, err error) {
374
375 // build the address manual way
376 split := strings.Split(remote, ":")
377 if len(split) != 2 {
378 return address, errors.New("invalid remote addr")
379 }
380
381 port, err := strconv.ParseUint(split[1], 10, 16)
382 if err != nil {
383 return address, err
384
385 }
386
387 address = tcpip.FullAddress{
388 NIC: nicID,
389 Addr: tcpip.AddrFrom4Slice(net.ParseIP(split[0]).To4()),
390 Port: uint16(port),
391 }
392
393 return address, err
394}