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