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