]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys/windows/fs.rs
Rollup merge of #89876 - AlexApps99:const_ops, r=oli-obk
[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::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 {
86     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>;
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 {
120     fn drop(&mut self) {
121         let r = unsafe { c::FindClose(self.0) };
122         debug_assert!(r != 0);
123     }
124 }
125
126 impl 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
137     pub fn path(&self) -> PathBuf {
138         self.root.join(&self.file_name())
139     }
140
141     pub fn file_name(&self) -> OsString {
142         let filename = super::truncate_utf16_at_nul(&self.data.cFileName);
143         OsString::from_wide(filename)
144     }
145
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
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 {
174     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
193     pub fn read(&mut self, read: bool) {
194         self.read = read;
195     }
196     pub fn write(&mut self, write: bool) {
197         self.write = write;
198     }
199     pub fn append(&mut self, append: bool) {
200         self.append = append;
201     }
202     pub fn truncate(&mut self, truncate: bool) {
203         self.truncate = truncate;
204     }
205     pub fn create(&mut self, create: bool) {
206         self.create = create;
207     }
208     pub fn create_new(&mut self, create_new: bool) {
209         self.create_new = create_new;
210     }
211
212     pub fn custom_flags(&mut self, flags: u32) {
213         self.custom_flags = flags;
214     }
215     pub fn access_mode(&mut self, access_mode: u32) {
216         self.access_mode = Some(access_mode);
217     }
218     pub fn share_mode(&mut self, share_mode: u32) {
219         self.share_mode = share_mode;
220     }
221     pub fn attributes(&mut self, attrs: u32) {
222         self.attributes = attrs;
223     }
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     }
229     pub fn security_attributes(&mut self, attrs: c::LPSECURITY_ATTRIBUTES) {
230         self.security_attributes = attrs as usize;
231     }
232
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
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
275     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 {
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
304     pub fn fsync(&self) -> io::Result<()> {
305         cvt(unsafe { c::FlushFileBuffers(self.handle.as_raw_handle()) })?;
306         Ok(())
307     }
308
309     pub fn datasync(&self) -> io::Result<()> {
310         self.fsync()
311     }
312
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"))]
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")]
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
406     pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
407         self.handle.read(buf)
408     }
409
410     pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
411         self.handle.read_vectored(bufs)
412     }
413
414     #[inline]
415     pub fn is_read_vectored(&self) -> bool {
416         self.handle.is_read_vectored()
417     }
418
419     pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
420         self.handle.read_at(buf, offset)
421     }
422
423     pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
424         self.handle.write(buf)
425     }
426
427     pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
428         self.handle.write_vectored(bufs)
429     }
430
431     #[inline]
432     pub fn is_write_vectored(&self) -> bool {
433         self.handle.is_write_vectored()
434     }
435
436     pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
437         self.handle.write_at(buf, offset)
438     }
439
440     pub fn flush(&self) -> io::Result<()> {
441         Ok(())
442     }
443
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
458     pub fn duplicate(&self) -> io::Result<File> {
459         Ok(File { handle: self.handle.duplicate(0, false, c::DUPLICATE_SAME_ACCESS)? })
460     }
461
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
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
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 }
547
548 impl AsInner<Handle> for File {
549     fn as_inner(&self) -> &Handle {
550         &self.handle
551     }
552 }
553
554 impl IntoInner<Handle> for File {
555     fn into_inner(self) -> Handle {
556         self.handle
557     }
558 }
559
560 impl FromInner<Handle> for File {
561     fn from_inner(handle: Handle) -> File {
562         File { handle }
563     }
564 }
565
566 impl AsHandle for File {
567     fn as_handle(&self) -> BorrowedHandle<'_> {
568         self.as_inner().as_handle()
569     }
570 }
571
572 impl AsRawHandle for File {
573     fn as_raw_handle(&self) -> RawHandle {
574         self.as_inner().as_raw_handle()
575     }
576 }
577
578 impl IntoRawHandle for File {
579     fn into_raw_handle(self) -> RawHandle {
580         self.into_inner().into_raw_handle()
581     }
582 }
583
584 impl FromRawHandle for File {
585     unsafe fn from_raw_handle(raw_handle: RawHandle) -> Self {
586         Self { handle: FromInner::from_inner(FromRawHandle::from_raw_handle(raw_handle)) }
587     }
588 }
589
590 impl fmt::Debug for File {
591     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
592         // FIXME(#24570): add more info here (e.g., mode)
593         let mut b = f.debug_struct("File");
594         b.field("handle", &self.handle.as_raw_handle());
595         if let Ok(path) = get_path(&self) {
596             b.field("path", &path);
597         }
598         b.finish()
599     }
600 }
601
602 impl FileAttr {
603     pub fn size(&self) -> u64 {
604         self.file_size
605     }
606
607     pub fn perm(&self) -> FilePermissions {
608         FilePermissions { attrs: self.attributes }
609     }
610
611     pub fn attrs(&self) -> u32 {
612         self.attributes
613     }
614
615     pub fn file_type(&self) -> FileType {
616         FileType::new(self.attributes, self.reparse_tag)
617     }
618
619     pub fn modified(&self) -> io::Result<SystemTime> {
620         Ok(SystemTime::from(self.last_write_time))
621     }
622
623     pub fn accessed(&self) -> io::Result<SystemTime> {
624         Ok(SystemTime::from(self.last_access_time))
625     }
626
627     pub fn created(&self) -> io::Result<SystemTime> {
628         Ok(SystemTime::from(self.creation_time))
629     }
630
631     pub fn modified_u64(&self) -> u64 {
632         to_u64(&self.last_write_time)
633     }
634
635     pub fn accessed_u64(&self) -> u64 {
636         to_u64(&self.last_access_time)
637     }
638
639     pub fn created_u64(&self) -> u64 {
640         to_u64(&self.creation_time)
641     }
642
643     pub fn volume_serial_number(&self) -> Option<u32> {
644         self.volume_serial_number
645     }
646
647     pub fn number_of_links(&self) -> Option<u32> {
648         self.number_of_links
649     }
650
651     pub fn file_index(&self) -> Option<u64> {
652         self.file_index
653     }
654 }
655
656 fn to_u64(ft: &c::FILETIME) -> u64 {
657     (ft.dwLowDateTime as u64) | ((ft.dwHighDateTime as u64) << 32)
658 }
659
660 impl FilePermissions {
661     pub fn readonly(&self) -> bool {
662         self.attrs & c::FILE_ATTRIBUTE_READONLY != 0
663     }
664
665     pub fn set_readonly(&mut self, readonly: bool) {
666         if readonly {
667             self.attrs |= c::FILE_ATTRIBUTE_READONLY;
668         } else {
669             self.attrs &= !c::FILE_ATTRIBUTE_READONLY;
670         }
671     }
672 }
673
674 impl FileType {
675     fn new(attrs: c::DWORD, reparse_tag: c::DWORD) -> FileType {
676         FileType { attributes: attrs, reparse_tag }
677     }
678     pub fn is_dir(&self) -> bool {
679         !self.is_symlink() && self.is_directory()
680     }
681     pub fn is_file(&self) -> bool {
682         !self.is_symlink() && !self.is_directory()
683     }
684     pub fn is_symlink(&self) -> bool {
685         self.is_reparse_point() && self.is_reparse_tag_name_surrogate()
686     }
687     pub fn is_symlink_dir(&self) -> bool {
688         self.is_symlink() && self.is_directory()
689     }
690     pub fn is_symlink_file(&self) -> bool {
691         self.is_symlink() && !self.is_directory()
692     }
693     fn is_directory(&self) -> bool {
694         self.attributes & c::FILE_ATTRIBUTE_DIRECTORY != 0
695     }
696     fn is_reparse_point(&self) -> bool {
697         self.attributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0
698     }
699     fn is_reparse_tag_name_surrogate(&self) -> bool {
700         self.reparse_tag & 0x20000000 != 0
701     }
702 }
703
704 impl DirBuilder {
705     pub fn new() -> DirBuilder {
706         DirBuilder
707     }
708
709     pub fn mkdir(&self, p: &Path) -> io::Result<()> {
710         let p = maybe_verbatim(p)?;
711         cvt(unsafe { c::CreateDirectoryW(p.as_ptr(), ptr::null_mut()) })?;
712         Ok(())
713     }
714 }
715
716 pub fn readdir(p: &Path) -> io::Result<ReadDir> {
717     let root = p.to_path_buf();
718     let star = p.join("*");
719     let path = maybe_verbatim(&star)?;
720
721     unsafe {
722         let mut wfd = mem::zeroed();
723         let find_handle = c::FindFirstFileW(path.as_ptr(), &mut wfd);
724         if find_handle != c::INVALID_HANDLE_VALUE {
725             Ok(ReadDir {
726                 handle: FindNextFileHandle(find_handle),
727                 root: Arc::new(root),
728                 first: Some(wfd),
729             })
730         } else {
731             Err(Error::last_os_error())
732         }
733     }
734 }
735
736 pub fn unlink(p: &Path) -> io::Result<()> {
737     let p_u16s = maybe_verbatim(p)?;
738     cvt(unsafe { c::DeleteFileW(p_u16s.as_ptr()) })?;
739     Ok(())
740 }
741
742 pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
743     let old = maybe_verbatim(old)?;
744     let new = maybe_verbatim(new)?;
745     cvt(unsafe { c::MoveFileExW(old.as_ptr(), new.as_ptr(), c::MOVEFILE_REPLACE_EXISTING) })?;
746     Ok(())
747 }
748
749 pub fn rmdir(p: &Path) -> io::Result<()> {
750     let p = maybe_verbatim(p)?;
751     cvt(unsafe { c::RemoveDirectoryW(p.as_ptr()) })?;
752     Ok(())
753 }
754
755 pub fn remove_dir_all(path: &Path) -> io::Result<()> {
756     let filetype = lstat(path)?.file_type();
757     if filetype.is_symlink() {
758         // On Windows symlinks to files and directories are removed differently.
759         // rmdir only deletes dir symlinks and junctions, not file symlinks.
760         rmdir(path)
761     } else {
762         remove_dir_all_recursive(path)
763     }
764 }
765
766 fn remove_dir_all_recursive(path: &Path) -> io::Result<()> {
767     for child in readdir(path)? {
768         let child = child?;
769         let child_type = child.file_type()?;
770         if child_type.is_dir() {
771             remove_dir_all_recursive(&child.path())?;
772         } else if child_type.is_symlink_dir() {
773             rmdir(&child.path())?;
774         } else {
775             unlink(&child.path())?;
776         }
777     }
778     rmdir(path)
779 }
780
781 pub fn readlink(path: &Path) -> io::Result<PathBuf> {
782     // Open the link with no access mode, instead of generic read.
783     // By default FILE_LIST_DIRECTORY is denied for the junction "C:\Documents and Settings", so
784     // this is needed for a common case.
785     let mut opts = OpenOptions::new();
786     opts.access_mode(0);
787     opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT | c::FILE_FLAG_BACKUP_SEMANTICS);
788     let file = File::open(&path, &opts)?;
789     file.readlink()
790 }
791
792 pub fn symlink(original: &Path, link: &Path) -> io::Result<()> {
793     symlink_inner(original, link, false)
794 }
795
796 pub fn symlink_inner(original: &Path, link: &Path, dir: bool) -> io::Result<()> {
797     let original = to_u16s(original)?;
798     let link = maybe_verbatim(link)?;
799     let flags = if dir { c::SYMBOLIC_LINK_FLAG_DIRECTORY } else { 0 };
800     // Formerly, symlink creation required the SeCreateSymbolicLink privilege. For the Windows 10
801     // Creators Update, Microsoft loosened this to allow unprivileged symlink creation if the
802     // computer is in Developer Mode, but SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE must be
803     // added to dwFlags to opt into this behaviour.
804     let result = cvt(unsafe {
805         c::CreateSymbolicLinkW(
806             link.as_ptr(),
807             original.as_ptr(),
808             flags | c::SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE,
809         ) as c::BOOL
810     });
811     if let Err(err) = result {
812         if err.raw_os_error() == Some(c::ERROR_INVALID_PARAMETER as i32) {
813             // Older Windows objects to SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE,
814             // so if we encounter ERROR_INVALID_PARAMETER, retry without that flag.
815             cvt(unsafe {
816                 c::CreateSymbolicLinkW(link.as_ptr(), original.as_ptr(), flags) as c::BOOL
817             })?;
818         } else {
819             return Err(err);
820         }
821     }
822     Ok(())
823 }
824
825 #[cfg(not(target_vendor = "uwp"))]
826 pub fn link(original: &Path, link: &Path) -> io::Result<()> {
827     let original = maybe_verbatim(original)?;
828     let link = maybe_verbatim(link)?;
829     cvt(unsafe { c::CreateHardLinkW(link.as_ptr(), original.as_ptr(), ptr::null_mut()) })?;
830     Ok(())
831 }
832
833 #[cfg(target_vendor = "uwp")]
834 pub fn link(_original: &Path, _link: &Path) -> io::Result<()> {
835     return Err(io::Error::new_const(
836         io::ErrorKind::Unsupported,
837         &"hard link are not supported on UWP",
838     ));
839 }
840
841 pub fn stat(path: &Path) -> io::Result<FileAttr> {
842     let mut opts = OpenOptions::new();
843     // No read or write permissions are necessary
844     opts.access_mode(0);
845     // This flag is so we can open directories too
846     opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS);
847     let file = File::open(path, &opts)?;
848     file.file_attr()
849 }
850
851 pub fn lstat(path: &Path) -> io::Result<FileAttr> {
852     let mut opts = OpenOptions::new();
853     // No read or write permissions are necessary
854     opts.access_mode(0);
855     opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS | c::FILE_FLAG_OPEN_REPARSE_POINT);
856     let file = File::open(path, &opts)?;
857     file.file_attr()
858 }
859
860 pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
861     let p = maybe_verbatim(p)?;
862     unsafe {
863         cvt(c::SetFileAttributesW(p.as_ptr(), perm.attrs))?;
864         Ok(())
865     }
866 }
867
868 fn get_path(f: &File) -> io::Result<PathBuf> {
869     super::fill_utf16_buf(
870         |buf, sz| unsafe {
871             c::GetFinalPathNameByHandleW(f.handle.as_raw_handle(), buf, sz, c::VOLUME_NAME_DOS)
872         },
873         |buf| PathBuf::from(OsString::from_wide(buf)),
874     )
875 }
876
877 pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
878     let mut opts = OpenOptions::new();
879     // No read or write permissions are necessary
880     opts.access_mode(0);
881     // This flag is so we can open directories too
882     opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS);
883     let f = File::open(p, &opts)?;
884     get_path(&f)
885 }
886
887 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
888     unsafe extern "system" fn callback(
889         _TotalFileSize: c::LARGE_INTEGER,
890         _TotalBytesTransferred: c::LARGE_INTEGER,
891         _StreamSize: c::LARGE_INTEGER,
892         StreamBytesTransferred: c::LARGE_INTEGER,
893         dwStreamNumber: c::DWORD,
894         _dwCallbackReason: c::DWORD,
895         _hSourceFile: c::HANDLE,
896         _hDestinationFile: c::HANDLE,
897         lpData: c::LPVOID,
898     ) -> c::DWORD {
899         if dwStreamNumber == 1 {
900             *(lpData as *mut i64) = StreamBytesTransferred;
901         }
902         c::PROGRESS_CONTINUE
903     }
904     let pfrom = maybe_verbatim(from)?;
905     let pto = maybe_verbatim(to)?;
906     let mut size = 0i64;
907     cvt(unsafe {
908         c::CopyFileExW(
909             pfrom.as_ptr(),
910             pto.as_ptr(),
911             Some(callback),
912             &mut size as *mut _ as *mut _,
913             ptr::null_mut(),
914             0,
915         )
916     })?;
917     Ok(size as u64)
918 }
919
920 #[allow(dead_code)]
921 pub fn symlink_junction<P: AsRef<Path>, Q: AsRef<Path>>(
922     original: P,
923     junction: Q,
924 ) -> io::Result<()> {
925     symlink_junction_inner(original.as_ref(), junction.as_ref())
926 }
927
928 // Creating a directory junction on windows involves dealing with reparse
929 // points and the DeviceIoControl function, and this code is a skeleton of
930 // what can be found here:
931 //
932 // http://www.flexhex.com/docs/articles/hard-links.phtml
933 #[allow(dead_code)]
934 fn symlink_junction_inner(original: &Path, junction: &Path) -> io::Result<()> {
935     let d = DirBuilder::new();
936     d.mkdir(&junction)?;
937
938     let mut opts = OpenOptions::new();
939     opts.write(true);
940     opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT | c::FILE_FLAG_BACKUP_SEMANTICS);
941     let f = File::open(junction, &opts)?;
942     let h = f.as_inner().as_raw_handle();
943
944     unsafe {
945         let mut data = [0u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
946         let db = data.as_mut_ptr() as *mut c::REPARSE_MOUNTPOINT_DATA_BUFFER;
947         let buf = &mut (*db).ReparseTarget as *mut c::WCHAR;
948         let mut i = 0;
949         // FIXME: this conversion is very hacky
950         let v = br"\??\";
951         let v = v.iter().map(|x| *x as u16);
952         for c in v.chain(original.as_os_str().encode_wide()) {
953             *buf.offset(i) = c;
954             i += 1;
955         }
956         *buf.offset(i) = 0;
957         i += 1;
958         (*db).ReparseTag = c::IO_REPARSE_TAG_MOUNT_POINT;
959         (*db).ReparseTargetMaximumLength = (i * 2) as c::WORD;
960         (*db).ReparseTargetLength = ((i - 1) * 2) as c::WORD;
961         (*db).ReparseDataLength = (*db).ReparseTargetLength as c::DWORD + 12;
962
963         let mut ret = 0;
964         cvt(c::DeviceIoControl(
965             h as *mut _,
966             c::FSCTL_SET_REPARSE_POINT,
967             data.as_ptr() as *mut _,
968             (*db).ReparseDataLength + 8,
969             ptr::null_mut(),
970             0,
971             &mut ret,
972             ptr::null_mut(),
973         ))
974         .map(drop)
975     }
976 }
977
978 // Try to see if a file exists but, unlike `exists`, report I/O errors.
979 pub fn try_exists(path: &Path) -> io::Result<bool> {
980     // Open the file to ensure any symlinks are followed to their target.
981     let mut opts = OpenOptions::new();
982     // No read, write, etc access rights are needed.
983     opts.access_mode(0);
984     // Backup semantics enables opening directories as well as files.
985     opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS);
986     match File::open(path, &opts) {
987         Err(e) => match e.kind() {
988             // The file definitely does not exist
989             io::ErrorKind::NotFound => Ok(false),
990
991             // `ERROR_SHARING_VIOLATION` means that the file has been locked by
992             // another process. This is often temporary so we simply report it
993             // as the file existing.
994             _ if e.raw_os_error() == Some(c::ERROR_SHARING_VIOLATION as i32) => Ok(true),
995
996             // Other errors such as `ERROR_ACCESS_DENIED` may indicate that the
997             // file exists. However, these types of errors are usually more
998             // permanent so we report them here.
999             _ => Err(e),
1000         },
1001         // The file was opened successfully therefore it must exist,
1002         Ok(_) => Ok(true),
1003     }
1004 }