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.
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.
12 use os::unix::prelude::*;
14 use ffi::{CString, CStr, OsString, OsStr};
16 use io::{self, Error, ErrorKind, SeekFrom};
17 use libc::{self, c_int, size_t, off_t, c_char, mode_t};
19 use path::{Path, PathBuf};
22 use sys::fd::FileDesc;
23 use sys::platform::raw;
24 use sys::{c, cvt, cvt_r};
25 use sys_common::{AsInner, FromInner};
28 pub struct File(FileDesc);
40 struct Dir(*mut libc::DIR);
42 unsafe impl Send for Dir {}
43 unsafe impl Sync for Dir {}
46 buf: Vec<u8>, // actually *mut libc::dirent_t
51 pub struct OpenOptions {
58 #[derive(Clone, PartialEq, Eq, Debug)]
59 pub struct FilePermissions { mode: mode_t }
61 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
62 pub struct FileType { mode: mode_t }
64 pub struct DirBuilder { mode: mode_t }
67 pub fn size(&self) -> u64 { self.stat.st_size as u64 }
68 pub fn perm(&self) -> FilePermissions {
69 FilePermissions { mode: (self.stat.st_mode as mode_t) & 0o777 }
72 pub fn file_type(&self) -> FileType {
73 FileType { mode: self.stat.st_mode as mode_t }
77 impl AsInner<raw::stat> for FileAttr {
78 fn as_inner(&self) -> &raw::stat { &self.stat }
81 /// OS-specific extension methods for `fs::Metadata`
82 #[stable(feature = "metadata_ext", since = "1.1.0")]
83 pub trait MetadataExt {
84 /// Gain a reference to the underlying `stat` structure which contains the
85 /// raw information returned by the OS.
87 /// The contents of the returned `stat` are **not** consistent across Unix
88 /// platforms. The `os::unix::fs::MetadataExt` trait contains the cross-Unix
89 /// abstractions contained within the raw stat.
90 #[stable(feature = "metadata_ext", since = "1.1.0")]
91 fn as_raw_stat(&self) -> &raw::stat;
94 #[stable(feature = "metadata_ext", since = "1.1.0")]
95 impl MetadataExt for ::fs::Metadata {
96 fn as_raw_stat(&self) -> &raw::stat { &self.as_inner().stat }
99 impl FilePermissions {
100 pub fn readonly(&self) -> bool { self.mode & 0o222 == 0 }
101 pub fn set_readonly(&mut self, readonly: bool) {
108 pub fn mode(&self) -> raw::mode_t { self.mode }
112 pub fn is_dir(&self) -> bool { self.is(libc::S_IFDIR) }
113 pub fn is_file(&self) -> bool { self.is(libc::S_IFREG) }
114 pub fn is_symlink(&self) -> bool { self.is(libc::S_IFLNK) }
116 pub fn is(&self, mode: mode_t) -> bool { self.mode & libc::S_IFMT == mode }
119 impl FromInner<raw::mode_t> for FilePermissions {
120 fn from_inner(mode: raw::mode_t) -> FilePermissions {
121 FilePermissions { mode: mode as mode_t }
125 impl Iterator for ReadDir {
126 type Item = io::Result<DirEntry>;
128 fn next(&mut self) -> Option<io::Result<DirEntry>> {
130 fn rust_dirent_t_size() -> c_int;
133 let mut buf: Vec<u8> = Vec::with_capacity(unsafe {
134 rust_dirent_t_size() as usize
136 let ptr = buf.as_mut_ptr() as *mut libc::dirent_t;
138 let mut entry_ptr = ptr::null_mut();
140 if unsafe { libc::readdir_r(self.dirp.0, ptr, &mut entry_ptr) != 0 } {
141 return Some(Err(Error::last_os_error()))
143 if entry_ptr.is_null() {
147 let entry = DirEntry {
149 root: self.root.clone()
151 if entry.name_bytes() == b"." || entry.name_bytes() == b".." {
154 return Some(Ok(entry))
162 let r = unsafe { libc::closedir(self.0) };
163 debug_assert_eq!(r, 0);
168 pub fn path(&self) -> PathBuf {
169 self.root.join(<OsStr as OsStrExt>::from_bytes(self.name_bytes()))
172 pub fn file_name(&self) -> OsString {
173 OsStr::from_bytes(self.name_bytes()).to_os_string()
176 pub fn metadata(&self) -> io::Result<FileAttr> {
180 pub fn file_type(&self) -> io::Result<FileType> {
182 fn rust_dir_get_mode(ptr: *mut libc::dirent_t) -> c_int;
185 match rust_dir_get_mode(self.dirent()) {
186 -1 => lstat(&self.path()).map(|m| m.file_type()),
187 n => Ok(FileType { mode: n as mode_t }),
192 pub fn ino(&self) -> raw::ino_t {
194 fn rust_dir_get_ino(ptr: *mut libc::dirent_t) -> raw::ino_t;
196 unsafe { rust_dir_get_ino(self.dirent()) }
199 fn name_bytes(&self) -> &[u8] {
201 fn rust_list_dir_val(ptr: *mut libc::dirent_t) -> *const c_char;
204 CStr::from_ptr(rust_list_dir_val(self.dirent())).to_bytes()
208 fn dirent(&self) -> *mut libc::dirent_t {
209 self.buf.as_ptr() as *mut _
214 pub fn new() -> OpenOptions {
216 flags: libc::O_CLOEXEC,
223 pub fn read(&mut self, read: bool) {
227 pub fn write(&mut self, write: bool) {
231 pub fn append(&mut self, append: bool) {
232 self.flag(libc::O_APPEND, append);
235 pub fn truncate(&mut self, truncate: bool) {
236 self.flag(libc::O_TRUNC, truncate);
239 pub fn create(&mut self, create: bool) {
240 self.flag(libc::O_CREAT, create);
243 pub fn mode(&mut self, mode: raw::mode_t) {
244 self.mode = mode as mode_t;
247 fn flag(&mut self, bit: c_int, on: bool) {
257 pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
258 let path = try!(cstr(path));
259 File::open_c(&path, opts)
262 pub fn open_c(path: &CStr, opts: &OpenOptions) -> io::Result<File> {
263 let flags = opts.flags | match (opts.read, opts.write) {
264 (true, true) => libc::O_RDWR,
265 (false, true) => libc::O_WRONLY,
267 (false, false) => libc::O_RDONLY,
269 let fd = try!(cvt_r(|| unsafe {
270 libc::open(path.as_ptr(), flags, opts.mode)
272 let fd = FileDesc::new(fd);
273 // Even though we open with the O_CLOEXEC flag, still set CLOEXEC here,
274 // in case the open flag is not supported (it's just ignored by the OS
280 pub fn file_attr(&self) -> io::Result<FileAttr> {
281 let mut stat: raw::stat = unsafe { mem::zeroed() };
283 libc::fstat(self.0.raw(), &mut stat as *mut _ as *mut _)
285 Ok(FileAttr { stat: stat })
288 pub fn fsync(&self) -> io::Result<()> {
289 try!(cvt_r(|| unsafe { libc::fsync(self.0.raw()) }));
293 pub fn datasync(&self) -> io::Result<()> {
294 try!(cvt_r(|| unsafe { os_datasync(self.0.raw()) }));
297 #[cfg(any(target_os = "macos", target_os = "ios"))]
298 unsafe fn os_datasync(fd: c_int) -> c_int {
299 libc::fcntl(fd, libc::F_FULLFSYNC)
301 #[cfg(target_os = "linux")]
302 unsafe fn os_datasync(fd: c_int) -> c_int { libc::fdatasync(fd) }
303 #[cfg(not(any(target_os = "macos",
305 target_os = "linux")))]
306 unsafe fn os_datasync(fd: c_int) -> c_int { libc::fsync(fd) }
309 pub fn truncate(&self, size: u64) -> io::Result<()> {
310 try!(cvt_r(|| unsafe {
311 libc::ftruncate(self.0.raw(), size as libc::off_t)
316 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
320 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
324 pub fn flush(&self) -> io::Result<()> { Ok(()) }
326 pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
327 let (whence, pos) = match pos {
328 SeekFrom::Start(off) => (libc::SEEK_SET, off as off_t),
329 SeekFrom::End(off) => (libc::SEEK_END, off as off_t),
330 SeekFrom::Current(off) => (libc::SEEK_CUR, off as off_t),
332 let n = try!(cvt(unsafe { libc::lseek(self.0.raw(), pos, whence) }));
336 pub fn fd(&self) -> &FileDesc { &self.0 }
338 pub fn into_fd(self) -> FileDesc { self.0 }
342 pub fn new() -> DirBuilder {
343 DirBuilder { mode: 0o777 }
346 pub fn mkdir(&self, p: &Path) -> io::Result<()> {
347 let p = try!(cstr(p));
348 try!(cvt(unsafe { libc::mkdir(p.as_ptr(), self.mode) }));
352 pub fn set_mode(&mut self, mode: mode_t) {
357 fn cstr(path: &Path) -> io::Result<CString> {
358 path.as_os_str().to_cstring().ok_or(
359 io::Error::new(io::ErrorKind::InvalidInput, "path contained a null"))
362 impl FromInner<c_int> for File {
363 fn from_inner(fd: c_int) -> File {
364 File(FileDesc::new(fd))
368 impl fmt::Debug for File {
369 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
370 #[cfg(target_os = "linux")]
371 fn get_path(fd: c_int) -> Option<PathBuf> {
372 use string::ToString;
373 let mut p = PathBuf::from("/proc/self/fd");
374 p.push(&fd.to_string());
378 #[cfg(target_os = "macos")]
379 fn get_path(fd: c_int) -> Option<PathBuf> {
380 // FIXME: The use of PATH_MAX is generally not encouraged, but it
381 // is inevitable in this case because OS X defines `fcntl` with
382 // `F_GETPATH` in terms of `MAXPATHLEN`, and there are no
383 // alternatives. If a better method is invented, it should be used
385 let mut buf = vec![0;libc::PATH_MAX as usize];
386 let n = unsafe { libc::fcntl(fd, libc::F_GETPATH, buf.as_ptr()) };
390 let l = buf.iter().position(|&c| c == 0).unwrap();
391 buf.truncate(l as usize);
393 Some(PathBuf::from(OsString::from_vec(buf)))
396 #[cfg(not(any(target_os = "linux", target_os = "macos")))]
397 fn get_path(_fd: c_int) -> Option<PathBuf> {
398 // FIXME(#24570): implement this for other Unix platforms
402 #[cfg(any(target_os = "linux", target_os = "macos"))]
403 fn get_mode(fd: c_int) -> Option<(bool, bool)> {
404 let mode = unsafe { libc::fcntl(fd, libc::F_GETFL) };
408 match mode & libc::O_ACCMODE {
409 libc::O_RDONLY => Some((true, false)),
410 libc::O_RDWR => Some((true, true)),
411 libc::O_WRONLY => Some((false, true)),
416 #[cfg(not(any(target_os = "linux", target_os = "macos")))]
417 fn get_mode(_fd: c_int) -> Option<(bool, bool)> {
418 // FIXME(#24570): implement this for other Unix platforms
422 let fd = self.0.raw();
423 let mut b = f.debug_struct("File");
425 if let Some(path) = get_path(fd) {
426 b.field("path", &path);
428 if let Some((read, write)) = get_mode(fd) {
429 b.field("read", &read).field("write", &write);
435 pub fn readdir(p: &Path) -> io::Result<ReadDir> {
436 let root = Arc::new(p.to_path_buf());
437 let p = try!(cstr(p));
439 let ptr = libc::opendir(p.as_ptr());
441 Err(Error::last_os_error())
443 Ok(ReadDir { dirp: Dir(ptr), root: root })
448 pub fn unlink(p: &Path) -> io::Result<()> {
449 let p = try!(cstr(p));
450 try!(cvt(unsafe { libc::unlink(p.as_ptr()) }));
454 pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
455 let old = try!(cstr(old));
456 let new = try!(cstr(new));
457 try!(cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) }));
461 pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
462 let p = try!(cstr(p));
463 try!(cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) }));
467 pub fn rmdir(p: &Path) -> io::Result<()> {
468 let p = try!(cstr(p));
469 try!(cvt(unsafe { libc::rmdir(p.as_ptr()) }));
473 pub fn readlink(p: &Path) -> io::Result<PathBuf> {
474 let c_path = try!(cstr(p));
475 let p = c_path.as_ptr();
477 let mut buf = Vec::with_capacity(256);
480 let buf_read = try!(cvt(unsafe {
481 libc::readlink(p, buf.as_mut_ptr() as *mut _, buf.capacity() as libc::size_t)
484 unsafe { buf.set_len(buf_read); }
486 if buf_read != buf.capacity() {
489 return Ok(PathBuf::from(OsString::from_vec(buf)));
492 // Trigger the internal buffer resizing logic of `Vec` by requiring
493 // more space than the current capacity. The length is guaranteed to be
494 // the same as the capacity due to the if statement above.
499 pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
500 let src = try!(cstr(src));
501 let dst = try!(cstr(dst));
502 try!(cvt(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) }));
506 pub fn link(src: &Path, dst: &Path) -> io::Result<()> {
507 let src = try!(cstr(src));
508 let dst = try!(cstr(dst));
509 try!(cvt(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) }));
513 pub fn stat(p: &Path) -> io::Result<FileAttr> {
514 let p = try!(cstr(p));
515 let mut stat: raw::stat = unsafe { mem::zeroed() };
517 libc::stat(p.as_ptr(), &mut stat as *mut _ as *mut _)
519 Ok(FileAttr { stat: stat })
522 pub fn lstat(p: &Path) -> io::Result<FileAttr> {
523 let p = try!(cstr(p));
524 let mut stat: raw::stat = unsafe { mem::zeroed() };
526 libc::lstat(p.as_ptr(), &mut stat as *mut _ as *mut _)
528 Ok(FileAttr { stat: stat })
531 pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
532 let path = try!(CString::new(p.as_os_str().as_bytes()));
535 let r = c::realpath(path.as_ptr(), ptr::null_mut());
537 return Err(io::Error::last_os_error())
539 buf = CStr::from_ptr(r).to_bytes().to_vec();
540 libc::free(r as *mut _);
542 Ok(PathBuf::from(OsString::from_vec(buf)))
545 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
546 use fs::{File, PathExt, set_permissions};
548 return Err(Error::new(ErrorKind::InvalidInput,
549 "the source path is not an existing regular file"))
552 let mut reader = try!(File::open(from));
553 let mut writer = try!(File::create(to));
554 let perm = try!(reader.metadata()).permissions();
556 let ret = try!(io::copy(&mut reader, &mut writer));
557 try!(set_permissions(to, perm));