1 use crate::os::windows::prelude::*;
2
3 use crate::ffi::OsString;
4 use crate::fmt;
5 use crate::io::{self, Error, IoSlice, IoSliceMut, SeekFrom};
6 use crate::mem;
7 use crate::os::windows::io::{AsHandle, BorrowedHandle};
8 use crate::path::{Path, PathBuf};
9 use crate::ptr;
10 use crate::slice;
11 use crate::sync::Arc;
12 use crate::sys::handle::Handle;
13 use crate::sys::time::SystemTime;
14 use crate::sys::{c, cvt};
15 use crate::sys_common::{AsInner, FromInner, IntoInner};
16
17 use super::path::maybe_verbatim;
18 use super::to_u16s;
19
20 pub struct File {
21 handle: Handle,
22 }
23
24 #[derive(Clone)]
25 pub struct FileAttr {
26 attributes: c::DWORD,
27 creation_time: c::FILETIME,
28 last_access_time: c::FILETIME,
29 last_write_time: c::FILETIME,
30 file_size: u64,
31 reparse_tag: c::DWORD,
32 volume_serial_number: Option<u32>,
33 number_of_links: Option<u32>,
34 file_index: Option<u64>,
35 }
36
37 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
38 pub struct FileType {
39 attributes: c::DWORD,
40 reparse_tag: c::DWORD,
41 }
42
43 pub struct ReadDir {
44 handle: FindNextFileHandle,
45 root: Arc<PathBuf>,
46 first: Option<c::WIN32_FIND_DATAW>,
47 }
48
49 struct FindNextFileHandle(c::HANDLE);
50
51 unsafe impl Send for FindNextFileHandle {}
52 unsafe impl Sync for FindNextFileHandle {}
53
54 pub struct DirEntry {
55 root: Arc<PathBuf>,
56 data: c::WIN32_FIND_DATAW,
57 }
58
59 #[derive(Clone, Debug)]
60 pub struct OpenOptions {
61 // generic
62 read: bool,
63 write: bool,
64 append: bool,
65 truncate: bool,
66 create: bool,
67 create_new: bool,
68 // system-specific
69 custom_flags: u32,
70 access_mode: Option<c::DWORD>,
71 attributes: c::DWORD,
72 share_mode: c::DWORD,
73 security_qos_flags: c::DWORD,
74 security_attributes: usize, // FIXME: should be a reference
75 }
76
77 #[derive(Clone, PartialEq, Eq, Debug)]
78 pub struct FilePermissions {
79 attrs: c::DWORD,
80 }
81
82 #[derive(Debug)]
83 pub struct DirBuilder;
84
85 impl fmt::Debug for ReadDir {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result86 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87 // This will only be called from std::fs::ReadDir, which will add a "ReadDir()" frame.
88 // Thus the result will be e g 'ReadDir("C:\")'
89 fmt::Debug::fmt(&*self.root, f)
90 }
91 }
92
93 impl Iterator for ReadDir {
94 type Item = io::Result<DirEntry>;
next(&mut self) -> Option<io::Result<DirEntry>>95 fn next(&mut self) -> Option<io::Result<DirEntry>> {
96 if let Some(first) = self.first.take() {
97 if let Some(e) = DirEntry::new(&self.root, &first) {
98 return Some(Ok(e));
99 }
100 }
101 unsafe {
102 let mut wfd = mem::zeroed();
103 loop {
104 if c::FindNextFileW(self.handle.0, &mut wfd) == 0 {
105 if c::GetLastError() == c::ERROR_NO_MORE_FILES {
106 return None;
107 } else {
108 return Some(Err(Error::last_os_error()));
109 }
110 }
111 if let Some(e) = DirEntry::new(&self.root, &wfd) {
112 return Some(Ok(e));
113 }
114 }
115 }
116 }
117 }
118
119 impl Drop for FindNextFileHandle {
drop(&mut self)120 fn drop(&mut self) {
121 let r = unsafe { c::FindClose(self.0) };
122 debug_assert!(r != 0);
123 }
124 }
125
126 impl DirEntry {
new(root: &Arc<PathBuf>, wfd: &c::WIN32_FIND_DATAW) -> Option<DirEntry>127 fn new(root: &Arc<PathBuf>, wfd: &c::WIN32_FIND_DATAW) -> Option<DirEntry> {
128 match &wfd.cFileName[0..3] {
129 // check for '.' and '..'
130 &[46, 0, ..] | &[46, 46, 0, ..] => return None,
131 _ => {}
132 }
133
134 Some(DirEntry { root: root.clone(), data: *wfd })
135 }
136
path(&self) -> PathBuf137 pub fn path(&self) -> PathBuf {
138 self.root.join(&self.file_name())
139 }
140
file_name(&self) -> OsString141 pub fn file_name(&self) -> OsString {
142 let filename = super::truncate_utf16_at_nul(&self.data.cFileName);
143 OsString::from_wide(filename)
144 }
145
file_type(&self) -> io::Result<FileType>146 pub fn file_type(&self) -> io::Result<FileType> {
147 Ok(FileType::new(
148 self.data.dwFileAttributes,
149 /* reparse_tag = */ self.data.dwReserved0,
150 ))
151 }
152
metadata(&self) -> io::Result<FileAttr>153 pub fn metadata(&self) -> io::Result<FileAttr> {
154 Ok(FileAttr {
155 attributes: self.data.dwFileAttributes,
156 creation_time: self.data.ftCreationTime,
157 last_access_time: self.data.ftLastAccessTime,
158 last_write_time: self.data.ftLastWriteTime,
159 file_size: ((self.data.nFileSizeHigh as u64) << 32) | (self.data.nFileSizeLow as u64),
160 reparse_tag: if self.data.dwFileAttributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
161 // reserved unless this is a reparse point
162 self.data.dwReserved0
163 } else {
164 0
165 },
166 volume_serial_number: None,
167 number_of_links: None,
168 file_index: None,
169 })
170 }
171 }
172
173 impl OpenOptions {
new() -> OpenOptions174 pub fn new() -> OpenOptions {
175 OpenOptions {
176 // generic
177 read: false,
178 write: false,
179 append: false,
180 truncate: false,
181 create: false,
182 create_new: false,
183 // system-specific
184 custom_flags: 0,
185 access_mode: None,
186 share_mode: c::FILE_SHARE_READ | c::FILE_SHARE_WRITE | c::FILE_SHARE_DELETE,
187 attributes: 0,
188 security_qos_flags: 0,
189 security_attributes: 0,
190 }
191 }
192
read(&mut self, read: bool)193 pub fn read(&mut self, read: bool) {
194 self.read = read;
195 }
write(&mut self, write: bool)196 pub fn write(&mut self, write: bool) {
197 self.write = write;
198 }
append(&mut self, append: bool)199 pub fn append(&mut self, append: bool) {
200 self.append = append;
201 }
truncate(&mut self, truncate: bool)202 pub fn truncate(&mut self, truncate: bool) {
203 self.truncate = truncate;
204 }
create(&mut self, create: bool)205 pub fn create(&mut self, create: bool) {
206 self.create = create;
207 }
create_new(&mut self, create_new: bool)208 pub fn create_new(&mut self, create_new: bool) {
209 self.create_new = create_new;
210 }
211
custom_flags(&mut self, flags: u32)212 pub fn custom_flags(&mut self, flags: u32) {
213 self.custom_flags = flags;
214 }
access_mode(&mut self, access_mode: u32)215 pub fn access_mode(&mut self, access_mode: u32) {
216 self.access_mode = Some(access_mode);
217 }
share_mode(&mut self, share_mode: u32)218 pub fn share_mode(&mut self, share_mode: u32) {
219 self.share_mode = share_mode;
220 }
attributes(&mut self, attrs: u32)221 pub fn attributes(&mut self, attrs: u32) {
222 self.attributes = attrs;
223 }
security_qos_flags(&mut self, flags: u32)224 pub fn security_qos_flags(&mut self, flags: u32) {
225 // We have to set `SECURITY_SQOS_PRESENT` here, because one of the valid flags we can
226 // receive is `SECURITY_ANONYMOUS = 0x0`, which we can't check for later on.
227 self.security_qos_flags = flags | c::SECURITY_SQOS_PRESENT;
228 }
security_attributes(&mut self, attrs: c::LPSECURITY_ATTRIBUTES)229 pub fn security_attributes(&mut self, attrs: c::LPSECURITY_ATTRIBUTES) {
230 self.security_attributes = attrs as usize;
231 }
232
get_access_mode(&self) -> io::Result<c::DWORD>233 fn get_access_mode(&self) -> io::Result<c::DWORD> {
234 const ERROR_INVALID_PARAMETER: i32 = 87;
235
236 match (self.read, self.write, self.append, self.access_mode) {
237 (.., Some(mode)) => Ok(mode),
238 (true, false, false, None) => Ok(c::GENERIC_READ),
239 (false, true, false, None) => Ok(c::GENERIC_WRITE),
240 (true, true, false, None) => Ok(c::GENERIC_READ | c::GENERIC_WRITE),
241 (false, _, true, None) => Ok(c::FILE_GENERIC_WRITE & !c::FILE_WRITE_DATA),
242 (true, _, true, None) => {
243 Ok(c::GENERIC_READ | (c::FILE_GENERIC_WRITE & !c::FILE_WRITE_DATA))
244 }
245 (false, false, false, None) => Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER)),
246 }
247 }
248
get_creation_mode(&self) -> io::Result<c::DWORD>249 fn get_creation_mode(&self) -> io::Result<c::DWORD> {
250 const ERROR_INVALID_PARAMETER: i32 = 87;
251
252 match (self.write, self.append) {
253 (true, false) => {}
254 (false, false) => {
255 if self.truncate || self.create || self.create_new {
256 return Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER));
257 }
258 }
259 (_, true) => {
260 if self.truncate && !self.create_new {
261 return Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER));
262 }
263 }
264 }
265
266 Ok(match (self.create, self.truncate, self.create_new) {
267 (false, false, false) => c::OPEN_EXISTING,
268 (true, false, false) => c::OPEN_ALWAYS,
269 (false, true, false) => c::TRUNCATE_EXISTING,
270 (true, true, false) => c::CREATE_ALWAYS,
271 (_, _, true) => c::CREATE_NEW,
272 })
273 }
274
get_flags_and_attributes(&self) -> c::DWORD275 fn get_flags_and_attributes(&self) -> c::DWORD {
276 self.custom_flags
277 | self.attributes
278 | self.security_qos_flags
279 | if self.create_new { c::FILE_FLAG_OPEN_REPARSE_POINT } else { 0 }
280 }
281 }
282
283 impl File {
open(path: &Path, opts: &OpenOptions) -> io::Result<File>284 pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
285 let path = maybe_verbatim(path)?;
286 let handle = unsafe {
287 c::CreateFileW(
288 path.as_ptr(),
289 opts.get_access_mode()?,
290 opts.share_mode,
291 opts.security_attributes as *mut _,
292 opts.get_creation_mode()?,
293 opts.get_flags_and_attributes(),
294 ptr::null_mut(),
295 )
296 };
297 if handle == c::INVALID_HANDLE_VALUE {
298 Err(Error::last_os_error())
299 } else {
300 unsafe { Ok(File { handle: Handle::from_raw_handle(handle) }) }
301 }
302 }
303
fsync(&self) -> io::Result<()>304 pub fn fsync(&self) -> io::Result<()> {
305 cvt(unsafe { c::FlushFileBuffers(self.handle.as_raw_handle()) })?;
306 Ok(())
307 }
308
datasync(&self) -> io::Result<()>309 pub fn datasync(&self) -> io::Result<()> {
310 self.fsync()
311 }
312
truncate(&self, size: u64) -> io::Result<()>313 pub fn truncate(&self, size: u64) -> io::Result<()> {
314 let mut info = c::FILE_END_OF_FILE_INFO { EndOfFile: size as c::LARGE_INTEGER };
315 let size = mem::size_of_val(&info);
316 cvt(unsafe {
317 c::SetFileInformationByHandle(
318 self.handle.as_raw_handle(),
319 c::FileEndOfFileInfo,
320 &mut info as *mut _ as *mut _,
321 size as c::DWORD,
322 )
323 })?;
324 Ok(())
325 }
326
327 #[cfg(not(target_vendor = "uwp"))]
file_attr(&self) -> io::Result<FileAttr>328 pub fn file_attr(&self) -> io::Result<FileAttr> {
329 unsafe {
330 let mut info: c::BY_HANDLE_FILE_INFORMATION = mem::zeroed();
331 cvt(c::GetFileInformationByHandle(self.handle.as_raw_handle(), &mut info))?;
332 let mut reparse_tag = 0;
333 if info.dwFileAttributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
334 let mut b = [0; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
335 if let Ok((_, buf)) = self.reparse_point(&mut b) {
336 reparse_tag = buf.ReparseTag;
337 }
338 }
339 Ok(FileAttr {
340 attributes: info.dwFileAttributes,
341 creation_time: info.ftCreationTime,
342 last_access_time: info.ftLastAccessTime,
343 last_write_time: info.ftLastWriteTime,
344 file_size: (info.nFileSizeLow as u64) | ((info.nFileSizeHigh as u64) << 32),
345 reparse_tag,
346 volume_serial_number: Some(info.dwVolumeSerialNumber),
347 number_of_links: Some(info.nNumberOfLinks),
348 file_index: Some(
349 (info.nFileIndexLow as u64) | ((info.nFileIndexHigh as u64) << 32),
350 ),
351 })
352 }
353 }
354
355 #[cfg(target_vendor = "uwp")]
file_attr(&self) -> io::Result<FileAttr>356 pub fn file_attr(&self) -> io::Result<FileAttr> {
357 unsafe {
358 let mut info: c::FILE_BASIC_INFO = mem::zeroed();
359 let size = mem::size_of_val(&info);
360 cvt(c::GetFileInformationByHandleEx(
361 self.handle.as_raw_handle(),
362 c::FileBasicInfo,
363 &mut info as *mut _ as *mut libc::c_void,
364 size as c::DWORD,
365 ))?;
366 let mut attr = FileAttr {
367 attributes: info.FileAttributes,
368 creation_time: c::FILETIME {
369 dwLowDateTime: info.CreationTime as c::DWORD,
370 dwHighDateTime: (info.CreationTime >> 32) as c::DWORD,
371 },
372 last_access_time: c::FILETIME {
373 dwLowDateTime: info.LastAccessTime as c::DWORD,
374 dwHighDateTime: (info.LastAccessTime >> 32) as c::DWORD,
375 },
376 last_write_time: c::FILETIME {
377 dwLowDateTime: info.LastWriteTime as c::DWORD,
378 dwHighDateTime: (info.LastWriteTime >> 32) as c::DWORD,
379 },
380 file_size: 0,
381 reparse_tag: 0,
382 volume_serial_number: None,
383 number_of_links: None,
384 file_index: None,
385 };
386 let mut info: c::FILE_STANDARD_INFO = mem::zeroed();
387 let size = mem::size_of_val(&info);
388 cvt(c::GetFileInformationByHandleEx(
389 self.handle.as_raw_handle(),
390 c::FileStandardInfo,
391 &mut info as *mut _ as *mut libc::c_void,
392 size as c::DWORD,
393 ))?;
394 attr.file_size = info.AllocationSize as u64;
395 attr.number_of_links = Some(info.NumberOfLinks);
396 if attr.file_type().is_reparse_point() {
397 let mut b = [0; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
398 if let Ok((_, buf)) = self.reparse_point(&mut b) {
399 attr.reparse_tag = buf.ReparseTag;
400 }
401 }
402 Ok(attr)
403 }
404 }
405
read(&self, buf: &mut [u8]) -> io::Result<usize>406 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
407 self.handle.read(buf)
408 }
409
read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize>410 pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
411 self.handle.read_vectored(bufs)
412 }
413
414 #[inline]
is_read_vectored(&self) -> bool415 pub fn is_read_vectored(&self) -> bool {
416 self.handle.is_read_vectored()
417 }
418
read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize>419 pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
420 self.handle.read_at(buf, offset)
421 }
422
write(&self, buf: &[u8]) -> io::Result<usize>423 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
424 self.handle.write(buf)
425 }
426
write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize>427 pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
428 self.handle.write_vectored(bufs)
429 }
430
431 #[inline]
is_write_vectored(&self) -> bool432 pub fn is_write_vectored(&self) -> bool {
433 self.handle.is_write_vectored()
434 }
435
write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize>436 pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
437 self.handle.write_at(buf, offset)
438 }
439
flush(&self) -> io::Result<()>440 pub fn flush(&self) -> io::Result<()> {
441 Ok(())
442 }
443
seek(&self, pos: SeekFrom) -> io::Result<u64>444 pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
445 let (whence, pos) = match pos {
446 // Casting to `i64` is fine, `SetFilePointerEx` reinterprets this
447 // integer as `u64`.
448 SeekFrom::Start(n) => (c::FILE_BEGIN, n as i64),
449 SeekFrom::End(n) => (c::FILE_END, n),
450 SeekFrom::Current(n) => (c::FILE_CURRENT, n),
451 };
452 let pos = pos as c::LARGE_INTEGER;
453 let mut newpos = 0;
454 cvt(unsafe { c::SetFilePointerEx(self.handle.as_raw_handle(), pos, &mut newpos, whence) })?;
455 Ok(newpos as u64)
456 }
457
duplicate(&self) -> io::Result<File>458 pub fn duplicate(&self) -> io::Result<File> {
459 Ok(File { handle: self.handle.duplicate(0, false, c::DUPLICATE_SAME_ACCESS)? })
460 }
461
reparse_point<'a>( &self, space: &'a mut [u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE], ) -> io::Result<(c::DWORD, &'a c::REPARSE_DATA_BUFFER)>462 fn reparse_point<'a>(
463 &self,
464 space: &'a mut [u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE],
465 ) -> io::Result<(c::DWORD, &'a c::REPARSE_DATA_BUFFER)> {
466 unsafe {
467 let mut bytes = 0;
468 cvt({
469 c::DeviceIoControl(
470 self.handle.as_raw_handle(),
471 c::FSCTL_GET_REPARSE_POINT,
472 ptr::null_mut(),
473 0,
474 space.as_mut_ptr() as *mut _,
475 space.len() as c::DWORD,
476 &mut bytes,
477 ptr::null_mut(),
478 )
479 })?;
480 Ok((bytes, &*(space.as_ptr() as *const c::REPARSE_DATA_BUFFER)))
481 }
482 }
483
readlink(&self) -> io::Result<PathBuf>484 fn readlink(&self) -> io::Result<PathBuf> {
485 let mut space = [0u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
486 let (_bytes, buf) = self.reparse_point(&mut space)?;
487 unsafe {
488 let (path_buffer, subst_off, subst_len, relative) = match buf.ReparseTag {
489 c::IO_REPARSE_TAG_SYMLINK => {
490 let info: *const c::SYMBOLIC_LINK_REPARSE_BUFFER =
491 &buf.rest as *const _ as *const _;
492 (
493 &(*info).PathBuffer as *const _ as *const u16,
494 (*info).SubstituteNameOffset / 2,
495 (*info).SubstituteNameLength / 2,
496 (*info).Flags & c::SYMLINK_FLAG_RELATIVE != 0,
497 )
498 }
499 c::IO_REPARSE_TAG_MOUNT_POINT => {
500 let info: *const c::MOUNT_POINT_REPARSE_BUFFER =
501 &buf.rest as *const _ as *const _;
502 (
503 &(*info).PathBuffer as *const _ as *const u16,
504 (*info).SubstituteNameOffset / 2,
505 (*info).SubstituteNameLength / 2,
506 false,
507 )
508 }
509 _ => {
510 return Err(io::Error::new_const(
511 io::ErrorKind::Uncategorized,
512 &"Unsupported reparse point type",
513 ));
514 }
515 };
516 let subst_ptr = path_buffer.offset(subst_off as isize);
517 let mut subst = slice::from_raw_parts(subst_ptr, subst_len as usize);
518 // Absolute paths start with an NT internal namespace prefix `\??\`
519 // We should not let it leak through.
520 if !relative && subst.starts_with(&[92u16, 63u16, 63u16, 92u16]) {
521 subst = &subst[4..];
522 }
523 Ok(PathBuf::from(OsString::from_wide(subst)))
524 }
525 }
526
set_permissions(&self, perm: FilePermissions) -> io::Result<()>527 pub fn set_permissions(&self, perm: FilePermissions) -> io::Result<()> {
528 let mut info = c::FILE_BASIC_INFO {
529 CreationTime: 0,
530 LastAccessTime: 0,
531 LastWriteTime: 0,
532 ChangeTime: 0,
533 FileAttributes: perm.attrs,
534 };
535 let size = mem::size_of_val(&info);
536 cvt(unsafe {
537 c::SetFileInformationByHandle(
538 self.handle.as_raw_handle(),
539 c::FileBasicInfo,
540 &mut info as *mut _ as *mut _,
541 size as c::DWORD,
542 )
543 })?;
544 Ok(())
545 }
546 /// Get only basic file information such as attributes and file times.
basic_info(&self) -> io::Result<c::FILE_BASIC_INFO>547 fn basic_info(&self) -> io::Result<c::FILE_BASIC_INFO> {
548 unsafe {
549 let mut info: c::FILE_BASIC_INFO = mem::zeroed();
550 let size = mem::size_of_val(&info);
551 cvt(c::GetFileInformationByHandleEx(
552 self.handle.as_raw_handle(),
553 c::FileBasicInfo,
554 &mut info as *mut _ as *mut libc::c_void,
555 size as c::DWORD,
556 ))?;
557 Ok(info)
558 }
559 }
560 /// Delete using POSIX semantics.
561 ///
562 /// Files will be deleted as soon as the handle is closed. This is supported
563 /// for Windows 10 1607 (aka RS1) and later. However some filesystem
564 /// drivers will not support it even then, e.g. FAT32.
565 ///
566 /// If the operation is not supported for this filesystem or OS version
567 /// then errors will be `ERROR_NOT_SUPPORTED` or `ERROR_INVALID_PARAMETER`.
posix_delete(&self) -> io::Result<()>568 fn posix_delete(&self) -> io::Result<()> {
569 let mut info = c::FILE_DISPOSITION_INFO_EX {
570 Flags: c::FILE_DISPOSITION_DELETE
571 | c::FILE_DISPOSITION_POSIX_SEMANTICS
572 | c::FILE_DISPOSITION_IGNORE_READONLY_ATTRIBUTE,
573 };
574 let size = mem::size_of_val(&info);
575 cvt(unsafe {
576 c::SetFileInformationByHandle(
577 self.handle.as_raw_handle(),
578 c::FileDispositionInfoEx,
579 &mut info as *mut _ as *mut _,
580 size as c::DWORD,
581 )
582 })?;
583 Ok(())
584 }
585
586 /// Delete a file using win32 semantics. The file won't actually be deleted
587 /// until all file handles are closed. However, marking a file for deletion
588 /// will prevent anyone from opening a new handle to the file.
win32_delete(&self) -> io::Result<()>589 fn win32_delete(&self) -> io::Result<()> {
590 let mut info = c::FILE_DISPOSITION_INFO { DeleteFile: c::TRUE as _ };
591 let size = mem::size_of_val(&info);
592 cvt(unsafe {
593 c::SetFileInformationByHandle(
594 self.handle.as_raw_handle(),
595 c::FileDispositionInfo,
596 &mut info as *mut _ as *mut _,
597 size as c::DWORD,
598 )
599 })?;
600 Ok(())
601 }
602
603 /// Fill the given buffer with as many directory entries as will fit.
604 /// This will remember its position and continue from the last call unless
605 /// `restart` is set to `true`.
606 ///
607 /// The returned bool indicates if there are more entries or not.
608 /// It is an error if `self` is not a directory.
609 ///
610 /// # Symlinks and other reparse points
611 ///
612 /// On Windows a file is either a directory or a non-directory.
613 /// A symlink directory is simply an empty directory with some "reparse" metadata attached.
614 /// So if you open a link (not its target) and iterate the directory,
615 /// you will always iterate an empty directory regardless of the target.
fill_dir_buff(&self, buffer: &mut DirBuff, restart: bool) -> io::Result<bool>616 fn fill_dir_buff(&self, buffer: &mut DirBuff, restart: bool) -> io::Result<bool> {
617 let class =
618 if restart { c::FileIdBothDirectoryRestartInfo } else { c::FileIdBothDirectoryInfo };
619
620 unsafe {
621 let result = cvt(c::GetFileInformationByHandleEx(
622 self.handle.as_raw_handle(),
623 class,
624 buffer.as_mut_ptr().cast(),
625 buffer.capacity() as _,
626 ));
627 match result {
628 Ok(_) => Ok(true),
629 Err(e) if e.raw_os_error() == Some(c::ERROR_NO_MORE_FILES as _) => Ok(false),
630 Err(e) => Err(e),
631 }
632 }
633 }
634 }
635
636 /// A buffer for holding directory entries.
637 struct DirBuff {
638 buffer: Vec<u8>,
639 }
640 impl DirBuff {
new() -> Self641 fn new() -> Self {
642 const BUFFER_SIZE: usize = 1024;
643 Self { buffer: vec![0_u8; BUFFER_SIZE] }
644 }
capacity(&self) -> usize645 fn capacity(&self) -> usize {
646 self.buffer.len()
647 }
as_mut_ptr(&mut self) -> *mut u8648 fn as_mut_ptr(&mut self) -> *mut u8 {
649 self.buffer.as_mut_ptr().cast()
650 }
651 /// Returns a `DirBuffIter`.
iter(&self) -> DirBuffIter<'_>652 fn iter(&self) -> DirBuffIter<'_> {
653 DirBuffIter::new(self)
654 }
655 }
656 impl AsRef<[u8]> for DirBuff {
as_ref(&self) -> &[u8]657 fn as_ref(&self) -> &[u8] {
658 &self.buffer
659 }
660 }
661
662 /// An iterator over entries stored in a `DirBuff`.
663 ///
664 /// Currently only returns file names (UTF-16 encoded).
665 struct DirBuffIter<'a> {
666 buffer: Option<&'a [u8]>,
667 cursor: usize,
668 }
669 impl<'a> DirBuffIter<'a> {
new(buffer: &'a DirBuff) -> Self670 fn new(buffer: &'a DirBuff) -> Self {
671 Self { buffer: Some(buffer.as_ref()), cursor: 0 }
672 }
673 }
674 impl<'a> Iterator for DirBuffIter<'a> {
675 type Item = &'a [u16];
next(&mut self) -> Option<Self::Item>676 fn next(&mut self) -> Option<Self::Item> {
677 use crate::mem::size_of;
678 let buffer = &self.buffer?[self.cursor..];
679
680 // Get the name and next entry from the buffer.
681 // SAFETY: The buffer contains a `FILE_ID_BOTH_DIR_INFO` struct but the
682 // last field (the file name) is unsized. So an offset has to be
683 // used to get the file name slice.
684 let (name, next_entry) = unsafe {
685 let info = buffer.as_ptr().cast::<c::FILE_ID_BOTH_DIR_INFO>();
686 let next_entry = (*info).NextEntryOffset as usize;
687 let name = crate::slice::from_raw_parts(
688 (*info).FileName.as_ptr().cast::<u16>(),
689 (*info).FileNameLength as usize / size_of::<u16>(),
690 );
691 (name, next_entry)
692 };
693
694 if next_entry == 0 {
695 self.buffer = None
696 } else {
697 self.cursor += next_entry
698 }
699
700 // Skip `.` and `..` pseudo entries.
701 const DOT: u16 = b'.' as u16;
702 match name {
703 [DOT] | [DOT, DOT] => self.next(),
704 _ => Some(name),
705 }
706 }
707 }
708
709 /// Open a link relative to the parent directory, ensure no symlinks are followed.
open_link_no_reparse(parent: &File, name: &[u16], access: u32) -> io::Result<File>710 fn open_link_no_reparse(parent: &File, name: &[u16], access: u32) -> io::Result<File> {
711 // This is implemented using the lower level `NtOpenFile` function as
712 // unfortunately opening a file relative to a parent is not supported by
713 // win32 functions. It is however a fundamental feature of the NT kernel.
714 //
715 // See https://docs.microsoft.com/en-us/windows/win32/api/winternl/nf-winternl-ntopenfile
716 unsafe {
717 let mut handle = ptr::null_mut();
718 let mut io_status = c::IO_STATUS_BLOCK::default();
719 let name_str = c::UNICODE_STRING::from_ref(name);
720 use crate::sync::atomic::{AtomicU32, Ordering};
721 // The `OBJ_DONT_REPARSE` attribute ensures that we haven't been
722 // tricked into following a symlink. However, it may not be available in
723 // earlier versions of Windows.
724 static ATTRIBUTES: AtomicU32 = AtomicU32::new(c::OBJ_DONT_REPARSE);
725 let object = c::OBJECT_ATTRIBUTES {
726 ObjectName: &name_str,
727 RootDirectory: parent.as_raw_handle(),
728 Attributes: ATTRIBUTES.load(Ordering::Relaxed),
729 ..c::OBJECT_ATTRIBUTES::default()
730 };
731 let status = c::NtOpenFile(
732 &mut handle,
733 access,
734 &object,
735 &mut io_status,
736 c::FILE_SHARE_DELETE | c::FILE_SHARE_READ | c::FILE_SHARE_WRITE,
737 // If `name` is a symlink then open the link rather than the target.
738 c::FILE_OPEN_REPARSE_POINT,
739 );
740 // Convert an NTSTATUS to the more familiar Win32 error codes (aka "DosError")
741 if c::nt_success(status) {
742 Ok(File::from_raw_handle(handle))
743 } else if status == c::STATUS_DELETE_PENDING {
744 // We make a special exception for `STATUS_DELETE_PENDING` because
745 // otherwise this will be mapped to `ERROR_ACCESS_DENIED` which is
746 // very unhelpful.
747 Err(io::Error::from_raw_os_error(c::ERROR_DELETE_PENDING as _))
748 } else if status == c::STATUS_INVALID_PARAMETER
749 && ATTRIBUTES.load(Ordering::Relaxed) == c::OBJ_DONT_REPARSE
750 {
751 // Try without `OBJ_DONT_REPARSE`. See above.
752 ATTRIBUTES.store(0, Ordering::Relaxed);
753 open_link_no_reparse(parent, name, access)
754 } else {
755 Err(io::Error::from_raw_os_error(c::RtlNtStatusToDosError(status) as _))
756 }
757 }
758 }
759
760 impl AsInner<Handle> for File {
as_inner(&self) -> &Handle761 fn as_inner(&self) -> &Handle {
762 &self.handle
763 }
764 }
765
766 impl IntoInner<Handle> for File {
into_inner(self) -> Handle767 fn into_inner(self) -> Handle {
768 self.handle
769 }
770 }
771
772 impl FromInner<Handle> for File {
from_inner(handle: Handle) -> File773 fn from_inner(handle: Handle) -> File {
774 File { handle }
775 }
776 }
777
778 impl AsHandle for File {
as_handle(&self) -> BorrowedHandle<'_>779 fn as_handle(&self) -> BorrowedHandle<'_> {
780 self.as_inner().as_handle()
781 }
782 }
783
784 impl AsRawHandle for File {
as_raw_handle(&self) -> RawHandle785 fn as_raw_handle(&self) -> RawHandle {
786 self.as_inner().as_raw_handle()
787 }
788 }
789
790 impl IntoRawHandle for File {
into_raw_handle(self) -> RawHandle791 fn into_raw_handle(self) -> RawHandle {
792 self.into_inner().into_raw_handle()
793 }
794 }
795
796 impl FromRawHandle for File {
from_raw_handle(raw_handle: RawHandle) -> Self797 unsafe fn from_raw_handle(raw_handle: RawHandle) -> Self {
798 Self { handle: FromInner::from_inner(FromRawHandle::from_raw_handle(raw_handle)) }
799 }
800 }
801
802 impl fmt::Debug for File {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result803 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
804 // FIXME(#24570): add more info here (e.g., mode)
805 let mut b = f.debug_struct("File");
806 b.field("handle", &self.handle.as_raw_handle());
807 if let Ok(path) = get_path(&self) {
808 b.field("path", &path);
809 }
810 b.finish()
811 }
812 }
813
814 impl FileAttr {
size(&self) -> u64815 pub fn size(&self) -> u64 {
816 self.file_size
817 }
818
perm(&self) -> FilePermissions819 pub fn perm(&self) -> FilePermissions {
820 FilePermissions { attrs: self.attributes }
821 }
822
attrs(&self) -> u32823 pub fn attrs(&self) -> u32 {
824 self.attributes
825 }
826
file_type(&self) -> FileType827 pub fn file_type(&self) -> FileType {
828 FileType::new(self.attributes, self.reparse_tag)
829 }
830
modified(&self) -> io::Result<SystemTime>831 pub fn modified(&self) -> io::Result<SystemTime> {
832 Ok(SystemTime::from(self.last_write_time))
833 }
834
accessed(&self) -> io::Result<SystemTime>835 pub fn accessed(&self) -> io::Result<SystemTime> {
836 Ok(SystemTime::from(self.last_access_time))
837 }
838
created(&self) -> io::Result<SystemTime>839 pub fn created(&self) -> io::Result<SystemTime> {
840 Ok(SystemTime::from(self.creation_time))
841 }
842
modified_u64(&self) -> u64843 pub fn modified_u64(&self) -> u64 {
844 to_u64(&self.last_write_time)
845 }
846
accessed_u64(&self) -> u64847 pub fn accessed_u64(&self) -> u64 {
848 to_u64(&self.last_access_time)
849 }
850
created_u64(&self) -> u64851 pub fn created_u64(&self) -> u64 {
852 to_u64(&self.creation_time)
853 }
854
volume_serial_number(&self) -> Option<u32>855 pub fn volume_serial_number(&self) -> Option<u32> {
856 self.volume_serial_number
857 }
858
number_of_links(&self) -> Option<u32>859 pub fn number_of_links(&self) -> Option<u32> {
860 self.number_of_links
861 }
862
file_index(&self) -> Option<u64>863 pub fn file_index(&self) -> Option<u64> {
864 self.file_index
865 }
866 }
867
to_u64(ft: &c::FILETIME) -> u64868 fn to_u64(ft: &c::FILETIME) -> u64 {
869 (ft.dwLowDateTime as u64) | ((ft.dwHighDateTime as u64) << 32)
870 }
871
872 impl FilePermissions {
readonly(&self) -> bool873 pub fn readonly(&self) -> bool {
874 self.attrs & c::FILE_ATTRIBUTE_READONLY != 0
875 }
876
set_readonly(&mut self, readonly: bool)877 pub fn set_readonly(&mut self, readonly: bool) {
878 if readonly {
879 self.attrs |= c::FILE_ATTRIBUTE_READONLY;
880 } else {
881 self.attrs &= !c::FILE_ATTRIBUTE_READONLY;
882 }
883 }
884 }
885
886 impl FileType {
new(attrs: c::DWORD, reparse_tag: c::DWORD) -> FileType887 fn new(attrs: c::DWORD, reparse_tag: c::DWORD) -> FileType {
888 FileType { attributes: attrs, reparse_tag }
889 }
is_dir(&self) -> bool890 pub fn is_dir(&self) -> bool {
891 !self.is_symlink() && self.is_directory()
892 }
is_file(&self) -> bool893 pub fn is_file(&self) -> bool {
894 !self.is_symlink() && !self.is_directory()
895 }
is_symlink(&self) -> bool896 pub fn is_symlink(&self) -> bool {
897 self.is_reparse_point() && self.is_reparse_tag_name_surrogate()
898 }
is_symlink_dir(&self) -> bool899 pub fn is_symlink_dir(&self) -> bool {
900 self.is_symlink() && self.is_directory()
901 }
is_symlink_file(&self) -> bool902 pub fn is_symlink_file(&self) -> bool {
903 self.is_symlink() && !self.is_directory()
904 }
is_directory(&self) -> bool905 fn is_directory(&self) -> bool {
906 self.attributes & c::FILE_ATTRIBUTE_DIRECTORY != 0
907 }
is_reparse_point(&self) -> bool908 fn is_reparse_point(&self) -> bool {
909 self.attributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0
910 }
is_reparse_tag_name_surrogate(&self) -> bool911 fn is_reparse_tag_name_surrogate(&self) -> bool {
912 self.reparse_tag & 0x20000000 != 0
913 }
914 }
915
916 impl DirBuilder {
new() -> DirBuilder917 pub fn new() -> DirBuilder {
918 DirBuilder
919 }
920
mkdir(&self, p: &Path) -> io::Result<()>921 pub fn mkdir(&self, p: &Path) -> io::Result<()> {
922 let p = maybe_verbatim(p)?;
923 cvt(unsafe { c::CreateDirectoryW(p.as_ptr(), ptr::null_mut()) })?;
924 Ok(())
925 }
926 }
927
readdir(p: &Path) -> io::Result<ReadDir>928 pub fn readdir(p: &Path) -> io::Result<ReadDir> {
929 let root = p.to_path_buf();
930 let star = p.join("*");
931 let path = maybe_verbatim(&star)?;
932
933 unsafe {
934 let mut wfd = mem::zeroed();
935 let find_handle = c::FindFirstFileW(path.as_ptr(), &mut wfd);
936 if find_handle != c::INVALID_HANDLE_VALUE {
937 Ok(ReadDir {
938 handle: FindNextFileHandle(find_handle),
939 root: Arc::new(root),
940 first: Some(wfd),
941 })
942 } else {
943 Err(Error::last_os_error())
944 }
945 }
946 }
947
unlink(p: &Path) -> io::Result<()>948 pub fn unlink(p: &Path) -> io::Result<()> {
949 let p_u16s = maybe_verbatim(p)?;
950 cvt(unsafe { c::DeleteFileW(p_u16s.as_ptr()) })?;
951 Ok(())
952 }
953
rename(old: &Path, new: &Path) -> io::Result<()>954 pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
955 let old = maybe_verbatim(old)?;
956 let new = maybe_verbatim(new)?;
957 cvt(unsafe { c::MoveFileExW(old.as_ptr(), new.as_ptr(), c::MOVEFILE_REPLACE_EXISTING) })?;
958 Ok(())
959 }
960
rmdir(p: &Path) -> io::Result<()>961 pub fn rmdir(p: &Path) -> io::Result<()> {
962 let p = maybe_verbatim(p)?;
963 cvt(unsafe { c::RemoveDirectoryW(p.as_ptr()) })?;
964 Ok(())
965 }
966
967 /// Open a file or directory without following symlinks.
open_link(path: &Path, access_mode: u32) -> io::Result<File>968 fn open_link(path: &Path, access_mode: u32) -> io::Result<File> {
969 let mut opts = OpenOptions::new();
970 opts.access_mode(access_mode);
971 // `FILE_FLAG_BACKUP_SEMANTICS` allows opening directories.
972 // `FILE_FLAG_OPEN_REPARSE_POINT` opens a link instead of its target.
973 opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS | c::FILE_FLAG_OPEN_REPARSE_POINT);
974 File::open(path, &opts)
975 }
976
remove_dir_all(path: &Path) -> io::Result<()>977 pub fn remove_dir_all(path: &Path) -> io::Result<()> {
978 let file = open_link(path, c::DELETE | c::FILE_LIST_DIRECTORY)?;
979
980 // Test if the file is not a directory or a symlink to a directory.
981 if (file.basic_info()?.FileAttributes & c::FILE_ATTRIBUTE_DIRECTORY) == 0 {
982 return Err(io::Error::from_raw_os_error(c::ERROR_DIRECTORY as _));
983 }
984 let mut delete: fn(&File) -> io::Result<()> = File::posix_delete;
985 let result = match delete(&file) {
986 Err(e) if e.kind() == io::ErrorKind::DirectoryNotEmpty => {
987 match remove_dir_all_recursive(&file, delete) {
988 // Return unexpected errors.
989 Err(e) if e.kind() != io::ErrorKind::DirectoryNotEmpty => return Err(e),
990 result => result,
991 }
992 }
993 // If POSIX delete is not supported for this filesystem then fallback to win32 delete.
994 Err(e)
995 if e.raw_os_error() == Some(c::ERROR_NOT_SUPPORTED as i32)
996 || e.raw_os_error() == Some(c::ERROR_INVALID_PARAMETER as i32) =>
997 {
998 delete = File::win32_delete;
999 Err(e)
1000 }
1001 result => result,
1002 };
1003 if result.is_ok() {
1004 Ok(())
1005 } else {
1006 // This is a fallback to make sure the directory is actually deleted.
1007 // Otherwise this function is prone to failing with `DirectoryNotEmpty`
1008 // due to possible delays between marking a file for deletion and the
1009 // file actually being deleted from the filesystem.
1010 //
1011 // So we retry a few times before giving up.
1012 for _ in 0..5 {
1013 match remove_dir_all_recursive(&file, delete) {
1014 Err(e) if e.kind() == io::ErrorKind::DirectoryNotEmpty => {}
1015 result => return result,
1016 }
1017 }
1018 // Try one last time.
1019 delete(&file)
1020 }
1021 }
1022
remove_dir_all_recursive(f: &File, delete: fn(&File) -> io::Result<()>) -> io::Result<()>1023 fn remove_dir_all_recursive(f: &File, delete: fn(&File) -> io::Result<()>) -> io::Result<()> {
1024 let mut buffer = DirBuff::new();
1025 let mut restart = true;
1026 // Fill the buffer and iterate the entries.
1027 while f.fill_dir_buff(&mut buffer, restart)? {
1028 for name in buffer.iter() {
1029 // Open the file without following symlinks and try deleting it.
1030 // We try opening will all needed permissions and if that is denied
1031 // fallback to opening without `FILE_LIST_DIRECTORY` permission.
1032 // Note `SYNCHRONIZE` permission is needed for synchronous access.
1033 let mut result =
1034 open_link_no_reparse(&f, name, c::SYNCHRONIZE | c::DELETE | c::FILE_LIST_DIRECTORY);
1035 if matches!(&result, Err(e) if e.kind() == io::ErrorKind::PermissionDenied) {
1036 result = open_link_no_reparse(&f, name, c::SYNCHRONIZE | c::DELETE);
1037 }
1038 match result {
1039 Ok(file) => match delete(&file) {
1040 Err(e) if e.kind() == io::ErrorKind::DirectoryNotEmpty => {
1041 // Iterate the directory's files.
1042 // Ignore `DirectoryNotEmpty` errors here. They will be
1043 // caught when `remove_dir_all` tries to delete the top
1044 // level directory. It can then decide if to retry or not.
1045 match remove_dir_all_recursive(&file, delete) {
1046 Err(e) if e.kind() == io::ErrorKind::DirectoryNotEmpty => {}
1047 result => result?,
1048 }
1049 }
1050 result => result?,
1051 },
1052 // Ignore error if a delete is already in progress or the file
1053 // has already been deleted. It also ignores sharing violations
1054 // (where a file is locked by another process) as these are
1055 // usually temporary.
1056 Err(e)
1057 if e.raw_os_error() == Some(c::ERROR_DELETE_PENDING as _)
1058 || e.kind() == io::ErrorKind::NotFound
1059 || e.raw_os_error() == Some(c::ERROR_SHARING_VIOLATION as _) => {}
1060 Err(e) => return Err(e),
1061 }
1062 }
1063 // Continue reading directory entries without restarting from the beginning,
1064 restart = false;
1065 }
1066 delete(&f)
1067 }
1068
readlink(path: &Path) -> io::Result<PathBuf>1069 pub fn readlink(path: &Path) -> io::Result<PathBuf> {
1070 // Open the link with no access mode, instead of generic read.
1071 // By default FILE_LIST_DIRECTORY is denied for the junction "C:\Documents and Settings", so
1072 // this is needed for a common case.
1073 let mut opts = OpenOptions::new();
1074 opts.access_mode(0);
1075 opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT | c::FILE_FLAG_BACKUP_SEMANTICS);
1076 let file = File::open(&path, &opts)?;
1077 file.readlink()
1078 }
1079
symlink(original: &Path, link: &Path) -> io::Result<()>1080 pub fn symlink(original: &Path, link: &Path) -> io::Result<()> {
1081 symlink_inner(original, link, false)
1082 }
1083
symlink_inner(original: &Path, link: &Path, dir: bool) -> io::Result<()>1084 pub fn symlink_inner(original: &Path, link: &Path, dir: bool) -> io::Result<()> {
1085 let original = to_u16s(original)?;
1086 let link = maybe_verbatim(link)?;
1087 let flags = if dir { c::SYMBOLIC_LINK_FLAG_DIRECTORY } else { 0 };
1088 // Formerly, symlink creation required the SeCreateSymbolicLink privilege. For the Windows 10
1089 // Creators Update, Microsoft loosened this to allow unprivileged symlink creation if the
1090 // computer is in Developer Mode, but SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE must be
1091 // added to dwFlags to opt into this behaviour.
1092 let result = cvt(unsafe {
1093 c::CreateSymbolicLinkW(
1094 link.as_ptr(),
1095 original.as_ptr(),
1096 flags | c::SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE,
1097 ) as c::BOOL
1098 });
1099 if let Err(err) = result {
1100 if err.raw_os_error() == Some(c::ERROR_INVALID_PARAMETER as i32) {
1101 // Older Windows objects to SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE,
1102 // so if we encounter ERROR_INVALID_PARAMETER, retry without that flag.
1103 cvt(unsafe {
1104 c::CreateSymbolicLinkW(link.as_ptr(), original.as_ptr(), flags) as c::BOOL
1105 })?;
1106 } else {
1107 return Err(err);
1108 }
1109 }
1110 Ok(())
1111 }
1112
1113 #[cfg(not(target_vendor = "uwp"))]
link(original: &Path, link: &Path) -> io::Result<()>1114 pub fn link(original: &Path, link: &Path) -> io::Result<()> {
1115 let original = maybe_verbatim(original)?;
1116 let link = maybe_verbatim(link)?;
1117 cvt(unsafe { c::CreateHardLinkW(link.as_ptr(), original.as_ptr(), ptr::null_mut()) })?;
1118 Ok(())
1119 }
1120
1121 #[cfg(target_vendor = "uwp")]
link(_original: &Path, _link: &Path) -> io::Result<()>1122 pub fn link(_original: &Path, _link: &Path) -> io::Result<()> {
1123 return Err(io::Error::new_const(
1124 io::ErrorKind::Unsupported,
1125 &"hard link are not supported on UWP",
1126 ));
1127 }
1128
stat(path: &Path) -> io::Result<FileAttr>1129 pub fn stat(path: &Path) -> io::Result<FileAttr> {
1130 let mut opts = OpenOptions::new();
1131 // No read or write permissions are necessary
1132 opts.access_mode(0);
1133 // This flag is so we can open directories too
1134 opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS);
1135 let file = File::open(path, &opts)?;
1136 file.file_attr()
1137 }
1138
lstat(path: &Path) -> io::Result<FileAttr>1139 pub fn lstat(path: &Path) -> io::Result<FileAttr> {
1140 let mut opts = OpenOptions::new();
1141 // No read or write permissions are necessary
1142 opts.access_mode(0);
1143 opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS | c::FILE_FLAG_OPEN_REPARSE_POINT);
1144 let file = File::open(path, &opts)?;
1145 file.file_attr()
1146 }
1147
set_perm(p: &Path, perm: FilePermissions) -> io::Result<()>1148 pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
1149 let p = maybe_verbatim(p)?;
1150 unsafe {
1151 cvt(c::SetFileAttributesW(p.as_ptr(), perm.attrs))?;
1152 Ok(())
1153 }
1154 }
1155
get_path(f: &File) -> io::Result<PathBuf>1156 fn get_path(f: &File) -> io::Result<PathBuf> {
1157 super::fill_utf16_buf(
1158 |buf, sz| unsafe {
1159 c::GetFinalPathNameByHandleW(f.handle.as_raw_handle(), buf, sz, c::VOLUME_NAME_DOS)
1160 },
1161 |buf| PathBuf::from(OsString::from_wide(buf)),
1162 )
1163 }
1164
canonicalize(p: &Path) -> io::Result<PathBuf>1165 pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
1166 let mut opts = OpenOptions::new();
1167 // No read or write permissions are necessary
1168 opts.access_mode(0);
1169 // This flag is so we can open directories too
1170 opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS);
1171 let f = File::open(p, &opts)?;
1172 get_path(&f)
1173 }
1174
copy(from: &Path, to: &Path) -> io::Result<u64>1175 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
1176 unsafe extern "system" fn callback(
1177 _TotalFileSize: c::LARGE_INTEGER,
1178 _TotalBytesTransferred: c::LARGE_INTEGER,
1179 _StreamSize: c::LARGE_INTEGER,
1180 StreamBytesTransferred: c::LARGE_INTEGER,
1181 dwStreamNumber: c::DWORD,
1182 _dwCallbackReason: c::DWORD,
1183 _hSourceFile: c::HANDLE,
1184 _hDestinationFile: c::HANDLE,
1185 lpData: c::LPVOID,
1186 ) -> c::DWORD {
1187 if dwStreamNumber == 1 {
1188 *(lpData as *mut i64) = StreamBytesTransferred;
1189 }
1190 c::PROGRESS_CONTINUE
1191 }
1192 let pfrom = maybe_verbatim(from)?;
1193 let pto = maybe_verbatim(to)?;
1194 let mut size = 0i64;
1195 cvt(unsafe {
1196 c::CopyFileExW(
1197 pfrom.as_ptr(),
1198 pto.as_ptr(),
1199 Some(callback),
1200 &mut size as *mut _ as *mut _,
1201 ptr::null_mut(),
1202 0,
1203 )
1204 })?;
1205 Ok(size as u64)
1206 }
1207
1208 #[allow(dead_code)]
symlink_junction<P: AsRef<Path>, Q: AsRef<Path>>( original: P, junction: Q, ) -> io::Result<()>1209 pub fn symlink_junction<P: AsRef<Path>, Q: AsRef<Path>>(
1210 original: P,
1211 junction: Q,
1212 ) -> io::Result<()> {
1213 symlink_junction_inner(original.as_ref(), junction.as_ref())
1214 }
1215
1216 // Creating a directory junction on windows involves dealing with reparse
1217 // points and the DeviceIoControl function, and this code is a skeleton of
1218 // what can be found here:
1219 //
1220 // http://www.flexhex.com/docs/articles/hard-links.phtml
1221 #[allow(dead_code)]
symlink_junction_inner(original: &Path, junction: &Path) -> io::Result<()>1222 fn symlink_junction_inner(original: &Path, junction: &Path) -> io::Result<()> {
1223 let d = DirBuilder::new();
1224 d.mkdir(&junction)?;
1225
1226 let mut opts = OpenOptions::new();
1227 opts.write(true);
1228 opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT | c::FILE_FLAG_BACKUP_SEMANTICS);
1229 let f = File::open(junction, &opts)?;
1230 let h = f.as_inner().as_raw_handle();
1231
1232 unsafe {
1233 let mut data = [0u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
1234 let db = data.as_mut_ptr() as *mut c::REPARSE_MOUNTPOINT_DATA_BUFFER;
1235 let buf = &mut (*db).ReparseTarget as *mut c::WCHAR;
1236 let mut i = 0;
1237 // FIXME: this conversion is very hacky
1238 let v = br"\??\";
1239 let v = v.iter().map(|x| *x as u16);
1240 for c in v.chain(original.as_os_str().encode_wide()) {
1241 *buf.offset(i) = c;
1242 i += 1;
1243 }
1244 *buf.offset(i) = 0;
1245 i += 1;
1246 (*db).ReparseTag = c::IO_REPARSE_TAG_MOUNT_POINT;
1247 (*db).ReparseTargetMaximumLength = (i * 2) as c::WORD;
1248 (*db).ReparseTargetLength = ((i - 1) * 2) as c::WORD;
1249 (*db).ReparseDataLength = (*db).ReparseTargetLength as c::DWORD + 12;
1250
1251 let mut ret = 0;
1252 cvt(c::DeviceIoControl(
1253 h as *mut _,
1254 c::FSCTL_SET_REPARSE_POINT,
1255 data.as_ptr() as *mut _,
1256 (*db).ReparseDataLength + 8,
1257 ptr::null_mut(),
1258 0,
1259 &mut ret,
1260 ptr::null_mut(),
1261 ))
1262 .map(drop)
1263 }
1264 }
1265
1266 // Try to see if a file exists but, unlike `exists`, report I/O errors.
1267 pub fn try_exists(path: &Path) -> io::Result<bool> {
1268 // Open the file to ensure any symlinks are followed to their target.
1269 let mut opts = OpenOptions::new();
1270 // No read, write, etc access rights are needed.
1271 opts.access_mode(0);
1272 // Backup semantics enables opening directories as well as files.
1273 opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS);
1274 match File::open(path, &opts) {
1275 Err(e) => match e.kind() {
1276 // The file definitely does not exist
1277 io::ErrorKind::NotFound => Ok(false),
1278
1279 // `ERROR_SHARING_VIOLATION` means that the file has been locked by
1280 // another process. This is often temporary so we simply report it
1281 // as the file existing.
1282 _ if e.raw_os_error() == Some(c::ERROR_SHARING_VIOLATION as i32) => Ok(true),
1283
1284 // Other errors such as `ERROR_ACCESS_DENIED` may indicate that the
1285 // file exists. However, these types of errors are usually more
1286 // permanent so we report them here.
1287 _ => Err(e),
1288 },
1289 // The file was opened successfully therefore it must exist,
1290 Ok(_) => Ok(true),
1291 }
1292 }
1293