basicfs_platformdata_windows.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Copyright (C) 2022 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package fs
  7. import (
  8. "fmt"
  9. "github.com/syncthing/syncthing/lib/protocol"
  10. "golang.org/x/sys/windows"
  11. )
  12. func (f *BasicFilesystem) PlatformData(name string) (protocol.PlatformData, error) {
  13. rootedName, err := f.rooted(name)
  14. if err != nil {
  15. return protocol.PlatformData{}, fmt.Errorf("rooted for %s: %w", name, err)
  16. }
  17. hdl, err := openReadOnlyWithBackupSemantics(rootedName)
  18. if err != nil {
  19. return protocol.PlatformData{}, fmt.Errorf("open %s: %w", rootedName, err)
  20. }
  21. defer windows.Close(hdl)
  22. // GetSecurityInfo returns an owner SID.
  23. sd, err := windows.GetSecurityInfo(hdl, windows.SE_FILE_OBJECT, windows.OWNER_SECURITY_INFORMATION)
  24. if err != nil {
  25. return protocol.PlatformData{}, fmt.Errorf("get security info for %s: %w", rootedName, err)
  26. }
  27. owner, _, err := sd.Owner()
  28. if err != nil {
  29. return protocol.PlatformData{}, fmt.Errorf("get owner for %s: %w", rootedName, err)
  30. }
  31. pd := &protocol.WindowsData{}
  32. if us := f.userCache.lookup(owner.String()); us != nil {
  33. pd.OwnerName = us.Username
  34. } else if gr := f.groupCache.lookup(owner.String()); gr != nil {
  35. pd.OwnerName = gr.Name
  36. pd.OwnerIsGroup = true
  37. } else {
  38. l.Debugf("Failed to resolve owner for %s: %v", rootedName, err)
  39. }
  40. return protocol.PlatformData{Windows: pd}, nil
  41. }
  42. func openReadOnlyWithBackupSemantics(path string) (fd windows.Handle, err error) {
  43. // This is windows.Open but simplified to read-only only, and adding
  44. // FILE_FLAG_BACKUP_SEMANTICS which is required to open directories.
  45. if len(path) == 0 {
  46. return windows.InvalidHandle, windows.ERROR_FILE_NOT_FOUND
  47. }
  48. pathp, err := windows.UTF16PtrFromString(path)
  49. if err != nil {
  50. return windows.InvalidHandle, err
  51. }
  52. var access uint32 = windows.GENERIC_READ
  53. var sharemode uint32 = windows.FILE_SHARE_READ | windows.FILE_SHARE_WRITE
  54. var sa *windows.SecurityAttributes
  55. var createmode uint32 = windows.OPEN_EXISTING
  56. var attrs uint32 = windows.FILE_ATTRIBUTE_READONLY | windows.FILE_FLAG_BACKUP_SEMANTICS
  57. return windows.CreateFile(pathp, access, sharemode, sa, createmode, attrs, 0)
  58. }