跳到主要内容

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

浏览文件

main.go

235 行 · 5.3 KB历史下载
1//go:build windows
2
3package main
4
5import (
6 "context"
7 "errors"
8 "fmt"
9 "net/url"
10 "os"
11 "path/filepath"
12 "strings"
13 "syscall"
14 "time"
15 "unsafe"
16
17 "github.com/containers/gvisor-tap-vsock/pkg/sshclient"
18 "github.com/containers/gvisor-tap-vsock/pkg/types"
19 "github.com/containers/gvisor-tap-vsock/pkg/utils"
20 "github.com/containers/winquit/pkg/winquit"
21 "github.com/sirupsen/logrus"
22 "golang.org/x/sync/errgroup"
23 "golang.org/x/sys/windows/svc/eventlog"
24)
25
26const (
27 ERR_BAD_ARGS = 0x000A
28 WM_QUIT = 0x12
29 RPC_S_SERVER_UNAVAILABLE syscall.Errno = 1722
30)
31
32var (
33 stateDir string
34 debug bool
35)
36
37func main() {
38 args := os.Args
39 if len(args) > 1 {
40 switch args[1] {
41 case "-version":
42 version := types.NewVersion("win-sshproxy")
43 fmt.Println(version.String())
44 os.Exit(0)
45 case "-debug":
46 debug = true
47 args = args[2:]
48 default:
49 args = args[1:]
50 }
51 }
52
53 if len(args) < 5 || (len(args)-2)%3 != 0 {
54 alert("Usage: " + filepath.Base(os.Args[0]) + "(-debug) [name] [statedir] ([source] [dest] [identity])... \n\nThis facilty proxies windows pipes and unix sockets over ssh using the specified identity.")
55 os.Exit(ERR_BAD_ARGS)
56 }
57
58 // Attempt to set up logging with the event log service.
59 // If it fails because the Windows Event Log Service is not running, show a warning
60 // and continue execution. There could be a reason why user disabled the Event Log.
61 log, err := setupLogging(args[0])
62 if err != nil {
63 if errors.Is(err, syscall.Errno(RPC_S_SERVER_UNAVAILABLE)) {
64 logrus.Warn("RPC server is unavailable, continuing without event log")
65 } else {
66 logrus.Errorf("Error setting up logging: %v", err)
67 os.Exit(1)
68 }
69 }
70
71 // Defer closing the log if setup was successful
72 if log != nil {
73 defer log.Close()
74 }
75
76 stateDir = args[1]
77
78 var sources, dests, identities []string
79 for i := 2; i < len(args)-2; i += 3 {
80 sources = append(sources, args[i])
81 dests = append(dests, args[i+1])
82 identities = append(identities, args[i+2])
83 }
84
85 ctx, cancel := context.WithCancel(context.Background())
86 group, ctx := errgroup.WithContext(ctx)
87
88 quit := make(chan bool, 1)
89 // Wait for a WM_QUIT message to exit
90 winquit.NotifyOnQuit(quit)
91 go func() {
92 <-quit
93 cancel()
94 }()
95
96 // Save thread for legacy callers which use it to post a quit
97 if _, err := saveThreadId(); err != nil {
98 logrus.Errorf("Error saving thread id: %v", err)
99 }
100
101 logrus.Debug("Setting up proxies")
102 err = setupProxies(ctx, group, sources, dests, identities)
103 if err != nil {
104 logrus.Errorf("Error setting up proxies: %v", err)
105 return
106 }
107
108 // Wait for completion (cancellation) or error
109 if err := group.Wait(); err != nil {
110 logrus.Errorf("Error occurred in execution group: %v", err)
111 return
112 }
113}
114
115func setupLogging(name string) (*eventlog.Log, error) {
116 // Reuse the Built-in .NET Runtime Source so that we do not
117 // have to provide a messaage table and modify the system
118 // event configuration
119 log, err := eventlog.Open(".NET Runtime")
120 if err != nil {
121 return nil, err
122 }
123
124 logrus.AddHook(NewEventHook(log, name))
125 if debug {
126 logrus.SetLevel(logrus.DebugLevel)
127 } else {
128 logrus.SetLevel(logrus.InfoLevel)
129 }
130
131 return log, nil
132}
133
134func setupProxies(ctx context.Context, g *errgroup.Group, sources []string, dests []string, identities []string) error {
135 for i := 0; i < len(sources); i++ {
136 var (
137 src *url.URL
138 dest *url.URL
139 err error
140 )
141 if strings.Contains(sources[i], "://") {
142 src, err = url.Parse(sources[i])
143 if err != nil {
144 return err
145 }
146 } else {
147 src = &url.URL{
148 Scheme: "unix",
149 Path: sources[i],
150 }
151 }
152
153 dest, err = url.Parse(dests[i])
154 if err != nil {
155 return err
156 }
157 j := i
158 g.Go(func() error {
159 forward, err := sshclient.CreateSSHForward(ctx, src, dest, identities[j], nil)
160 if err != nil {
161 return err
162 }
163 go func() {
164 <-ctx.Done()
165 // Abort pending accepts
166 forward.Close()
167 }()
168 loop:
169 for {
170 select {
171 case <-ctx.Done():
172 break loop
173 default:
174 // proceed
175 }
176 err := forward.AcceptAndTunnel(ctx)
177 if err != nil {
178 logrus.Debugf("Error occurred handling ssh forwarded connection: %q", err)
179 }
180 }
181 return nil
182 })
183 }
184
185 return nil
186}
187
188func saveThreadId() (uint32, error) {
189 path := filepath.Join(stateDir, "win-sshproxy.tid")
190 file, err := os.OpenFile(path, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
191 if err != nil {
192 return 0, err
193 }
194 defer file.Close()
195
196 tid, err := getThreadId()
197 if err != nil {
198 return 0, err
199 }
200
201 fmt.Fprintf(file, "%d:%d\n", os.Getpid(), tid)
202 return tid, nil
203}
204
205func getThreadId() (uint32, error) {
206 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
207 defer cancel()
208
209 getTid := func() (uint32, error) {
210 tid := winquit.GetCurrentMessageLoopThreadId()
211 if tid != 0 {
212 return tid, nil
213 }
214 return 0, fmt.Errorf("failed to get thread ID")
215 }
216
217 return utils.Retry(ctx, getTid, "Waiting for message loop thread id")
218}
219
220// Creates an "error" style pop-up window
221func alert(caption string) int {
222 // Error box style
223 format := 0x10
224
225 user32 := syscall.NewLazyDLL("user32.dll")
226 captionPtr, _ := syscall.UTF16PtrFromString(caption)
227 titlePtr, _ := syscall.UTF16PtrFromString("winpath")
228 ret, _, _ := user32.NewProc("MessageBoxW").Call(
229 uintptr(0),
230 uintptr(unsafe.Pointer(captionPtr)),
231 uintptr(unsafe.Pointer(titlePtr)),
232 uintptr(format))
233
234 return int(ret)
235}