]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/windows/fs.rs
Add File::try_clone
[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::{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     data: c::WIN32_FILE_ATTRIBUTE_DATA,
33     reparse_tag: c::DWORD,
34 }
35
36 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
37 pub enum FileType {
38     Dir, File, Symlink, ReparsePoint, MountPoint,
39 }
40
41 pub struct ReadDir {
42     handle: FindNextFileHandle,
43     root: Arc<PathBuf>,
44     first: Option<c::WIN32_FIND_DATAW>,
45 }
46
47 struct FindNextFileHandle(c::HANDLE);
48
49 unsafe impl Send for FindNextFileHandle {}
50 unsafe impl Sync for FindNextFileHandle {}
51
52 pub struct DirEntry {
53     root: Arc<PathBuf>,
54     data: c::WIN32_FIND_DATAW,
55 }
56
57 #[derive(Clone)]
58 pub struct OpenOptions {
59     // generic
60     read: bool,
61     write: bool,
62     append: bool,
63     truncate: bool,
64     create: bool,
65     create_new: bool,
66     // system-specific
67     custom_flags: u32,
68     access_mode: Option<c::DWORD>,
69     attributes: c::DWORD,
70     share_mode: c::DWORD,
71     security_qos_flags: c::DWORD,
72     security_attributes: usize, // FIXME: should be a reference
73 }
74
75 #[derive(Clone, PartialEq, Eq, Debug)]
76 pub struct FilePermissions { attrs: c::DWORD }
77
78 pub struct DirBuilder;
79
80 impl Iterator for ReadDir {
81     type Item = io::Result<DirEntry>;
82     fn next(&mut self) -> Option<io::Result<DirEntry>> {
83         if let Some(first) = self.first.take() {
84             if let Some(e) = DirEntry::new(&self.root, &first) {
85                 return Some(Ok(e));
86             }
87         }
88         unsafe {
89             let mut wfd = mem::zeroed();
90             loop {
91                 if c::FindNextFileW(self.handle.0, &mut wfd) == 0 {
92                     if c::GetLastError() == c::ERROR_NO_MORE_FILES {
93                         return None
94                     } else {
95                         return Some(Err(Error::last_os_error()))
96                     }
97                 }
98                 if let Some(e) = DirEntry::new(&self.root, &wfd) {
99                     return Some(Ok(e))
100                 }
101             }
102         }
103     }
104 }
105
106 impl Drop for FindNextFileHandle {
107     fn drop(&mut self) {
108         let r = unsafe { c::FindClose(self.0) };
109         debug_assert!(r != 0);
110     }
111 }
112
113 impl DirEntry {
114     fn new(root: &Arc<PathBuf>, wfd: &c::WIN32_FIND_DATAW) -> Option<DirEntry> {
115         match &wfd.cFileName[0..3] {
116             // check for '.' and '..'
117             [46, 0, ..] |
118             [46, 46, 0, ..] => return None,
119             _ => {}
120         }
121
122         Some(DirEntry {
123             root: root.clone(),
124             data: *wfd,
125         })
126     }
127
128     pub fn path(&self) -> PathBuf {
129         self.root.join(&self.file_name())
130     }
131
132     pub fn file_name(&self) -> OsString {
133         let filename = super::truncate_utf16_at_nul(&self.data.cFileName);
134         OsString::from_wide(filename)
135     }
136
137     pub fn file_type(&self) -> io::Result<FileType> {
138         Ok(FileType::new(self.data.dwFileAttributes,
139                          /* reparse_tag = */ self.data.dwReserved0))
140     }
141
142     pub fn metadata(&self) -> io::Result<FileAttr> {
143         Ok(FileAttr {
144             data: c::WIN32_FILE_ATTRIBUTE_DATA {
145                 dwFileAttributes: self.data.dwFileAttributes,
146                 ftCreationTime: self.data.ftCreationTime,
147                 ftLastAccessTime: self.data.ftLastAccessTime,
148                 ftLastWriteTime: self.data.ftLastWriteTime,
149                 nFileSizeHigh: self.data.nFileSizeHigh,
150                 nFileSizeLow: self.data.nFileSizeLow,
151             },
152             reparse_tag: self.data.dwReserved0,
153         })
154     }
155 }
156
157 impl OpenOptions {
158     pub fn new() -> OpenOptions {
159         OpenOptions {
160             // generic
161             read: false,
162             write: false,
163             append: false,
164             truncate: false,
165             create: false,
166             create_new: false,
167             // system-specific
168             custom_flags: 0,
169             access_mode: None,
170             share_mode: c::FILE_SHARE_READ | c::FILE_SHARE_WRITE | c::FILE_SHARE_DELETE,
171             attributes: 0,
172             security_qos_flags: 0,
173             security_attributes: 0,
174         }
175     }
176
177     pub fn read(&mut self, read: bool) { self.read = read; }
178     pub fn write(&mut self, write: bool) { self.write = write; }
179     pub fn append(&mut self, append: bool) { self.append = append; }
180     pub fn truncate(&mut self, truncate: bool) { self.truncate = truncate; }
181     pub fn create(&mut self, create: bool) { self.create = create; }
182     pub fn create_new(&mut self, create_new: bool) { self.create_new = create_new; }
183
184     pub fn custom_flags(&mut self, flags: u32) { self.custom_flags = flags; }
185     pub fn access_mode(&mut self, access_mode: u32) { self.access_mode = Some(access_mode); }
186     pub fn share_mode(&mut self, share_mode: u32) { self.share_mode = share_mode; }
187     pub fn attributes(&mut self, attrs: u32) { self.attributes = attrs; }
188     pub fn security_qos_flags(&mut self, flags: u32) { self.security_qos_flags = flags; }
189     pub fn security_attributes(&mut self, attrs: c::LPSECURITY_ATTRIBUTES) {
190         self.security_attributes = attrs as usize;
191     }
192
193     fn get_access_mode(&self) -> io::Result<c::DWORD> {
194         const ERROR_INVALID_PARAMETER: i32 = 87;
195
196         match (self.read, self.write, self.append, self.access_mode) {
197             (_, _, _, Some(mode)) => Ok(mode),
198             (true,  false, false, None) => Ok(c::GENERIC_READ),
199             (false, true,  false, None) => Ok(c::GENERIC_WRITE),
200             (true,  true,  false, None) => Ok(c::GENERIC_READ | c::GENERIC_WRITE),
201             (false, _,     true,  None) => Ok(c::FILE_GENERIC_WRITE & !c::FILE_WRITE_DATA),
202             (true,  _,     true,  None) => Ok(c::GENERIC_READ |
203                                               (c::FILE_GENERIC_WRITE & !c::FILE_WRITE_DATA)),
204             (false, false, false, None) => Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER)),
205         }
206     }
207
208     fn get_creation_mode(&self) -> io::Result<c::DWORD> {
209         const ERROR_INVALID_PARAMETER: i32 = 87;
210
211         match (self.write, self.append) {
212             (true, false) => {}
213             (false, false) =>
214                 if self.truncate || self.create || self.create_new {
215                     return Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER));
216                 },
217             (_, true) =>
218                 if self.truncate && !self.create_new {
219                     return Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER));
220                 },
221         }
222
223         Ok(match (self.create, self.truncate, self.create_new) {
224                 (false, false, false) => c::OPEN_EXISTING,
225                 (true,  false, false) => c::OPEN_ALWAYS,
226                 (false, true,  false) => c::TRUNCATE_EXISTING,
227                 (true,  true,  false) => c::CREATE_ALWAYS,
228                 (_,      _,    true)  => c::CREATE_NEW,
229            })
230     }
231
232     fn get_flags_and_attributes(&self) -> c::DWORD {
233         self.custom_flags |
234         self.attributes |
235         self.security_qos_flags |
236         if self.security_qos_flags != 0 { c::SECURITY_SQOS_PRESENT } else { 0 } |
237         if self.create_new { c::FILE_FLAG_OPEN_REPARSE_POINT } else { 0 }
238     }
239 }
240
241 impl File {
242     fn open_reparse_point(path: &Path, write: bool) -> io::Result<File> {
243         let mut opts = OpenOptions::new();
244         opts.read(!write);
245         opts.write(write);
246         opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT |
247                           c::FILE_FLAG_BACKUP_SEMANTICS);
248         File::open(path, &opts)
249     }
250
251     pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
252         let path = try!(to_u16s(path));
253         let handle = unsafe {
254             c::CreateFileW(path.as_ptr(),
255                            try!(opts.get_access_mode()),
256                            opts.share_mode,
257                            opts.security_attributes as *mut _,
258                            try!(opts.get_creation_mode()),
259                            opts.get_flags_and_attributes(),
260                            ptr::null_mut())
261         };
262         if handle == c::INVALID_HANDLE_VALUE {
263             Err(Error::last_os_error())
264         } else {
265             Ok(File { handle: Handle::new(handle) })
266         }
267     }
268
269     pub fn fsync(&self) -> io::Result<()> {
270         try!(cvt(unsafe { c::FlushFileBuffers(self.handle.raw()) }));
271         Ok(())
272     }
273
274     pub fn datasync(&self) -> io::Result<()> { self.fsync() }
275
276     pub fn truncate(&self, size: u64) -> io::Result<()> {
277         let mut info = c::FILE_END_OF_FILE_INFO {
278             EndOfFile: size as c::LARGE_INTEGER,
279         };
280         let size = mem::size_of_val(&info);
281         try!(cvt(unsafe {
282             c::SetFileInformationByHandle(self.handle.raw(),
283                                           c::FileEndOfFileInfo,
284                                           &mut info as *mut _ as *mut _,
285                                           size as c::DWORD)
286         }));
287         Ok(())
288     }
289
290     pub fn file_attr(&self) -> io::Result<FileAttr> {
291         unsafe {
292             let mut info: c::BY_HANDLE_FILE_INFORMATION = mem::zeroed();
293             try!(cvt(c::GetFileInformationByHandle(self.handle.raw(),
294                                                    &mut info)));
295             let mut attr = FileAttr {
296                 data: c::WIN32_FILE_ATTRIBUTE_DATA {
297                     dwFileAttributes: info.dwFileAttributes,
298                     ftCreationTime: info.ftCreationTime,
299                     ftLastAccessTime: info.ftLastAccessTime,
300                     ftLastWriteTime: info.ftLastWriteTime,
301                     nFileSizeHigh: info.nFileSizeHigh,
302                     nFileSizeLow: info.nFileSizeLow,
303                 },
304                 reparse_tag: 0,
305             };
306             if attr.is_reparse_point() {
307                 let mut b = [0; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
308                 if let Ok((_, buf)) = self.reparse_point(&mut b) {
309                     attr.reparse_tag = buf.ReparseTag;
310                 }
311             }
312             Ok(attr)
313         }
314     }
315
316     pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
317         self.handle.read(buf)
318     }
319
320     pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
321         self.handle.write(buf)
322     }
323
324     pub fn flush(&self) -> io::Result<()> { Ok(()) }
325
326     pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
327         let (whence, pos) = match pos {
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         try!(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: try!(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             try!(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) = try!(self.reparse_point(&mut space));
373         if buf.ReparseTag != c::IO_REPARSE_TAG_SYMLINK {
374             return Err(io::Error::new(io::ErrorKind::Other, "not a symlink"))
375         }
376
377         unsafe {
378             let info: *const c::SYMBOLIC_LINK_REPARSE_BUFFER =
379                     &buf.rest as *const _ as *const _;
380             let path_buffer = &(*info).PathBuffer as *const _ as *const u16;
381             let subst_off = (*info).SubstituteNameOffset / 2;
382             let subst_ptr = path_buffer.offset(subst_off as isize);
383             let subst_len = (*info).SubstituteNameLength / 2;
384             let subst = slice::from_raw_parts(subst_ptr, subst_len as usize);
385
386             Ok(PathBuf::from(OsString::from_wide(subst)))
387         }
388     }
389 }
390
391 impl FromInner<c::HANDLE> for File {
392     fn from_inner(handle: c::HANDLE) -> File {
393         File { handle: Handle::new(handle) }
394     }
395 }
396
397 impl fmt::Debug for File {
398     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
399         // FIXME(#24570): add more info here (e.g. mode)
400         let mut b = f.debug_struct("File");
401         b.field("handle", &self.handle.raw());
402         if let Ok(path) = get_path(&self) {
403             b.field("path", &path);
404         }
405         b.finish()
406     }
407 }
408
409 impl FileAttr {
410     pub fn size(&self) -> u64 {
411         ((self.data.nFileSizeHigh as u64) << 32) | (self.data.nFileSizeLow as u64)
412     }
413
414     pub fn perm(&self) -> FilePermissions {
415         FilePermissions { attrs: self.data.dwFileAttributes }
416     }
417
418     pub fn attrs(&self) -> u32 { self.data.dwFileAttributes as u32 }
419
420     pub fn file_type(&self) -> FileType {
421         FileType::new(self.data.dwFileAttributes, self.reparse_tag)
422     }
423
424     pub fn created(&self) -> u64 { self.to_u64(&self.data.ftCreationTime) }
425     pub fn accessed(&self) -> u64 { self.to_u64(&self.data.ftLastAccessTime) }
426     pub fn modified(&self) -> u64 { self.to_u64(&self.data.ftLastWriteTime) }
427
428     fn to_u64(&self, ft: &c::FILETIME) -> u64 {
429         (ft.dwLowDateTime as u64) | ((ft.dwHighDateTime as u64) << 32)
430     }
431
432     fn is_reparse_point(&self) -> bool {
433         self.data.dwFileAttributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0
434     }
435 }
436
437 impl FilePermissions {
438     pub fn readonly(&self) -> bool {
439         self.attrs & c::FILE_ATTRIBUTE_READONLY != 0
440     }
441
442     pub fn set_readonly(&mut self, readonly: bool) {
443         if readonly {
444             self.attrs |= c::FILE_ATTRIBUTE_READONLY;
445         } else {
446             self.attrs &= !c::FILE_ATTRIBUTE_READONLY;
447         }
448     }
449 }
450
451 impl FileType {
452     fn new(attrs: c::DWORD, reparse_tag: c::DWORD) -> FileType {
453         if attrs & c::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
454             match reparse_tag {
455                 c::IO_REPARSE_TAG_SYMLINK => FileType::Symlink,
456                 c::IO_REPARSE_TAG_MOUNT_POINT => FileType::MountPoint,
457                 _ => FileType::ReparsePoint,
458             }
459         } else if attrs & c::FILE_ATTRIBUTE_DIRECTORY != 0 {
460             FileType::Dir
461         } else {
462             FileType::File
463         }
464     }
465
466     pub fn is_dir(&self) -> bool { *self == FileType::Dir }
467     pub fn is_file(&self) -> bool { *self == FileType::File }
468     pub fn is_symlink(&self) -> bool {
469         *self == FileType::Symlink || *self == FileType::MountPoint
470     }
471 }
472
473 impl DirBuilder {
474     pub fn new() -> DirBuilder { DirBuilder }
475
476     pub fn mkdir(&self, p: &Path) -> io::Result<()> {
477         let p = try!(to_u16s(p));
478         try!(cvt(unsafe {
479             c::CreateDirectoryW(p.as_ptr(), ptr::null_mut())
480         }));
481         Ok(())
482     }
483 }
484
485 pub fn readdir(p: &Path) -> io::Result<ReadDir> {
486     let root = p.to_path_buf();
487     let star = p.join("*");
488     let path = try!(to_u16s(&star));
489
490     unsafe {
491         let mut wfd = mem::zeroed();
492         let find_handle = c::FindFirstFileW(path.as_ptr(), &mut wfd);
493         if find_handle != c::INVALID_HANDLE_VALUE {
494             Ok(ReadDir {
495                 handle: FindNextFileHandle(find_handle),
496                 root: Arc::new(root),
497                 first: Some(wfd),
498             })
499         } else {
500             Err(Error::last_os_error())
501         }
502     }
503 }
504
505 pub fn unlink(p: &Path) -> io::Result<()> {
506     let p_u16s = try!(to_u16s(p));
507     try!(cvt(unsafe { c::DeleteFileW(p_u16s.as_ptr()) }));
508     Ok(())
509 }
510
511 pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
512     let old = try!(to_u16s(old));
513     let new = try!(to_u16s(new));
514     try!(cvt(unsafe {
515         c::MoveFileExW(old.as_ptr(), new.as_ptr(), c::MOVEFILE_REPLACE_EXISTING)
516     }));
517     Ok(())
518 }
519
520 pub fn rmdir(p: &Path) -> io::Result<()> {
521     let p = try!(to_u16s(p));
522     try!(cvt(unsafe { c::RemoveDirectoryW(p.as_ptr()) }));
523     Ok(())
524 }
525
526 pub fn readlink(p: &Path) -> io::Result<PathBuf> {
527     let file = try!(File::open_reparse_point(p, false));
528     file.readlink()
529 }
530
531 pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
532     symlink_inner(src, dst, false)
533 }
534
535 pub fn symlink_inner(src: &Path, dst: &Path, dir: bool) -> io::Result<()> {
536     let src = try!(to_u16s(src));
537     let dst = try!(to_u16s(dst));
538     let flags = if dir { c::SYMBOLIC_LINK_FLAG_DIRECTORY } else { 0 };
539     try!(cvt(unsafe {
540         c::CreateSymbolicLinkW(dst.as_ptr(), src.as_ptr(), flags) as c::BOOL
541     }));
542     Ok(())
543 }
544
545 pub fn link(src: &Path, dst: &Path) -> io::Result<()> {
546     let src = try!(to_u16s(src));
547     let dst = try!(to_u16s(dst));
548     try!(cvt(unsafe {
549         c::CreateHardLinkW(dst.as_ptr(), src.as_ptr(), ptr::null_mut())
550     }));
551     Ok(())
552 }
553
554 pub fn stat(p: &Path) -> io::Result<FileAttr> {
555     let attr = try!(lstat(p));
556
557     // If this is a reparse point, then we need to reopen the file to get the
558     // actual destination. We also pass the FILE_FLAG_BACKUP_SEMANTICS flag to
559     // ensure that we can open directories (this path may be a directory
560     // junction). Once the file is opened we ask the opened handle what its
561     // metadata information is.
562     if attr.is_reparse_point() {
563         let mut opts = OpenOptions::new();
564         // No read or write permissions are necessary
565         opts.access_mode(0);
566         // This flag is so we can open directories too
567         opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS);
568         let file = try!(File::open(p, &opts));
569         file.file_attr()
570     } else {
571         Ok(attr)
572     }
573 }
574
575 pub fn lstat(p: &Path) -> io::Result<FileAttr> {
576     let u16s = try!(to_u16s(p));
577     unsafe {
578         let mut attr: FileAttr = mem::zeroed();
579         try!(cvt(c::GetFileAttributesExW(u16s.as_ptr(),
580                                          c::GetFileExInfoStandard,
581                                          &mut attr.data as *mut _ as *mut _)));
582         if attr.is_reparse_point() {
583             attr.reparse_tag = File::open_reparse_point(p, false).and_then(|f| {
584                 let mut b = [0; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
585                 f.reparse_point(&mut b).map(|(_, b)| b.ReparseTag)
586             }).unwrap_or(0);
587         }
588         Ok(attr)
589     }
590 }
591
592 pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
593     let p = try!(to_u16s(p));
594     unsafe {
595         try!(cvt(c::SetFileAttributesW(p.as_ptr(), perm.attrs)));
596         Ok(())
597     }
598 }
599
600 fn get_path(f: &File) -> io::Result<PathBuf> {
601     super::fill_utf16_buf(|buf, sz| unsafe {
602         c::GetFinalPathNameByHandleW(f.handle.raw(), buf, sz,
603                                      c::VOLUME_NAME_DOS)
604     }, |buf| {
605         PathBuf::from(OsString::from_wide(buf))
606     })
607 }
608
609 pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
610     let mut opts = OpenOptions::new();
611     // No read or write permissions are necessary
612     opts.access_mode(0);
613     // This flag is so we can open directories too
614     opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS);
615     let f = try!(File::open(p, &opts));
616     get_path(&f)
617 }
618
619 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
620     unsafe extern "system" fn callback(
621         _TotalFileSize: c::LARGE_INTEGER,
622         TotalBytesTransferred: c::LARGE_INTEGER,
623         _StreamSize: c::LARGE_INTEGER,
624         _StreamBytesTransferred: c::LARGE_INTEGER,
625         _dwStreamNumber: c::DWORD,
626         _dwCallbackReason: c::DWORD,
627         _hSourceFile: c::HANDLE,
628         _hDestinationFile: c::HANDLE,
629         lpData: c::LPVOID,
630     ) -> c::DWORD {
631         *(lpData as *mut i64) = TotalBytesTransferred;
632         c::PROGRESS_CONTINUE
633     }
634     let pfrom = try!(to_u16s(from));
635     let pto = try!(to_u16s(to));
636     let mut size = 0i64;
637     try!(cvt(unsafe {
638         c::CopyFileExW(pfrom.as_ptr(), pto.as_ptr(), Some(callback),
639                        &mut size as *mut _ as *mut _, ptr::null_mut(), 0)
640     }));
641     Ok(size as u64)
642 }
643
644 #[test]
645 fn directory_junctions_are_directories() {
646     use ffi::OsStr;
647     use env;
648     use rand::{self, StdRng, Rng};
649     use vec::Vec;
650
651     macro_rules! t {
652         ($e:expr) => (match $e {
653             Ok(e) => e,
654             Err(e) => panic!("{} failed with: {}", stringify!($e), e),
655         })
656     }
657
658     let d = DirBuilder::new();
659     let p = env::temp_dir();
660     let mut r = rand::thread_rng();
661     let ret = p.join(&format!("rust-{}", r.next_u32()));
662     let foo = ret.join("foo");
663     let bar = ret.join("bar");
664     t!(d.mkdir(&ret));
665     t!(d.mkdir(&foo));
666     t!(d.mkdir(&bar));
667
668     t!(create_junction(&bar, &foo));
669     let metadata = stat(&bar);
670     t!(delete_junction(&bar));
671
672     t!(rmdir(&foo));
673     t!(rmdir(&bar));
674     t!(rmdir(&ret));
675
676     let metadata = t!(metadata);
677     assert!(metadata.file_type().is_dir());
678
679     // Creating a directory junction on windows involves dealing with reparse
680     // points and the DeviceIoControl function, and this code is a skeleton of
681     // what can be found here:
682     //
683     // http://www.flexhex.com/docs/articles/hard-links.phtml
684     fn create_junction(src: &Path, dst: &Path) -> io::Result<()> {
685         let f = try!(opendir(src, true));
686         let h = f.handle().raw();
687
688         unsafe {
689             let mut data = [0u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
690             let mut db = data.as_mut_ptr()
691                             as *mut c::REPARSE_MOUNTPOINT_DATA_BUFFER;
692             let mut buf = &mut (*db).ReparseTarget as *mut _;
693             let mut i = 0;
694             let v = br"\??\";
695             let v = v.iter().map(|x| *x as u16);
696             for c in v.chain(dst.as_os_str().encode_wide()) {
697                 *buf.offset(i) = c;
698                 i += 1;
699             }
700             *buf.offset(i) = 0;
701             i += 1;
702             (*db).ReparseTag = c::IO_REPARSE_TAG_MOUNT_POINT;
703             (*db).ReparseTargetMaximumLength = (i * 2) as c::WORD;
704             (*db).ReparseTargetLength = ((i - 1) * 2) as c::WORD;
705             (*db).ReparseDataLength =
706                     (*db).ReparseTargetLength as c::DWORD + 12;
707
708             let mut ret = 0;
709             cvt(c::DeviceIoControl(h as *mut _,
710                                    c::FSCTL_SET_REPARSE_POINT,
711                                    data.as_ptr() as *mut _,
712                                    (*db).ReparseDataLength + 8,
713                                    ptr::null_mut(), 0,
714                                    &mut ret,
715                                    ptr::null_mut())).map(|_| ())
716         }
717     }
718
719     fn opendir(p: &Path, write: bool) -> io::Result<File> {
720         unsafe {
721             let mut token = ptr::null_mut();
722             let mut tp: c::TOKEN_PRIVILEGES = mem::zeroed();
723             try!(cvt(c::OpenProcessToken(c::GetCurrentProcess(),
724                                          c::TOKEN_ADJUST_PRIVILEGES,
725                                          &mut token)));
726             let name: &OsStr = if write {
727                 "SeRestorePrivilege".as_ref()
728             } else {
729                 "SeBackupPrivilege".as_ref()
730             };
731             let name = name.encode_wide().chain(Some(0)).collect::<Vec<_>>();
732             try!(cvt(c::LookupPrivilegeValueW(ptr::null(),
733                                               name.as_ptr(),
734                                               &mut tp.Privileges[0].Luid)));
735             tp.PrivilegeCount = 1;
736             tp.Privileges[0].Attributes = c::SE_PRIVILEGE_ENABLED;
737             let size = mem::size_of::<c::TOKEN_PRIVILEGES>() as c::DWORD;
738             try!(cvt(c::AdjustTokenPrivileges(token, c::FALSE, &mut tp, size,
739                                               ptr::null_mut(), ptr::null_mut())));
740             try!(cvt(c::CloseHandle(token)));
741
742             File::open_reparse_point(p, write)
743         }
744     }
745
746     fn delete_junction(p: &Path) -> io::Result<()> {
747         unsafe {
748             let f = try!(opendir(p, true));
749             let h = f.handle().raw();
750             let mut data = [0u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
751             let mut db = data.as_mut_ptr()
752                             as *mut c::REPARSE_MOUNTPOINT_DATA_BUFFER;
753             (*db).ReparseTag = c::IO_REPARSE_TAG_MOUNT_POINT;
754             let mut bytes = 0;
755             cvt(c::DeviceIoControl(h as *mut _,
756                                    c::FSCTL_DELETE_REPARSE_POINT,
757                                    data.as_ptr() as *mut _,
758                                    (*db).ReparseDataLength + 8,
759                                    ptr::null_mut(), 0,
760                                    &mut bytes,
761                                    ptr::null_mut())).map(|_| ())
762         }
763     }
764 }