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