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