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