]> git.lizzy.rs Git - rust.git/blob - src/libnative/io/file_unix.rs
fda9b7b1932b0a4b03477c4ecae18dfa2e4ae0de
[rust.git] / src / libnative / io / file_unix.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 alloc::arc::Arc;
14 use libc::{c_int, c_void};
15 use libc;
16 use std::c_str::CString;
17 use std::mem;
18 use std::rt::rtio;
19 use std::rt::rtio::IoResult;
20
21 use io::{retry, keep_going};
22 use io::util;
23
24 pub type fd_t = libc::c_int;
25
26 struct Inner {
27     fd: fd_t,
28     close_on_drop: bool,
29 }
30
31 pub struct FileDesc {
32     inner: Arc<Inner>
33 }
34
35 impl FileDesc {
36     /// Create a `FileDesc` from an open C file descriptor.
37     ///
38     /// The `FileDesc` will take ownership of the specified file descriptor and
39     /// close it upon destruction if the `close_on_drop` flag is true, otherwise
40     /// it will not close the file descriptor when this `FileDesc` is dropped.
41     ///
42     /// Note that all I/O operations done on this object will be *blocking*, but
43     /// they do not require the runtime to be active.
44     pub fn new(fd: fd_t, close_on_drop: bool) -> FileDesc {
45         FileDesc { inner: Arc::new(Inner {
46             fd: fd,
47             close_on_drop: close_on_drop
48         }) }
49     }
50
51     // FIXME(#10465) these functions should not be public, but anything in
52     //               native::io wanting to use them is forced to have all the
53     //               rtio traits in scope
54     pub fn inner_read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
55         let ret = retry(|| unsafe {
56             libc::read(self.fd(),
57                        buf.as_mut_ptr() as *mut libc::c_void,
58                        buf.len() as libc::size_t) as libc::c_int
59         });
60         if ret == 0 {
61             Err(util::eof())
62         } else if ret < 0 {
63             Err(super::last_error())
64         } else {
65             Ok(ret as uint)
66         }
67     }
68     pub fn inner_write(&mut self, buf: &[u8]) -> IoResult<()> {
69         let ret = keep_going(buf, |buf, len| {
70             unsafe {
71                 libc::write(self.fd(), buf as *libc::c_void,
72                             len as libc::size_t) as i64
73             }
74         });
75         if ret < 0 {
76             Err(super::last_error())
77         } else {
78             Ok(())
79         }
80     }
81
82     pub fn fd(&self) -> fd_t { self.inner.fd }
83 }
84
85 impl rtio::RtioFileStream for FileDesc {
86     fn read(&mut self, buf: &mut [u8]) -> IoResult<int> {
87         self.inner_read(buf).map(|i| i as int)
88     }
89     fn write(&mut self, buf: &[u8]) -> IoResult<()> {
90         self.inner_write(buf)
91     }
92     fn pread(&mut self, buf: &mut [u8], offset: u64) -> IoResult<int> {
93         match retry(|| unsafe {
94             libc::pread(self.fd(), buf.as_ptr() as *libc::c_void,
95                         buf.len() as libc::size_t,
96                         offset as libc::off_t) as libc::c_int
97         }) {
98             -1 => Err(super::last_error()),
99             n => Ok(n as int)
100         }
101     }
102     fn pwrite(&mut self, buf: &[u8], offset: u64) -> IoResult<()> {
103         super::mkerr_libc(retry(|| unsafe {
104             libc::pwrite(self.fd(), buf.as_ptr() as *libc::c_void,
105                          buf.len() as libc::size_t, offset as libc::off_t)
106         } as c_int))
107     }
108     fn seek(&mut self, pos: i64, whence: rtio::SeekStyle) -> IoResult<u64> {
109         let whence = match whence {
110             rtio::SeekSet => libc::SEEK_SET,
111             rtio::SeekEnd => libc::SEEK_END,
112             rtio::SeekCur => libc::SEEK_CUR,
113         };
114         let n = unsafe { libc::lseek(self.fd(), pos as libc::off_t, whence) };
115         if n < 0 {
116             Err(super::last_error())
117         } else {
118             Ok(n as u64)
119         }
120     }
121     fn tell(&self) -> IoResult<u64> {
122         let n = unsafe { libc::lseek(self.fd(), 0, libc::SEEK_CUR) };
123         if n < 0 {
124             Err(super::last_error())
125         } else {
126             Ok(n as u64)
127         }
128     }
129     fn fsync(&mut self) -> IoResult<()> {
130         super::mkerr_libc(retry(|| unsafe { libc::fsync(self.fd()) }))
131     }
132     fn datasync(&mut self) -> IoResult<()> {
133         return super::mkerr_libc(os_datasync(self.fd()));
134
135         #[cfg(target_os = "macos")]
136         fn os_datasync(fd: c_int) -> c_int {
137             unsafe { libc::fcntl(fd, libc::F_FULLFSYNC) }
138         }
139         #[cfg(target_os = "linux")]
140         fn os_datasync(fd: c_int) -> c_int {
141             retry(|| unsafe { libc::fdatasync(fd) })
142         }
143         #[cfg(not(target_os = "macos"), not(target_os = "linux"))]
144         fn os_datasync(fd: c_int) -> c_int {
145             retry(|| unsafe { libc::fsync(fd) })
146         }
147     }
148     fn truncate(&mut self, offset: i64) -> IoResult<()> {
149         super::mkerr_libc(retry(|| unsafe {
150             libc::ftruncate(self.fd(), offset as libc::off_t)
151         }))
152     }
153
154     fn fstat(&mut self) -> IoResult<rtio::FileStat> {
155         let mut stat: libc::stat = unsafe { mem::zeroed() };
156         match retry(|| unsafe { libc::fstat(self.fd(), &mut stat) }) {
157             0 => Ok(mkstat(&stat)),
158             _ => Err(super::last_error()),
159         }
160     }
161 }
162
163 impl rtio::RtioPipe for FileDesc {
164     fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
165         self.inner_read(buf)
166     }
167     fn write(&mut self, buf: &[u8]) -> IoResult<()> {
168         self.inner_write(buf)
169     }
170     fn clone(&self) -> Box<rtio::RtioPipe:Send> {
171         box FileDesc { inner: self.inner.clone() } as Box<rtio::RtioPipe:Send>
172     }
173
174     // Only supported on named pipes currently. Note that this doesn't have an
175     // impact on the std::io primitives, this is never called via
176     // std::io::PipeStream. If the functionality is exposed in the future, then
177     // these methods will need to be implemented.
178     fn close_read(&mut self) -> IoResult<()> {
179         Err(super::unimpl())
180     }
181     fn close_write(&mut self) -> IoResult<()> {
182         Err(super::unimpl())
183     }
184     fn set_timeout(&mut self, _t: Option<u64>) {}
185     fn set_read_timeout(&mut self, _t: Option<u64>) {}
186     fn set_write_timeout(&mut self, _t: Option<u64>) {}
187 }
188
189 impl rtio::RtioTTY for FileDesc {
190     fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
191         self.inner_read(buf)
192     }
193     fn write(&mut self, buf: &[u8]) -> IoResult<()> {
194         self.inner_write(buf)
195     }
196     fn set_raw(&mut self, _raw: bool) -> IoResult<()> {
197         Err(super::unimpl())
198     }
199     fn get_winsize(&mut self) -> IoResult<(int, int)> {
200         Err(super::unimpl())
201     }
202     fn isatty(&self) -> bool { false }
203 }
204
205 impl Drop for Inner {
206     fn drop(&mut self) {
207         // closing stdio file handles makes no sense, so never do it. Also, note
208         // that errors are ignored when closing a file descriptor. The reason
209         // for this is that if an error occurs we don't actually know if the
210         // file descriptor was closed or not, and if we retried (for something
211         // like EINTR), we might close another valid file descriptor (opened
212         // after we closed ours.
213         if self.close_on_drop && self.fd > libc::STDERR_FILENO {
214             let n = unsafe { libc::close(self.fd) };
215             if n != 0 {
216                 println!("error {} when closing file descriptor {}", n,
217                          self.fd);
218             }
219         }
220     }
221 }
222
223 pub struct CFile {
224     file: *libc::FILE,
225     fd: FileDesc,
226 }
227
228 impl CFile {
229     /// Create a `CFile` from an open `FILE` pointer.
230     ///
231     /// The `CFile` takes ownership of the `FILE` pointer and will close it upon
232     /// destruction.
233     pub fn new(file: *libc::FILE) -> CFile {
234         CFile {
235             file: file,
236             fd: FileDesc::new(unsafe { libc::fileno(file) }, false)
237         }
238     }
239
240     pub fn flush(&mut self) -> IoResult<()> {
241         super::mkerr_libc(retry(|| unsafe { libc::fflush(self.file) }))
242     }
243 }
244
245 impl rtio::RtioFileStream for CFile {
246     fn read(&mut self, buf: &mut [u8]) -> IoResult<int> {
247         let ret = keep_going(buf, |buf, len| {
248             unsafe {
249                 libc::fread(buf as *mut libc::c_void, 1, len as libc::size_t,
250                             self.file) as i64
251             }
252         });
253         if ret == 0 {
254             Err(util::eof())
255         } else if ret < 0 {
256             Err(super::last_error())
257         } else {
258             Ok(ret as int)
259         }
260     }
261
262     fn write(&mut self, buf: &[u8]) -> IoResult<()> {
263         let ret = keep_going(buf, |buf, len| {
264             unsafe {
265                 libc::fwrite(buf as *libc::c_void, 1, len as libc::size_t,
266                             self.file) as i64
267             }
268         });
269         if ret < 0 {
270             Err(super::last_error())
271         } else {
272             Ok(())
273         }
274     }
275
276     fn pread(&mut self, buf: &mut [u8], offset: u64) -> IoResult<int> {
277         self.flush().and_then(|()| self.fd.pread(buf, offset))
278     }
279     fn pwrite(&mut self, buf: &[u8], offset: u64) -> IoResult<()> {
280         self.flush().and_then(|()| self.fd.pwrite(buf, offset))
281     }
282     fn seek(&mut self, pos: i64, style: rtio::SeekStyle) -> IoResult<u64> {
283         let whence = match style {
284             rtio::SeekSet => libc::SEEK_SET,
285             rtio::SeekEnd => libc::SEEK_END,
286             rtio::SeekCur => libc::SEEK_CUR,
287         };
288         let n = unsafe { libc::fseek(self.file, pos as libc::c_long, whence) };
289         if n < 0 {
290             Err(super::last_error())
291         } else {
292             Ok(n as u64)
293         }
294     }
295     fn tell(&self) -> IoResult<u64> {
296         let ret = unsafe { libc::ftell(self.file) };
297         if ret < 0 {
298             Err(super::last_error())
299         } else {
300             Ok(ret as u64)
301         }
302     }
303     fn fsync(&mut self) -> IoResult<()> {
304         self.flush().and_then(|()| self.fd.fsync())
305     }
306     fn datasync(&mut self) -> IoResult<()> {
307         self.flush().and_then(|()| self.fd.fsync())
308     }
309     fn truncate(&mut self, offset: i64) -> IoResult<()> {
310         self.flush().and_then(|()| self.fd.truncate(offset))
311     }
312
313     fn fstat(&mut self) -> IoResult<rtio::FileStat> {
314         self.flush().and_then(|()| self.fd.fstat())
315     }
316 }
317
318 impl Drop for CFile {
319     fn drop(&mut self) {
320         unsafe { let _ = libc::fclose(self.file); }
321     }
322 }
323
324 pub fn open(path: &CString, fm: rtio::FileMode, fa: rtio::FileAccess)
325     -> IoResult<FileDesc>
326 {
327     let flags = match fm {
328         rtio::Open => 0,
329         rtio::Append => libc::O_APPEND,
330         rtio::Truncate => libc::O_TRUNC,
331     };
332     // Opening with a write permission must silently create the file.
333     let (flags, mode) = match fa {
334         rtio::Read => (flags | libc::O_RDONLY, 0),
335         rtio::Write => (flags | libc::O_WRONLY | libc::O_CREAT,
336                         libc::S_IRUSR | libc::S_IWUSR),
337         rtio::ReadWrite => (flags | libc::O_RDWR | libc::O_CREAT,
338                             libc::S_IRUSR | libc::S_IWUSR),
339     };
340
341     match retry(|| unsafe { libc::open(path.with_ref(|p| p), flags, mode) }) {
342         -1 => Err(super::last_error()),
343         fd => Ok(FileDesc::new(fd, true)),
344     }
345 }
346
347 pub fn mkdir(p: &CString, mode: uint) -> IoResult<()> {
348     super::mkerr_libc(retry(|| unsafe {
349         libc::mkdir(p.with_ref(|p| p), mode as libc::mode_t)
350     }))
351 }
352
353 pub fn readdir(p: &CString) -> IoResult<Vec<CString>> {
354     use libc::{dirent_t};
355     use libc::{opendir, readdir_r, closedir};
356
357     fn prune(root: &CString, dirs: Vec<Path>) -> Vec<CString> {
358         let root = unsafe { CString::new(root.with_ref(|p| p), false) };
359         let root = Path::new(root);
360
361         dirs.move_iter().filter(|path| {
362             path.as_vec() != bytes!(".") && path.as_vec() != bytes!("..")
363         }).map(|path| root.join(path).to_c_str()).collect()
364     }
365
366     extern {
367         fn rust_dirent_t_size() -> libc::c_int;
368         fn rust_list_dir_val(ptr: *mut dirent_t) -> *libc::c_char;
369     }
370
371     let size = unsafe { rust_dirent_t_size() };
372     let mut buf = Vec::<u8>::with_capacity(size as uint);
373     let ptr = buf.as_mut_slice().as_mut_ptr() as *mut dirent_t;
374
375     let dir_ptr = p.with_ref(|buf| unsafe { opendir(buf) });
376
377     if dir_ptr as uint != 0 {
378         let mut paths = vec!();
379         let mut entry_ptr = 0 as *mut dirent_t;
380         while unsafe { readdir_r(dir_ptr, ptr, &mut entry_ptr) == 0 } {
381             if entry_ptr.is_null() { break }
382             let cstr = unsafe {
383                 CString::new(rust_list_dir_val(entry_ptr), false)
384             };
385             paths.push(Path::new(cstr));
386         }
387         assert_eq!(unsafe { closedir(dir_ptr) }, 0);
388         Ok(prune(p, paths))
389     } else {
390         Err(super::last_error())
391     }
392 }
393
394 pub fn unlink(p: &CString) -> IoResult<()> {
395     super::mkerr_libc(retry(|| unsafe { libc::unlink(p.with_ref(|p| p)) }))
396 }
397
398 pub fn rename(old: &CString, new: &CString) -> IoResult<()> {
399     super::mkerr_libc(retry(|| unsafe {
400         libc::rename(old.with_ref(|p| p), new.with_ref(|p| p))
401     }))
402 }
403
404 pub fn chmod(p: &CString, mode: uint) -> IoResult<()> {
405     super::mkerr_libc(retry(|| unsafe {
406         libc::chmod(p.with_ref(|p| p), mode as libc::mode_t)
407     }))
408 }
409
410 pub fn rmdir(p: &CString) -> IoResult<()> {
411     super::mkerr_libc(retry(|| unsafe {
412         libc::rmdir(p.with_ref(|p| p))
413     }))
414 }
415
416 pub fn chown(p: &CString, uid: int, gid: int) -> IoResult<()> {
417     super::mkerr_libc(retry(|| unsafe {
418         libc::chown(p.with_ref(|p| p), uid as libc::uid_t,
419                     gid as libc::gid_t)
420     }))
421 }
422
423 pub fn readlink(p: &CString) -> IoResult<CString> {
424     let p = p.with_ref(|p| p);
425     let mut len = unsafe { libc::pathconf(p, libc::_PC_NAME_MAX) };
426     if len == -1 {
427         len = 1024; // FIXME: read PATH_MAX from C ffi?
428     }
429     let mut buf: Vec<u8> = Vec::with_capacity(len as uint);
430     match retry(|| unsafe {
431         libc::readlink(p, buf.as_ptr() as *mut libc::c_char,
432                        len as libc::size_t) as libc::c_int
433     }) {
434         -1 => Err(super::last_error()),
435         n => {
436             assert!(n > 0);
437             unsafe { buf.set_len(n as uint); }
438             Ok(buf.as_slice().to_c_str())
439         }
440     }
441 }
442
443 pub fn symlink(src: &CString, dst: &CString) -> IoResult<()> {
444     super::mkerr_libc(retry(|| unsafe {
445         libc::symlink(src.with_ref(|p| p), dst.with_ref(|p| p))
446     }))
447 }
448
449 pub fn link(src: &CString, dst: &CString) -> IoResult<()> {
450     super::mkerr_libc(retry(|| unsafe {
451         libc::link(src.with_ref(|p| p), dst.with_ref(|p| p))
452     }))
453 }
454
455 fn mkstat(stat: &libc::stat) -> rtio::FileStat {
456     // FileStat times are in milliseconds
457     fn mktime(secs: u64, nsecs: u64) -> u64 { secs * 1000 + nsecs / 1000000 }
458
459     #[cfg(not(target_os = "linux"), not(target_os = "android"))]
460     fn flags(stat: &libc::stat) -> u64 { stat.st_flags as u64 }
461     #[cfg(target_os = "linux")] #[cfg(target_os = "android")]
462     fn flags(_stat: &libc::stat) -> u64 { 0 }
463
464     #[cfg(not(target_os = "linux"), not(target_os = "android"))]
465     fn gen(stat: &libc::stat) -> u64 { stat.st_gen as u64 }
466     #[cfg(target_os = "linux")] #[cfg(target_os = "android")]
467     fn gen(_stat: &libc::stat) -> u64 { 0 }
468
469     rtio::FileStat {
470         size: stat.st_size as u64,
471         kind: stat.st_mode as u64,
472         perm: stat.st_mode as u64,
473         created: mktime(stat.st_ctime as u64, stat.st_ctime_nsec as u64),
474         modified: mktime(stat.st_mtime as u64, stat.st_mtime_nsec as u64),
475         accessed: mktime(stat.st_atime as u64, stat.st_atime_nsec as u64),
476         device: stat.st_dev as u64,
477         inode: stat.st_ino as u64,
478         rdev: stat.st_rdev as u64,
479         nlink: stat.st_nlink as u64,
480         uid: stat.st_uid as u64,
481         gid: stat.st_gid as u64,
482         blksize: stat.st_blksize as u64,
483         blocks: stat.st_blocks as u64,
484         flags: flags(stat),
485         gen: gen(stat),
486     }
487 }
488
489 pub fn stat(p: &CString) -> IoResult<rtio::FileStat> {
490     let mut stat: libc::stat = unsafe { mem::zeroed() };
491     match retry(|| unsafe { libc::stat(p.with_ref(|p| p), &mut stat) }) {
492         0 => Ok(mkstat(&stat)),
493         _ => Err(super::last_error()),
494     }
495 }
496
497 pub fn lstat(p: &CString) -> IoResult<rtio::FileStat> {
498     let mut stat: libc::stat = unsafe { mem::zeroed() };
499     match retry(|| unsafe { libc::lstat(p.with_ref(|p| p), &mut stat) }) {
500         0 => Ok(mkstat(&stat)),
501         _ => Err(super::last_error()),
502     }
503 }
504
505 pub fn utime(p: &CString, atime: u64, mtime: u64) -> IoResult<()> {
506     let buf = libc::utimbuf {
507         actime: (atime / 1000) as libc::time_t,
508         modtime: (mtime / 1000) as libc::time_t,
509     };
510     super::mkerr_libc(retry(|| unsafe {
511         libc::utime(p.with_ref(|p| p), &buf)
512     }))
513 }
514
515 #[cfg(test)]
516 mod tests {
517     use super::{CFile, FileDesc};
518     use libc;
519     use std::os;
520     use std::rt::rtio::{RtioFileStream, SeekSet};
521
522     #[ignore(cfg(target_os = "freebsd"))] // hmm, maybe pipes have a tiny buffer
523     #[test]
524     fn test_file_desc() {
525         // Run this test with some pipes so we don't have to mess around with
526         // opening or closing files.
527         let os::Pipe { input, out } = os::pipe();
528         let mut reader = FileDesc::new(input, true);
529         let mut writer = FileDesc::new(out, true);
530
531         writer.inner_write(bytes!("test")).ok().unwrap();
532         let mut buf = [0u8, ..4];
533         match reader.inner_read(buf) {
534             Ok(4) => {
535                 assert_eq!(buf[0], 't' as u8);
536                 assert_eq!(buf[1], 'e' as u8);
537                 assert_eq!(buf[2], 's' as u8);
538                 assert_eq!(buf[3], 't' as u8);
539             }
540             r => fail!("invalid read: {:?}", r)
541         }
542
543         assert!(writer.inner_read(buf).is_err());
544         assert!(reader.inner_write(buf).is_err());
545     }
546
547     #[test]
548     fn test_cfile() {
549         unsafe {
550             let f = libc::tmpfile();
551             assert!(!f.is_null());
552             let mut file = CFile::new(f);
553
554             file.write(bytes!("test")).ok().unwrap();
555             let mut buf = [0u8, ..4];
556             let _ = file.seek(0, SeekSet).ok().unwrap();
557             match file.read(buf) {
558                 Ok(4) => {
559                     assert_eq!(buf[0], 't' as u8);
560                     assert_eq!(buf[1], 'e' as u8);
561                     assert_eq!(buf[2], 's' as u8);
562                     assert_eq!(buf[3], 't' as u8);
563                 }
564                 r => fail!("invalid read: {:?}", r)
565             }
566         }
567     }
568 }