]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys/windows/fs.rs
Rename ErrorKind::Unknown to Uncategorized.
[rust.git] / library / std / src / sys / windows / fs.rs
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::path::{Path, PathBuf};
8 use crate::ptr;
9 use crate::slice;
10 use crate::sync::Arc;
11 use crate::sys::handle::Handle;
12 use crate::sys::time::SystemTime;
13 use crate::sys::{c, cvt};
14 use crate::sys_common::FromInner;
15
16 use super::to_u16s;
17
18 pub struct File {
19     handle: Handle,
20 }
21
22 #[derive(Clone)]
23 pub struct FileAttr {
24     attributes: c::DWORD,
25     creation_time: c::FILETIME,
26     last_access_time: c::FILETIME,
27     last_write_time: c::FILETIME,
28     file_size: u64,
29     reparse_tag: c::DWORD,
30     volume_serial_number: Option<u32>,
31     number_of_links: Option<u32>,
32     file_index: Option<u64>,
33 }
34
35 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
36 pub struct FileType {
37     attributes: c::DWORD,
38     reparse_tag: c::DWORD,
39 }
40
41 pub struct ReadDir {
42     handle: FindNextFileHandle,
43     root: Arc<PathBuf>,
44     first: Option<c::WIN32_FIND_DATAW>,
45 }
46
47 struct FindNextFileHandle(c::HANDLE);
48
49 unsafe impl Send for FindNextFileHandle {}
50 unsafe impl Sync for FindNextFileHandle {}
51
52 pub struct DirEntry {
53     root: Arc<PathBuf>,
54     data: c::WIN32_FIND_DATAW,
55 }
56
57 #[derive(Clone, Debug)]
58 pub struct OpenOptions {
59     // generic
60     read: bool,
61     write: bool,
62     append: bool,
63     truncate: bool,
64     create: bool,
65     create_new: bool,
66     // system-specific
67     custom_flags: u32,
68     access_mode: Option<c::DWORD>,
69     attributes: c::DWORD,
70     share_mode: c::DWORD,
71     security_qos_flags: c::DWORD,
72     security_attributes: usize, // FIXME: should be a reference
73 }
74
75 #[derive(Clone, PartialEq, Eq, Debug)]
76 pub struct FilePermissions {
77     attrs: c::DWORD,
78 }
79
80 #[derive(Debug)]
81 pub struct DirBuilder;
82
83 impl fmt::Debug for ReadDir {
84     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85         // This will only be called from std::fs::ReadDir, which will add a "ReadDir()" frame.
86         // Thus the result will be e g 'ReadDir("C:\")'
87         fmt::Debug::fmt(&*self.root, f)
88     }
89 }
90
91 impl Iterator for ReadDir {
92     type Item = io::Result<DirEntry>;
93     fn next(&mut self) -> Option<io::Result<DirEntry>> {
94         if let Some(first) = self.first.take() {
95             if let Some(e) = DirEntry::new(&self.root, &first) {
96                 return Some(Ok(e));
97             }
98         }
99         unsafe {
100             let mut wfd = mem::zeroed();
101             loop {
102                 if c::FindNextFileW(self.handle.0, &mut wfd) == 0 {
103                     if c::GetLastError() == c::ERROR_NO_MORE_FILES {
104                         return None;
105                     } else {
106                         return Some(Err(Error::last_os_error()));
107                     }
108                 }
109                 if let Some(e) = DirEntry::new(&self.root, &wfd) {
110                     return Some(Ok(e));
111                 }
112             }
113         }
114     }
115 }
116
117 impl Drop for FindNextFileHandle {
118     fn drop(&mut self) {
119         let r = unsafe { c::FindClose(self.0) };
120         debug_assert!(r != 0);
121     }
122 }
123
124 impl DirEntry {
125     fn new(root: &Arc<PathBuf>, wfd: &c::WIN32_FIND_DATAW) -> Option<DirEntry> {
126         match &wfd.cFileName[0..3] {
127             // check for '.' and '..'
128             &[46, 0, ..] | &[46, 46, 0, ..] => return None,
129             _ => {}
130         }
131
132         Some(DirEntry { root: root.clone(), data: *wfd })
133     }
134
135     pub fn path(&self) -> PathBuf {
136         self.root.join(&self.file_name())
137     }
138
139     pub fn file_name(&self) -> OsString {
140         let filename = super::truncate_utf16_at_nul(&self.data.cFileName);
141         OsString::from_wide(filename)
142     }
143
144     pub fn file_type(&self) -> io::Result<FileType> {
145         Ok(FileType::new(
146             self.data.dwFileAttributes,
147             /* reparse_tag = */ self.data.dwReserved0,
148         ))
149     }
150
151     pub fn metadata(&self) -> io::Result<FileAttr> {
152         Ok(FileAttr {
153             attributes: self.data.dwFileAttributes,
154             creation_time: self.data.ftCreationTime,
155             last_access_time: self.data.ftLastAccessTime,
156             last_write_time: self.data.ftLastWriteTime,
157             file_size: ((self.data.nFileSizeHigh as u64) << 32) | (self.data.nFileSizeLow as u64),
158             reparse_tag: if self.data.dwFileAttributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
159                 // reserved unless this is a reparse point
160                 self.data.dwReserved0
161             } else {
162                 0
163             },
164             volume_serial_number: None,
165             number_of_links: None,
166             file_index: None,
167         })
168     }
169 }
170
171 impl OpenOptions {
172     pub fn new() -> OpenOptions {
173         OpenOptions {
174             // generic
175             read: false,
176             write: false,
177             append: false,
178             truncate: false,
179             create: false,
180             create_new: false,
181             // system-specific
182             custom_flags: 0,
183             access_mode: None,
184             share_mode: c::FILE_SHARE_READ | c::FILE_SHARE_WRITE | c::FILE_SHARE_DELETE,
185             attributes: 0,
186             security_qos_flags: 0,
187             security_attributes: 0,
188         }
189     }
190
191     pub fn read(&mut self, read: bool) {
192         self.read = read;
193     }
194     pub fn write(&mut self, write: bool) {
195         self.write = write;
196     }
197     pub fn append(&mut self, append: bool) {
198         self.append = append;
199     }
200     pub fn truncate(&mut self, truncate: bool) {
201         self.truncate = truncate;
202     }
203     pub fn create(&mut self, create: bool) {
204         self.create = create;
205     }
206     pub fn create_new(&mut self, create_new: bool) {
207         self.create_new = create_new;
208     }
209
210     pub fn custom_flags(&mut self, flags: u32) {
211         self.custom_flags = flags;
212     }
213     pub fn access_mode(&mut self, access_mode: u32) {
214         self.access_mode = Some(access_mode);
215     }
216     pub fn share_mode(&mut self, share_mode: u32) {
217         self.share_mode = share_mode;
218     }
219     pub fn attributes(&mut self, attrs: u32) {
220         self.attributes = attrs;
221     }
222     pub fn security_qos_flags(&mut self, flags: u32) {
223         // We have to set `SECURITY_SQOS_PRESENT` here, because one of the valid flags we can
224         // receive is `SECURITY_ANONYMOUS = 0x0`, which we can't check for later on.
225         self.security_qos_flags = flags | c::SECURITY_SQOS_PRESENT;
226     }
227     pub fn security_attributes(&mut self, attrs: c::LPSECURITY_ATTRIBUTES) {
228         self.security_attributes = attrs as usize;
229     }
230
231     fn get_access_mode(&self) -> io::Result<c::DWORD> {
232         const ERROR_INVALID_PARAMETER: i32 = 87;
233
234         match (self.read, self.write, self.append, self.access_mode) {
235             (.., Some(mode)) => Ok(mode),
236             (true, false, false, None) => Ok(c::GENERIC_READ),
237             (false, true, false, None) => Ok(c::GENERIC_WRITE),
238             (true, true, false, None) => Ok(c::GENERIC_READ | c::GENERIC_WRITE),
239             (false, _, true, None) => Ok(c::FILE_GENERIC_WRITE & !c::FILE_WRITE_DATA),
240             (true, _, true, None) => {
241                 Ok(c::GENERIC_READ | (c::FILE_GENERIC_WRITE & !c::FILE_WRITE_DATA))
242             }
243             (false, false, false, None) => Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER)),
244         }
245     }
246
247     fn get_creation_mode(&self) -> io::Result<c::DWORD> {
248         const ERROR_INVALID_PARAMETER: i32 = 87;
249
250         match (self.write, self.append) {
251             (true, false) => {}
252             (false, false) => {
253                 if self.truncate || self.create || self.create_new {
254                     return Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER));
255                 }
256             }
257             (_, true) => {
258                 if self.truncate && !self.create_new {
259                     return Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER));
260                 }
261             }
262         }
263
264         Ok(match (self.create, self.truncate, self.create_new) {
265             (false, false, false) => c::OPEN_EXISTING,
266             (true, false, false) => c::OPEN_ALWAYS,
267             (false, true, false) => c::TRUNCATE_EXISTING,
268             (true, true, false) => c::CREATE_ALWAYS,
269             (_, _, true) => c::CREATE_NEW,
270         })
271     }
272
273     fn get_flags_and_attributes(&self) -> c::DWORD {
274         self.custom_flags
275             | self.attributes
276             | self.security_qos_flags
277             | if self.create_new { c::FILE_FLAG_OPEN_REPARSE_POINT } else { 0 }
278     }
279 }
280
281 impl File {
282     pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
283         let path = to_u16s(path)?;
284         let handle = unsafe {
285             c::CreateFileW(
286                 path.as_ptr(),
287                 opts.get_access_mode()?,
288                 opts.share_mode,
289                 opts.security_attributes as *mut _,
290                 opts.get_creation_mode()?,
291                 opts.get_flags_and_attributes(),
292                 ptr::null_mut(),
293             )
294         };
295         if handle == c::INVALID_HANDLE_VALUE {
296             Err(Error::last_os_error())
297         } else {
298             Ok(File { handle: Handle::new(handle) })
299         }
300     }
301
302     pub fn fsync(&self) -> io::Result<()> {
303         cvt(unsafe { c::FlushFileBuffers(self.handle.raw()) })?;
304         Ok(())
305     }
306
307     pub fn datasync(&self) -> io::Result<()> {
308         self.fsync()
309     }
310
311     pub fn truncate(&self, size: u64) -> io::Result<()> {
312         let mut info = c::FILE_END_OF_FILE_INFO { EndOfFile: size as c::LARGE_INTEGER };
313         let size = mem::size_of_val(&info);
314         cvt(unsafe {
315             c::SetFileInformationByHandle(
316                 self.handle.raw(),
317                 c::FileEndOfFileInfo,
318                 &mut info as *mut _ as *mut _,
319                 size as c::DWORD,
320             )
321         })?;
322         Ok(())
323     }
324
325     #[cfg(not(target_vendor = "uwp"))]
326     pub fn file_attr(&self) -> io::Result<FileAttr> {
327         unsafe {
328             let mut info: c::BY_HANDLE_FILE_INFORMATION = mem::zeroed();
329             cvt(c::GetFileInformationByHandle(self.handle.raw(), &mut info))?;
330             let mut reparse_tag = 0;
331             if info.dwFileAttributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
332                 let mut b = [0; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
333                 if let Ok((_, buf)) = self.reparse_point(&mut b) {
334                     reparse_tag = buf.ReparseTag;
335                 }
336             }
337             Ok(FileAttr {
338                 attributes: info.dwFileAttributes,
339                 creation_time: info.ftCreationTime,
340                 last_access_time: info.ftLastAccessTime,
341                 last_write_time: info.ftLastWriteTime,
342                 file_size: (info.nFileSizeLow as u64) | ((info.nFileSizeHigh as u64) << 32),
343                 reparse_tag,
344                 volume_serial_number: Some(info.dwVolumeSerialNumber),
345                 number_of_links: Some(info.nNumberOfLinks),
346                 file_index: Some(
347                     (info.nFileIndexLow as u64) | ((info.nFileIndexHigh as u64) << 32),
348                 ),
349             })
350         }
351     }
352
353     #[cfg(target_vendor = "uwp")]
354     pub fn file_attr(&self) -> io::Result<FileAttr> {
355         unsafe {
356             let mut info: c::FILE_BASIC_INFO = mem::zeroed();
357             let size = mem::size_of_val(&info);
358             cvt(c::GetFileInformationByHandleEx(
359                 self.handle.raw(),
360                 c::FileBasicInfo,
361                 &mut info as *mut _ as *mut libc::c_void,
362                 size as c::DWORD,
363             ))?;
364             let mut attr = FileAttr {
365                 attributes: info.FileAttributes,
366                 creation_time: c::FILETIME {
367                     dwLowDateTime: info.CreationTime as c::DWORD,
368                     dwHighDateTime: (info.CreationTime >> 32) as c::DWORD,
369                 },
370                 last_access_time: c::FILETIME {
371                     dwLowDateTime: info.LastAccessTime as c::DWORD,
372                     dwHighDateTime: (info.LastAccessTime >> 32) as c::DWORD,
373                 },
374                 last_write_time: c::FILETIME {
375                     dwLowDateTime: info.LastWriteTime as c::DWORD,
376                     dwHighDateTime: (info.LastWriteTime >> 32) as c::DWORD,
377                 },
378                 file_size: 0,
379                 reparse_tag: 0,
380                 volume_serial_number: None,
381                 number_of_links: None,
382                 file_index: None,
383             };
384             let mut info: c::FILE_STANDARD_INFO = mem::zeroed();
385             let size = mem::size_of_val(&info);
386             cvt(c::GetFileInformationByHandleEx(
387                 self.handle.raw(),
388                 c::FileStandardInfo,
389                 &mut info as *mut _ as *mut libc::c_void,
390                 size as c::DWORD,
391             ))?;
392             attr.file_size = info.AllocationSize as u64;
393             attr.number_of_links = Some(info.NumberOfLinks);
394             if attr.file_type().is_reparse_point() {
395                 let mut b = [0; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
396                 if let Ok((_, buf)) = self.reparse_point(&mut b) {
397                     attr.reparse_tag = buf.ReparseTag;
398                 }
399             }
400             Ok(attr)
401         }
402     }
403
404     pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
405         self.handle.read(buf)
406     }
407
408     pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
409         self.handle.read_vectored(bufs)
410     }
411
412     #[inline]
413     pub fn is_read_vectored(&self) -> bool {
414         self.handle.is_read_vectored()
415     }
416
417     pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
418         self.handle.read_at(buf, offset)
419     }
420
421     pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
422         self.handle.write(buf)
423     }
424
425     pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
426         self.handle.write_vectored(bufs)
427     }
428
429     #[inline]
430     pub fn is_write_vectored(&self) -> bool {
431         self.handle.is_write_vectored()
432     }
433
434     pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
435         self.handle.write_at(buf, offset)
436     }
437
438     pub fn flush(&self) -> io::Result<()> {
439         Ok(())
440     }
441
442     pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
443         let (whence, pos) = match pos {
444             // Casting to `i64` is fine, `SetFilePointerEx` reinterprets this
445             // integer as `u64`.
446             SeekFrom::Start(n) => (c::FILE_BEGIN, n as i64),
447             SeekFrom::End(n) => (c::FILE_END, n),
448             SeekFrom::Current(n) => (c::FILE_CURRENT, n),
449         };
450         let pos = pos as c::LARGE_INTEGER;
451         let mut newpos = 0;
452         cvt(unsafe { c::SetFilePointerEx(self.handle.raw(), pos, &mut newpos, whence) })?;
453         Ok(newpos as u64)
454     }
455
456     pub fn duplicate(&self) -> io::Result<File> {
457         Ok(File { handle: self.handle.duplicate(0, false, c::DUPLICATE_SAME_ACCESS)? })
458     }
459
460     pub fn handle(&self) -> &Handle {
461         &self.handle
462     }
463
464     pub fn into_handle(self) -> Handle {
465         self.handle
466     }
467
468     fn reparse_point<'a>(
469         &self,
470         space: &'a mut [u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE],
471     ) -> io::Result<(c::DWORD, &'a c::REPARSE_DATA_BUFFER)> {
472         unsafe {
473             let mut bytes = 0;
474             cvt({
475                 c::DeviceIoControl(
476                     self.handle.raw(),
477                     c::FSCTL_GET_REPARSE_POINT,
478                     ptr::null_mut(),
479                     0,
480                     space.as_mut_ptr() as *mut _,
481                     space.len() as c::DWORD,
482                     &mut bytes,
483                     ptr::null_mut(),
484                 )
485             })?;
486             Ok((bytes, &*(space.as_ptr() as *const c::REPARSE_DATA_BUFFER)))
487         }
488     }
489
490     fn readlink(&self) -> io::Result<PathBuf> {
491         let mut space = [0u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
492         let (_bytes, buf) = self.reparse_point(&mut space)?;
493         unsafe {
494             let (path_buffer, subst_off, subst_len, relative) = match buf.ReparseTag {
495                 c::IO_REPARSE_TAG_SYMLINK => {
496                     let info: *const c::SYMBOLIC_LINK_REPARSE_BUFFER =
497                         &buf.rest as *const _ as *const _;
498                     (
499                         &(*info).PathBuffer as *const _ as *const u16,
500                         (*info).SubstituteNameOffset / 2,
501                         (*info).SubstituteNameLength / 2,
502                         (*info).Flags & c::SYMLINK_FLAG_RELATIVE != 0,
503                     )
504                 }
505                 c::IO_REPARSE_TAG_MOUNT_POINT => {
506                     let info: *const c::MOUNT_POINT_REPARSE_BUFFER =
507                         &buf.rest as *const _ as *const _;
508                     (
509                         &(*info).PathBuffer as *const _ as *const u16,
510                         (*info).SubstituteNameOffset / 2,
511                         (*info).SubstituteNameLength / 2,
512                         false,
513                     )
514                 }
515                 _ => {
516                     return Err(io::Error::new_const(
517                         io::ErrorKind::Uncategorized,
518                         &"Unsupported reparse point type",
519                     ));
520                 }
521             };
522             let subst_ptr = path_buffer.offset(subst_off as isize);
523             let mut subst = slice::from_raw_parts(subst_ptr, subst_len as usize);
524             // Absolute paths start with an NT internal namespace prefix `\??\`
525             // We should not let it leak through.
526             if !relative && subst.starts_with(&[92u16, 63u16, 63u16, 92u16]) {
527                 subst = &subst[4..];
528             }
529             Ok(PathBuf::from(OsString::from_wide(subst)))
530         }
531     }
532
533     pub fn set_permissions(&self, perm: FilePermissions) -> io::Result<()> {
534         let mut info = c::FILE_BASIC_INFO {
535             CreationTime: 0,
536             LastAccessTime: 0,
537             LastWriteTime: 0,
538             ChangeTime: 0,
539             FileAttributes: perm.attrs,
540         };
541         let size = mem::size_of_val(&info);
542         cvt(unsafe {
543             c::SetFileInformationByHandle(
544                 self.handle.raw(),
545                 c::FileBasicInfo,
546                 &mut info as *mut _ as *mut _,
547                 size as c::DWORD,
548             )
549         })?;
550         Ok(())
551     }
552 }
553
554 impl FromInner<c::HANDLE> for File {
555     fn from_inner(handle: c::HANDLE) -> File {
556         File { handle: Handle::new(handle) }
557     }
558 }
559
560 impl fmt::Debug for File {
561     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
562         // FIXME(#24570): add more info here (e.g., mode)
563         let mut b = f.debug_struct("File");
564         b.field("handle", &self.handle.raw());
565         if let Ok(path) = get_path(&self) {
566             b.field("path", &path);
567         }
568         b.finish()
569     }
570 }
571
572 impl FileAttr {
573     pub fn size(&self) -> u64 {
574         self.file_size
575     }
576
577     pub fn perm(&self) -> FilePermissions {
578         FilePermissions { attrs: self.attributes }
579     }
580
581     pub fn attrs(&self) -> u32 {
582         self.attributes
583     }
584
585     pub fn file_type(&self) -> FileType {
586         FileType::new(self.attributes, self.reparse_tag)
587     }
588
589     pub fn modified(&self) -> io::Result<SystemTime> {
590         Ok(SystemTime::from(self.last_write_time))
591     }
592
593     pub fn accessed(&self) -> io::Result<SystemTime> {
594         Ok(SystemTime::from(self.last_access_time))
595     }
596
597     pub fn created(&self) -> io::Result<SystemTime> {
598         Ok(SystemTime::from(self.creation_time))
599     }
600
601     pub fn modified_u64(&self) -> u64 {
602         to_u64(&self.last_write_time)
603     }
604
605     pub fn accessed_u64(&self) -> u64 {
606         to_u64(&self.last_access_time)
607     }
608
609     pub fn created_u64(&self) -> u64 {
610         to_u64(&self.creation_time)
611     }
612
613     pub fn volume_serial_number(&self) -> Option<u32> {
614         self.volume_serial_number
615     }
616
617     pub fn number_of_links(&self) -> Option<u32> {
618         self.number_of_links
619     }
620
621     pub fn file_index(&self) -> Option<u64> {
622         self.file_index
623     }
624 }
625
626 fn to_u64(ft: &c::FILETIME) -> u64 {
627     (ft.dwLowDateTime as u64) | ((ft.dwHighDateTime as u64) << 32)
628 }
629
630 impl FilePermissions {
631     pub fn readonly(&self) -> bool {
632         self.attrs & c::FILE_ATTRIBUTE_READONLY != 0
633     }
634
635     pub fn set_readonly(&mut self, readonly: bool) {
636         if readonly {
637             self.attrs |= c::FILE_ATTRIBUTE_READONLY;
638         } else {
639             self.attrs &= !c::FILE_ATTRIBUTE_READONLY;
640         }
641     }
642 }
643
644 impl FileType {
645     fn new(attrs: c::DWORD, reparse_tag: c::DWORD) -> FileType {
646         FileType { attributes: attrs, reparse_tag: reparse_tag }
647     }
648     pub fn is_dir(&self) -> bool {
649         !self.is_symlink() && self.is_directory()
650     }
651     pub fn is_file(&self) -> bool {
652         !self.is_symlink() && !self.is_directory()
653     }
654     pub fn is_symlink(&self) -> bool {
655         self.is_reparse_point() && self.is_reparse_tag_name_surrogate()
656     }
657     pub fn is_symlink_dir(&self) -> bool {
658         self.is_symlink() && self.is_directory()
659     }
660     pub fn is_symlink_file(&self) -> bool {
661         self.is_symlink() && !self.is_directory()
662     }
663     fn is_directory(&self) -> bool {
664         self.attributes & c::FILE_ATTRIBUTE_DIRECTORY != 0
665     }
666     fn is_reparse_point(&self) -> bool {
667         self.attributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0
668     }
669     fn is_reparse_tag_name_surrogate(&self) -> bool {
670         self.reparse_tag & 0x20000000 != 0
671     }
672 }
673
674 impl DirBuilder {
675     pub fn new() -> DirBuilder {
676         DirBuilder
677     }
678
679     pub fn mkdir(&self, p: &Path) -> io::Result<()> {
680         let p = to_u16s(p)?;
681         cvt(unsafe { c::CreateDirectoryW(p.as_ptr(), ptr::null_mut()) })?;
682         Ok(())
683     }
684 }
685
686 pub fn readdir(p: &Path) -> io::Result<ReadDir> {
687     let root = p.to_path_buf();
688     let star = p.join("*");
689     let path = to_u16s(&star)?;
690
691     unsafe {
692         let mut wfd = mem::zeroed();
693         let find_handle = c::FindFirstFileW(path.as_ptr(), &mut wfd);
694         if find_handle != c::INVALID_HANDLE_VALUE {
695             Ok(ReadDir {
696                 handle: FindNextFileHandle(find_handle),
697                 root: Arc::new(root),
698                 first: Some(wfd),
699             })
700         } else {
701             Err(Error::last_os_error())
702         }
703     }
704 }
705
706 pub fn unlink(p: &Path) -> io::Result<()> {
707     let p_u16s = to_u16s(p)?;
708     cvt(unsafe { c::DeleteFileW(p_u16s.as_ptr()) })?;
709     Ok(())
710 }
711
712 pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
713     let old = to_u16s(old)?;
714     let new = to_u16s(new)?;
715     cvt(unsafe { c::MoveFileExW(old.as_ptr(), new.as_ptr(), c::MOVEFILE_REPLACE_EXISTING) })?;
716     Ok(())
717 }
718
719 pub fn rmdir(p: &Path) -> io::Result<()> {
720     let p = to_u16s(p)?;
721     cvt(unsafe { c::RemoveDirectoryW(p.as_ptr()) })?;
722     Ok(())
723 }
724
725 pub fn remove_dir_all(path: &Path) -> io::Result<()> {
726     let filetype = lstat(path)?.file_type();
727     if filetype.is_symlink() {
728         // On Windows symlinks to files and directories are removed differently.
729         // rmdir only deletes dir symlinks and junctions, not file symlinks.
730         rmdir(path)
731     } else {
732         remove_dir_all_recursive(path)
733     }
734 }
735
736 fn remove_dir_all_recursive(path: &Path) -> io::Result<()> {
737     for child in readdir(path)? {
738         let child = child?;
739         let child_type = child.file_type()?;
740         if child_type.is_dir() {
741             remove_dir_all_recursive(&child.path())?;
742         } else if child_type.is_symlink_dir() {
743             rmdir(&child.path())?;
744         } else {
745             unlink(&child.path())?;
746         }
747     }
748     rmdir(path)
749 }
750
751 pub fn readlink(path: &Path) -> io::Result<PathBuf> {
752     // Open the link with no access mode, instead of generic read.
753     // By default FILE_LIST_DIRECTORY is denied for the junction "C:\Documents and Settings", so
754     // this is needed for a common case.
755     let mut opts = OpenOptions::new();
756     opts.access_mode(0);
757     opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT | c::FILE_FLAG_BACKUP_SEMANTICS);
758     let file = File::open(&path, &opts)?;
759     file.readlink()
760 }
761
762 pub fn symlink(original: &Path, link: &Path) -> io::Result<()> {
763     symlink_inner(original, link, false)
764 }
765
766 pub fn symlink_inner(original: &Path, link: &Path, dir: bool) -> io::Result<()> {
767     let original = to_u16s(original)?;
768     let link = to_u16s(link)?;
769     let flags = if dir { c::SYMBOLIC_LINK_FLAG_DIRECTORY } else { 0 };
770     // Formerly, symlink creation required the SeCreateSymbolicLink privilege. For the Windows 10
771     // Creators Update, Microsoft loosened this to allow unprivileged symlink creation if the
772     // computer is in Developer Mode, but SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE must be
773     // added to dwFlags to opt into this behaviour.
774     let result = cvt(unsafe {
775         c::CreateSymbolicLinkW(
776             link.as_ptr(),
777             original.as_ptr(),
778             flags | c::SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE,
779         ) as c::BOOL
780     });
781     if let Err(err) = result {
782         if err.raw_os_error() == Some(c::ERROR_INVALID_PARAMETER as i32) {
783             // Older Windows objects to SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE,
784             // so if we encounter ERROR_INVALID_PARAMETER, retry without that flag.
785             cvt(unsafe {
786                 c::CreateSymbolicLinkW(link.as_ptr(), original.as_ptr(), flags) as c::BOOL
787             })?;
788         } else {
789             return Err(err);
790         }
791     }
792     Ok(())
793 }
794
795 #[cfg(not(target_vendor = "uwp"))]
796 pub fn link(original: &Path, link: &Path) -> io::Result<()> {
797     let original = to_u16s(original)?;
798     let link = to_u16s(link)?;
799     cvt(unsafe { c::CreateHardLinkW(link.as_ptr(), original.as_ptr(), ptr::null_mut()) })?;
800     Ok(())
801 }
802
803 #[cfg(target_vendor = "uwp")]
804 pub fn link(_original: &Path, _link: &Path) -> io::Result<()> {
805     return Err(io::Error::new_const(
806         io::ErrorKind::Unsupported,
807         &"hard link are not supported on UWP",
808     ));
809 }
810
811 pub fn stat(path: &Path) -> io::Result<FileAttr> {
812     let mut opts = OpenOptions::new();
813     // No read or write permissions are necessary
814     opts.access_mode(0);
815     // This flag is so we can open directories too
816     opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS);
817     let file = File::open(path, &opts)?;
818     file.file_attr()
819 }
820
821 pub fn lstat(path: &Path) -> io::Result<FileAttr> {
822     let mut opts = OpenOptions::new();
823     // No read or write permissions are necessary
824     opts.access_mode(0);
825     opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS | c::FILE_FLAG_OPEN_REPARSE_POINT);
826     let file = File::open(path, &opts)?;
827     file.file_attr()
828 }
829
830 pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
831     let p = to_u16s(p)?;
832     unsafe {
833         cvt(c::SetFileAttributesW(p.as_ptr(), perm.attrs))?;
834         Ok(())
835     }
836 }
837
838 fn get_path(f: &File) -> io::Result<PathBuf> {
839     super::fill_utf16_buf(
840         |buf, sz| unsafe {
841             c::GetFinalPathNameByHandleW(f.handle.raw(), buf, sz, c::VOLUME_NAME_DOS)
842         },
843         |buf| PathBuf::from(OsString::from_wide(buf)),
844     )
845 }
846
847 pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
848     let mut opts = OpenOptions::new();
849     // No read or write permissions are necessary
850     opts.access_mode(0);
851     // This flag is so we can open directories too
852     opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS);
853     let f = File::open(p, &opts)?;
854     get_path(&f)
855 }
856
857 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
858     unsafe extern "system" fn callback(
859         _TotalFileSize: c::LARGE_INTEGER,
860         _TotalBytesTransferred: c::LARGE_INTEGER,
861         _StreamSize: c::LARGE_INTEGER,
862         StreamBytesTransferred: c::LARGE_INTEGER,
863         dwStreamNumber: c::DWORD,
864         _dwCallbackReason: c::DWORD,
865         _hSourceFile: c::HANDLE,
866         _hDestinationFile: c::HANDLE,
867         lpData: c::LPVOID,
868     ) -> c::DWORD {
869         if dwStreamNumber == 1 {
870             *(lpData as *mut i64) = StreamBytesTransferred;
871         }
872         c::PROGRESS_CONTINUE
873     }
874     let pfrom = to_u16s(from)?;
875     let pto = to_u16s(to)?;
876     let mut size = 0i64;
877     cvt(unsafe {
878         c::CopyFileExW(
879             pfrom.as_ptr(),
880             pto.as_ptr(),
881             Some(callback),
882             &mut size as *mut _ as *mut _,
883             ptr::null_mut(),
884             0,
885         )
886     })?;
887     Ok(size as u64)
888 }
889
890 #[allow(dead_code)]
891 pub fn symlink_junction<P: AsRef<Path>, Q: AsRef<Path>>(
892     original: P,
893     junction: Q,
894 ) -> io::Result<()> {
895     symlink_junction_inner(original.as_ref(), junction.as_ref())
896 }
897
898 // Creating a directory junction on windows involves dealing with reparse
899 // points and the DeviceIoControl function, and this code is a skeleton of
900 // what can be found here:
901 //
902 // http://www.flexhex.com/docs/articles/hard-links.phtml
903 #[allow(dead_code)]
904 fn symlink_junction_inner(original: &Path, junction: &Path) -> io::Result<()> {
905     let d = DirBuilder::new();
906     d.mkdir(&junction)?;
907
908     let mut opts = OpenOptions::new();
909     opts.write(true);
910     opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT | c::FILE_FLAG_BACKUP_SEMANTICS);
911     let f = File::open(junction, &opts)?;
912     let h = f.handle().raw();
913
914     unsafe {
915         let mut data = [0u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
916         let db = data.as_mut_ptr() as *mut c::REPARSE_MOUNTPOINT_DATA_BUFFER;
917         let buf = &mut (*db).ReparseTarget as *mut c::WCHAR;
918         let mut i = 0;
919         // FIXME: this conversion is very hacky
920         let v = br"\??\";
921         let v = v.iter().map(|x| *x as u16);
922         for c in v.chain(original.as_os_str().encode_wide()) {
923             *buf.offset(i) = c;
924             i += 1;
925         }
926         *buf.offset(i) = 0;
927         i += 1;
928         (*db).ReparseTag = c::IO_REPARSE_TAG_MOUNT_POINT;
929         (*db).ReparseTargetMaximumLength = (i * 2) as c::WORD;
930         (*db).ReparseTargetLength = ((i - 1) * 2) as c::WORD;
931         (*db).ReparseDataLength = (*db).ReparseTargetLength as c::DWORD + 12;
932
933         let mut ret = 0;
934         cvt(c::DeviceIoControl(
935             h as *mut _,
936             c::FSCTL_SET_REPARSE_POINT,
937             data.as_ptr() as *mut _,
938             (*db).ReparseDataLength + 8,
939             ptr::null_mut(),
940             0,
941             &mut ret,
942             ptr::null_mut(),
943         ))
944         .map(drop)
945     }
946 }
947
948 // Try to see if a file exists but, unlike `exists`, report I/O errors.
949 pub fn try_exists(path: &Path) -> io::Result<bool> {
950     // Open the file to ensure any symlinks are followed to their target.
951     let mut opts = OpenOptions::new();
952     // No read, write, etc access rights are needed.
953     opts.access_mode(0);
954     // Backup semantics enables opening directories as well as files.
955     opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS);
956     match File::open(path, &opts) {
957         Err(e) => match e.kind() {
958             // The file definitely does not exist
959             io::ErrorKind::NotFound => Ok(false),
960
961             // `ERROR_SHARING_VIOLATION` means that the file has been locked by
962             // another process. This is often temporary so we simply report it
963             // as the file existing.
964             _ if e.raw_os_error() == Some(c::ERROR_SHARING_VIOLATION as i32) => Ok(true),
965
966             // Other errors such as `ERROR_ACCESS_DENIED` may indicate that the
967             // file exists. However, these types of errors are usually more
968             // permanent so we report them here.
969             _ => Err(e),
970         },
971         // The file was opened successfully therefore it must exist,
972         Ok(_) => Ok(true),
973     }
974 }