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