]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/fs.rs
doc: remove incomplete sentence
[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 c_str::{CString, ToCStr};
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::{mod, 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 pub fn open(path: &Path, fm: FileMode, fa: FileAccess) -> IoResult<FileDesc> {
154     let flags = match fm {
155         Open => 0,
156         Append => libc::O_APPEND,
157         Truncate => libc::O_TRUNC,
158     };
159     // Opening with a write permission must silently create the file.
160     let (flags, mode) = match fa {
161         Read => (flags | libc::O_RDONLY, 0),
162         Write => (flags | libc::O_WRONLY | libc::O_CREAT,
163                         libc::S_IRUSR | libc::S_IWUSR),
164         ReadWrite => (flags | libc::O_RDWR | libc::O_CREAT,
165                             libc::S_IRUSR | libc::S_IWUSR),
166     };
167
168     let path = path.to_c_str();
169     match retry(|| unsafe { libc::open(path.as_ptr(), flags, mode) }) {
170         -1 => Err(super::last_error()),
171         fd => Ok(FileDesc::new(fd, true)),
172     }
173 }
174
175 pub fn mkdir(p: &Path, mode: uint) -> IoResult<()> {
176     let p = p.to_c_str();
177     mkerr_libc(unsafe { libc::mkdir(p.as_ptr(), mode as libc::mode_t) })
178 }
179
180 pub fn readdir(p: &Path) -> IoResult<Vec<Path>> {
181     use libc::{dirent_t};
182     use libc::{opendir, readdir_r, closedir};
183
184     fn prune(root: &CString, dirs: Vec<Path>) -> Vec<Path> {
185         let root = unsafe { CString::new(root.as_ptr(), false) };
186         let root = Path::new(root);
187
188         dirs.into_iter().filter(|path| {
189             path.as_vec() != b"." && path.as_vec() != b".."
190         }).map(|path| root.join(path)).collect()
191     }
192
193     extern {
194         fn rust_dirent_t_size() -> libc::c_int;
195         fn rust_list_dir_val(ptr: *mut dirent_t) -> *const libc::c_char;
196     }
197
198     let size = unsafe { rust_dirent_t_size() };
199     let mut buf = Vec::<u8>::with_capacity(size as uint);
200     let ptr = buf.as_mut_ptr() as *mut dirent_t;
201
202     let p = p.to_c_str();
203     let dir_ptr = unsafe {opendir(p.as_ptr())};
204
205     if dir_ptr as uint != 0 {
206         let mut paths = vec!();
207         let mut entry_ptr = 0 as *mut dirent_t;
208         while unsafe { readdir_r(dir_ptr, ptr, &mut entry_ptr) == 0 } {
209             if entry_ptr.is_null() { break }
210             let cstr = unsafe {
211                 CString::new(rust_list_dir_val(entry_ptr), false)
212             };
213             paths.push(Path::new(cstr));
214         }
215         assert_eq!(unsafe { closedir(dir_ptr) }, 0);
216         Ok(prune(&p, paths))
217     } else {
218         Err(super::last_error())
219     }
220 }
221
222 pub fn unlink(p: &Path) -> IoResult<()> {
223     let p = p.to_c_str();
224     mkerr_libc(unsafe { libc::unlink(p.as_ptr()) })
225 }
226
227 pub fn rename(old: &Path, new: &Path) -> IoResult<()> {
228     let old = old.to_c_str();
229     let new = new.to_c_str();
230     mkerr_libc(unsafe {
231         libc::rename(old.as_ptr(), new.as_ptr())
232     })
233 }
234
235 pub fn chmod(p: &Path, mode: uint) -> IoResult<()> {
236     let p = p.to_c_str();
237     mkerr_libc(retry(|| unsafe {
238         libc::chmod(p.as_ptr(), mode as libc::mode_t)
239     }))
240 }
241
242 pub fn rmdir(p: &Path) -> IoResult<()> {
243     let p = p.to_c_str();
244     mkerr_libc(unsafe { libc::rmdir(p.as_ptr()) })
245 }
246
247 pub fn chown(p: &Path, uid: int, gid: int) -> IoResult<()> {
248     let p = p.to_c_str();
249     mkerr_libc(retry(|| unsafe {
250         libc::chown(p.as_ptr(), uid as libc::uid_t, gid as libc::gid_t)
251     }))
252 }
253
254 pub fn readlink(p: &Path) -> IoResult<Path> {
255     let c_path = p.to_c_str();
256     let p = c_path.as_ptr();
257     let mut len = unsafe { libc::pathconf(p as *mut _, libc::_PC_NAME_MAX) };
258     if len == -1 {
259         len = 1024; // FIXME: read PATH_MAX from C ffi?
260     }
261     let mut buf: Vec<u8> = Vec::with_capacity(len as uint);
262     match unsafe {
263         libc::readlink(p, buf.as_ptr() as *mut libc::c_char,
264                        len as libc::size_t) as libc::c_int
265     } {
266         -1 => Err(super::last_error()),
267         n => {
268             assert!(n > 0);
269             unsafe { buf.set_len(n as uint); }
270             Ok(Path::new(buf))
271         }
272     }
273 }
274
275 pub fn symlink(src: &Path, dst: &Path) -> IoResult<()> {
276     let src = src.to_c_str();
277     let dst = dst.to_c_str();
278     mkerr_libc(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) })
279 }
280
281 pub fn link(src: &Path, dst: &Path) -> IoResult<()> {
282     let src = src.to_c_str();
283     let dst = dst.to_c_str();
284     mkerr_libc(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) })
285 }
286
287 fn mkstat(stat: &libc::stat) -> FileStat {
288     // FileStat times are in milliseconds
289     fn mktime(secs: u64, nsecs: u64) -> u64 { secs * 1000 + nsecs / 1000000 }
290
291     #[cfg(not(any(target_os = "linux", target_os = "android")))]
292     fn flags(stat: &libc::stat) -> u64 { stat.st_flags as u64 }
293     #[cfg(any(target_os = "linux", target_os = "android"))]
294     fn flags(_stat: &libc::stat) -> u64 { 0 }
295
296     #[cfg(not(any(target_os = "linux", target_os = "android")))]
297     fn gen(stat: &libc::stat) -> u64 { stat.st_gen as u64 }
298     #[cfg(any(target_os = "linux", target_os = "android"))]
299     fn gen(_stat: &libc::stat) -> u64 { 0 }
300
301     FileStat {
302         size: stat.st_size as u64,
303         kind: match (stat.st_mode as libc::mode_t) & libc::S_IFMT {
304             libc::S_IFREG => io::FileType::RegularFile,
305             libc::S_IFDIR => io::FileType::Directory,
306             libc::S_IFIFO => io::FileType::NamedPipe,
307             libc::S_IFBLK => io::FileType::BlockSpecial,
308             libc::S_IFLNK => io::FileType::Symlink,
309             _ => io::FileType::Unknown,
310         },
311         perm: FilePermission::from_bits_truncate(stat.st_mode as u32),
312         created: mktime(stat.st_ctime as u64, stat.st_ctime_nsec as u64),
313         modified: mktime(stat.st_mtime as u64, stat.st_mtime_nsec as u64),
314         accessed: mktime(stat.st_atime as u64, stat.st_atime_nsec as u64),
315         unstable: UnstableFileStat {
316             device: stat.st_dev as u64,
317             inode: stat.st_ino as u64,
318             rdev: stat.st_rdev as u64,
319             nlink: stat.st_nlink as u64,
320             uid: stat.st_uid as u64,
321             gid: stat.st_gid as u64,
322             blksize: stat.st_blksize as u64,
323             blocks: stat.st_blocks as u64,
324             flags: flags(stat),
325             gen: gen(stat),
326         },
327     }
328 }
329
330 pub fn stat(p: &Path) -> IoResult<FileStat> {
331     let p = p.to_c_str();
332     let mut stat: libc::stat = unsafe { mem::zeroed() };
333     match unsafe { libc::stat(p.as_ptr(), &mut stat) } {
334         0 => Ok(mkstat(&stat)),
335         _ => Err(super::last_error()),
336     }
337 }
338
339 pub fn lstat(p: &Path) -> IoResult<FileStat> {
340     let p = p.to_c_str();
341     let mut stat: libc::stat = unsafe { mem::zeroed() };
342     match unsafe { libc::lstat(p.as_ptr(), &mut stat) } {
343         0 => Ok(mkstat(&stat)),
344         _ => Err(super::last_error()),
345     }
346 }
347
348 pub fn utime(p: &Path, atime: u64, mtime: u64) -> IoResult<()> {
349     let p = p.to_c_str();
350     let buf = libc::utimbuf {
351         actime: (atime / 1000) as libc::time_t,
352         modtime: (mtime / 1000) as libc::time_t,
353     };
354     mkerr_libc(unsafe { libc::utime(p.as_ptr(), &buf) })
355 }
356
357 #[cfg(test)]
358 mod tests {
359     use super::FileDesc;
360     use libc;
361     use os;
362     use prelude::v1::*;
363
364     #[cfg_attr(target_os = "freebsd", ignore)] // hmm, maybe pipes have a tiny buffer
365     #[test]
366     fn test_file_desc() {
367         // Run this test with some pipes so we don't have to mess around with
368         // opening or closing files.
369         let os::Pipe { reader, writer } = unsafe { os::pipe().unwrap() };
370         let mut reader = FileDesc::new(reader, true);
371         let mut writer = FileDesc::new(writer, true);
372
373         writer.write(b"test").ok().unwrap();
374         let mut buf = [0u8; 4];
375         match reader.read(&mut buf) {
376             Ok(4) => {
377                 assert_eq!(buf[0], 't' as u8);
378                 assert_eq!(buf[1], 'e' as u8);
379                 assert_eq!(buf[2], 's' as u8);
380                 assert_eq!(buf[3], 't' as u8);
381             }
382             r => panic!("invalid read: {}", r),
383         }
384
385         assert!(writer.read(&mut buf).is_err());
386         assert!(reader.write(&buf).is_err());
387     }
388 }