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