]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/fs.rs
Implement reading and writing atomically at certain offsets
[rust.git] / src / libstd / sys / unix / fs.rs
1 // Copyright 2013-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::unix::prelude::*;
12
13 use ffi::{CString, CStr, OsString, OsStr};
14 use fmt;
15 use io::{self, Error, ErrorKind, SeekFrom};
16 use libc::{self, c_int, mode_t};
17 use mem;
18 use path::{Path, PathBuf};
19 use ptr;
20 use sync::Arc;
21 use sys::fd::FileDesc;
22 use sys::time::SystemTime;
23 use sys::{cvt, cvt_r};
24 use sys_common::{AsInner, FromInner};
25
26 #[cfg(any(target_os = "linux", target_os = "emscripten"))]
27 use libc::{stat64, fstat64, lstat64, off64_t, ftruncate64, lseek64, dirent64, readdir64_r, open64};
28 #[cfg(target_os = "android")]
29 use libc::{stat as stat64, fstat as fstat64, lstat as lstat64, lseek64,
30            dirent as dirent64, open as open64};
31 #[cfg(not(any(target_os = "linux",
32               target_os = "emscripten",
33               target_os = "android")))]
34 use libc::{stat as stat64, fstat as fstat64, lstat as lstat64, off_t as off64_t,
35            ftruncate as ftruncate64, lseek as lseek64, dirent as dirent64, open as open64};
36 #[cfg(not(any(target_os = "linux",
37               target_os = "emscripten",
38               target_os = "solaris")))]
39 use libc::{readdir_r as readdir64_r};
40
41 pub struct File(FileDesc);
42
43 #[derive(Clone)]
44 pub struct FileAttr {
45     stat: stat64,
46 }
47
48 pub struct ReadDir {
49     dirp: Dir,
50     root: Arc<PathBuf>,
51 }
52
53 struct Dir(*mut libc::DIR);
54
55 unsafe impl Send for Dir {}
56 unsafe impl Sync for Dir {}
57
58 pub struct DirEntry {
59     entry: dirent64,
60     root: Arc<PathBuf>,
61     // We need to store an owned copy of the directory name
62     // on Solaris because a) it uses a zero-length array to
63     // store the name, b) its lifetime between readdir calls
64     // is not guaranteed.
65     #[cfg(target_os = "solaris")]
66     name: Box<[u8]>
67 }
68
69 #[derive(Clone)]
70 pub struct OpenOptions {
71     // generic
72     read: bool,
73     write: bool,
74     append: bool,
75     truncate: bool,
76     create: bool,
77     create_new: bool,
78     // system-specific
79     custom_flags: i32,
80     mode: mode_t,
81 }
82
83 #[derive(Clone, PartialEq, Eq, Debug)]
84 pub struct FilePermissions { mode: mode_t }
85
86 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
87 pub struct FileType { mode: mode_t }
88
89 pub struct DirBuilder { mode: mode_t }
90
91 impl FileAttr {
92     pub fn size(&self) -> u64 { self.stat.st_size as u64 }
93     pub fn perm(&self) -> FilePermissions {
94         FilePermissions { mode: (self.stat.st_mode as mode_t) & 0o777 }
95     }
96
97     pub fn file_type(&self) -> FileType {
98         FileType { mode: self.stat.st_mode as mode_t }
99     }
100 }
101
102 #[cfg(target_os = "netbsd")]
103 impl FileAttr {
104     pub fn modified(&self) -> io::Result<SystemTime> {
105         Ok(SystemTime::from(libc::timespec {
106             tv_sec: self.stat.st_mtime as libc::time_t,
107             tv_nsec: self.stat.st_mtimensec as libc::c_long,
108         }))
109     }
110
111     pub fn accessed(&self) -> io::Result<SystemTime> {
112         Ok(SystemTime::from(libc::timespec {
113             tv_sec: self.stat.st_atime as libc::time_t,
114             tv_nsec: self.stat.st_atimensec as libc::c_long,
115         }))
116     }
117
118     pub fn created(&self) -> io::Result<SystemTime> {
119         Ok(SystemTime::from(libc::timespec {
120             tv_sec: self.stat.st_birthtime as libc::time_t,
121             tv_nsec: self.stat.st_birthtimensec as libc::c_long,
122         }))
123     }
124 }
125
126 #[cfg(not(target_os = "netbsd"))]
127 impl FileAttr {
128     pub fn modified(&self) -> io::Result<SystemTime> {
129         Ok(SystemTime::from(libc::timespec {
130             tv_sec: self.stat.st_mtime as libc::time_t,
131             tv_nsec: self.stat.st_mtime_nsec as libc::c_long,
132         }))
133     }
134
135     pub fn accessed(&self) -> io::Result<SystemTime> {
136         Ok(SystemTime::from(libc::timespec {
137             tv_sec: self.stat.st_atime as libc::time_t,
138             tv_nsec: self.stat.st_atime_nsec as libc::c_long,
139         }))
140     }
141
142     #[cfg(any(target_os = "bitrig",
143               target_os = "freebsd",
144               target_os = "openbsd",
145               target_os = "macos",
146               target_os = "ios"))]
147     pub fn created(&self) -> io::Result<SystemTime> {
148         Ok(SystemTime::from(libc::timespec {
149             tv_sec: self.stat.st_birthtime as libc::time_t,
150             tv_nsec: self.stat.st_birthtime_nsec as libc::c_long,
151         }))
152     }
153
154     #[cfg(not(any(target_os = "bitrig",
155                   target_os = "freebsd",
156                   target_os = "openbsd",
157                   target_os = "macos",
158                   target_os = "ios")))]
159     pub fn created(&self) -> io::Result<SystemTime> {
160         Err(io::Error::new(io::ErrorKind::Other,
161                            "creation time is not available on this platform \
162                             currently"))
163     }
164 }
165
166 impl AsInner<stat64> for FileAttr {
167     fn as_inner(&self) -> &stat64 { &self.stat }
168 }
169
170 impl FilePermissions {
171     pub fn readonly(&self) -> bool { self.mode & 0o222 == 0 }
172     pub fn set_readonly(&mut self, readonly: bool) {
173         if readonly {
174             self.mode &= !0o222;
175         } else {
176             self.mode |= 0o222;
177         }
178     }
179     pub fn mode(&self) -> u32 { self.mode as u32 }
180 }
181
182 impl FileType {
183     pub fn is_dir(&self) -> bool { self.is(libc::S_IFDIR) }
184     pub fn is_file(&self) -> bool { self.is(libc::S_IFREG) }
185     pub fn is_symlink(&self) -> bool { self.is(libc::S_IFLNK) }
186
187     pub fn is(&self, mode: mode_t) -> bool { self.mode & libc::S_IFMT == mode }
188 }
189
190 impl FromInner<u32> for FilePermissions {
191     fn from_inner(mode: u32) -> FilePermissions {
192         FilePermissions { mode: mode as mode_t }
193     }
194 }
195
196 impl Iterator for ReadDir {
197     type Item = io::Result<DirEntry>;
198
199     #[cfg(target_os = "solaris")]
200     fn next(&mut self) -> Option<io::Result<DirEntry>> {
201         unsafe {
202             loop {
203                 // Although readdir_r(3) would be a correct function to use here because
204                 // of the thread safety, on Illumos the readdir(3C) function is safe to use
205                 // in threaded applications and it is generally preferred over the
206                 // readdir_r(3C) function.
207                 super::os::set_errno(0);
208                 let entry_ptr = libc::readdir(self.dirp.0);
209                 if entry_ptr.is_null() {
210                     // NULL can mean either the end is reached or an error occurred.
211                     // So we had to clear errno beforehand to check for an error now.
212                     return match super::os::errno() {
213                         0 => None,
214                         e => Some(Err(Error::from_raw_os_error(e))),
215                     }
216                 }
217
218                 let name = (*entry_ptr).d_name.as_ptr();
219                 let namelen = libc::strlen(name) as usize;
220
221                 let ret = DirEntry {
222                     entry: *entry_ptr,
223                     name: ::slice::from_raw_parts(name as *const u8,
224                                                   namelen as usize).to_owned().into_boxed_slice(),
225                     root: self.root.clone()
226                 };
227                 if ret.name_bytes() != b"." && ret.name_bytes() != b".." {
228                     return Some(Ok(ret))
229                 }
230             }
231         }
232     }
233
234     #[cfg(not(target_os = "solaris"))]
235     fn next(&mut self) -> Option<io::Result<DirEntry>> {
236         unsafe {
237             let mut ret = DirEntry {
238                 entry: mem::zeroed(),
239                 root: self.root.clone()
240             };
241             let mut entry_ptr = ptr::null_mut();
242             loop {
243                 if readdir64_r(self.dirp.0, &mut ret.entry, &mut entry_ptr) != 0 {
244                     return Some(Err(Error::last_os_error()))
245                 }
246                 if entry_ptr.is_null() {
247                     return None
248                 }
249                 if ret.name_bytes() != b"." && ret.name_bytes() != b".." {
250                     return Some(Ok(ret))
251                 }
252             }
253         }
254     }
255 }
256
257 impl Drop for Dir {
258     fn drop(&mut self) {
259         let r = unsafe { libc::closedir(self.0) };
260         debug_assert_eq!(r, 0);
261     }
262 }
263
264 impl DirEntry {
265     pub fn path(&self) -> PathBuf {
266         self.root.join(OsStr::from_bytes(self.name_bytes()))
267     }
268
269     pub fn file_name(&self) -> OsString {
270         OsStr::from_bytes(self.name_bytes()).to_os_string()
271     }
272
273     pub fn metadata(&self) -> io::Result<FileAttr> {
274         lstat(&self.path())
275     }
276
277     #[cfg(target_os = "solaris")]
278     pub fn file_type(&self) -> io::Result<FileType> {
279         stat(&self.path()).map(|m| m.file_type())
280     }
281
282     #[cfg(target_os = "haiku")]
283     pub fn file_type(&self) -> io::Result<FileType> {
284         lstat(&self.path()).map(|m| m.file_type())
285     }
286
287     #[cfg(not(any(target_os = "solaris", target_os = "haiku")))]
288     pub fn file_type(&self) -> io::Result<FileType> {
289         match self.entry.d_type {
290             libc::DT_CHR => Ok(FileType { mode: libc::S_IFCHR }),
291             libc::DT_FIFO => Ok(FileType { mode: libc::S_IFIFO }),
292             libc::DT_LNK => Ok(FileType { mode: libc::S_IFLNK }),
293             libc::DT_REG => Ok(FileType { mode: libc::S_IFREG }),
294             libc::DT_SOCK => Ok(FileType { mode: libc::S_IFSOCK }),
295             libc::DT_DIR => Ok(FileType { mode: libc::S_IFDIR }),
296             libc::DT_BLK => Ok(FileType { mode: libc::S_IFBLK }),
297             _ => lstat(&self.path()).map(|m| m.file_type()),
298         }
299     }
300
301     #[cfg(any(target_os = "macos",
302               target_os = "ios",
303               target_os = "linux",
304               target_os = "emscripten",
305               target_os = "android",
306               target_os = "solaris",
307               target_os = "haiku"))]
308     pub fn ino(&self) -> u64 {
309         self.entry.d_ino as u64
310     }
311
312     #[cfg(any(target_os = "freebsd",
313               target_os = "openbsd",
314               target_os = "bitrig",
315               target_os = "netbsd",
316               target_os = "dragonfly"))]
317     pub fn ino(&self) -> u64 {
318         self.entry.d_fileno as u64
319     }
320
321     #[cfg(any(target_os = "macos",
322               target_os = "ios",
323               target_os = "netbsd",
324               target_os = "openbsd",
325               target_os = "freebsd",
326               target_os = "dragonfly",
327               target_os = "bitrig"))]
328     fn name_bytes(&self) -> &[u8] {
329         unsafe {
330             ::slice::from_raw_parts(self.entry.d_name.as_ptr() as *const u8,
331                                     self.entry.d_namlen as usize)
332         }
333     }
334     #[cfg(any(target_os = "android",
335               target_os = "linux",
336               target_os = "emscripten",
337               target_os = "haiku"))]
338     fn name_bytes(&self) -> &[u8] {
339         unsafe {
340             CStr::from_ptr(self.entry.d_name.as_ptr()).to_bytes()
341         }
342     }
343     #[cfg(target_os = "solaris")]
344     fn name_bytes(&self) -> &[u8] {
345         &*self.name
346     }
347 }
348
349 impl OpenOptions {
350     pub fn new() -> OpenOptions {
351         OpenOptions {
352             // generic
353             read: false,
354             write: false,
355             append: false,
356             truncate: false,
357             create: false,
358             create_new: false,
359             // system-specific
360             custom_flags: 0,
361             mode: 0o666,
362         }
363     }
364
365     pub fn read(&mut self, read: bool) { self.read = read; }
366     pub fn write(&mut self, write: bool) { self.write = write; }
367     pub fn append(&mut self, append: bool) { self.append = append; }
368     pub fn truncate(&mut self, truncate: bool) { self.truncate = truncate; }
369     pub fn create(&mut self, create: bool) { self.create = create; }
370     pub fn create_new(&mut self, create_new: bool) { self.create_new = create_new; }
371
372     pub fn custom_flags(&mut self, flags: i32) { self.custom_flags = flags; }
373     pub fn mode(&mut self, mode: u32) { self.mode = mode as mode_t; }
374
375     fn get_access_mode(&self) -> io::Result<c_int> {
376         match (self.read, self.write, self.append) {
377             (true,  false, false) => Ok(libc::O_RDONLY),
378             (false, true,  false) => Ok(libc::O_WRONLY),
379             (true,  true,  false) => Ok(libc::O_RDWR),
380             (false, _,     true)  => Ok(libc::O_WRONLY | libc::O_APPEND),
381             (true,  _,     true)  => Ok(libc::O_RDWR | libc::O_APPEND),
382             (false, false, false) => Err(Error::from_raw_os_error(libc::EINVAL)),
383         }
384     }
385
386     fn get_creation_mode(&self) -> io::Result<c_int> {
387         match (self.write, self.append) {
388             (true, false) => {}
389             (false, false) =>
390                 if self.truncate || self.create || self.create_new {
391                     return Err(Error::from_raw_os_error(libc::EINVAL));
392                 },
393             (_, true) =>
394                 if self.truncate && !self.create_new {
395                     return Err(Error::from_raw_os_error(libc::EINVAL));
396                 },
397         }
398
399         Ok(match (self.create, self.truncate, self.create_new) {
400                 (false, false, false) => 0,
401                 (true,  false, false) => libc::O_CREAT,
402                 (false, true,  false) => libc::O_TRUNC,
403                 (true,  true,  false) => libc::O_CREAT | libc::O_TRUNC,
404                 (_,      _,    true)  => libc::O_CREAT | libc::O_EXCL,
405            })
406     }
407 }
408
409 impl File {
410     pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
411         let path = cstr(path)?;
412         File::open_c(&path, opts)
413     }
414
415     pub fn open_c(path: &CStr, opts: &OpenOptions) -> io::Result<File> {
416         let flags = libc::O_CLOEXEC |
417                     opts.get_access_mode()? |
418                     opts.get_creation_mode()? |
419                     (opts.custom_flags as c_int & !libc::O_ACCMODE);
420         let fd = cvt_r(|| unsafe {
421             open64(path.as_ptr(), flags, opts.mode as c_int)
422         })?;
423         let fd = FileDesc::new(fd);
424
425         // Currently the standard library supports Linux 2.6.18 which did not
426         // have the O_CLOEXEC flag (passed above). If we're running on an older
427         // Linux kernel then the flag is just ignored by the OS, so we continue
428         // to explicitly ask for a CLOEXEC fd here.
429         //
430         // The CLOEXEC flag, however, is supported on versions of OSX/BSD/etc
431         // that we support, so we only do this on Linux currently.
432         if cfg!(target_os = "linux") {
433             fd.set_cloexec()?;
434         }
435
436         Ok(File(fd))
437     }
438
439     pub fn file_attr(&self) -> io::Result<FileAttr> {
440         let mut stat: stat64 = unsafe { mem::zeroed() };
441         cvt(unsafe {
442             fstat64(self.0.raw(), &mut stat)
443         })?;
444         Ok(FileAttr { stat: stat })
445     }
446
447     pub fn fsync(&self) -> io::Result<()> {
448         cvt_r(|| unsafe { libc::fsync(self.0.raw()) })?;
449         Ok(())
450     }
451
452     pub fn datasync(&self) -> io::Result<()> {
453         cvt_r(|| unsafe { os_datasync(self.0.raw()) })?;
454         return Ok(());
455
456         #[cfg(any(target_os = "macos", target_os = "ios"))]
457         unsafe fn os_datasync(fd: c_int) -> c_int {
458             libc::fcntl(fd, libc::F_FULLFSYNC)
459         }
460         #[cfg(target_os = "linux")]
461         unsafe fn os_datasync(fd: c_int) -> c_int { libc::fdatasync(fd) }
462         #[cfg(not(any(target_os = "macos",
463                       target_os = "ios",
464                       target_os = "linux")))]
465         unsafe fn os_datasync(fd: c_int) -> c_int { libc::fsync(fd) }
466     }
467
468     pub fn truncate(&self, size: u64) -> io::Result<()> {
469         #[cfg(target_os = "android")]
470         return ::sys::android::ftruncate64(self.0.raw(), size);
471
472         #[cfg(not(target_os = "android"))]
473         return cvt_r(|| unsafe {
474             ftruncate64(self.0.raw(), size as off64_t)
475         }).map(|_| ());
476     }
477
478     pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
479         self.0.read(buf)
480     }
481
482     pub fn read_to_end(&self, buf: &mut Vec<u8>) -> io::Result<usize> {
483         self.0.read_to_end(buf)
484     }
485
486     pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
487         self.0.read_at(buf, offset)
488     }
489
490     pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
491         self.0.write(buf)
492     }
493
494     pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
495         self.0.write_at(buf, offset)
496     }
497
498     pub fn flush(&self) -> io::Result<()> { Ok(()) }
499
500     pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
501         let (whence, pos) = match pos {
502             // Casting to `i64` is fine, too large values will end up as
503             // negative which will cause an error in `lseek64`.
504             SeekFrom::Start(off) => (libc::SEEK_SET, off as i64),
505             SeekFrom::End(off) => (libc::SEEK_END, off),
506             SeekFrom::Current(off) => (libc::SEEK_CUR, off),
507         };
508         let n = cvt(unsafe { lseek64(self.0.raw(), pos, whence) })?;
509         Ok(n as u64)
510     }
511
512     pub fn duplicate(&self) -> io::Result<File> {
513         self.0.duplicate().map(File)
514     }
515
516     pub fn fd(&self) -> &FileDesc { &self.0 }
517
518     pub fn into_fd(self) -> FileDesc { self.0 }
519 }
520
521 impl DirBuilder {
522     pub fn new() -> DirBuilder {
523         DirBuilder { mode: 0o777 }
524     }
525
526     pub fn mkdir(&self, p: &Path) -> io::Result<()> {
527         let p = cstr(p)?;
528         cvt(unsafe { libc::mkdir(p.as_ptr(), self.mode) })?;
529         Ok(())
530     }
531
532     pub fn set_mode(&mut self, mode: u32) {
533         self.mode = mode as mode_t;
534     }
535 }
536
537 fn cstr(path: &Path) -> io::Result<CString> {
538     Ok(CString::new(path.as_os_str().as_bytes())?)
539 }
540
541 impl FromInner<c_int> for File {
542     fn from_inner(fd: c_int) -> File {
543         File(FileDesc::new(fd))
544     }
545 }
546
547 impl fmt::Debug for File {
548     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
549         #[cfg(target_os = "linux")]
550         fn get_path(fd: c_int) -> Option<PathBuf> {
551             let mut p = PathBuf::from("/proc/self/fd");
552             p.push(&fd.to_string());
553             readlink(&p).ok()
554         }
555
556         #[cfg(target_os = "macos")]
557         fn get_path(fd: c_int) -> Option<PathBuf> {
558             // FIXME: The use of PATH_MAX is generally not encouraged, but it
559             // is inevitable in this case because OS X defines `fcntl` with
560             // `F_GETPATH` in terms of `MAXPATHLEN`, and there are no
561             // alternatives. If a better method is invented, it should be used
562             // instead.
563             let mut buf = vec![0;libc::PATH_MAX as usize];
564             let n = unsafe { libc::fcntl(fd, libc::F_GETPATH, buf.as_ptr()) };
565             if n == -1 {
566                 return None;
567             }
568             let l = buf.iter().position(|&c| c == 0).unwrap();
569             buf.truncate(l as usize);
570             buf.shrink_to_fit();
571             Some(PathBuf::from(OsString::from_vec(buf)))
572         }
573
574         #[cfg(not(any(target_os = "linux", target_os = "macos")))]
575         fn get_path(_fd: c_int) -> Option<PathBuf> {
576             // FIXME(#24570): implement this for other Unix platforms
577             None
578         }
579
580         #[cfg(any(target_os = "linux", target_os = "macos"))]
581         fn get_mode(fd: c_int) -> Option<(bool, bool)> {
582             let mode = unsafe { libc::fcntl(fd, libc::F_GETFL) };
583             if mode == -1 {
584                 return None;
585             }
586             match mode & libc::O_ACCMODE {
587                 libc::O_RDONLY => Some((true, false)),
588                 libc::O_RDWR => Some((true, true)),
589                 libc::O_WRONLY => Some((false, true)),
590                 _ => None
591             }
592         }
593
594         #[cfg(not(any(target_os = "linux", target_os = "macos")))]
595         fn get_mode(_fd: c_int) -> Option<(bool, bool)> {
596             // FIXME(#24570): implement this for other Unix platforms
597             None
598         }
599
600         let fd = self.0.raw();
601         let mut b = f.debug_struct("File");
602         b.field("fd", &fd);
603         if let Some(path) = get_path(fd) {
604             b.field("path", &path);
605         }
606         if let Some((read, write)) = get_mode(fd) {
607             b.field("read", &read).field("write", &write);
608         }
609         b.finish()
610     }
611 }
612
613 pub fn readdir(p: &Path) -> io::Result<ReadDir> {
614     let root = Arc::new(p.to_path_buf());
615     let p = cstr(p)?;
616     unsafe {
617         let ptr = libc::opendir(p.as_ptr());
618         if ptr.is_null() {
619             Err(Error::last_os_error())
620         } else {
621             Ok(ReadDir { dirp: Dir(ptr), root: root })
622         }
623     }
624 }
625
626 pub fn unlink(p: &Path) -> io::Result<()> {
627     let p = cstr(p)?;
628     cvt(unsafe { libc::unlink(p.as_ptr()) })?;
629     Ok(())
630 }
631
632 pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
633     let old = cstr(old)?;
634     let new = cstr(new)?;
635     cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) })?;
636     Ok(())
637 }
638
639 pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
640     let p = cstr(p)?;
641     cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) })?;
642     Ok(())
643 }
644
645 pub fn rmdir(p: &Path) -> io::Result<()> {
646     let p = cstr(p)?;
647     cvt(unsafe { libc::rmdir(p.as_ptr()) })?;
648     Ok(())
649 }
650
651 pub fn remove_dir_all(path: &Path) -> io::Result<()> {
652     let filetype = lstat(path)?.file_type();
653     if filetype.is_symlink() {
654         unlink(path)
655     } else {
656         remove_dir_all_recursive(path)
657     }
658 }
659
660 fn remove_dir_all_recursive(path: &Path) -> io::Result<()> {
661     for child in readdir(path)? {
662         let child = child?;
663         if child.file_type()?.is_dir() {
664             remove_dir_all_recursive(&child.path())?;
665         } else {
666             unlink(&child.path())?;
667         }
668     }
669     rmdir(path)
670 }
671
672 pub fn readlink(p: &Path) -> io::Result<PathBuf> {
673     let c_path = cstr(p)?;
674     let p = c_path.as_ptr();
675
676     let mut buf = Vec::with_capacity(256);
677
678     loop {
679         let buf_read = cvt(unsafe {
680             libc::readlink(p, buf.as_mut_ptr() as *mut _, buf.capacity())
681         })? as usize;
682
683         unsafe { buf.set_len(buf_read); }
684
685         if buf_read != buf.capacity() {
686             buf.shrink_to_fit();
687
688             return Ok(PathBuf::from(OsString::from_vec(buf)));
689         }
690
691         // Trigger the internal buffer resizing logic of `Vec` by requiring
692         // more space than the current capacity. The length is guaranteed to be
693         // the same as the capacity due to the if statement above.
694         buf.reserve(1);
695     }
696 }
697
698 pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
699     let src = cstr(src)?;
700     let dst = cstr(dst)?;
701     cvt(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) })?;
702     Ok(())
703 }
704
705 pub fn link(src: &Path, dst: &Path) -> io::Result<()> {
706     let src = cstr(src)?;
707     let dst = cstr(dst)?;
708     cvt(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) })?;
709     Ok(())
710 }
711
712 pub fn stat(p: &Path) -> io::Result<FileAttr> {
713     let p = cstr(p)?;
714     let mut stat: stat64 = unsafe { mem::zeroed() };
715     cvt(unsafe {
716         stat64(p.as_ptr(), &mut stat as *mut _ as *mut _)
717     })?;
718     Ok(FileAttr { stat: stat })
719 }
720
721 pub fn lstat(p: &Path) -> io::Result<FileAttr> {
722     let p = cstr(p)?;
723     let mut stat: stat64 = unsafe { mem::zeroed() };
724     cvt(unsafe {
725         lstat64(p.as_ptr(), &mut stat as *mut _ as *mut _)
726     })?;
727     Ok(FileAttr { stat: stat })
728 }
729
730 pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
731     let path = CString::new(p.as_os_str().as_bytes())?;
732     let buf;
733     unsafe {
734         let r = libc::realpath(path.as_ptr(), ptr::null_mut());
735         if r.is_null() {
736             return Err(io::Error::last_os_error())
737         }
738         buf = CStr::from_ptr(r).to_bytes().to_vec();
739         libc::free(r as *mut _);
740     }
741     Ok(PathBuf::from(OsString::from_vec(buf)))
742 }
743
744 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
745     use fs::{File, set_permissions};
746     if !from.is_file() {
747         return Err(Error::new(ErrorKind::InvalidInput,
748                               "the source path is not an existing regular file"))
749     }
750
751     let mut reader = File::open(from)?;
752     let mut writer = File::create(to)?;
753     let perm = reader.metadata()?.permissions();
754
755     let ret = io::copy(&mut reader, &mut writer)?;
756     set_permissions(to, perm)?;
757     Ok(ret)
758 }