]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/fs.rs
Auto merge of #28957 - GuillaumeGomez:patch-5, r=Manishearth
[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 use io::prelude::*;
12 use os::unix::prelude::*;
13
14 use ffi::{CString, CStr, OsString, OsStr};
15 use fmt;
16 use io::{self, Error, ErrorKind, SeekFrom};
17 use libc::{self, c_int, size_t, off_t, c_char, mode_t};
18 use mem;
19 use path::{Path, PathBuf};
20 use ptr;
21 use sync::Arc;
22 use sys::fd::FileDesc;
23 use sys::platform::raw;
24 use sys::{c, cvt, cvt_r};
25 use sys_common::{AsInner, FromInner};
26 use vec::Vec;
27
28 pub struct File(FileDesc);
29
30 #[derive(Clone)]
31 pub struct FileAttr {
32     stat: raw::stat,
33 }
34
35 pub struct ReadDir {
36     dirp: Dir,
37     root: Arc<PathBuf>,
38 }
39
40 struct Dir(*mut libc::DIR);
41
42 unsafe impl Send for Dir {}
43 unsafe impl Sync for Dir {}
44
45 pub struct DirEntry {
46     buf: Vec<u8>, // actually *mut libc::dirent_t
47     root: Arc<PathBuf>,
48 }
49
50 #[derive(Clone)]
51 pub struct OpenOptions {
52     flags: c_int,
53     read: bool,
54     write: bool,
55     mode: mode_t,
56 }
57
58 #[derive(Clone, PartialEq, Eq, Debug)]
59 pub struct FilePermissions { mode: mode_t }
60
61 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
62 pub struct FileType { mode: mode_t }
63
64 pub struct DirBuilder { mode: mode_t }
65
66 impl FileAttr {
67     pub fn size(&self) -> u64 { self.stat.st_size as u64 }
68     pub fn perm(&self) -> FilePermissions {
69         FilePermissions { mode: (self.stat.st_mode as mode_t) & 0o777 }
70     }
71
72     pub fn file_type(&self) -> FileType {
73         FileType { mode: self.stat.st_mode as mode_t }
74     }
75 }
76
77 impl AsInner<raw::stat> for FileAttr {
78     fn as_inner(&self) -> &raw::stat { &self.stat }
79 }
80
81 /// OS-specific extension methods for `fs::Metadata`
82 #[stable(feature = "metadata_ext", since = "1.1.0")]
83 pub trait MetadataExt {
84     /// Gain a reference to the underlying `stat` structure which contains the
85     /// raw information returned by the OS.
86     ///
87     /// The contents of the returned `stat` are **not** consistent across Unix
88     /// platforms. The `os::unix::fs::MetadataExt` trait contains the cross-Unix
89     /// abstractions contained within the raw stat.
90     #[stable(feature = "metadata_ext", since = "1.1.0")]
91     fn as_raw_stat(&self) -> &raw::stat;
92 }
93
94 #[stable(feature = "metadata_ext", since = "1.1.0")]
95 impl MetadataExt for ::fs::Metadata {
96     fn as_raw_stat(&self) -> &raw::stat { &self.as_inner().stat }
97 }
98
99 impl FilePermissions {
100     pub fn readonly(&self) -> bool { self.mode & 0o222 == 0 }
101     pub fn set_readonly(&mut self, readonly: bool) {
102         if readonly {
103             self.mode &= !0o222;
104         } else {
105             self.mode |= 0o222;
106         }
107     }
108     pub fn mode(&self) -> raw::mode_t { self.mode }
109 }
110
111 impl FileType {
112     pub fn is_dir(&self) -> bool { self.is(libc::S_IFDIR) }
113     pub fn is_file(&self) -> bool { self.is(libc::S_IFREG) }
114     pub fn is_symlink(&self) -> bool { self.is(libc::S_IFLNK) }
115
116     pub fn is(&self, mode: mode_t) -> bool { self.mode & libc::S_IFMT == mode }
117 }
118
119 impl FromInner<raw::mode_t> for FilePermissions {
120     fn from_inner(mode: raw::mode_t) -> FilePermissions {
121         FilePermissions { mode: mode as mode_t }
122     }
123 }
124
125 impl Iterator for ReadDir {
126     type Item = io::Result<DirEntry>;
127
128     fn next(&mut self) -> Option<io::Result<DirEntry>> {
129         extern {
130             fn rust_dirent_t_size() -> c_int;
131         }
132
133         let mut buf: Vec<u8> = Vec::with_capacity(unsafe {
134             rust_dirent_t_size() as usize
135         });
136         let ptr = buf.as_mut_ptr() as *mut libc::dirent_t;
137
138         let mut entry_ptr = ptr::null_mut();
139         loop {
140             if unsafe { libc::readdir_r(self.dirp.0, ptr, &mut entry_ptr) != 0 } {
141                 return Some(Err(Error::last_os_error()))
142             }
143             if entry_ptr.is_null() {
144                 return None
145             }
146
147             let entry = DirEntry {
148                 buf: buf,
149                 root: self.root.clone()
150             };
151             if entry.name_bytes() == b"." || entry.name_bytes() == b".." {
152                 buf = entry.buf;
153             } else {
154                 return Some(Ok(entry))
155             }
156         }
157     }
158 }
159
160 impl Drop for Dir {
161     fn drop(&mut self) {
162         let r = unsafe { libc::closedir(self.0) };
163         debug_assert_eq!(r, 0);
164     }
165 }
166
167 impl DirEntry {
168     pub fn path(&self) -> PathBuf {
169         self.root.join(<OsStr as OsStrExt>::from_bytes(self.name_bytes()))
170     }
171
172     pub fn file_name(&self) -> OsString {
173         OsStr::from_bytes(self.name_bytes()).to_os_string()
174     }
175
176     pub fn metadata(&self) -> io::Result<FileAttr> {
177         lstat(&self.path())
178     }
179
180     pub fn file_type(&self) -> io::Result<FileType> {
181         extern {
182             fn rust_dir_get_mode(ptr: *mut libc::dirent_t) -> c_int;
183         }
184         unsafe {
185             match rust_dir_get_mode(self.dirent()) {
186                 -1 => lstat(&self.path()).map(|m| m.file_type()),
187                 n => Ok(FileType { mode: n as mode_t }),
188             }
189         }
190     }
191
192     pub fn ino(&self) -> raw::ino_t {
193         extern {
194             fn rust_dir_get_ino(ptr: *mut libc::dirent_t) -> raw::ino_t;
195         }
196         unsafe { rust_dir_get_ino(self.dirent()) }
197     }
198
199     fn name_bytes(&self) -> &[u8] {
200         extern {
201             fn rust_list_dir_val(ptr: *mut libc::dirent_t) -> *const c_char;
202         }
203         unsafe {
204             CStr::from_ptr(rust_list_dir_val(self.dirent())).to_bytes()
205         }
206     }
207
208     fn dirent(&self) -> *mut libc::dirent_t {
209         self.buf.as_ptr() as *mut _
210     }
211 }
212
213 impl OpenOptions {
214     pub fn new() -> OpenOptions {
215         OpenOptions {
216             flags: libc::O_CLOEXEC,
217             read: false,
218             write: false,
219             mode: 0o666,
220         }
221     }
222
223     pub fn read(&mut self, read: bool) {
224         self.read = read;
225     }
226
227     pub fn write(&mut self, write: bool) {
228         self.write = write;
229     }
230
231     pub fn append(&mut self, append: bool) {
232         self.flag(libc::O_APPEND, append);
233     }
234
235     pub fn truncate(&mut self, truncate: bool) {
236         self.flag(libc::O_TRUNC, truncate);
237     }
238
239     pub fn create(&mut self, create: bool) {
240         self.flag(libc::O_CREAT, create);
241     }
242
243     pub fn mode(&mut self, mode: raw::mode_t) {
244         self.mode = mode as mode_t;
245     }
246
247     fn flag(&mut self, bit: c_int, on: bool) {
248         if on {
249             self.flags |= bit;
250         } else {
251             self.flags &= !bit;
252         }
253     }
254 }
255
256 impl File {
257     pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
258         let path = try!(cstr(path));
259         File::open_c(&path, opts)
260     }
261
262     pub fn open_c(path: &CStr, opts: &OpenOptions) -> io::Result<File> {
263         let flags = opts.flags | match (opts.read, opts.write) {
264             (true, true) => libc::O_RDWR,
265             (false, true) => libc::O_WRONLY,
266             (true, false) |
267             (false, false) => libc::O_RDONLY,
268         };
269         let fd = try!(cvt_r(|| unsafe {
270             libc::open(path.as_ptr(), flags, opts.mode)
271         }));
272         let fd = FileDesc::new(fd);
273         // Even though we open with the O_CLOEXEC flag, still set CLOEXEC here,
274         // in case the open flag is not supported (it's just ignored by the OS
275         // in that case).
276         fd.set_cloexec();
277         Ok(File(fd))
278     }
279
280     pub fn file_attr(&self) -> io::Result<FileAttr> {
281         let mut stat: raw::stat = unsafe { mem::zeroed() };
282         try!(cvt(unsafe {
283             libc::fstat(self.0.raw(), &mut stat as *mut _ as *mut _)
284         }));
285         Ok(FileAttr { stat: stat })
286     }
287
288     pub fn fsync(&self) -> io::Result<()> {
289         try!(cvt_r(|| unsafe { libc::fsync(self.0.raw()) }));
290         Ok(())
291     }
292
293     pub fn datasync(&self) -> io::Result<()> {
294         try!(cvt_r(|| unsafe { os_datasync(self.0.raw()) }));
295         return Ok(());
296
297         #[cfg(any(target_os = "macos", target_os = "ios"))]
298         unsafe fn os_datasync(fd: c_int) -> c_int {
299             libc::fcntl(fd, libc::F_FULLFSYNC)
300         }
301         #[cfg(target_os = "linux")]
302         unsafe fn os_datasync(fd: c_int) -> c_int { libc::fdatasync(fd) }
303         #[cfg(not(any(target_os = "macos",
304                       target_os = "ios",
305                       target_os = "linux")))]
306         unsafe fn os_datasync(fd: c_int) -> c_int { libc::fsync(fd) }
307     }
308
309     pub fn truncate(&self, size: u64) -> io::Result<()> {
310         try!(cvt_r(|| unsafe {
311             libc::ftruncate(self.0.raw(), size as libc::off_t)
312         }));
313         Ok(())
314     }
315
316     pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
317         self.0.read(buf)
318     }
319
320     pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
321         self.0.write(buf)
322     }
323
324     pub fn flush(&self) -> io::Result<()> { Ok(()) }
325
326     pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
327         let (whence, pos) = match pos {
328             SeekFrom::Start(off) => (libc::SEEK_SET, off as off_t),
329             SeekFrom::End(off) => (libc::SEEK_END, off as off_t),
330             SeekFrom::Current(off) => (libc::SEEK_CUR, off as off_t),
331         };
332         let n = try!(cvt(unsafe { libc::lseek(self.0.raw(), pos, whence) }));
333         Ok(n as u64)
334     }
335
336     pub fn fd(&self) -> &FileDesc { &self.0 }
337
338     pub fn into_fd(self) -> FileDesc { self.0 }
339 }
340
341 impl DirBuilder {
342     pub fn new() -> DirBuilder {
343         DirBuilder { mode: 0o777 }
344     }
345
346     pub fn mkdir(&self, p: &Path) -> io::Result<()> {
347         let p = try!(cstr(p));
348         try!(cvt(unsafe { libc::mkdir(p.as_ptr(), self.mode) }));
349         Ok(())
350     }
351
352     pub fn set_mode(&mut self, mode: mode_t) {
353         self.mode = mode;
354     }
355 }
356
357 fn cstr(path: &Path) -> io::Result<CString> {
358     path.as_os_str().to_cstring().ok_or(
359         io::Error::new(io::ErrorKind::InvalidInput, "path contained a null"))
360 }
361
362 impl FromInner<c_int> for File {
363     fn from_inner(fd: c_int) -> File {
364         File(FileDesc::new(fd))
365     }
366 }
367
368 impl fmt::Debug for File {
369     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
370         #[cfg(target_os = "linux")]
371         fn get_path(fd: c_int) -> Option<PathBuf> {
372             use string::ToString;
373             let mut p = PathBuf::from("/proc/self/fd");
374             p.push(&fd.to_string());
375             readlink(&p).ok()
376         }
377
378         #[cfg(target_os = "macos")]
379         fn get_path(fd: c_int) -> Option<PathBuf> {
380             // FIXME: The use of PATH_MAX is generally not encouraged, but it
381             // is inevitable in this case because OS X defines `fcntl` with
382             // `F_GETPATH` in terms of `MAXPATHLEN`, and there are no
383             // alternatives. If a better method is invented, it should be used
384             // instead.
385             let mut buf = vec![0;libc::PATH_MAX as usize];
386             let n = unsafe { libc::fcntl(fd, libc::F_GETPATH, buf.as_ptr()) };
387             if n == -1 {
388                 return None;
389             }
390             let l = buf.iter().position(|&c| c == 0).unwrap();
391             buf.truncate(l as usize);
392             buf.shrink_to_fit();
393             Some(PathBuf::from(OsString::from_vec(buf)))
394         }
395
396         #[cfg(not(any(target_os = "linux", target_os = "macos")))]
397         fn get_path(_fd: c_int) -> Option<PathBuf> {
398             // FIXME(#24570): implement this for other Unix platforms
399             None
400         }
401
402         #[cfg(any(target_os = "linux", target_os = "macos"))]
403         fn get_mode(fd: c_int) -> Option<(bool, bool)> {
404             let mode = unsafe { libc::fcntl(fd, libc::F_GETFL) };
405             if mode == -1 {
406                 return None;
407             }
408             match mode & libc::O_ACCMODE {
409                 libc::O_RDONLY => Some((true, false)),
410                 libc::O_RDWR => Some((true, true)),
411                 libc::O_WRONLY => Some((false, true)),
412                 _ => None
413             }
414         }
415
416         #[cfg(not(any(target_os = "linux", target_os = "macos")))]
417         fn get_mode(_fd: c_int) -> Option<(bool, bool)> {
418             // FIXME(#24570): implement this for other Unix platforms
419             None
420         }
421
422         let fd = self.0.raw();
423         let mut b = f.debug_struct("File");
424         b.field("fd", &fd);
425         if let Some(path) = get_path(fd) {
426             b.field("path", &path);
427         }
428         if let Some((read, write)) = get_mode(fd) {
429             b.field("read", &read).field("write", &write);
430         }
431         b.finish()
432     }
433 }
434
435 pub fn readdir(p: &Path) -> io::Result<ReadDir> {
436     let root = Arc::new(p.to_path_buf());
437     let p = try!(cstr(p));
438     unsafe {
439         let ptr = libc::opendir(p.as_ptr());
440         if ptr.is_null() {
441             Err(Error::last_os_error())
442         } else {
443             Ok(ReadDir { dirp: Dir(ptr), root: root })
444         }
445     }
446 }
447
448 pub fn unlink(p: &Path) -> io::Result<()> {
449     let p = try!(cstr(p));
450     try!(cvt(unsafe { libc::unlink(p.as_ptr()) }));
451     Ok(())
452 }
453
454 pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
455     let old = try!(cstr(old));
456     let new = try!(cstr(new));
457     try!(cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) }));
458     Ok(())
459 }
460
461 pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
462     let p = try!(cstr(p));
463     try!(cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) }));
464     Ok(())
465 }
466
467 pub fn rmdir(p: &Path) -> io::Result<()> {
468     let p = try!(cstr(p));
469     try!(cvt(unsafe { libc::rmdir(p.as_ptr()) }));
470     Ok(())
471 }
472
473 pub fn readlink(p: &Path) -> io::Result<PathBuf> {
474     let c_path = try!(cstr(p));
475     let p = c_path.as_ptr();
476
477     let mut buf = Vec::with_capacity(256);
478
479     loop {
480         let buf_read = try!(cvt(unsafe {
481             libc::readlink(p, buf.as_mut_ptr() as *mut _, buf.capacity() as libc::size_t)
482         })) as usize;
483
484         unsafe { buf.set_len(buf_read); }
485
486         if buf_read != buf.capacity() {
487             buf.shrink_to_fit();
488
489             return Ok(PathBuf::from(OsString::from_vec(buf)));
490         }
491
492         // Trigger the internal buffer resizing logic of `Vec` by requiring
493         // more space than the current capacity. The length is guaranteed to be
494         // the same as the capacity due to the if statement above.
495         buf.reserve(1);
496     }
497 }
498
499 pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
500     let src = try!(cstr(src));
501     let dst = try!(cstr(dst));
502     try!(cvt(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) }));
503     Ok(())
504 }
505
506 pub fn link(src: &Path, dst: &Path) -> io::Result<()> {
507     let src = try!(cstr(src));
508     let dst = try!(cstr(dst));
509     try!(cvt(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) }));
510     Ok(())
511 }
512
513 pub fn stat(p: &Path) -> io::Result<FileAttr> {
514     let p = try!(cstr(p));
515     let mut stat: raw::stat = unsafe { mem::zeroed() };
516     try!(cvt(unsafe {
517         libc::stat(p.as_ptr(), &mut stat as *mut _ as *mut _)
518     }));
519     Ok(FileAttr { stat: stat })
520 }
521
522 pub fn lstat(p: &Path) -> io::Result<FileAttr> {
523     let p = try!(cstr(p));
524     let mut stat: raw::stat = unsafe { mem::zeroed() };
525     try!(cvt(unsafe {
526         libc::lstat(p.as_ptr(), &mut stat as *mut _ as *mut _)
527     }));
528     Ok(FileAttr { stat: stat })
529 }
530
531 pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
532     let path = try!(CString::new(p.as_os_str().as_bytes()));
533     let buf;
534     unsafe {
535         let r = c::realpath(path.as_ptr(), ptr::null_mut());
536         if r.is_null() {
537             return Err(io::Error::last_os_error())
538         }
539         buf = CStr::from_ptr(r).to_bytes().to_vec();
540         libc::free(r as *mut _);
541     }
542     Ok(PathBuf::from(OsString::from_vec(buf)))
543 }
544
545 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
546     use fs::{File, PathExt, set_permissions};
547     if !from.is_file() {
548         return Err(Error::new(ErrorKind::InvalidInput,
549                               "the source path is not an existing regular file"))
550     }
551
552     let mut reader = try!(File::open(from));
553     let mut writer = try!(File::create(to));
554     let perm = try!(reader.metadata()).permissions();
555
556     let ret = try!(io::copy(&mut reader, &mut writer));
557     try!(set_permissions(to, perm));
558     Ok(ret)
559 }