]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/windows/fs.rs
Auto merge of #31656 - jonas-schievink:mirdump, r=nrc
[rust.git] / src / libstd / sys / windows / fs.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use io::prelude::*;
12 use os::windows::prelude::*;
13
14 use ffi::OsString;
15 use fmt;
16 use io::{self, Error, SeekFrom};
17 use mem;
18 use path::{Path, PathBuf};
19 use ptr;
20 use slice;
21 use sync::Arc;
22 use sys::handle::Handle;
23 use sys::time::SystemTime;
24 use sys::{c, cvt};
25 use sys_common::FromInner;
26
27 use super::to_u16s;
28
29 pub struct File { handle: Handle }
30
31 #[derive(Clone)]
32 pub struct FileAttr {
33     data: c::WIN32_FILE_ATTRIBUTE_DATA,
34     reparse_tag: c::DWORD,
35 }
36
37 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
38 pub enum FileType {
39     Dir, File, SymlinkFile, SymlinkDir, ReparsePoint, MountPoint,
40 }
41
42 pub struct ReadDir {
43     handle: FindNextFileHandle,
44     root: Arc<PathBuf>,
45     first: Option<c::WIN32_FIND_DATAW>,
46 }
47
48 struct FindNextFileHandle(c::HANDLE);
49
50 unsafe impl Send for FindNextFileHandle {}
51 unsafe impl Sync for FindNextFileHandle {}
52
53 pub struct DirEntry {
54     root: Arc<PathBuf>,
55     data: c::WIN32_FIND_DATAW,
56 }
57
58 #[derive(Clone)]
59 pub struct OpenOptions {
60     // generic
61     read: bool,
62     write: bool,
63     append: bool,
64     truncate: bool,
65     create: bool,
66     create_new: bool,
67     // system-specific
68     custom_flags: u32,
69     access_mode: Option<c::DWORD>,
70     attributes: c::DWORD,
71     share_mode: c::DWORD,
72     security_qos_flags: c::DWORD,
73     security_attributes: usize, // FIXME: should be a reference
74 }
75
76 #[derive(Clone, PartialEq, Eq, Debug)]
77 pub struct FilePermissions { attrs: c::DWORD }
78
79 pub struct DirBuilder;
80
81 impl Iterator for ReadDir {
82     type Item = io::Result<DirEntry>;
83     fn next(&mut self) -> Option<io::Result<DirEntry>> {
84         if let Some(first) = self.first.take() {
85             if let Some(e) = DirEntry::new(&self.root, &first) {
86                 return Some(Ok(e));
87             }
88         }
89         unsafe {
90             let mut wfd = mem::zeroed();
91             loop {
92                 if c::FindNextFileW(self.handle.0, &mut wfd) == 0 {
93                     if c::GetLastError() == c::ERROR_NO_MORE_FILES {
94                         return None
95                     } else {
96                         return Some(Err(Error::last_os_error()))
97                     }
98                 }
99                 if let Some(e) = DirEntry::new(&self.root, &wfd) {
100                     return Some(Ok(e))
101                 }
102             }
103         }
104     }
105 }
106
107 impl Drop for FindNextFileHandle {
108     fn drop(&mut self) {
109         let r = unsafe { c::FindClose(self.0) };
110         debug_assert!(r != 0);
111     }
112 }
113
114 impl DirEntry {
115     fn new(root: &Arc<PathBuf>, wfd: &c::WIN32_FIND_DATAW) -> Option<DirEntry> {
116         match &wfd.cFileName[0..3] {
117             // check for '.' and '..'
118             [46, 0, ..] |
119             [46, 46, 0, ..] => return None,
120             _ => {}
121         }
122
123         Some(DirEntry {
124             root: root.clone(),
125             data: *wfd,
126         })
127     }
128
129     pub fn path(&self) -> PathBuf {
130         self.root.join(&self.file_name())
131     }
132
133     pub fn file_name(&self) -> OsString {
134         let filename = super::truncate_utf16_at_nul(&self.data.cFileName);
135         OsString::from_wide(filename)
136     }
137
138     pub fn file_type(&self) -> io::Result<FileType> {
139         Ok(FileType::new(self.data.dwFileAttributes,
140                          /* reparse_tag = */ self.data.dwReserved0))
141     }
142
143     pub fn metadata(&self) -> io::Result<FileAttr> {
144         Ok(FileAttr {
145             data: c::WIN32_FILE_ATTRIBUTE_DATA {
146                 dwFileAttributes: self.data.dwFileAttributes,
147                 ftCreationTime: self.data.ftCreationTime,
148                 ftLastAccessTime: self.data.ftLastAccessTime,
149                 ftLastWriteTime: self.data.ftLastWriteTime,
150                 nFileSizeHigh: self.data.nFileSizeHigh,
151                 nFileSizeLow: self.data.nFileSizeLow,
152             },
153             reparse_tag: if self.data.dwFileAttributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
154                     // reserved unless this is a reparse point
155                     self.data.dwReserved0
156                 } else {
157                     0
158                 },
159         })
160     }
161 }
162
163 impl OpenOptions {
164     pub fn new() -> OpenOptions {
165         OpenOptions {
166             // generic
167             read: false,
168             write: false,
169             append: false,
170             truncate: false,
171             create: false,
172             create_new: false,
173             // system-specific
174             custom_flags: 0,
175             access_mode: None,
176             share_mode: c::FILE_SHARE_READ | c::FILE_SHARE_WRITE | c::FILE_SHARE_DELETE,
177             attributes: 0,
178             security_qos_flags: 0,
179             security_attributes: 0,
180         }
181     }
182
183     pub fn read(&mut self, read: bool) { self.read = read; }
184     pub fn write(&mut self, write: bool) { self.write = write; }
185     pub fn append(&mut self, append: bool) { self.append = append; }
186     pub fn truncate(&mut self, truncate: bool) { self.truncate = truncate; }
187     pub fn create(&mut self, create: bool) { self.create = create; }
188     pub fn create_new(&mut self, create_new: bool) { self.create_new = create_new; }
189
190     pub fn custom_flags(&mut self, flags: u32) { self.custom_flags = flags; }
191     pub fn access_mode(&mut self, access_mode: u32) { self.access_mode = Some(access_mode); }
192     pub fn share_mode(&mut self, share_mode: u32) { self.share_mode = share_mode; }
193     pub fn attributes(&mut self, attrs: u32) { self.attributes = attrs; }
194     pub fn security_qos_flags(&mut self, flags: u32) { self.security_qos_flags = flags; }
195     pub fn security_attributes(&mut self, attrs: c::LPSECURITY_ATTRIBUTES) {
196         self.security_attributes = attrs as usize;
197     }
198
199     fn get_access_mode(&self) -> io::Result<c::DWORD> {
200         const ERROR_INVALID_PARAMETER: i32 = 87;
201
202         match (self.read, self.write, self.append, self.access_mode) {
203             (_, _, _, Some(mode)) => Ok(mode),
204             (true,  false, false, None) => Ok(c::GENERIC_READ),
205             (false, true,  false, None) => Ok(c::GENERIC_WRITE),
206             (true,  true,  false, None) => Ok(c::GENERIC_READ | c::GENERIC_WRITE),
207             (false, _,     true,  None) => Ok(c::FILE_GENERIC_WRITE & !c::FILE_WRITE_DATA),
208             (true,  _,     true,  None) => Ok(c::GENERIC_READ |
209                                               (c::FILE_GENERIC_WRITE & !c::FILE_WRITE_DATA)),
210             (false, false, false, None) => Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER)),
211         }
212     }
213
214     fn get_creation_mode(&self) -> io::Result<c::DWORD> {
215         const ERROR_INVALID_PARAMETER: i32 = 87;
216
217         match (self.write, self.append) {
218             (true, false) => {}
219             (false, false) =>
220                 if self.truncate || self.create || self.create_new {
221                     return Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER));
222                 },
223             (_, true) =>
224                 if self.truncate && !self.create_new {
225                     return Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER));
226                 },
227         }
228
229         Ok(match (self.create, self.truncate, self.create_new) {
230                 (false, false, false) => c::OPEN_EXISTING,
231                 (true,  false, false) => c::OPEN_ALWAYS,
232                 (false, true,  false) => c::TRUNCATE_EXISTING,
233                 (true,  true,  false) => c::CREATE_ALWAYS,
234                 (_,      _,    true)  => c::CREATE_NEW,
235            })
236     }
237
238     fn get_flags_and_attributes(&self) -> c::DWORD {
239         self.custom_flags |
240         self.attributes |
241         self.security_qos_flags |
242         if self.security_qos_flags != 0 { c::SECURITY_SQOS_PRESENT } else { 0 } |
243         if self.create_new { c::FILE_FLAG_OPEN_REPARSE_POINT } else { 0 }
244     }
245 }
246
247 impl File {
248     pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
249         let path = try!(to_u16s(path));
250         let handle = unsafe {
251             c::CreateFileW(path.as_ptr(),
252                            try!(opts.get_access_mode()),
253                            opts.share_mode,
254                            opts.security_attributes as *mut _,
255                            try!(opts.get_creation_mode()),
256                            opts.get_flags_and_attributes(),
257                            ptr::null_mut())
258         };
259         if handle == c::INVALID_HANDLE_VALUE {
260             Err(Error::last_os_error())
261         } else {
262             Ok(File { handle: Handle::new(handle) })
263         }
264     }
265
266     pub fn fsync(&self) -> io::Result<()> {
267         try!(cvt(unsafe { c::FlushFileBuffers(self.handle.raw()) }));
268         Ok(())
269     }
270
271     pub fn datasync(&self) -> io::Result<()> { self.fsync() }
272
273     pub fn truncate(&self, size: u64) -> io::Result<()> {
274         let mut info = c::FILE_END_OF_FILE_INFO {
275             EndOfFile: size as c::LARGE_INTEGER,
276         };
277         let size = mem::size_of_val(&info);
278         try!(cvt(unsafe {
279             c::SetFileInformationByHandle(self.handle.raw(),
280                                           c::FileEndOfFileInfo,
281                                           &mut info as *mut _ as *mut _,
282                                           size as c::DWORD)
283         }));
284         Ok(())
285     }
286
287     pub fn file_attr(&self) -> io::Result<FileAttr> {
288         unsafe {
289             let mut info: c::BY_HANDLE_FILE_INFORMATION = mem::zeroed();
290             try!(cvt(c::GetFileInformationByHandle(self.handle.raw(),
291                                                    &mut info)));
292             let mut attr = FileAttr {
293                 data: c::WIN32_FILE_ATTRIBUTE_DATA {
294                     dwFileAttributes: info.dwFileAttributes,
295                     ftCreationTime: info.ftCreationTime,
296                     ftLastAccessTime: info.ftLastAccessTime,
297                     ftLastWriteTime: info.ftLastWriteTime,
298                     nFileSizeHigh: info.nFileSizeHigh,
299                     nFileSizeLow: info.nFileSizeLow,
300                 },
301                 reparse_tag: 0,
302             };
303             if attr.is_reparse_point() {
304                 let mut b = [0; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
305                 if let Ok((_, buf)) = self.reparse_point(&mut b) {
306                     attr.reparse_tag = buf.ReparseTag;
307                 }
308             }
309             Ok(attr)
310         }
311     }
312
313     pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
314         self.handle.read(buf)
315     }
316
317     pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
318         self.handle.write(buf)
319     }
320
321     pub fn flush(&self) -> io::Result<()> { Ok(()) }
322
323     pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
324         let (whence, pos) = match pos {
325             SeekFrom::Start(n) => (c::FILE_BEGIN, n as i64),
326             SeekFrom::End(n) => (c::FILE_END, n),
327             SeekFrom::Current(n) => (c::FILE_CURRENT, n),
328         };
329         let pos = pos as c::LARGE_INTEGER;
330         let mut newpos = 0;
331         try!(cvt(unsafe {
332             c::SetFilePointerEx(self.handle.raw(), pos,
333                                 &mut newpos, whence)
334         }));
335         Ok(newpos as u64)
336     }
337
338     pub fn duplicate(&self) -> io::Result<File> {
339         Ok(File {
340             handle: try!(self.handle.duplicate(0, true, c::DUPLICATE_SAME_ACCESS)),
341         })
342     }
343
344     pub fn handle(&self) -> &Handle { &self.handle }
345
346     pub fn into_handle(self) -> Handle { self.handle }
347
348     fn reparse_point<'a>(&self,
349                          space: &'a mut [u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE])
350                          -> io::Result<(c::DWORD, &'a c::REPARSE_DATA_BUFFER)> {
351         unsafe {
352             let mut bytes = 0;
353             try!(cvt({
354                 c::DeviceIoControl(self.handle.raw(),
355                                    c::FSCTL_GET_REPARSE_POINT,
356                                    ptr::null_mut(),
357                                    0,
358                                    space.as_mut_ptr() as *mut _,
359                                    space.len() as c::DWORD,
360                                    &mut bytes,
361                                    ptr::null_mut())
362             }));
363             Ok((bytes, &*(space.as_ptr() as *const c::REPARSE_DATA_BUFFER)))
364         }
365     }
366
367     fn readlink(&self) -> io::Result<PathBuf> {
368         let mut space = [0u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
369         let (_bytes, buf) = try!(self.reparse_point(&mut space));
370         unsafe {
371             let (path_buffer, subst_off, subst_len, relative) = match buf.ReparseTag {
372                 c::IO_REPARSE_TAG_SYMLINK => {
373                     let info: *const c::SYMBOLIC_LINK_REPARSE_BUFFER =
374                         &buf.rest as *const _ as *const _;
375                     (&(*info).PathBuffer as *const _ as *const u16,
376                      (*info).SubstituteNameOffset / 2,
377                      (*info).SubstituteNameLength / 2,
378                      (*info).Flags & c::SYMLINK_FLAG_RELATIVE != 0)
379                 },
380                 c::IO_REPARSE_TAG_MOUNT_POINT => {
381                     let info: *const c::MOUNT_POINT_REPARSE_BUFFER =
382                         &buf.rest as *const _ as *const _;
383                     (&(*info).PathBuffer as *const _ as *const u16,
384                      (*info).SubstituteNameOffset / 2,
385                      (*info).SubstituteNameLength / 2,
386                      false)
387                 },
388                 _ => return Err(io::Error::new(io::ErrorKind::Other,
389                                                "Unsupported reparse point type"))
390             };
391             let subst_ptr = path_buffer.offset(subst_off as isize);
392             let mut subst = slice::from_raw_parts(subst_ptr, subst_len as usize);
393             // Absolute paths start with an NT internal namespace prefix `\??\`
394             // We should not let it leak through.
395             if !relative && subst.starts_with(&[92u16, 63u16, 63u16, 92u16]) {
396                 subst = &subst[4..];
397             }
398             Ok(PathBuf::from(OsString::from_wide(subst)))
399         }
400     }
401 }
402
403 impl FromInner<c::HANDLE> for File {
404     fn from_inner(handle: c::HANDLE) -> File {
405         File { handle: Handle::new(handle) }
406     }
407 }
408
409 impl fmt::Debug for File {
410     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
411         // FIXME(#24570): add more info here (e.g. mode)
412         let mut b = f.debug_struct("File");
413         b.field("handle", &self.handle.raw());
414         if let Ok(path) = get_path(&self) {
415             b.field("path", &path);
416         }
417         b.finish()
418     }
419 }
420
421 impl FileAttr {
422     pub fn size(&self) -> u64 {
423         ((self.data.nFileSizeHigh as u64) << 32) | (self.data.nFileSizeLow as u64)
424     }
425
426     pub fn perm(&self) -> FilePermissions {
427         FilePermissions { attrs: self.data.dwFileAttributes }
428     }
429
430     pub fn attrs(&self) -> u32 { self.data.dwFileAttributes as u32 }
431
432     pub fn file_type(&self) -> FileType {
433         FileType::new(self.data.dwFileAttributes, self.reparse_tag)
434     }
435
436     pub fn modified(&self) -> io::Result<SystemTime> {
437         Ok(SystemTime::from(self.data.ftLastWriteTime))
438     }
439
440     pub fn accessed(&self) -> io::Result<SystemTime> {
441         Ok(SystemTime::from(self.data.ftLastAccessTime))
442     }
443
444     pub fn created(&self) -> io::Result<SystemTime> {
445         Ok(SystemTime::from(self.data.ftCreationTime))
446     }
447
448     pub fn modified_u64(&self) -> u64 {
449         to_u64(&self.data.ftLastWriteTime)
450     }
451
452     pub fn accessed_u64(&self) -> u64 {
453         to_u64(&self.data.ftLastAccessTime)
454     }
455
456     pub fn created_u64(&self) -> u64 {
457         to_u64(&self.data.ftCreationTime)
458     }
459
460     fn is_reparse_point(&self) -> bool {
461         self.data.dwFileAttributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0
462     }
463 }
464
465 fn to_u64(ft: &c::FILETIME) -> u64 {
466     (ft.dwLowDateTime as u64) | ((ft.dwHighDateTime as u64) << 32)
467 }
468
469 impl FilePermissions {
470     pub fn readonly(&self) -> bool {
471         self.attrs & c::FILE_ATTRIBUTE_READONLY != 0
472     }
473
474     pub fn set_readonly(&mut self, readonly: bool) {
475         if readonly {
476             self.attrs |= c::FILE_ATTRIBUTE_READONLY;
477         } else {
478             self.attrs &= !c::FILE_ATTRIBUTE_READONLY;
479         }
480     }
481 }
482
483 impl FileType {
484     fn new(attrs: c::DWORD, reparse_tag: c::DWORD) -> FileType {
485         match (attrs & c::FILE_ATTRIBUTE_DIRECTORY != 0,
486                attrs & c::FILE_ATTRIBUTE_REPARSE_POINT != 0,
487                reparse_tag) {
488             (false, false, _) => FileType::File,
489             (true, false, _) => FileType::Dir,
490             (false, true, c::IO_REPARSE_TAG_SYMLINK) => FileType::SymlinkFile,
491             (true, true, c::IO_REPARSE_TAG_SYMLINK) => FileType::SymlinkDir,
492             (true, true, c::IO_REPARSE_TAG_MOUNT_POINT) => FileType::MountPoint,
493             (_, true, _) => FileType::ReparsePoint,
494             // Note: if a _file_ has a reparse tag of the type IO_REPARSE_TAG_MOUNT_POINT it is
495             // invalid, as junctions always have to be dirs. We set the filetype to ReparsePoint
496             // to indicate it is something symlink-like, but not something you can follow.
497         }
498     }
499
500     pub fn is_dir(&self) -> bool { *self == FileType::Dir }
501     pub fn is_file(&self) -> bool { *self == FileType::File }
502     pub fn is_symlink(&self) -> bool {
503         *self == FileType::SymlinkFile ||
504         *self == FileType::SymlinkDir ||
505         *self == FileType::MountPoint
506     }
507     pub fn is_symlink_dir(&self) -> bool {
508         *self == FileType::SymlinkDir || *self == FileType::MountPoint
509     }
510 }
511
512 impl DirBuilder {
513     pub fn new() -> DirBuilder { DirBuilder }
514
515     pub fn mkdir(&self, p: &Path) -> io::Result<()> {
516         let p = try!(to_u16s(p));
517         try!(cvt(unsafe {
518             c::CreateDirectoryW(p.as_ptr(), ptr::null_mut())
519         }));
520         Ok(())
521     }
522 }
523
524 pub fn readdir(p: &Path) -> io::Result<ReadDir> {
525     let root = p.to_path_buf();
526     let star = p.join("*");
527     let path = try!(to_u16s(&star));
528
529     unsafe {
530         let mut wfd = mem::zeroed();
531         let find_handle = c::FindFirstFileW(path.as_ptr(), &mut wfd);
532         if find_handle != c::INVALID_HANDLE_VALUE {
533             Ok(ReadDir {
534                 handle: FindNextFileHandle(find_handle),
535                 root: Arc::new(root),
536                 first: Some(wfd),
537             })
538         } else {
539             Err(Error::last_os_error())
540         }
541     }
542 }
543
544 pub fn unlink(p: &Path) -> io::Result<()> {
545     let p_u16s = try!(to_u16s(p));
546     try!(cvt(unsafe { c::DeleteFileW(p_u16s.as_ptr()) }));
547     Ok(())
548 }
549
550 pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
551     let old = try!(to_u16s(old));
552     let new = try!(to_u16s(new));
553     try!(cvt(unsafe {
554         c::MoveFileExW(old.as_ptr(), new.as_ptr(), c::MOVEFILE_REPLACE_EXISTING)
555     }));
556     Ok(())
557 }
558
559 pub fn rmdir(p: &Path) -> io::Result<()> {
560     let p = try!(to_u16s(p));
561     try!(cvt(unsafe { c::RemoveDirectoryW(p.as_ptr()) }));
562     Ok(())
563 }
564
565 pub fn remove_dir_all(path: &Path) -> io::Result<()> {
566     let filetype = try!(lstat(path)).file_type();
567     if filetype.is_symlink() {
568         // On Windows symlinks to files and directories are removed differently.
569         // rmdir only deletes dir symlinks and junctions, not file symlinks.
570         rmdir(path)
571     } else {
572         remove_dir_all_recursive(path)
573     }
574 }
575
576 fn remove_dir_all_recursive(path: &Path) -> io::Result<()> {
577     for child in try!(readdir(path)) {
578         let child = try!(child);
579         let child_type = try!(child.file_type());
580         if child_type.is_dir() {
581             try!(remove_dir_all_recursive(&child.path()));
582         } else if child_type.is_symlink_dir() {
583             try!(rmdir(&child.path()));
584         } else {
585             try!(unlink(&child.path()));
586         }
587     }
588     rmdir(path)
589 }
590
591 pub fn readlink(path: &Path) -> io::Result<PathBuf> {
592     // Open the link with no access mode, instead of generic read.
593     // By default FILE_LIST_DIRECTORY is denied for the junction "C:\Documents and Settings", so
594     // this is needed for a common case.
595     let mut opts = OpenOptions::new();
596     opts.access_mode(0);
597     opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT |
598                       c::FILE_FLAG_BACKUP_SEMANTICS);
599     let file = try!(File::open(&path, &opts));
600     file.readlink()
601 }
602
603 pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
604     symlink_inner(src, dst, false)
605 }
606
607 pub fn symlink_inner(src: &Path, dst: &Path, dir: bool) -> io::Result<()> {
608     let src = try!(to_u16s(src));
609     let dst = try!(to_u16s(dst));
610     let flags = if dir { c::SYMBOLIC_LINK_FLAG_DIRECTORY } else { 0 };
611     try!(cvt(unsafe {
612         c::CreateSymbolicLinkW(dst.as_ptr(), src.as_ptr(), flags) as c::BOOL
613     }));
614     Ok(())
615 }
616
617 pub fn link(src: &Path, dst: &Path) -> io::Result<()> {
618     let src = try!(to_u16s(src));
619     let dst = try!(to_u16s(dst));
620     try!(cvt(unsafe {
621         c::CreateHardLinkW(dst.as_ptr(), src.as_ptr(), ptr::null_mut())
622     }));
623     Ok(())
624 }
625
626 pub fn stat(path: &Path) -> io::Result<FileAttr> {
627     let mut opts = OpenOptions::new();
628     // No read or write permissions are necessary
629     opts.access_mode(0);
630     // This flag is so we can open directories too
631     opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS);
632     let file = try!(File::open(path, &opts));
633     file.file_attr()
634 }
635
636 pub fn lstat(path: &Path) -> io::Result<FileAttr> {
637     let mut opts = OpenOptions::new();
638     // No read or write permissions are necessary
639     opts.access_mode(0);
640     opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS | c::FILE_FLAG_OPEN_REPARSE_POINT);
641     let file = try!(File::open(path, &opts));
642     file.file_attr()
643 }
644
645 pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
646     let p = try!(to_u16s(p));
647     unsafe {
648         try!(cvt(c::SetFileAttributesW(p.as_ptr(), perm.attrs)));
649         Ok(())
650     }
651 }
652
653 fn get_path(f: &File) -> io::Result<PathBuf> {
654     super::fill_utf16_buf(|buf, sz| unsafe {
655         c::GetFinalPathNameByHandleW(f.handle.raw(), buf, sz,
656                                      c::VOLUME_NAME_DOS)
657     }, |buf| {
658         PathBuf::from(OsString::from_wide(buf))
659     })
660 }
661
662 pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
663     let mut opts = OpenOptions::new();
664     // No read or write permissions are necessary
665     opts.access_mode(0);
666     // This flag is so we can open directories too
667     opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS);
668     let f = try!(File::open(p, &opts));
669     get_path(&f)
670 }
671
672 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
673     unsafe extern "system" fn callback(
674         _TotalFileSize: c::LARGE_INTEGER,
675         TotalBytesTransferred: c::LARGE_INTEGER,
676         _StreamSize: c::LARGE_INTEGER,
677         _StreamBytesTransferred: c::LARGE_INTEGER,
678         _dwStreamNumber: c::DWORD,
679         _dwCallbackReason: c::DWORD,
680         _hSourceFile: c::HANDLE,
681         _hDestinationFile: c::HANDLE,
682         lpData: c::LPVOID,
683     ) -> c::DWORD {
684         *(lpData as *mut i64) = TotalBytesTransferred;
685         c::PROGRESS_CONTINUE
686     }
687     let pfrom = try!(to_u16s(from));
688     let pto = try!(to_u16s(to));
689     let mut size = 0i64;
690     try!(cvt(unsafe {
691         c::CopyFileExW(pfrom.as_ptr(), pto.as_ptr(), Some(callback),
692                        &mut size as *mut _ as *mut _, ptr::null_mut(), 0)
693     }));
694     Ok(size as u64)
695 }
696
697 #[allow(dead_code)]
698 pub fn symlink_junction<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
699     symlink_junction_inner(src.as_ref(), dst.as_ref())
700 }
701
702 // Creating a directory junction on windows involves dealing with reparse
703 // points and the DeviceIoControl function, and this code is a skeleton of
704 // what can be found here:
705 //
706 // http://www.flexhex.com/docs/articles/hard-links.phtml
707 #[allow(dead_code)]
708 fn symlink_junction_inner(target: &Path, junction: &Path) -> io::Result<()> {
709     let d = DirBuilder::new();
710     try!(d.mkdir(&junction));
711
712     let mut opts = OpenOptions::new();
713     opts.write(true);
714     opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT |
715                       c::FILE_FLAG_BACKUP_SEMANTICS);
716     let f = try!(File::open(junction, &opts));
717     let h = f.handle().raw();
718
719     unsafe {
720         let mut data = [0u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
721         let mut db = data.as_mut_ptr()
722                         as *mut c::REPARSE_MOUNTPOINT_DATA_BUFFER;
723         let buf = &mut (*db).ReparseTarget as *mut _;
724         let mut i = 0;
725         // FIXME: this conversion is very hacky
726         let v = br"\??\";
727         let v = v.iter().map(|x| *x as u16);
728         for c in v.chain(target.as_os_str().encode_wide()) {
729             *buf.offset(i) = c;
730             i += 1;
731         }
732         *buf.offset(i) = 0;
733         i += 1;
734         (*db).ReparseTag = c::IO_REPARSE_TAG_MOUNT_POINT;
735         (*db).ReparseTargetMaximumLength = (i * 2) as c::WORD;
736         (*db).ReparseTargetLength = ((i - 1) * 2) as c::WORD;
737         (*db).ReparseDataLength =
738                 (*db).ReparseTargetLength as c::DWORD + 12;
739
740         let mut ret = 0;
741         cvt(c::DeviceIoControl(h as *mut _,
742                                c::FSCTL_SET_REPARSE_POINT,
743                                data.as_ptr() as *mut _,
744                                (*db).ReparseDataLength + 8,
745                                ptr::null_mut(), 0,
746                                &mut ret,
747                                ptr::null_mut())).map(|_| ())
748     }
749 }