]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/fs.rs
Merge remote-tracking branch 'erickt/rustup'
[rust.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 //! Blocking posix-based file I/O
12
13 use libc::{mod, c_int, c_void};
14 use c_str::CString;
15 use mem;
16 use io;
17
18 use prelude::*;
19
20 use io::{FilePermission, Write, UnstableFileStat, Open, FileAccess, FileMode};
21 use io::{IoResult, FileStat, SeekStyle};
22 use io::{Read, Truncate, SeekCur, SeekSet, ReadWrite, SeekEnd, Append};
23 use sys::retry;
24 use sys_common::{keep_going, eof, mkerr_libc};
25
26 pub type fd_t = libc::c_int;
27
28 pub struct FileDesc {
29     /// The underlying C file descriptor.
30     fd: fd_t,
31
32     /// Whether to close the file descriptor on drop.
33     close_on_drop: bool,
34 }
35
36 impl FileDesc {
37     pub fn new(fd: fd_t, close_on_drop: bool) -> FileDesc {
38         FileDesc { fd: fd, close_on_drop: close_on_drop }
39     }
40
41     pub fn read(&self, buf: &mut [u8]) -> IoResult<uint> {
42         let ret = retry(|| unsafe {
43             libc::read(self.fd(),
44                        buf.as_mut_ptr() as *mut libc::c_void,
45                        buf.len() as libc::size_t)
46         });
47         if ret == 0 {
48             Err(eof())
49         } else if ret < 0 {
50             Err(super::last_error())
51         } else {
52             Ok(ret as uint)
53         }
54     }
55     pub fn write(&self, buf: &[u8]) -> IoResult<()> {
56         let ret = keep_going(buf, |buf, len| {
57             unsafe {
58                 libc::write(self.fd(), buf as *const libc::c_void,
59                             len as libc::size_t) as i64
60             }
61         });
62         if ret < 0 {
63             Err(super::last_error())
64         } else {
65             Ok(())
66         }
67     }
68
69     pub fn fd(&self) -> fd_t { self.fd }
70
71     pub fn seek(&self, pos: i64, whence: SeekStyle) -> IoResult<u64> {
72         let whence = match whence {
73             SeekSet => libc::SEEK_SET,
74             SeekEnd => libc::SEEK_END,
75             SeekCur => libc::SEEK_CUR,
76         };
77         let n = unsafe { libc::lseek(self.fd(), pos as libc::off_t, whence) };
78         if n < 0 {
79             Err(super::last_error())
80         } else {
81             Ok(n as u64)
82         }
83     }
84
85     pub fn tell(&self) -> IoResult<u64> {
86         let n = unsafe { libc::lseek(self.fd(), 0, libc::SEEK_CUR) };
87         if n < 0 {
88             Err(super::last_error())
89         } else {
90             Ok(n as u64)
91         }
92     }
93
94     pub fn fsync(&self) -> IoResult<()> {
95         mkerr_libc(retry(|| unsafe { libc::fsync(self.fd()) }))
96     }
97
98     pub fn datasync(&self) -> IoResult<()> {
99         return mkerr_libc(os_datasync(self.fd()));
100
101         #[cfg(any(target_os = "macos", target_os = "ios"))]
102         fn os_datasync(fd: c_int) -> c_int {
103             unsafe { libc::fcntl(fd, libc::F_FULLFSYNC) }
104         }
105         #[cfg(target_os = "linux")]
106         fn os_datasync(fd: c_int) -> c_int {
107             retry(|| unsafe { libc::fdatasync(fd) })
108         }
109         #[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "linux")))]
110         fn os_datasync(fd: c_int) -> c_int {
111             retry(|| unsafe { libc::fsync(fd) })
112         }
113     }
114
115     pub fn truncate(&self, offset: i64) -> IoResult<()> {
116         mkerr_libc(retry(|| unsafe {
117             libc::ftruncate(self.fd(), offset as libc::off_t)
118         }))
119     }
120
121     pub fn fstat(&self) -> IoResult<FileStat> {
122         let mut stat: libc::stat = unsafe { mem::zeroed() };
123         match unsafe { libc::fstat(self.fd(), &mut stat) } {
124             0 => Ok(mkstat(&stat)),
125             _ => Err(super::last_error()),
126         }
127     }
128
129     /// Extract the actual filedescriptor without closing it.
130     pub fn unwrap(self) -> fd_t {
131         let fd = self.fd;
132         unsafe { mem::forget(self) };
133         fd
134     }
135 }
136
137 impl Drop for FileDesc {
138     fn drop(&mut self) {
139         // closing stdio file handles makes no sense, so never do it. Also, note
140         // that errors are ignored when closing a file descriptor. The reason
141         // for this is that if an error occurs we don't actually know if the
142         // file descriptor was closed or not, and if we retried (for something
143         // like EINTR), we might close another valid file descriptor (opened
144         // after we closed ours.
145         if self.close_on_drop && self.fd > libc::STDERR_FILENO {
146             let n = unsafe { libc::close(self.fd) };
147             if n != 0 {
148                 println!("error {} when closing file descriptor {}", n, self.fd);
149             }
150         }
151     }
152 }
153
154 pub fn open(path: &Path, fm: FileMode, fa: FileAccess) -> IoResult<FileDesc> {
155     let flags = match fm {
156         Open => 0,
157         Append => libc::O_APPEND,
158         Truncate => libc::O_TRUNC,
159     };
160     // Opening with a write permission must silently create the file.
161     let (flags, mode) = match fa {
162         Read => (flags | libc::O_RDONLY, 0),
163         Write => (flags | libc::O_WRONLY | libc::O_CREAT,
164                         libc::S_IRUSR | libc::S_IWUSR),
165         ReadWrite => (flags | libc::O_RDWR | libc::O_CREAT,
166                             libc::S_IRUSR | libc::S_IWUSR),
167     };
168
169     let path = path.to_c_str();
170     match retry(|| unsafe { libc::open(path.as_ptr(), flags, mode) }) {
171         -1 => Err(super::last_error()),
172         fd => Ok(FileDesc::new(fd, true)),
173     }
174 }
175
176 pub fn mkdir(p: &Path, mode: uint) -> IoResult<()> {
177     let p = p.to_c_str();
178     mkerr_libc(unsafe { libc::mkdir(p.as_ptr(), mode as libc::mode_t) })
179 }
180
181 pub fn readdir(p: &Path) -> IoResult<Vec<Path>> {
182     use libc::{dirent_t};
183     use libc::{opendir, readdir_r, closedir};
184
185     fn prune(root: &CString, dirs: Vec<Path>) -> Vec<Path> {
186         let root = unsafe { CString::new(root.as_ptr(), false) };
187         let root = Path::new(root);
188
189         dirs.into_iter().filter(|path| {
190             path.as_vec() != b"." && path.as_vec() != b".."
191         }).map(|path| root.join(path)).collect()
192     }
193
194     extern {
195         fn rust_dirent_t_size() -> libc::c_int;
196         fn rust_list_dir_val(ptr: *mut dirent_t) -> *const libc::c_char;
197     }
198
199     let size = unsafe { rust_dirent_t_size() };
200     let mut buf = Vec::<u8>::with_capacity(size as uint);
201     let ptr = buf.as_mut_ptr() as *mut dirent_t;
202
203     let p = p.to_c_str();
204     let dir_ptr = unsafe {opendir(p.as_ptr())};
205
206     if dir_ptr as uint != 0 {
207         let mut paths = vec!();
208         let mut entry_ptr = 0 as *mut dirent_t;
209         while unsafe { readdir_r(dir_ptr, ptr, &mut entry_ptr) == 0 } {
210             if entry_ptr.is_null() { break }
211             let cstr = unsafe {
212                 CString::new(rust_list_dir_val(entry_ptr), false)
213             };
214             paths.push(Path::new(cstr));
215         }
216         assert_eq!(unsafe { closedir(dir_ptr) }, 0);
217         Ok(prune(&p, paths))
218     } else {
219         Err(super::last_error())
220     }
221 }
222
223 pub fn unlink(p: &Path) -> IoResult<()> {
224     let p = p.to_c_str();
225     mkerr_libc(unsafe { libc::unlink(p.as_ptr()) })
226 }
227
228 pub fn rename(old: &Path, new: &Path) -> IoResult<()> {
229     let old = old.to_c_str();
230     let new = new.to_c_str();
231     mkerr_libc(unsafe {
232         libc::rename(old.as_ptr(), new.as_ptr())
233     })
234 }
235
236 pub fn chmod(p: &Path, mode: uint) -> IoResult<()> {
237     let p = p.to_c_str();
238     mkerr_libc(retry(|| unsafe {
239         libc::chmod(p.as_ptr(), mode as libc::mode_t)
240     }))
241 }
242
243 pub fn rmdir(p: &Path) -> IoResult<()> {
244     let p = p.to_c_str();
245     mkerr_libc(unsafe { libc::rmdir(p.as_ptr()) })
246 }
247
248 pub fn chown(p: &Path, uid: int, gid: int) -> IoResult<()> {
249     let p = p.to_c_str();
250     mkerr_libc(retry(|| unsafe {
251         libc::chown(p.as_ptr(), uid as libc::uid_t, gid as libc::gid_t)
252     }))
253 }
254
255 pub fn readlink(p: &Path) -> IoResult<Path> {
256     let c_path = p.to_c_str();
257     let p = c_path.as_ptr();
258     let mut len = unsafe { libc::pathconf(p as *mut _, libc::_PC_NAME_MAX) };
259     if len == -1 {
260         len = 1024; // FIXME: read PATH_MAX from C ffi?
261     }
262     let mut buf: Vec<u8> = Vec::with_capacity(len as uint);
263     match unsafe {
264         libc::readlink(p, buf.as_ptr() as *mut libc::c_char,
265                        len as libc::size_t) as libc::c_int
266     } {
267         -1 => Err(super::last_error()),
268         n => {
269             assert!(n > 0);
270             unsafe { buf.set_len(n as uint); }
271             Ok(Path::new(buf))
272         }
273     }
274 }
275
276 pub fn symlink(src: &Path, dst: &Path) -> IoResult<()> {
277     let src = src.to_c_str();
278     let dst = dst.to_c_str();
279     mkerr_libc(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) })
280 }
281
282 pub fn link(src: &Path, dst: &Path) -> IoResult<()> {
283     let src = src.to_c_str();
284     let dst = dst.to_c_str();
285     mkerr_libc(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) })
286 }
287
288 fn mkstat(stat: &libc::stat) -> FileStat {
289     // FileStat times are in milliseconds
290     fn mktime(secs: u64, nsecs: u64) -> u64 { secs * 1000 + nsecs / 1000000 }
291
292     #[cfg(not(any(target_os = "linux", target_os = "android")))]
293     fn flags(stat: &libc::stat) -> u64 { stat.st_flags as u64 }
294     #[cfg(any(target_os = "linux", target_os = "android"))]
295     fn flags(_stat: &libc::stat) -> u64 { 0 }
296
297     #[cfg(not(any(target_os = "linux", target_os = "android")))]
298     fn gen(stat: &libc::stat) -> u64 { stat.st_gen as u64 }
299     #[cfg(any(target_os = "linux", target_os = "android"))]
300     fn gen(_stat: &libc::stat) -> u64 { 0 }
301
302     FileStat {
303         size: stat.st_size as u64,
304         kind: match (stat.st_mode as libc::mode_t) & libc::S_IFMT {
305             libc::S_IFREG => io::FileType::RegularFile,
306             libc::S_IFDIR => io::FileType::Directory,
307             libc::S_IFIFO => io::FileType::NamedPipe,
308             libc::S_IFBLK => io::FileType::BlockSpecial,
309             libc::S_IFLNK => io::FileType::Symlink,
310             _ => io::FileType::Unknown,
311         },
312         perm: FilePermission::from_bits_truncate(stat.st_mode as u32),
313         created: mktime(stat.st_ctime as u64, stat.st_ctime_nsec as u64),
314         modified: mktime(stat.st_mtime as u64, stat.st_mtime_nsec as u64),
315         accessed: mktime(stat.st_atime as u64, stat.st_atime_nsec as u64),
316         unstable: UnstableFileStat {
317             device: stat.st_dev as u64,
318             inode: stat.st_ino as u64,
319             rdev: stat.st_rdev as u64,
320             nlink: stat.st_nlink as u64,
321             uid: stat.st_uid as u64,
322             gid: stat.st_gid as u64,
323             blksize: stat.st_blksize as u64,
324             blocks: stat.st_blocks as u64,
325             flags: flags(stat),
326             gen: gen(stat),
327         },
328     }
329 }
330
331 pub fn stat(p: &Path) -> IoResult<FileStat> {
332     let p = p.to_c_str();
333     let mut stat: libc::stat = unsafe { mem::zeroed() };
334     match unsafe { libc::stat(p.as_ptr(), &mut stat) } {
335         0 => Ok(mkstat(&stat)),
336         _ => Err(super::last_error()),
337     }
338 }
339
340 pub fn lstat(p: &Path) -> IoResult<FileStat> {
341     let p = p.to_c_str();
342     let mut stat: libc::stat = unsafe { mem::zeroed() };
343     match unsafe { libc::lstat(p.as_ptr(), &mut stat) } {
344         0 => Ok(mkstat(&stat)),
345         _ => Err(super::last_error()),
346     }
347 }
348
349 pub fn utime(p: &Path, atime: u64, mtime: u64) -> IoResult<()> {
350     let p = p.to_c_str();
351     let buf = libc::utimbuf {
352         actime: (atime / 1000) as libc::time_t,
353         modtime: (mtime / 1000) as libc::time_t,
354     };
355     mkerr_libc(unsafe { libc::utime(p.as_ptr(), &buf) })
356 }
357
358 #[cfg(test)]
359 mod tests {
360     use super::FileDesc;
361     use libc;
362     use os;
363     use prelude::*;
364
365     #[cfg_attr(target_os = "freebsd", ignore)] // hmm, maybe pipes have a tiny buffer
366     #[test]
367     fn test_file_desc() {
368         // Run this test with some pipes so we don't have to mess around with
369         // opening or closing files.
370         let os::Pipe { reader, writer } = unsafe { os::pipe().unwrap() };
371         let mut reader = FileDesc::new(reader, true);
372         let mut writer = FileDesc::new(writer, true);
373
374         writer.write(b"test").ok().unwrap();
375         let mut buf = [0u8; 4];
376         match reader.read(&mut buf) {
377             Ok(4) => {
378                 assert_eq!(buf[0], 't' as u8);
379                 assert_eq!(buf[1], 'e' as u8);
380                 assert_eq!(buf[2], 's' as u8);
381                 assert_eq!(buf[3], 't' as u8);
382             }
383             r => panic!("invalid read: {}", r),
384         }
385
386         assert!(writer.read(&mut buf).is_err());
387         assert!(reader.write(&buf).is_err());
388     }
389 }