artifactize-foundation 0.27.1

Native file, path and executable primitives for Artifactize.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
//! Owner-only files and directories: a protected DACL whose single ACE grants the current
//! user full control, the Windows counterpart of modes 0700 and 0600.

use std::{
    ffi::c_void,
    fs::{File, OpenOptions},
    io, mem,
    os::windows::{
        ffi::OsStrExt,
        fs::OpenOptionsExt,
        io::{AsRawHandle, FromRawHandle, OwnedHandle},
    },
    path::Path,
    ptr, slice,
};

use windows_sys::Win32::{
    Foundation::{
        ERROR_ACCESS_DENIED, ERROR_SHARING_VIOLATION, ERROR_SUCCESS, GENERIC_READ, GENERIC_WRITE,
        HANDLE, INVALID_HANDLE_VALUE, LocalFree,
    },
    Security::{
        ACCESS_ALLOWED_ACE, ACE_HEADER, ACL, ACL_SIZE_INFORMATION, AclSizeInformation,
        Authorization::{
            ConvertSidToStringSidW, ConvertStringSecurityDescriptorToSecurityDescriptorW,
            GetSecurityInfo, SDDL_REVISION_1, SE_FILE_OBJECT, SetSecurityInfo,
        },
        CONTAINER_INHERIT_ACE, DACL_SECURITY_INFORMATION, EqualSid, GetAce, GetAclInformation,
        GetSecurityDescriptorControl, GetSecurityDescriptorDacl, GetTokenInformation,
        IsWellKnownSid, OBJECT_INHERIT_ACE, OWNER_SECURITY_INFORMATION,
        PROTECTED_DACL_SECURITY_INFORMATION, PSID, SE_DACL_PROTECTED, SECURITY_ATTRIBUTES,
        TOKEN_QUERY, TOKEN_USER, TokenUser, WinBuiltinAdministratorsSid, WinLocalSystemSid,
    },
    Storage::FileSystem::{
        BY_HANDLE_FILE_INFORMATION, CREATE_NEW, CreateDirectoryW, CreateFileW, FILE_ALL_ACCESS,
        FILE_ATTRIBUTE_DIRECTORY, FILE_ATTRIBUTE_NORMAL, FILE_ATTRIBUTE_REPARSE_POINT,
        FILE_FLAG_BACKUP_SEMANTICS, FILE_ID_INFO, FILE_LIST_DIRECTORY, FILE_READ_ATTRIBUTES,
        FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, FILE_TYPE_DISK, FileIdInfo,
        GetFileInformationByHandle, GetFileInformationByHandleEx, GetFileType, READ_CONTROL,
        ReOpenFile, WRITE_DAC,
    },
    System::{
        SystemServices::{
            ACCESS_ALLOWED_ACE_TYPE, ACCESS_DENIED_ACE_TYPE, ACCESS_DENIED_CALLBACK_ACE_TYPE,
            ACCESS_DENIED_CALLBACK_OBJECT_ACE_TYPE, ACCESS_DENIED_OBJECT_ACE_TYPE,
        },
        Threading::{GetCurrentProcess, OpenProcessToken},
    },
};

/// Create one directory with an owner-only DACL that new files and subdirectories inherit.
pub fn create_private_dir(path: &Path) -> io::Result<()> {
    let descriptor = owner_only(true)?;
    let attributes = SECURITY_ATTRIBUTES {
        nLength: mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
        lpSecurityDescriptor: descriptor.0,
        bInheritHandle: 0,
    };
    let path = wide(path)?;
    // SAFETY: a NUL-terminated path and a valid security descriptor, both alive for the call.
    if unsafe { CreateDirectoryW(path.as_ptr(), &attributes) } == 0 {
        return Err(io::Error::last_os_error());
    }
    Ok(())
}

/// Change the existing directory only through a handle that refuses reparse points.
pub(super) fn restrict_directory(path: &Path) -> io::Result<()> {
    let directory = open_directory_security(path, READ_CONTROL | WRITE_DAC)?;
    if !directory.metadata()?.is_dir() {
        return Err(io::ErrorKind::NotADirectory.into());
    }
    let handle = directory.as_raw_handle();
    let acl = SecurityDescriptor::read(handle)?;
    let current_user = current_user()?;
    let user = current_user.sid();
    if !acl.is_owned_by(user) {
        return Err(io::Error::new(
            io::ErrorKind::PermissionDenied,
            "private directory must belong to the current user",
        ));
    }
    if !acl.is_private_directory(user)? {
        restrict(handle, true)?;
    }
    Ok(())
}

/// Whether a directory belongs to the current user and grants access only to that user.
pub fn is_private_dir(path: &Path) -> io::Result<bool> {
    let directory = match open_directory_security(path, READ_CONTROL) {
        Ok(file) => file,
        Err(error) if super::super::files::is_link_refusal(&error) => return Ok(false),
        Err(error) => return Err(error),
    };
    if !directory.metadata()?.is_dir() {
        return Ok(false);
    }
    let acl = SecurityDescriptor::read(directory.as_raw_handle())?;
    let current_user = current_user()?;
    let user = current_user.sid();
    Ok(acl.is_owned_by(user) && acl.is_private_directory(user)?)
}

fn open_directory_security(path: &Path, access: u32) -> io::Result<File> {
    super::super::files::open_no_follow(OpenOptions::new().access_mode(access), path)
}

/// Whether an open file is a regular, single-link disk file that only the current user can
/// use: the counterparts of Unix's file type, link count and 0600 checks.
pub fn is_private_file(file: &File) -> io::Result<bool> {
    let handle = file.as_raw_handle();
    // SAFETY: an open file handle.
    if unsafe { GetFileType(handle) } != FILE_TYPE_DISK {
        return Ok(false);
    }
    let mut info = BY_HANDLE_FILE_INFORMATION::default();
    // SAFETY: an open file handle and a valid out pointer.
    if unsafe { GetFileInformationByHandle(handle, &mut info) } == 0 {
        return Err(io::Error::last_os_error());
    }
    if info.dwFileAttributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT) != 0
        || info.nNumberOfLinks != 1
    {
        return Ok(false);
    }
    owner_only_handle(handle)
}

/// Options for opening an existing private file. Use `create_private_file` to create an
/// owner-only file: `OpenOptions` cannot supply a security descriptor.
pub fn private_options() -> OpenOptions {
    OpenOptions::new()
}

/// Create a new owner-only read/write file, including in a shared directory.
pub fn create_private_file(path: &Path) -> io::Result<File> {
    let descriptor = owner_only(false)?;
    let attributes = SECURITY_ATTRIBUTES {
        nLength: mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
        lpSecurityDescriptor: descriptor.0,
        bInheritHandle: 0,
    };
    let path = wide(path)?;
    // SAFETY: the path is NUL-terminated and attributes borrow the live descriptor.
    let handle = unsafe {
        CreateFileW(
            path.as_ptr(),
            GENERIC_READ | GENERIC_WRITE,
            FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
            &attributes,
            CREATE_NEW,
            FILE_ATTRIBUTE_NORMAL,
            ptr::null_mut(),
        )
    };
    if handle == INVALID_HANDLE_VALUE {
        return Err(io::Error::last_os_error());
    }
    // SAFETY: CreateFileW returned a new, owned file handle.
    Ok(unsafe { File::from_raw_handle(handle) })
}

/// Replace an open file's DACL with a protected owner-only one.
pub fn restrict_file(file: &File) -> io::Result<()> {
    // The original handle may lack WRITE_DAC; reopening the same file object needs no path.
    // SAFETY: an open file handle; the result is checked and then owned.
    let handle = unsafe {
        ReOpenFile(
            file.as_raw_handle(),
            READ_CONTROL | WRITE_DAC,
            FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
            0,
        )
    };
    if handle == INVALID_HANDLE_VALUE {
        return Err(io::Error::last_os_error());
    }
    // SAFETY: ReOpenFile returned a new handle that nothing else owns.
    let handle = unsafe { OwnedHandle::from_raw_handle(handle) };
    restrict(handle.as_raw_handle(), false)
}

fn restrict(handle: HANDLE, directory: bool) -> io::Result<()> {
    let descriptor = owner_only(directory)?;
    let (mut present, mut defaulted) = (0, 0);
    let mut dacl: *mut ACL = ptr::null_mut();
    // SAFETY: a valid descriptor and out pointers; `dacl` points into the descriptor.
    if unsafe { GetSecurityDescriptorDacl(descriptor.0, &mut present, &mut dacl, &mut defaulted) }
        == 0
    {
        return Err(io::Error::last_os_error());
    }
    // SAFETY: an open handle with WRITE_DAC and a DACL that outlives the call.
    let error = unsafe {
        SetSecurityInfo(
            handle,
            SE_FILE_OBJECT,
            DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
            ptr::null_mut(),
            ptr::null_mut(),
            dacl,
            ptr::null(),
        )
    };
    if error != ERROR_SUCCESS {
        return Err(io::Error::from_raw_os_error(error as i32));
    }
    Ok(())
}

/// The closest Windows reading of Unix's "no group or other bits": the owner is the current
/// user or a privileged system principal; and every
/// ACE that can grant access now or on a descendant names the current user. Deny ACEs
/// grant nothing; unfamiliar ACEs fail closed, as does a NULL DACL.
fn owner_only_handle(handle: HANDLE) -> io::Result<bool> {
    protected_acl(handle)
}

struct SecurityDescriptor {
    owner: PSID,
    dacl: *mut ACL,
    descriptor: Local,
}

impl SecurityDescriptor {
    fn read(handle: HANDLE) -> io::Result<Self> {
        let mut owner: PSID = ptr::null_mut();
        let mut dacl: *mut ACL = ptr::null_mut();
        let mut descriptor = ptr::null_mut();
        // SAFETY: the open handle has READ_CONTROL; the pointers remain live through the
        // query. `owner` and `dacl` borrow the returned, owned security descriptor.
        let error = unsafe {
            GetSecurityInfo(
                handle,
                SE_FILE_OBJECT,
                OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
                &mut owner,
                ptr::null_mut(),
                &mut dacl,
                ptr::null_mut(),
                &mut descriptor,
            )
        };
        if error != ERROR_SUCCESS {
            return Err(io::Error::from_raw_os_error(error as i32));
        }
        Ok(Self {
            owner,
            dacl,
            descriptor: Local(descriptor),
        })
    }

    fn is_owned_by(&self, user: PSID) -> bool {
        // SAFETY: the SIDs borrow a live security descriptor and process token.
        unsafe { EqualSid(self.owner, user) != 0 }
    }

    fn is_private_directory(&self, user: PSID) -> io::Result<bool> {
        let (mut control, mut revision) = (0, 0);
        // SAFETY: the descriptor is live and its out parameters have the correct types.
        if unsafe { GetSecurityDescriptorControl(self.descriptor.0, &mut control, &mut revision) }
            == 0
        {
            return Err(io::Error::last_os_error());
        }
        if control & SE_DACL_PROTECTED == 0 || self.dacl.is_null() {
            return Ok(false);
        }
        // Accept the owner-only template without rewriting it. Also check the grant's
        // rights: a protected but empty DACL should not leave the owner locked out.
        if ace_count(self.dacl)? != 1 {
            return Ok(false);
        }
        let ace = access_entry(self.dacl, 0)?;
        // SAFETY: every ACE starts with this header and the descriptor is live.
        let header = unsafe { ace.cast::<ACE_HEADER>().read_unaligned() };
        if u32::from(header.AceType) != ACCESS_ALLOWED_ACE_TYPE
            || u32::from(header.AceFlags) != OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE
        {
            return Ok(false);
        }
        // SAFETY: this allow ACE has the access mask and a SID at SidStart.
        let allowed = unsafe { &*ace.cast::<ACCESS_ALLOWED_ACE>() };
        let sid = ptr::from_ref(&allowed.SidStart).cast_mut().cast();
        // SAFETY: both SIDs remain live throughout the comparison.
        Ok(allowed.Mask == FILE_ALL_ACCESS && unsafe { EqualSid(sid, user) != 0 })
    }
}

fn ace_count(dacl: *mut ACL) -> io::Result<u32> {
    let mut size = ACL_SIZE_INFORMATION::default();
    // SAFETY: a valid ACL and an output buffer of the size passed.
    if unsafe {
        GetAclInformation(
            dacl,
            (&raw mut size).cast(),
            mem::size_of::<ACL_SIZE_INFORMATION>() as u32,
            AclSizeInformation,
        )
    } == 0
    {
        return Err(io::Error::last_os_error());
    }
    Ok(size.AceCount)
}

fn access_entry(dacl: *mut ACL, index: u32) -> io::Result<*mut c_void> {
    let mut ace = ptr::null_mut();
    // SAFETY: the ACL is live and the index is below its ACE count.
    if unsafe { GetAce(dacl, index, &mut ace) } == 0 {
        return Err(io::Error::last_os_error());
    }
    Ok(ace)
}

fn protected_acl(handle: HANDLE) -> io::Result<bool> {
    let acl = SecurityDescriptor::read(handle)?;
    let user = current_user()?;
    let user = user.sid();
    if !trusted_sid(acl.owner, user) || acl.dacl.is_null() {
        return Ok(false);
    }
    for index in 0..ace_count(acl.dacl)? {
        let ace = access_entry(acl.dacl, index)?;
        // SAFETY: every ACE starts with an ACE_HEADER.
        let header = unsafe { ace.cast::<ACE_HEADER>().read_unaligned() };
        match u32::from(header.AceType) {
            ACCESS_ALLOWED_ACE_TYPE => {
                // SAFETY: this type has the access mask and a valid SID starting at SidStart.
                let allowed = unsafe { &*ace.cast::<ACCESS_ALLOWED_ACE>() };
                let sid = ptr::from_ref(&allowed.SidStart).cast_mut().cast();
                // SAFETY: both SIDs remain live throughout the comparison.
                let permitted = unsafe { EqualSid(sid, user) } != 0;
                if !permitted {
                    return Ok(false);
                }
            }
            ACCESS_DENIED_ACE_TYPE
            | ACCESS_DENIED_OBJECT_ACE_TYPE
            | ACCESS_DENIED_CALLBACK_ACE_TYPE
            | ACCESS_DENIED_CALLBACK_OBJECT_ACE_TYPE => {}
            _ => return Ok(false),
        }
    }
    Ok(true)
}

fn trusted_sid(sid: PSID, user: PSID) -> bool {
    #[repr(C)]
    struct ServiceSid {
        header: [u8; 8],
        subauthorities: [u32; 6],
    }
    // NT SERVICE\TrustedInstaller (S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464)
    // owns the system volume root on standard Windows installations.
    const TRUSTED_INSTALLER: ServiceSid = ServiceSid {
        header: [1, 6, 0, 0, 0, 0, 0, 5],
        subauthorities: [
            80, 956008885, 3418522649, 1831038044, 1853292631, 2271478464,
        ],
    };
    // SAFETY: the input SIDs come from live native queries, and the constant has the
    // Windows SID revision, authority and count followed by six aligned subauthorities.
    unsafe {
        EqualSid(sid, user) != 0
            || IsWellKnownSid(sid, WinBuiltinAdministratorsSid) != 0
            || IsWellKnownSid(sid, WinLocalSystemSid) != 0
            || EqualSid(sid, ptr::from_ref(&TRUSTED_INSTALLER).cast_mut().cast()) != 0
    }
}

/// A protected DACL with one ACE granting the current user full control. A directory's ACE
/// is inherited by the files and subdirectories created in it.
pub fn owner_only(directory: bool) -> io::Result<Local> {
    let sid = user_identity()?;
    let inheritance = if directory { "OICI" } else { "" };
    let sddl: Vec<u16> = format!("O:{sid}D:P(A;{inheritance};FA;;;{sid})")
        .encode_utf16()
        .chain([0])
        .collect();
    let mut descriptor = ptr::null_mut();
    // SAFETY: a NUL-terminated SDDL string; the descriptor is freed by `Local`.
    if unsafe {
        ConvertStringSecurityDescriptorToSecurityDescriptorW(
            sddl.as_ptr(),
            SDDL_REVISION_1,
            &mut descriptor,
            ptr::null_mut(),
        )
    } == 0
    {
        return Err(io::Error::last_os_error());
    }
    Ok(Local(descriptor))
}

/// Stable current-token SID, not an environment-provided username.
pub fn user_identity() -> io::Result<String> {
    let user = current_user()?;
    let mut text = ptr::null_mut();
    // SAFETY: a valid SID; the string is allocated by LocalAlloc and freed by `Local`.
    if unsafe { ConvertSidToStringSidW(user.sid(), &mut text) } == 0 {
        return Err(io::Error::last_os_error());
    }
    let text = Local(text.cast());
    // SAFETY: ConvertSidToStringSidW returned a NUL-terminated string.
    let sid = unsafe {
        let start = text.0.cast::<u16>();
        let length = (0..).take_while(|&index| *start.add(index) != 0).count();
        String::from_utf16_lossy(slice::from_raw_parts(start, length))
    };
    Ok(sid)
}

/// Memory from LocalAlloc, freed on drop.
pub struct Local(*mut c_void);

impl Local {
    pub fn as_ptr(&self) -> *mut c_void {
        self.0
    }
}

impl Drop for Local {
    fn drop(&mut self) {
        // SAFETY: the pointer came from LocalAlloc and is freed once.
        unsafe { LocalFree(self.0) };
    }
}

/// The current process's TOKEN_USER, in a buffer aligned for it.
struct User(Vec<u64>);

impl User {
    fn sid(&self) -> PSID {
        // SAFETY: GetTokenInformation filled the buffer with a TOKEN_USER.
        unsafe { (*self.0.as_ptr().cast::<TOKEN_USER>()).User.Sid }
    }
}

fn current_user() -> io::Result<User> {
    let mut token = ptr::null_mut();
    // SAFETY: GetCurrentProcess returns a pseudo-handle that needs no closing.
    if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) } == 0 {
        return Err(io::Error::last_os_error());
    }
    // SAFETY: OpenProcessToken returned a new handle that nothing else owns.
    let token = unsafe { OwnedHandle::from_raw_handle(token) };
    let mut length = 0;
    // SAFETY: an empty buffer only asks for the required length; this call fails by design.
    unsafe {
        GetTokenInformation(
            token.as_raw_handle(),
            TokenUser,
            ptr::null_mut(),
            0,
            &mut length,
        )
    };
    // Round the OS-reported byte count up to u64 words so TOKEN_USER/SID
    // storage remains eight-byte aligned without changing the requested byte length.
    let mut buffer = vec![0_u64; (length as usize).div_ceil(std::mem::size_of::<u64>())];
    // SAFETY: the buffer holds at least `length` bytes, aligned for TOKEN_USER and its SID.
    if unsafe {
        GetTokenInformation(
            token.as_raw_handle(),
            TokenUser,
            buffer.as_mut_ptr().cast(),
            length,
            &mut length,
        )
    } == 0
    {
        return Err(io::Error::last_os_error());
    }
    Ok(User(buffer))
}

/// A NUL-terminated UTF-16 path; an interior NUL would silently name another path.
fn wide(path: &Path) -> io::Result<Vec<u16>> {
    let mut wide: Vec<u16> = path.as_os_str().encode_wide().collect();
    if wide.contains(&0) {
        return Err(io::ErrorKind::InvalidInput.into());
    }
    wide.push(0);
    Ok(wide)
}

/// How a private directory and file are described in messages.
pub const PRIVATE_DIRECTORY: &str = "owner-only (a protected DACL granting only this user)";
pub const PRIVATE_FILE: &str = "readable by their owner only (a DACL granting only this user)";

/// NTFS persists a rename through its journal, and Windows cannot flush a directory handle
/// opened for reading, so there is nothing to sync.
pub fn sync_dir(_path: &Path) -> io::Result<()> {
    Ok(())
}

/// A file's identity on its volume: the volume serial number and the file index.
pub fn file_identity(file: &File) -> io::Result<super::FileIdentity> {
    // ReFS file IDs are 128 bits; the legacy 64-bit index can alias distinct files.
    let mut info = FILE_ID_INFO::default();
    // SAFETY: an open file handle and a correctly sized writable FILE_ID_INFO.
    if unsafe {
        GetFileInformationByHandleEx(
            file.as_raw_handle(),
            FileIdInfo,
            (&raw mut info).cast(),
            mem::size_of_val(&info) as u32,
        )
    } == 0
    {
        return Err(io::Error::last_os_error());
    }
    Ok(super::FileIdentity {
        volume: info.VolumeSerialNumber,
        index: u128::from_le_bytes(info.FileId.Identifier),
    })
}

/// Check the owner and access permissions of an already-open file or directory.
pub fn is_owner_only(file: &File) -> io::Result<bool> {
    owner_only_handle(file.as_raw_handle())
}

/// Open the scratch parent without following a final reparse point and keep it open
/// without delete sharing, so it cannot be renamed while a scratch name is in use.
pub(super) fn pin_scratch_parent(path: &Path) -> io::Result<Vec<File>> {
    let file = super::super::files::open_no_follow(
        OpenOptions::new()
            .access_mode(FILE_LIST_DIRECTORY | FILE_READ_ATTRIBUTES | READ_CONTROL)
            .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE)
            .custom_flags(FILE_FLAG_BACKUP_SEMANTICS),
        path,
    )?;
    if !file.metadata()?.is_dir() {
        return Err(io::ErrorKind::NotADirectory.into());
    }
    Ok(vec![file])
}

pub(super) fn empty_scratch(path: &Path) -> io::Result<()> {
    use std::os::windows::fs::FileTypeExt;
    retry_removal(|| {
        for child in std::fs::read_dir(path)? {
            let child = child?;
            let kind = child.file_type()?;
            if kind.is_symlink_dir() {
                std::fs::remove_dir(child.path())?;
            } else if kind.is_dir() {
                std::fs::remove_dir_all(child.path())?;
            } else {
                std::fs::remove_file(child.path())?;
            }
        }
        Ok(())
    })
}

/// Removal never traverses junctions. On Windows a process or a closing Job may
/// still own handles, so retry transient sharing failures within a fixed bound.
pub fn remove_tree(path: &Path) -> io::Result<()> {
    retry_removal(|| std::fs::remove_dir_all(path))
}

fn retry_removal(mut remove: impl FnMut() -> io::Result<()>) -> io::Result<()> {
    const RECOVERY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
    // Closing handles often clears the conflict quickly; a short sleep yields without spinning.
    const SHARING_INTERVAL: std::time::Duration = std::time::Duration::from_millis(10);
    let deadline = std::time::Instant::now() + RECOVERY_TIMEOUT;
    loop {
        match remove() {
            Err(error)
                if error.raw_os_error().is_some_and(|code| {
                    code == ERROR_ACCESS_DENIED as i32 || code == ERROR_SHARING_VIOLATION as i32
                }) && std::time::Instant::now() < deadline =>
            {
                std::thread::sleep(SHARING_INTERVAL)
            }
            result => return result,
        }
    }
}

#[cfg(test)]
mod tests;