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