Debian Codegraph @

copy/mkdir_windows.go

raw symbols SCIP
1 //go:build windows
2 // +build windows
3
4 package fs
5
6 import (
7 "fmt"
8 "os"
9 "syscall"
10 "time"
11
12 "github.com/Microsoft/go-winio"
13 "github.com/pkg/errors"
14 "golang.org/x/sys/windows"
15 )
16
17 const (
18 containerAdministratorSidString = "S-1-5-93-2-1"
19 )
20
21 func fixRootDirectory(p string) string {
22 if len(p) == len(`\\?\c:`) {
23 if os.IsPathSeparator(p[0]) && os.IsPathSeparator(p[1]) && p[2] == '?' && os.IsPathSeparator(p[3]) && p[5] == ':' {
24 return p + `\`
25 }
26 }
27 return p
28 }
29
30 func Utimes(p string, tm *time.Time) error {
31 info, err := os.Lstat(p)
32 if err != nil {
33 return errors.Wrap(err, "fetching file info")
34 }
35 if tm != nil && info.Mode()&os.ModeSymlink == 0 {
36 if err := os.Chtimes(p, *tm, *tm); err != nil {
37 return errors.Wrap(err, "changing times")
38 }
39 }
40 return nil
41 }
42
43 func Chown(p string, old *User, fn Chowner) error {
44 if fn == nil {
45 return nil
46 }
47 user, err := fn(old)
48 if err != nil {
49 return errors.WithStack(err)
50 }
51 var userSIDstring string
52 if user != nil && user.SID != "" {
53 userSIDstring = user.SID
54 }
55 if userSIDstring == "" {
56 userSIDstring = containerAdministratorSidString
57
58 }
59
60 sidPtr, err := syscall.UTF16PtrFromString(userSIDstring)
61 if err != nil {
62 return errors.Wrap(err, "converting to utf16 ptr")
63 }
64 var userSID *windows.SID
65 if err := windows.ConvertStringSidToSid(sidPtr, &userSID); err != nil {
66 return errors.Wrap(err, "converting to windows SID")
67 }
68 var dacl *windows.ACL
69 newEntries := []windows.EXPLICIT_ACCESS{
70 {
71 AccessPermissions: windows.GENERIC_ALL,
72 AccessMode: windows.GRANT_ACCESS,
73 Inheritance: windows.SUB_CONTAINERS_AND_OBJECTS_INHERIT,
74 Trustee: windows.TRUSTEE{
75 TrusteeForm: windows.TRUSTEE_IS_SID,
76 TrusteeValue: windows.TrusteeValueFromSID(userSID),
77 },
78 },
79 }
80 newAcl, err := windows.ACLFromEntries(newEntries, dacl)
81 if err != nil {
82 return fmt.Errorf("adding acls: %w", err)
83 }
84
85 // Copy file ownership and ACL
86 // We need SeRestorePrivilege and SeTakeOwnershipPrivilege in order
87 // to restore security info on a file, especially if we're trying to
88 // apply security info which includes SIDs not necessarily present on
89 // the host.
90 privileges := []string{winio.SeRestorePrivilege, seTakeOwnershipPrivilege}
91 err = winio.RunWithPrivileges(privileges, func() error {
92 if err := windows.SetNamedSecurityInfo(
93 p, windows.SE_FILE_OBJECT,
94 windows.OWNER_SECURITY_INFORMATION|windows.DACL_SECURITY_INFORMATION,
95 userSID, nil, newAcl, nil); err != nil {
96
97 return err
98 }
99 return nil
100 })
101
102 return err
103 }