]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/fs2.rs
Rollup merge of #22744 - alexcrichton:issue-22738, r=aturon
[rust.git] / src / libstd / sys / unix / fs2.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 core::prelude::*;
12 use io::prelude::*;
13 use os::unix::prelude::*;
14
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};
18 use mem;
19 use path::{Path, PathBuf};
20 use ptr;
21 use sync::Arc;
22 use sys::fd::FileDesc;
23 use sys::{c, cvt, cvt_r};
24 use sys_common::FromInner;
25 use vec::Vec;
26
27 pub struct File(FileDesc);
28
29 pub struct FileAttr {
30     stat: libc::stat,
31 }
32
33 pub struct ReadDir {
34     dirp: Dir,
35     root: Arc<PathBuf>,
36 }
37
38 struct Dir(*mut libc::DIR);
39
40 unsafe impl Send for Dir {}
41 unsafe impl Sync for Dir {}
42
43 pub struct DirEntry {
44     buf: Vec<u8>, // actually *mut libc::dirent_t
45     root: Arc<PathBuf>,
46 }
47
48 #[derive(Clone)]
49 pub struct OpenOptions {
50     flags: c_int,
51     read: bool,
52     write: bool,
53     mode: mode_t,
54 }
55
56 #[derive(Clone, PartialEq, Eq, Debug)]
57 pub struct FilePermissions { mode: mode_t }
58
59 impl FileAttr {
60     pub fn is_dir(&self) -> bool {
61         (self.stat.st_mode as mode_t) & libc::S_IFMT == libc::S_IFDIR
62     }
63     pub fn is_file(&self) -> bool {
64         (self.stat.st_mode as mode_t) & libc::S_IFMT == libc::S_IFREG
65     }
66     pub fn size(&self) -> u64 { self.stat.st_size as u64 }
67     pub fn perm(&self) -> FilePermissions {
68         FilePermissions { mode: (self.stat.st_mode as mode_t) & 0o777 }
69     }
70
71     pub fn accessed(&self) -> u64 {
72         self.mktime(self.stat.st_atime as u64, self.stat.st_atime_nsec as u64)
73     }
74     pub fn modified(&self) -> u64 {
75         self.mktime(self.stat.st_mtime as u64, self.stat.st_mtime_nsec as u64)
76     }
77
78     // times are in milliseconds (currently)
79     fn mktime(&self, secs: u64, nsecs: u64) -> u64 {
80         secs * 1000 + nsecs / 1000000
81     }
82 }
83
84 impl FilePermissions {
85     pub fn readonly(&self) -> bool { self.mode & 0o222 == 0 }
86     pub fn set_readonly(&mut self, readonly: bool) {
87         if readonly {
88             self.mode &= !0o222;
89         } else {
90             self.mode |= 0o222;
91         }
92     }
93     pub fn mode(&self) -> i32 { self.mode as i32 }
94 }
95
96 impl FromInner<i32> for FilePermissions {
97     fn from_inner(mode: i32) -> FilePermissions {
98         FilePermissions { mode: mode as mode_t }
99     }
100 }
101
102 impl Iterator for ReadDir {
103     type Item = io::Result<DirEntry>;
104
105     fn next(&mut self) -> Option<io::Result<DirEntry>> {
106         extern {
107             fn rust_dirent_t_size() -> c_int;
108         }
109
110         let mut buf: Vec<u8> = Vec::with_capacity(unsafe {
111             rust_dirent_t_size() as usize
112         });
113         let ptr = buf.as_mut_ptr() as *mut libc::dirent_t;
114
115         let mut entry_ptr = ptr::null_mut();
116         loop {
117             if unsafe { libc::readdir_r(self.dirp.0, ptr, &mut entry_ptr) != 0 } {
118                 return Some(Err(Error::last_os_error()))
119             }
120             if entry_ptr.is_null() {
121                 return None
122             }
123
124             let entry = DirEntry {
125                 buf: buf,
126                 root: self.root.clone()
127             };
128             if entry.name_bytes() == b"." || entry.name_bytes() == b".." {
129                 buf = entry.buf;
130             } else {
131                 return Some(Ok(entry))
132             }
133         }
134     }
135 }
136
137 impl Drop for Dir {
138     fn drop(&mut self) {
139         let r = unsafe { libc::closedir(self.0) };
140         debug_assert_eq!(r, 0);
141     }
142 }
143
144 impl DirEntry {
145     pub fn path(&self) -> PathBuf {
146         self.root.join(<OsStr as OsStrExt>::from_bytes(self.name_bytes()))
147     }
148
149     fn name_bytes(&self) -> &[u8] {
150         extern {
151             fn rust_list_dir_val(ptr: *mut libc::dirent_t) -> *const c_char;
152         }
153         unsafe {
154             CStr::from_ptr(rust_list_dir_val(self.dirent())).to_bytes()
155         }
156     }
157
158     fn dirent(&self) -> *mut libc::dirent_t {
159         self.buf.as_ptr() as *mut _
160     }
161 }
162
163 impl OpenOptions {
164     pub fn new() -> OpenOptions {
165         OpenOptions {
166             flags: 0,
167             read: false,
168             write: false,
169             mode: 0o666,
170         }
171     }
172
173     pub fn read(&mut self, read: bool) {
174         self.read = read;
175     }
176
177     pub fn write(&mut self, write: bool) {
178         self.write = write;
179     }
180
181     pub fn append(&mut self, append: bool) {
182         self.flag(libc::O_APPEND, append);
183     }
184
185     pub fn truncate(&mut self, truncate: bool) {
186         self.flag(libc::O_TRUNC, truncate);
187     }
188
189     pub fn create(&mut self, create: bool) {
190         self.flag(libc::O_CREAT, create);
191     }
192
193     pub fn mode(&mut self, mode: i32) {
194         self.mode = mode as mode_t;
195     }
196
197     fn flag(&mut self, bit: c_int, on: bool) {
198         if on {
199             self.flags |= bit;
200         } else {
201             self.flags &= !bit;
202         }
203     }
204 }
205
206 impl File {
207     pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
208         let flags = opts.flags | match (opts.read, opts.write) {
209             (true, true) => libc::O_RDWR,
210             (false, true) => libc::O_WRONLY,
211             (true, false) |
212             (false, false) => libc::O_RDONLY,
213         };
214         let path = try!(cstr(path));
215         let fd = try!(cvt_r(|| unsafe {
216             libc::open(path.as_ptr(), flags, opts.mode)
217         }));
218         Ok(File(FileDesc::new(fd)))
219     }
220
221     pub fn file_attr(&self) -> io::Result<FileAttr> {
222         let mut stat: libc::stat = unsafe { mem::zeroed() };
223         try!(cvt(unsafe { libc::fstat(self.0.raw(), &mut stat) }));
224         Ok(FileAttr { stat: stat })
225     }
226
227     pub fn fsync(&self) -> io::Result<()> {
228         try!(cvt_r(|| unsafe { libc::fsync(self.0.raw()) }));
229         Ok(())
230     }
231
232     pub fn datasync(&self) -> io::Result<()> {
233         try!(cvt_r(|| unsafe { os_datasync(self.0.raw()) }));
234         return Ok(());
235
236         #[cfg(any(target_os = "macos", target_os = "ios"))]
237         unsafe fn os_datasync(fd: c_int) -> c_int {
238             libc::fcntl(fd, libc::F_FULLFSYNC)
239         }
240         #[cfg(target_os = "linux")]
241         unsafe fn os_datasync(fd: c_int) -> c_int { libc::fdatasync(fd) }
242         #[cfg(not(any(target_os = "macos",
243                       target_os = "ios",
244                       target_os = "linux")))]
245         unsafe fn os_datasync(fd: c_int) -> c_int { libc::fsync(fd) }
246     }
247
248     pub fn truncate(&self, size: u64) -> io::Result<()> {
249         try!(cvt_r(|| unsafe {
250             libc::ftruncate(self.0.raw(), size as libc::off_t)
251         }));
252         Ok(())
253     }
254
255     pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
256         self.0.read(buf)
257     }
258
259     pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
260         self.0.write(buf)
261     }
262
263     pub fn flush(&self) -> io::Result<()> { Ok(()) }
264
265     pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
266         let (whence, pos) = match pos {
267             SeekFrom::Start(off) => (libc::SEEK_SET, off as off_t),
268             SeekFrom::End(off) => (libc::SEEK_END, off as off_t),
269             SeekFrom::Current(off) => (libc::SEEK_CUR, off as off_t),
270         };
271         let n = try!(cvt(unsafe { libc::lseek(self.0.raw(), pos, whence) }));
272         Ok(n as u64)
273     }
274
275     pub fn fd(&self) -> &FileDesc { &self.0 }
276 }
277
278 fn cstr(path: &Path) -> io::Result<CString> {
279     let cstring = try!(path.as_os_str().to_cstring());
280     Ok(cstring)
281 }
282
283 pub fn mkdir(p: &Path) -> io::Result<()> {
284     let p = try!(cstr(p));
285     try!(cvt(unsafe { libc::mkdir(p.as_ptr(), 0o777) }));
286     Ok(())
287 }
288
289 pub fn readdir(p: &Path) -> io::Result<ReadDir> {
290     let root = Arc::new(p.to_path_buf());
291     let p = try!(cstr(p));
292     unsafe {
293         let ptr = libc::opendir(p.as_ptr());
294         if ptr.is_null() {
295             Err(Error::last_os_error())
296         } else {
297             Ok(ReadDir { dirp: Dir(ptr), root: root })
298         }
299     }
300 }
301
302 pub fn unlink(p: &Path) -> io::Result<()> {
303     let p = try!(cstr(p));
304     try!(cvt(unsafe { libc::unlink(p.as_ptr()) }));
305     Ok(())
306 }
307
308 pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
309     let old = try!(cstr(old));
310     let new = try!(cstr(new));
311     try!(cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) }));
312     Ok(())
313 }
314
315 pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
316     let p = try!(cstr(p));
317     try!(cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) }));
318     Ok(())
319 }
320
321 pub fn rmdir(p: &Path) -> io::Result<()> {
322     let p = try!(cstr(p));
323     try!(cvt(unsafe { libc::rmdir(p.as_ptr()) }));
324     Ok(())
325 }
326
327 pub fn chown(p: &Path, uid: isize, gid: isize) -> io::Result<()> {
328     let p = try!(cstr(p));
329     try!(cvt_r(|| unsafe {
330         libc::chown(p.as_ptr(), uid as libc::uid_t, gid as libc::gid_t)
331     }));
332     Ok(())
333 }
334
335 pub fn readlink(p: &Path) -> io::Result<PathBuf> {
336     let c_path = try!(cstr(p));
337     let p = c_path.as_ptr();
338     let mut len = unsafe { libc::pathconf(p as *mut _, libc::_PC_NAME_MAX) };
339     if len < 0 {
340         len = 1024; // FIXME: read PATH_MAX from C ffi?
341     }
342     let mut buf: Vec<u8> = Vec::with_capacity(len as usize);
343     unsafe {
344         let n = try!(cvt({
345             libc::readlink(p, buf.as_ptr() as *mut c_char, len as size_t)
346         }));
347         buf.set_len(n as usize);
348     }
349     let s: OsString = OsStringExt::from_vec(buf);
350     Ok(PathBuf::new(&s))
351 }
352
353 pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
354     let src = try!(cstr(src));
355     let dst = try!(cstr(dst));
356     try!(cvt(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) }));
357     Ok(())
358 }
359
360 pub fn link(src: &Path, dst: &Path) -> io::Result<()> {
361     let src = try!(cstr(src));
362     let dst = try!(cstr(dst));
363     try!(cvt(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) }));
364     Ok(())
365 }
366
367 pub fn stat(p: &Path) -> io::Result<FileAttr> {
368     let p = try!(cstr(p));
369     let mut stat: libc::stat = unsafe { mem::zeroed() };
370     try!(cvt(unsafe { libc::stat(p.as_ptr(), &mut stat) }));
371     Ok(FileAttr { stat: stat })
372 }
373
374 pub fn lstat(p: &Path) -> io::Result<FileAttr> {
375     let p = try!(cstr(p));
376     let mut stat: libc::stat = unsafe { mem::zeroed() };
377     try!(cvt(unsafe { libc::lstat(p.as_ptr(), &mut stat) }));
378     Ok(FileAttr { stat: stat })
379 }
380
381 pub fn utimes(p: &Path, atime: u64, mtime: u64) -> io::Result<()> {
382     let p = try!(cstr(p));
383     let buf = [super::ms_to_timeval(atime), super::ms_to_timeval(mtime)];
384     try!(cvt(unsafe { c::utimes(p.as_ptr(), buf.as_ptr()) }));
385     Ok(())
386 }