1 // Copyright 2013 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.
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.
11 use std::c_str::CString;
13 use std::cast::transmute;
15 use libc::{c_int, c_char, c_void, ssize_t};
17 use std::rt::task::BlockedTask;
18 use std::io::{FileStat, IoError};
22 use homing::{HomingIO, HomeHandle};
23 use super::{Loop, UvError, uv_error_to_io_error, wait_until_woken_after, wakeup};
24 use uvio::UvIoFactory;
27 pub struct FsRequest {
32 pub struct FileWatcher {
35 close: rtio::CloseBehavior,
40 pub fn open(io: &mut UvIoFactory, path: &CString, flags: int, mode: int)
41 -> Result<FileWatcher, UvError>
43 execute(|req, cb| unsafe {
44 uvll::uv_fs_open(io.uv_loop(),
45 req, path.with_ref(|p| p), flags as c_int,
48 FileWatcher::new(io, req.get_result() as c_int,
49 rtio::CloseSynchronously)
53 pub fn unlink(loop_: &Loop, path: &CString) -> Result<(), UvError> {
54 execute_nop(|req, cb| unsafe {
55 uvll::uv_fs_unlink(loop_.handle, req, path.with_ref(|p| p),
60 pub fn lstat(loop_: &Loop, path: &CString) -> Result<FileStat, UvError> {
61 execute(|req, cb| unsafe {
62 uvll::uv_fs_lstat(loop_.handle, req, path.with_ref(|p| p),
64 }).map(|req| req.mkstat())
67 pub fn stat(loop_: &Loop, path: &CString) -> Result<FileStat, UvError> {
68 execute(|req, cb| unsafe {
69 uvll::uv_fs_stat(loop_.handle, req, path.with_ref(|p| p),
71 }).map(|req| req.mkstat())
74 pub fn write(loop_: &Loop, fd: c_int, buf: &[u8], offset: i64)
75 -> Result<(), UvError>
77 // In libuv, uv_fs_write is basically just shelling out to a write()
78 // syscall at some point, with very little fluff around it. This means
79 // that write() could actually be a short write, so we need to be sure
80 // to call it continuously if we get a short write back. This method is
81 // expected to write the full data if it returns success.
83 while written < buf.len() {
84 let offset = if offset == -1 {
87 offset + written as i64
89 let uvbuf = uvll::uv_buf_t {
90 base: buf.slice_from(written as uint).as_ptr(),
91 len: (buf.len() - written) as uvll::uv_buf_len_t,
93 match execute(|req, cb| unsafe {
94 uvll::uv_fs_write(loop_.handle, req, fd, &uvbuf, 1, offset, cb)
95 }).map(|req| req.get_result()) {
96 Err(e) => return Err(e),
97 Ok(n) => { written += n as uint; }
103 pub fn read(loop_: &Loop, fd: c_int, buf: &mut [u8], offset: i64)
104 -> Result<int, UvError>
106 execute(|req, cb| unsafe {
107 let uvbuf = uvll::uv_buf_t {
109 len: buf.len() as uvll::uv_buf_len_t,
111 uvll::uv_fs_read(loop_.handle, req, fd, &uvbuf, 1, offset, cb)
113 req.get_result() as int
117 pub fn mkdir(loop_: &Loop, path: &CString, mode: c_int)
118 -> Result<(), UvError>
120 execute_nop(|req, cb| unsafe {
121 uvll::uv_fs_mkdir(loop_.handle, req, path.with_ref(|p| p),
126 pub fn rmdir(loop_: &Loop, path: &CString) -> Result<(), UvError> {
127 execute_nop(|req, cb| unsafe {
128 uvll::uv_fs_rmdir(loop_.handle, req, path.with_ref(|p| p),
133 pub fn rename(loop_: &Loop, path: &CString, to: &CString)
134 -> Result<(), UvError>
136 execute_nop(|req, cb| unsafe {
137 uvll::uv_fs_rename(loop_.handle,
139 path.with_ref(|p| p),
145 pub fn chmod(loop_: &Loop, path: &CString, mode: c_int)
146 -> Result<(), UvError>
148 execute_nop(|req, cb| unsafe {
149 uvll::uv_fs_chmod(loop_.handle, req, path.with_ref(|p| p),
154 pub fn readdir(loop_: &Loop, path: &CString, flags: c_int)
155 -> Result<Vec<Path>, UvError>
157 execute(|req, cb| unsafe {
158 uvll::uv_fs_readdir(loop_.handle,
159 req, path.with_ref(|p| p), flags, cb)
160 }).map(|req| unsafe {
161 let mut paths = vec!();
162 let path = CString::new(path.with_ref(|p| p), false);
163 let parent = Path::new(path);
164 let _ = c_str::from_c_multistring(req.get_ptr() as *libc::c_char,
165 Some(req.get_result() as uint),
167 let p = rel.as_bytes();
168 paths.push(parent.join(p.slice_to(rel.len())));
174 pub fn readlink(loop_: &Loop, path: &CString) -> Result<Path, UvError> {
175 execute(|req, cb| unsafe {
176 uvll::uv_fs_readlink(loop_.handle, req,
177 path.with_ref(|p| p), cb)
180 CString::new(req.get_ptr() as *libc::c_char, false)
185 pub fn chown(loop_: &Loop, path: &CString, uid: int, gid: int)
186 -> Result<(), UvError>
188 execute_nop(|req, cb| unsafe {
189 uvll::uv_fs_chown(loop_.handle,
190 req, path.with_ref(|p| p),
191 uid as uvll::uv_uid_t,
192 gid as uvll::uv_gid_t,
197 pub fn truncate(loop_: &Loop, file: c_int, offset: i64)
198 -> Result<(), UvError>
200 execute_nop(|req, cb| unsafe {
201 uvll::uv_fs_ftruncate(loop_.handle, req, file, offset, cb)
205 pub fn link(loop_: &Loop, src: &CString, dst: &CString)
206 -> Result<(), UvError>
208 execute_nop(|req, cb| unsafe {
209 uvll::uv_fs_link(loop_.handle, req,
216 pub fn symlink(loop_: &Loop, src: &CString, dst: &CString)
217 -> Result<(), UvError>
219 execute_nop(|req, cb| unsafe {
220 uvll::uv_fs_symlink(loop_.handle, req,
227 pub fn fsync(loop_: &Loop, fd: c_int) -> Result<(), UvError> {
228 execute_nop(|req, cb| unsafe {
229 uvll::uv_fs_fsync(loop_.handle, req, fd, cb)
233 pub fn datasync(loop_: &Loop, fd: c_int) -> Result<(), UvError> {
234 execute_nop(|req, cb| unsafe {
235 uvll::uv_fs_fdatasync(loop_.handle, req, fd, cb)
239 pub fn utime(loop_: &Loop, path: &CString, atime: u64, mtime: u64)
240 -> Result<(), UvError>
242 // libuv takes seconds
243 let atime = atime as libc::c_double / 1000.0;
244 let mtime = mtime as libc::c_double / 1000.0;
245 execute_nop(|req, cb| unsafe {
246 uvll::uv_fs_utime(loop_.handle, req, path.with_ref(|p| p),
251 pub fn get_result(&self) -> ssize_t {
252 unsafe { uvll::get_result_from_fs_req(self.req) }
255 pub fn get_stat(&self) -> uvll::uv_stat_t {
256 let stat = uvll::uv_stat_t::new();
257 unsafe { uvll::populate_stat(self.req, &stat); }
261 pub fn get_ptr(&self) -> *libc::c_void {
262 unsafe { uvll::get_ptr_from_fs_req(self.req) }
265 pub fn mkstat(&self) -> FileStat {
266 let path = unsafe { uvll::get_path_from_fs_req(self.req) };
267 let path = unsafe { Path::new(CString::new(path, false)) };
268 let stat = self.get_stat();
269 fn to_msec(stat: uvll::uv_timespec_t) -> u64 {
270 // Be sure to cast to u64 first to prevent overflowing if the tv_sec
271 // field is a 32-bit integer.
272 (stat.tv_sec as u64) * 1000 + (stat.tv_nsec as u64) / 1000000
274 let kind = match (stat.st_mode as c_int) & libc::S_IFMT {
275 libc::S_IFREG => io::TypeFile,
276 libc::S_IFDIR => io::TypeDirectory,
277 libc::S_IFIFO => io::TypeNamedPipe,
278 libc::S_IFBLK => io::TypeBlockSpecial,
279 libc::S_IFLNK => io::TypeSymlink,
280 _ => io::TypeUnknown,
284 size: stat.st_size as u64,
286 perm: (stat.st_mode as io::FilePermission) & io::AllPermissions,
287 created: to_msec(stat.st_birthtim),
288 modified: to_msec(stat.st_mtim),
289 accessed: to_msec(stat.st_atim),
290 unstable: io::UnstableFileStat {
291 device: stat.st_dev as u64,
292 inode: stat.st_ino as u64,
293 rdev: stat.st_rdev as u64,
294 nlink: stat.st_nlink as u64,
295 uid: stat.st_uid as u64,
296 gid: stat.st_gid as u64,
297 blksize: stat.st_blksize as u64,
298 blocks: stat.st_blocks as u64,
299 flags: stat.st_flags as u64,
300 gen: stat.st_gen as u64,
306 impl Drop for FsRequest {
310 uvll::uv_fs_req_cleanup(self.req);
312 uvll::free_req(self.req);
317 fn execute(f: |*uvll::uv_fs_t, uvll::uv_fs_cb| -> c_int)
318 -> Result<FsRequest, UvError>
320 let mut req = FsRequest {
322 req: unsafe { uvll::malloc_req(uvll::UV_FS) }
324 return match f(req.req, fs_cb) {
328 let loop_ = unsafe { uvll::get_loop_from_fs_req(req.req) };
329 wait_until_woken_after(&mut slot, &Loop::wrap(loop_), || {
330 unsafe { uvll::set_data_for_req(req.req, &slot) }
332 match req.get_result() {
333 n if n < 0 => Err(UvError(n as i32)),
340 extern fn fs_cb(req: *uvll::uv_fs_t) {
341 let slot: &mut Option<BlockedTask> = unsafe {
342 cast::transmute(uvll::get_data_for_req(req))
348 fn execute_nop(f: |*uvll::uv_fs_t, uvll::uv_fs_cb| -> c_int)
349 -> Result<(), UvError> {
350 execute(f).map(|_| {})
353 impl HomingIO for FileWatcher {
354 fn home<'r>(&'r mut self) -> &'r mut HomeHandle { &mut self.home }
358 pub fn new(io: &mut UvIoFactory, fd: c_int,
359 close: rtio::CloseBehavior) -> FileWatcher {
361 loop_: Loop::wrap(io.uv_loop()),
364 home: io.make_handle(),
368 fn base_read(&mut self, buf: &mut [u8], offset: i64) -> Result<int, IoError> {
369 let _m = self.fire_homing_missile();
370 let r = FsRequest::read(&self.loop_, self.fd, buf, offset);
371 r.map_err(uv_error_to_io_error)
373 fn base_write(&mut self, buf: &[u8], offset: i64) -> Result<(), IoError> {
374 let _m = self.fire_homing_missile();
375 let r = FsRequest::write(&self.loop_, self.fd, buf, offset);
376 r.map_err(uv_error_to_io_error)
378 fn seek_common(&mut self, pos: i64, whence: c_int) ->
379 Result<u64, IoError>{
381 match libc::lseek(self.fd, pos as libc::off_t, whence) {
384 kind: io::OtherIoError,
385 desc: "Failed to lseek.",
395 impl Drop for FileWatcher {
397 let _m = self.fire_homing_missile();
399 rtio::DontClose => {}
400 rtio::CloseAsynchronously => {
402 let req = uvll::malloc_req(uvll::UV_FS);
403 assert_eq!(uvll::uv_fs_close(self.loop_.handle, req,
404 self.fd, close_cb), 0);
407 extern fn close_cb(req: *uvll::uv_fs_t) {
409 uvll::uv_fs_req_cleanup(req);
414 rtio::CloseSynchronously => {
415 let _ = execute_nop(|req, cb| unsafe {
416 uvll::uv_fs_close(self.loop_.handle, req, self.fd, cb)
423 impl rtio::RtioFileStream for FileWatcher {
424 fn read(&mut self, buf: &mut [u8]) -> Result<int, IoError> {
425 self.base_read(buf, -1)
427 fn write(&mut self, buf: &[u8]) -> Result<(), IoError> {
428 self.base_write(buf, -1)
430 fn pread(&mut self, buf: &mut [u8], offset: u64) -> Result<int, IoError> {
431 self.base_read(buf, offset as i64)
433 fn pwrite(&mut self, buf: &[u8], offset: u64) -> Result<(), IoError> {
434 self.base_write(buf, offset as i64)
436 fn seek(&mut self, pos: i64, whence: io::SeekStyle) -> Result<u64, IoError> {
437 use libc::{SEEK_SET, SEEK_CUR, SEEK_END};
438 let whence = match whence {
439 io::SeekSet => SEEK_SET,
440 io::SeekCur => SEEK_CUR,
441 io::SeekEnd => SEEK_END
443 self.seek_common(pos, whence)
445 fn tell(&self) -> Result<u64, IoError> {
448 // FIXME #13933: Remove/justify all `&T` to `&mut T` transmutes
449 let self_ = unsafe { cast::transmute::<&_, &mut FileWatcher>(self) };
450 self_.seek_common(0, SEEK_CUR)
452 fn fsync(&mut self) -> Result<(), IoError> {
453 let _m = self.fire_homing_missile();
454 FsRequest::fsync(&self.loop_, self.fd).map_err(uv_error_to_io_error)
456 fn datasync(&mut self) -> Result<(), IoError> {
457 let _m = self.fire_homing_missile();
458 FsRequest::datasync(&self.loop_, self.fd).map_err(uv_error_to_io_error)
460 fn truncate(&mut self, offset: i64) -> Result<(), IoError> {
461 let _m = self.fire_homing_missile();
462 let r = FsRequest::truncate(&self.loop_, self.fd, offset);
463 r.map_err(uv_error_to_io_error)
470 use libc::{O_CREAT, O_RDWR, O_RDONLY, S_IWUSR, S_IRUSR};
473 use super::FsRequest;
474 use super::super::Loop;
475 use super::super::local_loop;
477 fn l() -> &mut Loop { &mut local_loop().loop_ }
480 fn file_test_full_simple_sync() {
481 let create_flags = O_RDWR | O_CREAT;
482 let read_flags = O_RDONLY;
483 let mode = S_IWUSR | S_IRUSR;
484 let path_str = "./tmp/file_full_simple_sync.txt";
488 let result = FsRequest::open(local_loop(), &path_str.to_c_str(),
489 create_flags as int, mode as int);
490 assert!(result.is_ok());
491 let result = result.unwrap();
495 let result = FsRequest::write(l(), fd, "hello".as_bytes(), -1);
496 assert!(result.is_ok());
501 let result = FsRequest::open(local_loop(), &path_str.to_c_str(),
502 read_flags as int, 0);
503 assert!(result.is_ok());
504 let result = result.unwrap();
508 let mut read_mem = Vec::from_elem(1000, 0u8);
509 let result = FsRequest::read(l(), fd, read_mem.as_mut_slice(), 0);
510 assert!(result.is_ok());
512 let nread = result.unwrap();
514 let read_str = str::from_utf8(read_mem.slice_to(nread as uint)).unwrap();
515 assert_eq!(read_str, "hello");
518 let result = FsRequest::unlink(l(), &path_str.to_c_str());
519 assert!(result.is_ok());
523 fn file_test_stat() {
524 let path = &"./tmp/file_test_stat_simple".to_c_str();
525 let create_flags = (O_RDWR | O_CREAT) as int;
526 let mode = (S_IWUSR | S_IRUSR) as int;
528 let result = FsRequest::open(local_loop(), path, create_flags, mode);
529 assert!(result.is_ok());
530 let file = result.unwrap();
532 let result = FsRequest::write(l(), file.fd, "hello".as_bytes(), 0);
533 assert!(result.is_ok());
535 let result = FsRequest::stat(l(), path);
536 assert!(result.is_ok());
537 assert_eq!(result.unwrap().size, 5);
542 let result = FsRequest::unlink(l(), path);
543 assert!(result.is_ok());
547 fn file_test_mk_rm_dir() {
548 let path = &"./tmp/mk_rm_dir".to_c_str();
549 let mode = S_IWUSR | S_IRUSR;
551 let result = FsRequest::mkdir(l(), path, mode);
552 assert!(result.is_ok());
554 let result = FsRequest::stat(l(), path);
555 assert!(result.is_ok());
556 assert!(result.unwrap().kind == io::TypeDirectory);
558 let result = FsRequest::rmdir(l(), path);
559 assert!(result.is_ok());
561 let result = FsRequest::stat(l(), path);
562 assert!(result.is_err());
566 fn file_test_mkdir_chokes_on_double_create() {
567 let path = &"./tmp/double_create_dir".to_c_str();
568 let mode = S_IWUSR | S_IRUSR;
570 let result = FsRequest::stat(l(), path);
571 assert!(result.is_err(), "{:?}", result);
572 let result = FsRequest::mkdir(l(), path, mode as c_int);
573 assert!(result.is_ok(), "{:?}", result);
574 let result = FsRequest::mkdir(l(), path, mode as c_int);
575 assert!(result.is_err(), "{:?}", result);
576 let result = FsRequest::rmdir(l(), path);
577 assert!(result.is_ok(), "{:?}", result);
581 fn file_test_rmdir_chokes_on_nonexistant_path() {
582 let path = &"./tmp/never_existed_dir".to_c_str();
583 let result = FsRequest::rmdir(l(), path);
584 assert!(result.is_err());