跳到主要内容

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

浏览文件

request-server.go

422 行 · 11.4 KB历史下载
1package sftp
2
3import (
4 "context"
5 "errors"
6 "fmt"
7 "io"
8 "path"
9 "path/filepath"
10 rdebug "runtime/debug"
11 "strconv"
12 "sync"
13)
14
15const defaultMaxTxPacket uint32 = 1 << 15
16
17// Handlers contains the 4 SFTP server request handlers.
18type Handlers struct {
19 FileGet FileReader
20 FilePut FileWriter
21 FileCmd FileCmder
22 FileList FileLister
23}
24
25// RequestServer abstracts the sftp protocol with an http request-like protocol
26type RequestServer struct {
27 Handlers Handlers
28
29 *serverConn
30 pktMgr *packetManager
31
32 startDirectory string
33 maxTxPacket uint32
34 maxHandles int
35
36 mu sync.RWMutex
37 handleCount int
38 openRequests map[string]*Request
39}
40
41// A RequestServerOption is a function which applies configuration to a RequestServer.
42type RequestServerOption func(*RequestServer)
43
44// WithRSAllocator enable the allocator.
45// After processing a packet we keep in memory the allocated slices
46// and we reuse them for new packets.
47// The allocator is experimental
48func WithRSAllocator() RequestServerOption {
49 return func(rs *RequestServer) {
50 alloc := newAllocator()
51 rs.pktMgr.alloc = alloc
52 rs.conn.alloc = alloc
53 }
54}
55
56// WithStartDirectory sets a start directory to use as base for relative paths.
57// If unset the default is "/"
58func WithStartDirectory(startDirectory string) RequestServerOption {
59 return func(rs *RequestServer) {
60 rs.startDirectory = cleanPath(startDirectory)
61 }
62}
63
64// WithRSMaxTxPacket sets the maximum size of the payload returned to the client,
65// measured in bytes. The default value is 32768 bytes, and this option
66// can only be used to increase it. Setting this option to a larger value
67// should be safe, because the client decides the size of the requested payload.
68//
69// The default maximum packet size is 32768 bytes.
70func WithRSMaxTxPacket(size uint32) RequestServerOption {
71 return func(rs *RequestServer) {
72 if size < defaultMaxTxPacket {
73 return
74 }
75
76 rs.maxTxPacket = size
77 }
78}
79
80// WithRSMaxHandles makes OPEN and OPENDIR fail once n handles are open.
81// By default there is no limit, and each handle may hold a file descriptor and memory.
82func WithRSMaxHandles(n int) RequestServerOption {
83 return func(rs *RequestServer) {
84 rs.maxHandles = n
85 }
86}
87
88// WithRSSequential processes requests one at a time, in the order they are received.
89//
90// By default, reads and writes run concurrently with each other and with the other
91// requests, so a request can see or undo the effect of a write sent before it:
92// two writes to the same range can land in either order, and a FSTAT or FSETSTAT
93// sent after a WRITE can run before it. OpenSSH's sftp-server is sequential.
94func WithRSSequential() RequestServerOption {
95 return func(rs *RequestServer) {
96 rs.pktMgr.sequential = true
97 }
98}
99
100// NewRequestServer creates/allocates/returns new RequestServer.
101// Normally there will be one server per user-session.
102func NewRequestServer(rwc io.ReadWriteCloser, h Handlers, options ...RequestServerOption) *RequestServer {
103 svrConn := &serverConn{
104 conn: conn{
105 Reader: rwc,
106 WriteCloser: rwc,
107 },
108 }
109 rs := &RequestServer{
110 Handlers: h,
111
112 serverConn: svrConn,
113 pktMgr: newPktMgr(svrConn),
114
115 startDirectory: "/",
116 maxTxPacket: defaultMaxTxPacket,
117
118 openRequests: make(map[string]*Request),
119 }
120
121 for _, o := range options {
122 o(rs)
123 }
124 return rs
125}
126
127// New Open packet/Request
128func (rs *RequestServer) nextRequest(r *Request) string {
129 rs.mu.Lock()
130 defer rs.mu.Unlock()
131
132 rs.handleCount++
133
134 r.handle = strconv.Itoa(rs.handleCount)
135 rs.openRequests[r.handle] = r
136
137 return r.handle
138}
139
140// handleLimitReached reports whether no more handle may be opened (see WithRSMaxHandles).
141func (rs *RequestServer) handleLimitReached() bool {
142 if rs.maxHandles <= 0 {
143 return false
144 }
145 rs.mu.RLock()
146 defer rs.mu.RUnlock()
147 return len(rs.openRequests) >= rs.maxHandles
148}
149
150var errTooManyHandles = errors.New("too many open handles")
151
152// Returns Request from openRequests, bool is false if it is missing.
153//
154// The Requests in openRequests work essentially as open file descriptors that
155// you can do different things with. What you are doing with it are denoted by
156// the first packet of that type (read/write/etc).
157func (rs *RequestServer) getRequest(handle string) (*Request, bool) {
158 rs.mu.RLock()
159 defer rs.mu.RUnlock()
160
161 r, ok := rs.openRequests[handle]
162 return r, ok
163}
164
165// Close the Request and clear from openRequests map
166func (rs *RequestServer) closeRequest(handle string) error {
167 rs.mu.Lock()
168 defer rs.mu.Unlock()
169
170 if r, ok := rs.openRequests[handle]; ok {
171 delete(rs.openRequests, handle)
172 return r.close()
173 }
174
175 return EBADF
176}
177
178// Close the read/write/closer to trigger exiting the main server loop
179func (rs *RequestServer) Close() error { return rs.conn.Close() }
180
181func (rs *RequestServer) serveLoop(pktChan chan<- orderedRequest) error {
182 defer close(pktChan) // shuts down sftpServerWorkers
183
184 var err error
185 var pkt requestPacket
186 var pktType fxp
187 var pktBytes []byte
188
189 for {
190 pktType, pktBytes, err = rs.serverConn.recvPacket(rs.pktMgr.getNextOrderID())
191 if err != nil {
192 // we don't care about releasing allocated pages here, the server will quit and the allocator freed
193 return err
194 }
195
196 pkt, err = makePacket(rxPacket{pktType, pktBytes})
197 if err != nil {
198 switch {
199 case errors.Is(err, errUnknownExtendedPacket):
200 // do nothing
201 default:
202 debug("makePacket err: %v", err)
203 rs.conn.Close() // shuts down recvPacket
204 return err
205 }
206 }
207
208 pktChan <- rs.pktMgr.newOrderedRequest(pkt)
209 }
210}
211
212// Serve requests for user session
213func (rs *RequestServer) Serve() error {
214 defer func() {
215 if rs.pktMgr.alloc != nil {
216 rs.pktMgr.alloc.Free()
217 }
218 }()
219
220 ctx, cancel := context.WithCancel(context.Background())
221 defer cancel()
222
223 var wg sync.WaitGroup
224 runWorker := func(ch chan orderedRequest) {
225 wg.Add(1)
226 go func() {
227 defer wg.Done()
228 if err := rs.packetWorker(ctx, ch); err != nil {
229 rs.conn.Close() // shuts down recvPacket
230 }
231 }()
232 }
233 pktChan := rs.pktMgr.workerChan(runWorker)
234
235 err := rs.serveLoop(pktChan)
236
237 wg.Wait() // wait for all workers to exit
238
239 rs.mu.Lock()
240 defer rs.mu.Unlock()
241
242 // make sure all open requests are properly closed
243 // (eg. possible on dropped connections, client crashes, etc.)
244 for handle, req := range rs.openRequests {
245 if err == io.EOF {
246 err = io.ErrUnexpectedEOF
247 }
248 req.transferError(err)
249
250 delete(rs.openRequests, handle)
251 req.close()
252 }
253
254 return err
255}
256
257func (rs *RequestServer) packetWorker(ctx context.Context, pktChan chan orderedRequest) error {
258 for pkt := range pktChan {
259 orderID := pkt.orderID()
260 if epkt, ok := pkt.requestPacket.(*sshFxpExtendedPacket); ok {
261 if epkt.SpecificPacket != nil {
262 pkt.requestPacket = epkt.SpecificPacket
263 }
264 }
265
266 rpkt := rs.handlePacket(ctx, pkt.requestPacket, orderID)
267
268 rs.pktMgr.readyPacket(
269 rs.pktMgr.newOrderedResponse(rpkt, orderID))
270 }
271 return nil
272}
273
274// handlePacket answers one packet. A panic in a handler fails that request, instead of
275// the whole process, which may serve other connections or, as in Lima, run the VM.
276func (rs *RequestServer) handlePacket(ctx context.Context, pkt requestPacket, orderID uint32) (rpkt responsePacket) {
277 defer func() {
278 if p := recover(); p != nil {
279 debug("handlePacket: panic: %v\n%s", p, rdebug.Stack())
280 rpkt = statusFromError(pkt.id(), fmt.Errorf("sftp server: internal error: %v", p))
281 }
282 }()
283
284 switch pkt := pkt.(type) {
285 case *sshFxInitPacket:
286 rpkt = &sshFxVersionPacket{Version: sftpProtocolVersion, Extensions: sftpExtensions}
287 case *sshFxpClosePacket:
288 handle := pkt.getHandle()
289 rpkt = statusFromError(pkt.ID, rs.closeRequest(handle))
290 case *sshFxpRealpathPacket:
291 var realPath string
292 var err error
293
294 switch pather := rs.Handlers.FileList.(type) {
295 case RealPathFileLister:
296 realPath, err = pather.RealPath(pkt.getPath())
297 case legacyRealPathFileLister:
298 realPath = pather.RealPath(pkt.getPath())
299 default:
300 realPath = cleanPathWithBase(rs.startDirectory, pkt.getPath())
301 }
302 if err != nil {
303 rpkt = statusFromError(pkt.ID, err)
304 } else {
305 rpkt = cleanPacketPath(pkt, realPath)
306 }
307 case *sshFxpFsyncPacket:
308 request, ok := rs.getRequest(pkt.Handle)
309 if !ok {
310 rpkt = statusFromError(pkt.ID, EBADF)
311 } else if s, ok := request.opened().(interface{ Sync() error }); ok {
312 rpkt = statusFromError(pkt.ID, s.Sync())
313 } else {
314 rpkt = statusFromError(pkt.ID, ErrSSHFxOpUnsupported)
315 }
316 case *sshFxpOpendirPacket:
317 if rs.handleLimitReached() {
318 rpkt = statusFromError(pkt.ID, errTooManyHandles)
319 break
320 }
321 request := requestFromPacket(ctx, pkt, rs.startDirectory)
322 handle := rs.nextRequest(request)
323 rpkt = request.opendir(rs.Handlers, pkt)
324 if _, ok := rpkt.(*sshFxpHandlePacket); !ok {
325 // if we return an error we have to remove the handle from the active ones
326 rs.closeRequest(handle)
327 }
328 case *sshFxpOpenPacket:
329 if rs.handleLimitReached() {
330 rpkt = statusFromError(pkt.ID, errTooManyHandles)
331 break
332 }
333 request := requestFromPacket(ctx, pkt, rs.startDirectory)
334 handle := rs.nextRequest(request)
335 rpkt = request.open(rs.Handlers, pkt)
336 if _, ok := rpkt.(*sshFxpHandlePacket); !ok {
337 // if we return an error we have to remove the handle from the active ones
338 rs.closeRequest(handle)
339 }
340 case *sshFxpFstatPacket:
341 handle := pkt.getHandle()
342 request, ok := rs.getRequest(handle)
343 if !ok {
344 rpkt = statusFromError(pkt.ID, EBADF)
345 } else {
346 request = &Request{
347 Method: "Stat",
348 Filepath: cleanPathWithBase(rs.startDirectory, request.Filepath),
349 handleFile: request.opened(),
350 }
351 rpkt = request.call(rs.Handlers, pkt, rs.pktMgr.alloc, orderID, rs.maxTxPacket)
352 }
353 case *sshFxpFsetstatPacket:
354 handle := pkt.getHandle()
355 request, ok := rs.getRequest(handle)
356 if !ok {
357 rpkt = statusFromError(pkt.ID, EBADF)
358 } else {
359 request = &Request{
360 Method: "Setstat",
361 Filepath: cleanPathWithBase(rs.startDirectory, request.Filepath),
362 handleFile: request.opened(),
363 }
364 rpkt = request.call(rs.Handlers, pkt, rs.pktMgr.alloc, orderID, rs.maxTxPacket)
365 }
366 case *sshFxpExtendedPacketPosixRename:
367 request := &Request{
368 Method: "PosixRename",
369 Filepath: cleanPathWithBase(rs.startDirectory, pkt.Oldpath),
370 Target: cleanPathWithBase(rs.startDirectory, pkt.Newpath),
371 }
372 rpkt = request.call(rs.Handlers, pkt, rs.pktMgr.alloc, orderID, rs.maxTxPacket)
373 case *sshFxpExtendedPacketStatVFS:
374 request := &Request{
375 Method: "StatVFS",
376 Filepath: cleanPathWithBase(rs.startDirectory, pkt.Path),
377 }
378 rpkt = request.call(rs.Handlers, pkt, rs.pktMgr.alloc, orderID, rs.maxTxPacket)
379 case hasHandle:
380 handle := pkt.getHandle()
381 request, ok := rs.getRequest(handle)
382 if !ok {
383 rpkt = statusFromError(pkt.id(), EBADF)
384 } else {
385 rpkt = request.call(rs.Handlers, pkt, rs.pktMgr.alloc, orderID, rs.maxTxPacket)
386 }
387 case hasPath:
388 request := requestFromPacket(ctx, pkt, rs.startDirectory)
389 rpkt = request.call(rs.Handlers, pkt, rs.pktMgr.alloc, orderID, rs.maxTxPacket)
390 request.close()
391 default:
392 rpkt = statusFromError(pkt.id(), ErrSSHFxOpUnsupported)
393 }
394 return rpkt
395}
396
397// clean and return name packet for file
398func cleanPacketPath(pkt *sshFxpRealpathPacket, realPath string) responsePacket {
399 return &sshFxpNamePacket{
400 ID: pkt.id(),
401 NameAttrs: []*sshFxpNameAttr{
402 {
403 Name: realPath,
404 LongName: realPath,
405 Attrs: emptyFileStat,
406 },
407 },
408 }
409}
410
411// Makes sure we have a clean POSIX (/) absolute path to work with
412func cleanPath(p string) string {
413 return cleanPathWithBase("/", p)
414}
415
416func cleanPathWithBase(base, p string) string {
417 p = filepath.ToSlash(filepath.Clean(p))
418 if !path.IsAbs(p) {
419 return path.Join(base, p)
420 }
421 return p
422}