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.
13 use os::unix::prelude::*;
15 use ffi::{CString, CStr, OsString, AsOsStr, OsStr};
16 use io::{self, Error, Seek, SeekFrom};
17 use libc::{self, c_int, c_void, size_t, off_t, c_char, mode_t};
19 use path::{Path, PathBuf};
22 use sys::fd::FileDesc;
23 use sys::{c, cvt, cvt_r};
24 use sys_common::FromInner;
27 pub struct File(FileDesc);
40 dirent: *mut libc::dirent_t,
45 pub struct OpenOptions {
52 #[derive(Clone, PartialEq, Eq, Debug)]
53 pub struct FilePermissions { mode: mode_t }
56 pub fn is_dir(&self) -> bool {
57 (self.stat.st_mode as mode_t) & libc::S_IFMT == libc::S_IFDIR
59 pub fn is_file(&self) -> bool {
60 (self.stat.st_mode as mode_t) & libc::S_IFMT == libc::S_IFREG
62 pub fn size(&self) -> u64 { self.stat.st_size as u64 }
63 pub fn perm(&self) -> FilePermissions {
64 FilePermissions { mode: (self.stat.st_mode as mode_t) & 0o777 }
67 pub fn accessed(&self) -> u64 {
68 self.mktime(self.stat.st_atime as u64, self.stat.st_atime_nsec as u64)
70 pub fn modified(&self) -> u64 {
71 self.mktime(self.stat.st_mtime as u64, self.stat.st_mtime_nsec as u64)
74 // times are in milliseconds (currently)
75 fn mktime(&self, secs: u64, nsecs: u64) -> u64 {
76 secs * 1000 + nsecs / 1000000
80 impl FilePermissions {
81 pub fn readonly(&self) -> bool { self.mode & 0o222 == 0 }
82 pub fn set_readonly(&mut self, readonly: bool) {
91 impl FromInner<i32> for FilePermissions {
92 fn from_inner(mode: i32) -> FilePermissions {
93 FilePermissions { mode: mode as mode_t }
97 impl Iterator for ReadDir {
98 type Item = io::Result<DirEntry>;
100 fn next(&mut self) -> Option<io::Result<DirEntry>> {
102 fn rust_dirent_t_size() -> c_int;
105 let mut buf: Vec<u8> = Vec::with_capacity(unsafe {
106 rust_dirent_t_size() as usize
108 let ptr = buf.as_mut_ptr() as *mut libc::dirent_t;
110 let mut entry_ptr = ptr::null_mut();
112 if unsafe { libc::readdir_r(self.dirp, ptr, &mut entry_ptr) != 0 } {
113 return Some(Err(Error::last_os_error()))
115 if entry_ptr.is_null() {
119 let entry = DirEntry {
122 root: self.root.clone()
124 if entry.name_bytes() == b"." || entry.name_bytes() == b".." {
127 return Some(Ok(entry))
133 impl Drop for ReadDir {
135 let r = unsafe { libc::closedir(self.dirp) };
136 debug_assert_eq!(r, 0);
141 pub fn path(&self) -> PathBuf {
142 self.root.join(<OsStr as OsStrExt>::from_bytes(self.name_bytes()))
145 fn name_bytes(&self) -> &[u8] {
147 fn rust_list_dir_val(ptr: *mut libc::dirent_t) -> *const c_char;
150 CStr::from_ptr(rust_list_dir_val(self.dirent)).to_bytes()
156 pub fn new() -> OpenOptions {
165 pub fn read(&mut self, read: bool) {
169 pub fn write(&mut self, write: bool) {
173 pub fn append(&mut self, append: bool) {
174 self.flag(libc::O_APPEND, append);
177 pub fn truncate(&mut self, truncate: bool) {
178 self.flag(libc::O_TRUNC, truncate);
181 pub fn create(&mut self, create: bool) {
182 self.flag(libc::O_CREAT, create);
185 pub fn mode(&mut self, mode: i32) {
186 self.mode = mode as mode_t;
189 fn flag(&mut self, bit: c_int, on: bool) {
199 pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
200 let flags = opts.flags | match (opts.read, opts.write) {
201 (true, true) => libc::O_RDWR,
202 (false, true) => libc::O_WRONLY,
204 (false, false) => libc::O_RDONLY,
206 let path = try!(cstr(path));
207 let fd = try!(cvt_r(|| unsafe {
208 libc::open(path.as_ptr(), flags, opts.mode)
210 Ok(File(FileDesc::new(fd)))
213 pub fn file_attr(&self) -> io::Result<FileAttr> {
214 let mut stat: libc::stat = unsafe { mem::zeroed() };
215 try!(cvt(unsafe { libc::fstat(self.0.raw(), &mut stat) }));
216 Ok(FileAttr { stat: stat })
219 pub fn fsync(&self) -> io::Result<()> {
220 try!(cvt_r(|| unsafe { libc::fsync(self.0.raw()) }));
224 pub fn datasync(&self) -> io::Result<()> {
225 try!(cvt_r(|| unsafe { os_datasync(self.0.raw()) }));
228 #[cfg(any(target_os = "macos", target_os = "ios"))]
229 unsafe fn os_datasync(fd: c_int) -> c_int {
230 libc::fcntl(fd, libc::F_FULLFSYNC)
232 #[cfg(target_os = "linux")]
233 unsafe fn os_datasync(fd: c_int) -> c_int { libc::fdatasync(fd) }
234 #[cfg(not(any(target_os = "macos",
236 target_os = "linux")))]
237 unsafe fn os_datasync(fd: c_int) -> c_int { libc::fsync(fd) }
240 pub fn truncate(&self, size: u64) -> io::Result<()> {
241 try!(cvt_r(|| unsafe {
242 libc::ftruncate(self.0.raw(), size as libc::off_t)
247 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
251 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
255 pub fn flush(&self) -> io::Result<()> { Ok(()) }
257 pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
258 let (whence, pos) = match pos {
259 SeekFrom::Start(off) => (libc::SEEK_SET, off as off_t),
260 SeekFrom::End(off) => (libc::SEEK_END, off as off_t),
261 SeekFrom::Current(off) => (libc::SEEK_CUR, off as off_t),
263 let n = try!(cvt(unsafe { libc::lseek(self.0.raw(), pos, whence) }));
267 pub fn fd(&self) -> &FileDesc { &self.0 }
270 fn cstr(path: &Path) -> io::Result<CString> {
271 let cstring = try!(path.as_os_str().to_cstring());
275 pub fn mkdir(p: &Path) -> io::Result<()> {
276 let p = try!(cstr(p));
277 try!(cvt(unsafe { libc::mkdir(p.as_ptr(), 0o777) }));
281 pub fn readdir(p: &Path) -> io::Result<ReadDir> {
282 let root = Rc::new(p.to_path_buf());
283 let p = try!(cstr(p));
285 let ptr = libc::opendir(p.as_ptr());
287 Err(Error::last_os_error())
289 Ok(ReadDir { dirp: ptr, root: root })
294 pub fn unlink(p: &Path) -> io::Result<()> {
295 let p = try!(cstr(p));
296 try!(cvt(unsafe { libc::unlink(p.as_ptr()) }));
300 pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
301 let old = try!(cstr(old));
302 let new = try!(cstr(new));
303 try!(cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) }));
307 pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
308 let p = try!(cstr(p));
309 try!(cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) }));
313 pub fn rmdir(p: &Path) -> io::Result<()> {
314 let p = try!(cstr(p));
315 try!(cvt(unsafe { libc::rmdir(p.as_ptr()) }));
319 pub fn chown(p: &Path, uid: isize, gid: isize) -> io::Result<()> {
320 let p = try!(cstr(p));
321 try!(cvt_r(|| unsafe {
322 libc::chown(p.as_ptr(), uid as libc::uid_t, gid as libc::gid_t)
327 pub fn readlink(p: &Path) -> io::Result<PathBuf> {
328 let c_path = try!(cstr(p));
329 let p = c_path.as_ptr();
330 let mut len = unsafe { libc::pathconf(p as *mut _, libc::_PC_NAME_MAX) };
332 len = 1024; // FIXME: read PATH_MAX from C ffi?
334 let mut buf: Vec<u8> = Vec::with_capacity(len as usize);
337 libc::readlink(p, buf.as_ptr() as *mut c_char, len as size_t)
339 buf.set_len(n as usize);
341 let s: OsString = OsStringExt::from_vec(buf);
345 pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
346 let src = try!(cstr(src));
347 let dst = try!(cstr(dst));
348 try!(cvt(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) }));
352 pub fn link(src: &Path, dst: &Path) -> io::Result<()> {
353 let src = try!(cstr(src));
354 let dst = try!(cstr(dst));
355 try!(cvt(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) }));
359 pub fn stat(p: &Path) -> io::Result<FileAttr> {
360 let p = try!(cstr(p));
361 let mut stat: libc::stat = unsafe { mem::zeroed() };
362 try!(cvt(unsafe { libc::stat(p.as_ptr(), &mut stat) }));
363 Ok(FileAttr { stat: stat })
366 pub fn lstat(p: &Path) -> io::Result<FileAttr> {
367 let p = try!(cstr(p));
368 let mut stat: libc::stat = unsafe { mem::zeroed() };
369 try!(cvt(unsafe { libc::lstat(p.as_ptr(), &mut stat) }));
370 Ok(FileAttr { stat: stat })
373 pub fn utimes(p: &Path, atime: u64, mtime: u64) -> io::Result<()> {
374 let p = try!(cstr(p));
375 let buf = [super::ms_to_timeval(atime), super::ms_to_timeval(mtime)];
376 try!(cvt(unsafe { c::utimes(p.as_ptr(), buf.as_ptr()) }));