跳到主要内容

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

浏览文件

rooted_windows.go

644 行 · 21.1 KB历史下载
1package reversesshfs
2
3import (
4 "errors"
5 "os"
6 "path"
7 "path/filepath"
8 "strings"
9 "syscall"
10 "unsafe"
11
12 "github.com/pkg/sftp"
13 "golang.org/x/sys/windows"
14)
15
16var errDenied error = windows.ERROR_ACCESS_DENIED
17
18// lexicalGuard is false: a short name (VSCODE~1) hides the entry from the request path, so Guard
19// is asked with normalized names, by guardAt and guardHandle.
20const lexicalGuard = false
21
22// openNonblock: opening a file never blocks on Windows.
23const openNonblock = 0
24
25// appendWrite writes b at the end of f, as it is when the write happens.
26func appendWrite(f *os.File, b []byte) (int, error) {
27 var n uint32
28 // Offset and OffsetHigh both 0xFFFFFFFF: write to the end of the file (WriteFile documentation).
29 ov := windows.Overlapped{Offset: 0xFFFFFFFF, OffsetHigh: 0xFFFFFFFF}
30 err := windows.WriteFile(windows.Handle(f.Fd()), b, &n, &ov)
31 return int(n), err
32}
33
34// The first four are not defined in x/sys/windows.
35const (
36 fileNameNormalized = 0x0 // FILE_NAME_NORMALIZED
37 volumeNameNone = 0x4 // VOLUME_NAME_NONE
38 fileLinkInformation = 11
39 fileRenameInformationEx = 65
40 fileAttributeReadonly = windows.FILE_ATTRIBUTE_READONLY
41 fileAttributeNormal = windows.FILE_ATTRIBUTE_NORMAL
42 fileDirectoryAccess = windows.FILE_LIST_DIRECTORY | windows.FILE_TRAVERSE | windows.FILE_READ_ATTRIBUTES
43 fileShareAll = windows.FILE_SHARE_READ | windows.FILE_SHARE_WRITE | windows.FILE_SHARE_DELETE
44 fileDispositionFlagsPOSIX = windows.FILE_DISPOSITION_DELETE | windows.FILE_DISPOSITION_POSIX_SEMANTICS | windows.FILE_DISPOSITION_IGNORE_READONLY_ATTRIBUTE
45)
46
47// rootedSys walks paths with NtCreateFile relative to directory handles.
48// OBJ_DONT_REPARSE makes it fail on any reparse point (symlink, junction),
49// like O_NOFOLLOW on each component.
50//
51// A name that passes the lexical check may still refer to a read-only entry,
52// through its 8.3 short name (e.g. GIT~1 for .git, see CVE-2019-1353).
53// So every handle that a write goes through is checked by its normalized
54// name, in which the file system has replaced short names by long ones.
55type rootedSys struct {
56 localPath string
57 rootHandle windows.Handle
58 rootName string // normalized path of the root, without the volume and a trailing separator
59}
60
61func openRootedSys(localPath string) (rootedSys, error) {
62 p, err := windows.UTF16PtrFromString(localPath)
63 if err != nil {
64 return rootedSys{}, err
65 }
66 h, err := windows.CreateFile(p, fileDirectoryAccess|windows.SYNCHRONIZE, fileShareAll, nil,
67 windows.OPEN_EXISTING, windows.FILE_FLAG_BACKUP_SEMANTICS, 0)
68 if err != nil {
69 return rootedSys{}, &os.PathError{Op: "open", Path: localPath, Err: err}
70 }
71 name, err := normalizedName(h)
72 if err != nil {
73 windows.CloseHandle(h)
74 return rootedSys{}, &os.PathError{Op: "open", Path: localPath, Err: err}
75 }
76 return rootedSys{localPath: localPath, rootHandle: h, rootName: strings.TrimSuffix(name, `\`)}, nil
77}
78
79func (s rootedSys) close() error {
80 return windows.CloseHandle(s.rootHandle)
81}
82
83// slashPath returns the request path of the host path p.
84// sshfs sends the host path it was given, e.g. C:/Users/foo/bar,
85// which the sftp request server turns into /C:/Users/foo/bar.
86func slashPath(p string) string {
87 return path.Clean("/" + filepath.ToSlash(filepath.Clean(p)))
88}
89
90func startDirectory(string) string {
91 return "/"
92}
93
94func realPath(rootPath, p string) string {
95 if filepath.VolumeName(p) != "" || strings.HasPrefix(p, "/") || strings.HasPrefix(p, `\`) {
96 return slashPath(p)
97 }
98 return path.Join(rootPath, filepath.ToSlash(p))
99}
100
101// writableName rejects backslashes, which are separators on Windows,
102// and colons, which name NTFS streams (e.g. .git::$INDEX_ALLOCATION, see CVE-2019-1352).
103// It also rejects names NtCreateFile creates but Win32 tools cannot open or delete:
104// trailing dots or spaces, and device names (NUL, nul.txt, COM1...).
105func writableName(rel string) bool {
106 if strings.ContainsAny(rel, `\:`) {
107 return false
108 }
109 for _, c := range strings.Split(rel, "/") {
110 if c == "." {
111 continue
112 }
113 if strings.HasSuffix(c, ".") || strings.HasSuffix(c, " ") || isDeviceName(c) {
114 return false
115 }
116 }
117 return true
118}
119
120func isDeviceName(c string) bool {
121 stem, _, _ := strings.Cut(c, ".")
122 stem = strings.ToUpper(strings.TrimRight(stem, " "))
123 switch stem {
124 case "CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$":
125 return true
126 }
127 if len(stem) >= 4 && (strings.HasPrefix(stem, "COM") || strings.HasPrefix(stem, "LPT")) {
128 switch stem[3:] {
129 case "1", "2", "3", "4", "5", "6", "7", "8", "9", "¹", "²", "³":
130 return true
131 }
132 }
133 return false
134}
135
136func normalizedName(h windows.Handle) (string, error) {
137 buf := make([]uint16, windows.MAX_PATH)
138 for {
139 n, err := windows.GetFinalPathNameByHandle(h, &buf[0], uint32(len(buf)), fileNameNormalized|volumeNameNone)
140 if err != nil {
141 return "", err
142 }
143 if n < uint32(len(buf)) {
144 return windows.UTF16ToString(buf[:n]), nil
145 }
146 buf = make([]uint16, n)
147 }
148}
149
150// normalizedRel is the path of fh relative to the root, slash-separated, with the file system's own spelling.
151func (h *rootedHandlers) normalizedRel(fh windows.Handle) (string, error) {
152 name, err := normalizedName(fh)
153 if err != nil {
154 return "", err
155 }
156 if name == h.rootName {
157 return ".", nil
158 }
159 rel, ok := strings.CutPrefix(name, h.rootName+`\`)
160 if !ok {
161 return "", errDenied
162 }
163 return strings.ReplaceAll(rel, `\`, "/"), nil
164}
165
166// guardAt asks Guard about base in the directory parent, by the normalized name of parent.
167func (h *rootedHandlers) guardAt(parent windows.Handle, base string, entry bool) error {
168 if Guard == nil {
169 return nil
170 }
171 dir, err := h.normalizedRel(parent)
172 if err != nil {
173 return err
174 }
175 return h.guard(path.Join(dir, base), entry)
176}
177
178// guardHandle asks Guard about the file of fh, by its normalized name.
179func (h *rootedHandlers) guardHandle(fh windows.Handle, entry bool) error {
180 if Guard == nil {
181 return nil
182 }
183 rel, err := h.normalizedRel(fh)
184 if err != nil {
185 return err
186 }
187 return h.guard(rel, entry)
188}
189
190// checkHandle denies fh when its normalized path has a read-only component, or is not under the root.
191func (h *rootedHandlers) checkHandle(fh windows.Handle) error {
192 rel, err := h.normalizedRel(fh)
193 if err != nil {
194 return err
195 }
196 if rel == "." {
197 return nil
198 }
199 for _, c := range strings.Split(rel, "/") {
200 c, _, _ = strings.Cut(c, ":")
201 if h.isReadonlyName(c) {
202 return errDenied
203 }
204 }
205 return nil
206}
207
208func ntCreate(dir windows.Handle, name string, access, attrs, disposition, options, objFlags uint32) (windows.Handle, error) {
209 objectName, err := windows.NewNTUnicodeString(name)
210 if err != nil {
211 return windows.InvalidHandle, err
212 }
213 oa := &windows.OBJECT_ATTRIBUTES{
214 RootDirectory: dir,
215 ObjectName: objectName,
216 Attributes: windows.OBJ_CASE_INSENSITIVE | objFlags,
217 }
218 oa.Length = uint32(unsafe.Sizeof(*oa))
219 var fh windows.Handle
220 err = windows.NtCreateFile(&fh, access|windows.SYNCHRONIZE, oa, &windows.IO_STATUS_BLOCK{}, nil, attrs, fileShareAll,
221 disposition, options|windows.FILE_SYNCHRONOUS_IO_NONALERT|windows.FILE_OPEN_FOR_BACKUP_INTENT, 0, 0)
222 if err != nil {
223 return windows.InvalidHandle, ntError(err)
224 }
225 return fh, nil
226}
227
228func ntError(err error) error {
229 s, ok := err.(windows.NTStatus)
230 if !ok {
231 return err
232 }
233 if s == windows.STATUS_REPARSE_POINT_ENCOUNTERED {
234 return errDenied
235 }
236 return s.Errno()
237}
238
239// openParent returns a handle of the parent directory of rel, and the base name.
240// The caller must close the handle.
241func (h *rootedHandlers) openParent(rel string) (windows.Handle, string, error) {
242 if rel == "." {
243 return windows.InvalidHandle, "", errDenied
244 }
245 dir, base := path.Split(rel)
246 dir = strings.TrimSuffix(dir, "/")
247 if dir == "" {
248 var dup windows.Handle
249 p := windows.CurrentProcess()
250 if err := windows.DuplicateHandle(p, h.rootHandle, p, &dup, 0, false, windows.DUPLICATE_SAME_ACCESS); err != nil {
251 return windows.InvalidHandle, "", err
252 }
253 return dup, base, nil
254 }
255 for _, c := range strings.Split(dir, "/") {
256 if c == "" || c == "." || c == ".." {
257 return windows.InvalidHandle, "", errDenied
258 }
259 }
260 fh, err := ntCreate(h.rootHandle, filepath.FromSlash(dir), fileDirectoryAccess, 0, windows.FILE_OPEN,
261 windows.FILE_DIRECTORY_FILE, windows.OBJ_DONT_REPARSE)
262 if err != nil {
263 return windows.InvalidHandle, "", err
264 }
265 if err := h.checkHandle(fh); err != nil {
266 windows.CloseHandle(fh)
267 return windows.InvalidHandle, "", err
268 }
269 return fh, base, nil
270}
271
272// openChecked opens the writable path p, which must not be a reparse point unless options has FILE_OPEN_REPARSE_POINT.
273// The caller must close both handles.
274func (h *rootedHandlers) openChecked(p string, access, options uint32, entry bool) (parent, fh windows.Handle, err error) {
275 rel, err := h.writableRel(p, entry)
276 if err != nil {
277 return windows.InvalidHandle, windows.InvalidHandle, err
278 }
279 parent, base, err := h.openParent(rel)
280 if err != nil {
281 return windows.InvalidHandle, windows.InvalidHandle, err
282 }
283 if err := h.guardAt(parent, base, entry); err != nil {
284 windows.CloseHandle(parent)
285 return windows.InvalidHandle, windows.InvalidHandle, err
286 }
287 var objFlags uint32
288 if options&windows.FILE_OPEN_REPARSE_POINT == 0 {
289 objFlags = windows.OBJ_DONT_REPARSE
290 }
291 fh, err = ntCreate(parent, base, access, 0, windows.FILE_OPEN, options, objFlags)
292 if err == nil {
293 err = h.checkHandle(fh)
294 if err == nil {
295 err = h.guardHandle(fh, entry)
296 }
297 if err != nil {
298 windows.CloseHandle(fh)
299 }
300 }
301 if err != nil {
302 windows.CloseHandle(parent)
303 return windows.InvalidHandle, windows.InvalidHandle, err
304 }
305 return parent, fh, nil
306}
307
308func (h *rootedHandlers) openFile(r *sftp.Request) (*os.File, error) {
309 rel, err := h.writableRel(r.Filepath, false)
310 if err != nil {
311 return nil, err
312 }
313 parent, base, err := h.openParent(rel)
314 if err != nil {
315 return nil, err
316 }
317 defer windows.CloseHandle(parent)
318 if err := h.guardAt(parent, base, false); err != nil {
319 return nil, err
320 }
321 pf := r.Pflags()
322 var access, options uint32
323 switch {
324 case pf.Read && (pf.Write || pf.Append):
325 access = windows.FILE_GENERIC_READ | windows.FILE_GENERIC_WRITE
326 options = windows.FILE_NON_DIRECTORY_FILE
327 case pf.Write || pf.Append:
328 // FILE_READ_ATTRIBUTES: for fsetstat, as FILE_GENERIC_WRITE lacks it.
329 access = windows.FILE_GENERIC_WRITE | windows.FILE_READ_ATTRIBUTES
330 options = windows.FILE_NON_DIRECTORY_FILE
331 default:
332 access = windows.FILE_GENERIC_READ
333 }
334 // Appends are done by writableFile.WriteAt, so FILE_WRITE_DATA stays for truncation.
335 disposition := uint32(windows.FILE_OPEN)
336 switch {
337 case pf.Creat && pf.Excl:
338 disposition = windows.FILE_CREATE
339 case pf.Creat:
340 disposition = windows.FILE_OPEN_IF
341 }
342 var attrs uint32 = fileAttributeNormal
343 if m, ok := openMode(r); ok && m&0o200 == 0 {
344 attrs = fileAttributeReadonly
345 }
346 fh, err := ntCreate(parent, base, access, attrs, disposition, options, windows.OBJ_DONT_REPARSE)
347 if err != nil {
348 return nil, &os.PathError{Op: "open", Path: r.Filepath, Err: err}
349 }
350 // Checked before truncating: base may be the short name of an existing read-only name.
351 err = h.checkHandle(fh)
352 if err == nil {
353 err = h.guardHandle(fh, false)
354 }
355 if err != nil {
356 windows.CloseHandle(fh)
357 return nil, err
358 }
359 if h.cloud {
360 var fi windows.ByHandleFileInformation
361 err := windows.GetFileInformationByHandle(fh, &fi)
362 if err != nil || fi.NumberOfLinks != 1 || fi.FileAttributes&(windows.FILE_ATTRIBUTE_DIRECTORY|windows.FILE_ATTRIBUTE_REPARSE_POINT|windows.FILE_ATTRIBUTE_DEVICE) != 0 {
363 windows.CloseHandle(fh)
364 return nil, errDenied
365 }
366 }
367 if pf.Trunc {
368 if err := windows.Ftruncate(fh, 0); err != nil {
369 windows.CloseHandle(fh)
370 return nil, &os.PathError{Op: "truncate", Path: r.Filepath, Err: err}
371 }
372 }
373 return os.NewFile(uintptr(fh), r.Filepath), nil
374}
375
376func (h *rootedHandlers) remove(r *sftp.Request) error {
377 options := uint32(windows.FILE_OPEN_REPARSE_POINT)
378 if r.Method == "Rmdir" {
379 options |= windows.FILE_DIRECTORY_FILE
380 }
381 parent, fh, err := h.openChecked(r.Filepath, windows.DELETE|windows.FILE_READ_ATTRIBUTES, options, true)
382 if err != nil {
383 return err
384 }
385 defer windows.CloseHandle(parent)
386 defer windows.CloseHandle(fh)
387 if r.Method == "Remove" {
388 // As unlink, which removes a symlink to a directory but not a directory.
389 var fi windows.ByHandleFileInformation
390 if err := windows.GetFileInformationByHandle(fh, &fi); err != nil {
391 return &os.PathError{Op: "remove", Path: r.Filepath, Err: err}
392 }
393 if fi.FileAttributes&windows.FILE_ATTRIBUTE_DIRECTORY != 0 && fi.FileAttributes&windows.FILE_ATTRIBUTE_REPARSE_POINT == 0 {
394 return &os.PathError{Op: "remove", Path: r.Filepath, Err: syscall.EISDIR}
395 }
396 }
397 if err := deleteHandle(fh); err != nil {
398 return &os.PathError{Op: strings.ToLower(r.Method), Path: r.Filepath, Err: err}
399 }
400 return nil
401}
402
403// deleteHandle is Deleteat of Go's internal/syscall/windows.
404func deleteHandle(fh windows.Handle) error {
405 flags := uint32(fileDispositionFlagsPOSIX)
406 err := windows.NtSetInformationFile(fh, &windows.IO_STATUS_BLOCK{}, (*byte)(unsafe.Pointer(&flags)),
407 uint32(unsafe.Sizeof(flags)), windows.FileDispositionInformationEx)
408 switch err {
409 case nil:
410 return nil
411 case windows.STATUS_INVALID_INFO_CLASS, windows.STATUS_INVALID_PARAMETER, windows.STATUS_NOT_SUPPORTED:
412 // Older Windows, or a file system without POSIX semantics, such as FAT32.
413 deleteFile := uint8(1)
414 err = windows.NtSetInformationFile(fh, &windows.IO_STATUS_BLOCK{}, &deleteFile,
415 uint32(unsafe.Sizeof(deleteFile)), windows.FileDispositionInformation)
416 }
417 return ntError(err)
418}
419
420func (h *rootedHandlers) mkdir(r *sftp.Request) error {
421 rel, err := h.writableRel(r.Filepath, true)
422 if err != nil {
423 return err
424 }
425 parent, base, err := h.openParent(rel)
426 if err != nil {
427 return err
428 }
429 defer windows.CloseHandle(parent)
430 if err := h.guardAt(parent, base, true); err != nil {
431 return err
432 }
433 // A base that is the short name of an existing entry fails with STATUS_OBJECT_NAME_COLLISION.
434 fh, err := ntCreate(parent, base, fileDirectoryAccess, fileAttributeNormal, windows.FILE_CREATE,
435 windows.FILE_DIRECTORY_FILE, windows.OBJ_DONT_REPARSE)
436 if err != nil {
437 return &os.PathError{Op: "mkdir", Path: r.Filepath, Err: err}
438 }
439 return windows.CloseHandle(fh)
440}
441
442// symlink is not supported: creating a symlink needs a privilege, or the developer mode,
443// and CreateSymbolicLink takes a path, so it would follow symlinks in the parent directories.
444func (h *rootedHandlers) symlink(*sftp.Request) error {
445 return sftp.ErrSSHFxOpUnsupported
446}
447
448func (h *rootedHandlers) link(r *sftp.Request) error {
449 return h.twoPaths(r.Filepath, r.Target, windows.FILE_WRITE_ATTRIBUTES|windows.FILE_READ_ATTRIBUTES,
450 windows.FILE_NON_DIRECTORY_FILE, true, func(src, newParent windows.Handle, newBase string) error {
451 return setName(src, fileLinkInformation, 0, newParent, newBase)
452 })
453}
454
455func (h *rootedHandlers) rename(r *sftp.Request, noReplace bool) error {
456 return h.twoPaths(r.Filepath, r.Target, windows.DELETE|windows.FILE_READ_ATTRIBUTES, 0, noReplace,
457 func(src, newParent windows.Handle, newBase string) error {
458 var flags uint32 = windows.FILE_RENAME_POSIX_SEMANTICS | windows.FILE_RENAME_IGNORE_READONLY_ATTRIBUTE
459 if !noReplace {
460 flags |= windows.FILE_RENAME_REPLACE_IF_EXISTS
461 }
462 err := setName(src, fileRenameInformationEx, flags, newParent, newBase)
463 switch err {
464 case windows.STATUS_INVALID_INFO_CLASS, windows.STATUS_INVALID_PARAMETER, windows.STATUS_NOT_SUPPORTED:
465 // Older Windows, or a file system without POSIX semantics.
466 // The first byte of the flags is ReplaceIfExists.
467 err = setName(src, windows.FileRenameInformation, flags&windows.FILE_RENAME_REPLACE_IF_EXISTS, newParent, newBase)
468 }
469 return err
470 })
471}
472
473// twoPaths opens oldPath without following a symlink, and calls f with the parent directory handle and
474// the base name of newPath.
475func (h *rootedHandlers) twoPaths(oldPath, newPath string, access, options uint32, noReplace bool,
476 f func(src, newParent windows.Handle, newBase string) error,
477) error {
478 newRel, err := h.writableRel(newPath, true)
479 if err != nil {
480 return err
481 }
482 oldParent, src, err := h.openChecked(oldPath, access, options|windows.FILE_OPEN_REPARSE_POINT, true)
483 if err != nil {
484 return err
485 }
486 defer windows.CloseHandle(oldParent)
487 defer windows.CloseHandle(src)
488 newParent, newBase, err := h.openParent(newRel)
489 if err != nil {
490 return err
491 }
492 defer windows.CloseHandle(newParent)
493 if err := h.guardAt(newParent, newBase, true); err != nil {
494 return err
495 }
496 // newBase may be the short name of an existing read-only name, which would be replaced.
497 dst, err := ntCreate(newParent, newBase, windows.FILE_READ_ATTRIBUTES, 0, windows.FILE_OPEN, windows.FILE_OPEN_REPARSE_POINT, 0)
498 switch {
499 case err == nil:
500 err = h.checkHandle(dst)
501 if err == nil {
502 err = h.guardHandle(dst, true)
503 }
504 windows.CloseHandle(dst)
505 if err != nil {
506 return err
507 }
508 if noReplace {
509 return &os.LinkError{Op: "rename", Old: oldPath, New: newPath, Err: os.ErrExist}
510 }
511 case !errors.Is(err, os.ErrNotExist):
512 return &os.LinkError{Op: "rename", Old: oldPath, New: newPath, Err: err}
513 }
514 if err := f(src, newParent, newBase); err != nil {
515 return &os.LinkError{Op: "rename", Old: oldPath, New: newPath, Err: ntError(err)}
516 }
517 return nil
518}
519
520// fileNameInformation is FILE_RENAME_INFORMATION and FILE_LINK_INFORMATION.
521// Flags is a BOOLEAN ReplaceIfExists for the non-Ex classes.
522type fileNameInformation struct {
523 Flags uint32
524 RootDirectory windows.Handle
525 FileNameLength uint32
526 FileName [1]uint16
527}
528
529// setName renames src, or creates a hard link of it, to name in the directory dir.
530func setName(src windows.Handle, class, flags uint32, dir windows.Handle, name string) error {
531 name16, err := windows.UTF16FromString(name)
532 if err != nil {
533 return err
534 }
535 name16 = name16[:len(name16)-1]
536 size := unsafe.Offsetof(fileNameInformation{}.FileName) + uintptr(len(name16))*2
537 buf := make([]uint64, (size+7)/8)
538 info := (*fileNameInformation)(unsafe.Pointer(&buf[0]))
539 info.Flags = flags
540 info.RootDirectory = dir
541 info.FileNameLength = uint32(len(name16) * 2)
542 copy(unsafe.Slice(&info.FileName[0], len(name16)), name16)
543 return windows.NtSetInformationFile(src, &windows.IO_STATUS_BLOCK{}, (*byte)(unsafe.Pointer(&buf[0])), uint32(size), class)
544}
545
546// fileBasicInformation is FILE_BASIC_INFORMATION. Zero values are left unchanged.
547type fileBasicInformation struct {
548 CreationTime, LastAccessTime, LastWriteTime, ChangeTime int64
549 FileAttributes uint32
550 _ uint32 // the C struct is 40 bytes on 386 too
551}
552
553func (h *rootedHandlers) setstat(r *sftp.Request) error {
554 flags := r.AttrFlags()
555 if flags.UidGid {
556 return &os.PathError{Op: "chown", Path: r.Filepath, Err: syscall.EWINDOWS}
557 }
558 access := uint32(windows.FILE_READ_ATTRIBUTES | windows.FILE_WRITE_ATTRIBUTES)
559 if flags.Size {
560 access |= windows.FILE_WRITE_DATA
561 }
562 parent, fh, err := h.openChecked(r.Filepath, access, 0, false)
563 if err != nil {
564 return err
565 }
566 defer windows.CloseHandle(parent)
567 defer windows.CloseHandle(fh)
568 return setstatHandle(fh, r)
569}
570
571// fsetstat applies a FSETSTAT to the file f of the handle.
572func (h *rootedHandlers) fsetstat(f *os.File, r *sftp.Request) error {
573 if r.AttrFlags().UidGid {
574 return &os.PathError{Op: "chown", Path: f.Name(), Err: syscall.EWINDOWS}
575 }
576 return setstatHandle(windows.Handle(f.Fd()), r)
577}
578
579// setstatHandle applies the attributes of r to fh. r.Filepath is only used in errors.
580
581func setstatHandle(fh windows.Handle, r *sftp.Request) error {
582 flags := r.AttrFlags()
583 attrs := r.Attributes()
584 if attrs == nil {
585 return windows.ERROR_INVALID_PARAMETER
586 }
587 if flags.Size {
588 if err := windows.Ftruncate(fh, int64(attrs.Size)); err != nil {
589 return &os.PathError{Op: "truncate", Path: r.Filepath, Err: err}
590 }
591 }
592 if flags.Permissions {
593 // As os.Chmod: only the owner write bit is used, for the read-only attribute.
594 var fi windows.ByHandleFileInformation
595 if err := windows.GetFileInformationByHandle(fh, &fi); err != nil {
596 return &os.PathError{Op: "chmod", Path: r.Filepath, Err: err}
597 }
598 a := fi.FileAttributes &^ fileAttributeReadonly
599 if attrs.Mode&0o200 == 0 {
600 a |= fileAttributeReadonly
601 }
602 if a == 0 {
603 a = fileAttributeNormal
604 }
605 info := fileBasicInformation{FileAttributes: a}
606 err := windows.NtSetInformationFile(fh, &windows.IO_STATUS_BLOCK{}, (*byte)(unsafe.Pointer(&info)),
607 uint32(unsafe.Sizeof(info)), windows.FileBasicInformation)
608 if err != nil {
609 return &os.PathError{Op: "chmod", Path: r.Filepath, Err: ntError(err)}
610 }
611 }
612 if flags.Acmodtime {
613 atime := windows.NsecToFiletime(int64(attrs.Atime) * 1e9)
614 mtime := windows.NsecToFiletime(int64(attrs.Mtime) * 1e9)
615 if err := windows.SetFileTime(fh, nil, &atime, &mtime); err != nil {
616 return &os.PathError{Op: "chtimes", Path: r.Filepath, Err: err}
617 }
618 }
619 return nil
620}
621
622// StatVFS implements sftp.StatVFSFileCmder.
623func (h *rootedHandlers) StatVFS(r *sftp.Request) (*sftp.StatVFS, error) {
624 if _, err := h.rel(r.Filepath); err != nil {
625 return nil, err
626 }
627 p, err := windows.UTF16PtrFromString(h.localPath)
628 if err != nil {
629 return nil, err
630 }
631 var avail, total, free uint64
632 if err := windows.GetDiskFreeSpaceEx(p, &avail, &total, &free); err != nil {
633 return nil, &os.PathError{Op: "statvfs", Path: h.localPath, Err: err}
634 }
635 const bsize = 4096
636 return &sftp.StatVFS{
637 Bsize: bsize,
638 Frsize: bsize,
639 Blocks: total / bsize,
640 Bfree: free / bsize,
641 Bavail: avail / bsize,
642 Namemax: 255,
643 }, nil
644}