rust/src/test/run-pass/tempfile.rs

209 lines
6.4 KiB
Rust
Raw Normal View History

// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-windows TempDir may cause IoError on windows: #10463
// These tests are here to exercise the functionality of the `tempfile` module.
// One might expect these tests to be located in that module, but sadly they
// cannot. The tests need to invoke `os::change_dir` which cannot be done in the
// normal test infrastructure. If the tests change the current working
// directory, then *all* tests which require relative paths suddenly break b/c
// they're in a different location than before. Hence, these tests are all run
// serially here.
use std::io::fs::PathExtensions;
use std::io::{fs, TempDir};
use std::io;
use std::os;
std: Second pass stabilization for `comm` This commit is a second pass stabilization for the `std::comm` module, performing the following actions: * The entire `std::comm` module was moved under `std::sync::mpsc`. This movement reflects that channels are just yet another synchronization primitive, and they don't necessarily deserve a special place outside of the other concurrency primitives that the standard library offers. * The `send` and `recv` methods have all been removed. * The `send_opt` and `recv_opt` methods have been renamed to `send` and `recv`. This means that all send/receive operations return a `Result` now indicating whether the operation was successful or not. * The error type of `send` is now a `SendError` to implement a custom error message and allow for `unwrap()`. The error type contains an `into_inner` method to extract the value. * The error type of `recv` is now `RecvError` for the same reasons as `send`. * The `TryRecvError` and `TrySendError` types have had public reexports removed of their variants and the variant names have been tweaked with enum namespacing rules. * The `Messages` iterator is renamed to `Iter` This functionality is now all `#[stable]`: * `Sender` * `SyncSender` * `Receiver` * `std::sync::mpsc` * `channel` * `sync_channel` * `Iter` * `Sender::send` * `Sender::clone` * `SyncSender::send` * `SyncSender::try_send` * `SyncSender::clone` * `Receiver::recv` * `Receiver::try_recv` * `Receiver::iter` * `SendError` * `RecvError` * `TrySendError::{mod, Full, Disconnected}` * `TryRecvError::{mod, Empty, Disconnected}` * `SendError::into_inner` * `TrySendError::into_inner` This is a breaking change due to the modification of where this module is located, as well as the changing of the semantics of `send` and `recv`. Most programs just need to rename imports of `std::comm` to `std::sync::mpsc` and add calls to `unwrap` after a send or a receive operation. [breaking-change]
2014-12-23 13:53:35 -06:00
use std::sync::mpsc::channel;
use std::thread::Thread;
fn test_tempdir() {
let path = {
let p = TempDir::new_in(&Path::new("."), "foobar").unwrap();
let p = p.path();
Make temporary directory names non-deterministic. The previous scheme made it possible for another user/attacker to cause the temporary directory creation scheme to panic. All you needed to know was the pid of the process you wanted to target ('other_pid') and the suffix it was using (let's pretend it's 'sfx') and then code such as this would, in essence, DOS it: for i in range(0u, 1001) { let tp = &Path::new(format!("/tmp/rs-{}-{}-sfx", other_pid, i)); match fs::mkdir(tp, io::USER_RWX) { _ => () } } Since the scheme retried only 1000 times to create a temporary directory before dying, the next time the attacked process called TempDir::new("sfx") after that would typically cause a panic. Of course, you don't necessarily need an attacker to cause such a DOS: creating 1000 temporary directories without closing any of the previous would be enough to DOS yourself. This patch broadly follows the OpenBSD implementation of mkstemp. It uses the operating system's random number generator to produce random directory names that are impractical to guess (and, just in case someone manages to do that, it retries creating the directory for a long time before giving up; OpenBSD retries INT_MAX times, although 1<<31 seems enough to thwart even the most patient attacker). As a small additional change, this patch also makes the argument that TempDir::new takes a prefix rather than a suffix. This is because 1) it more closely matches what mkstemp and friends do 2) if you're going to have a deterministic part of a filename, you really want it at the beginning so that shell completion is useful.
2015-01-03 15:49:01 -06:00
assert!(p.as_str().unwrap().contains("foobar"));
p.clone()
};
assert!(!path.exists());
}
fn test_rm_tempdir() {
let (tx, rx) = channel();
let f = move|:| -> () {
let tmp = TempDir::new("test_rm_tempdir").unwrap();
std: Second pass stabilization for `comm` This commit is a second pass stabilization for the `std::comm` module, performing the following actions: * The entire `std::comm` module was moved under `std::sync::mpsc`. This movement reflects that channels are just yet another synchronization primitive, and they don't necessarily deserve a special place outside of the other concurrency primitives that the standard library offers. * The `send` and `recv` methods have all been removed. * The `send_opt` and `recv_opt` methods have been renamed to `send` and `recv`. This means that all send/receive operations return a `Result` now indicating whether the operation was successful or not. * The error type of `send` is now a `SendError` to implement a custom error message and allow for `unwrap()`. The error type contains an `into_inner` method to extract the value. * The error type of `recv` is now `RecvError` for the same reasons as `send`. * The `TryRecvError` and `TrySendError` types have had public reexports removed of their variants and the variant names have been tweaked with enum namespacing rules. * The `Messages` iterator is renamed to `Iter` This functionality is now all `#[stable]`: * `Sender` * `SyncSender` * `Receiver` * `std::sync::mpsc` * `channel` * `sync_channel` * `Iter` * `Sender::send` * `Sender::clone` * `SyncSender::send` * `SyncSender::try_send` * `SyncSender::clone` * `Receiver::recv` * `Receiver::try_recv` * `Receiver::iter` * `SendError` * `RecvError` * `TrySendError::{mod, Full, Disconnected}` * `TryRecvError::{mod, Empty, Disconnected}` * `SendError::into_inner` * `TrySendError::into_inner` This is a breaking change due to the modification of where this module is located, as well as the changing of the semantics of `send` and `recv`. Most programs just need to rename imports of `std::comm` to `std::sync::mpsc` and add calls to `unwrap` after a send or a receive operation. [breaking-change]
2014-12-23 13:53:35 -06:00
tx.send(tmp.path().clone()).unwrap();
panic!("panic to unwind past `tmp`");
};
2015-01-05 23:59:45 -06:00
let _ = Thread::scoped(f).join();
std: Second pass stabilization for `comm` This commit is a second pass stabilization for the `std::comm` module, performing the following actions: * The entire `std::comm` module was moved under `std::sync::mpsc`. This movement reflects that channels are just yet another synchronization primitive, and they don't necessarily deserve a special place outside of the other concurrency primitives that the standard library offers. * The `send` and `recv` methods have all been removed. * The `send_opt` and `recv_opt` methods have been renamed to `send` and `recv`. This means that all send/receive operations return a `Result` now indicating whether the operation was successful or not. * The error type of `send` is now a `SendError` to implement a custom error message and allow for `unwrap()`. The error type contains an `into_inner` method to extract the value. * The error type of `recv` is now `RecvError` for the same reasons as `send`. * The `TryRecvError` and `TrySendError` types have had public reexports removed of their variants and the variant names have been tweaked with enum namespacing rules. * The `Messages` iterator is renamed to `Iter` This functionality is now all `#[stable]`: * `Sender` * `SyncSender` * `Receiver` * `std::sync::mpsc` * `channel` * `sync_channel` * `Iter` * `Sender::send` * `Sender::clone` * `SyncSender::send` * `SyncSender::try_send` * `SyncSender::clone` * `Receiver::recv` * `Receiver::try_recv` * `Receiver::iter` * `SendError` * `RecvError` * `TrySendError::{mod, Full, Disconnected}` * `TryRecvError::{mod, Empty, Disconnected}` * `SendError::into_inner` * `TrySendError::into_inner` This is a breaking change due to the modification of where this module is located, as well as the changing of the semantics of `send` and `recv`. Most programs just need to rename imports of `std::comm` to `std::sync::mpsc` and add calls to `unwrap` after a send or a receive operation. [breaking-change]
2014-12-23 13:53:35 -06:00
let path = rx.recv().unwrap();
assert!(!path.exists());
let tmp = TempDir::new("test_rm_tempdir").unwrap();
let path = tmp.path().clone();
let f = move|:| -> () {
let _tmp = tmp;
panic!("panic to unwind past `tmp`");
};
2015-01-05 23:59:45 -06:00
let _ = Thread::scoped(f).join();
assert!(!path.exists());
let path;
{
let f = move|:| {
TempDir::new("test_rm_tempdir").unwrap()
};
2015-01-05 23:59:45 -06:00
let tmp = Thread::scoped(f).join().ok().expect("test_rm_tmdir");
path = tmp.path().clone();
assert!(path.exists());
}
assert!(!path.exists());
let path;
{
let tmp = TempDir::new("test_rm_tempdir").unwrap();
path = tmp.into_inner();
}
assert!(path.exists());
fs::rmdir_recursive(&path);
assert!(!path.exists());
}
fn test_rm_tempdir_close() {
let (tx, rx) = channel();
let f = move|:| -> () {
let tmp = TempDir::new("test_rm_tempdir").unwrap();
std: Second pass stabilization for `comm` This commit is a second pass stabilization for the `std::comm` module, performing the following actions: * The entire `std::comm` module was moved under `std::sync::mpsc`. This movement reflects that channels are just yet another synchronization primitive, and they don't necessarily deserve a special place outside of the other concurrency primitives that the standard library offers. * The `send` and `recv` methods have all been removed. * The `send_opt` and `recv_opt` methods have been renamed to `send` and `recv`. This means that all send/receive operations return a `Result` now indicating whether the operation was successful or not. * The error type of `send` is now a `SendError` to implement a custom error message and allow for `unwrap()`. The error type contains an `into_inner` method to extract the value. * The error type of `recv` is now `RecvError` for the same reasons as `send`. * The `TryRecvError` and `TrySendError` types have had public reexports removed of their variants and the variant names have been tweaked with enum namespacing rules. * The `Messages` iterator is renamed to `Iter` This functionality is now all `#[stable]`: * `Sender` * `SyncSender` * `Receiver` * `std::sync::mpsc` * `channel` * `sync_channel` * `Iter` * `Sender::send` * `Sender::clone` * `SyncSender::send` * `SyncSender::try_send` * `SyncSender::clone` * `Receiver::recv` * `Receiver::try_recv` * `Receiver::iter` * `SendError` * `RecvError` * `TrySendError::{mod, Full, Disconnected}` * `TryRecvError::{mod, Empty, Disconnected}` * `SendError::into_inner` * `TrySendError::into_inner` This is a breaking change due to the modification of where this module is located, as well as the changing of the semantics of `send` and `recv`. Most programs just need to rename imports of `std::comm` to `std::sync::mpsc` and add calls to `unwrap` after a send or a receive operation. [breaking-change]
2014-12-23 13:53:35 -06:00
tx.send(tmp.path().clone()).unwrap();
tmp.close();
panic!("panic when unwinding past `tmp`");
};
2015-01-05 23:59:45 -06:00
let _ = Thread::scoped(f).join();
std: Second pass stabilization for `comm` This commit is a second pass stabilization for the `std::comm` module, performing the following actions: * The entire `std::comm` module was moved under `std::sync::mpsc`. This movement reflects that channels are just yet another synchronization primitive, and they don't necessarily deserve a special place outside of the other concurrency primitives that the standard library offers. * The `send` and `recv` methods have all been removed. * The `send_opt` and `recv_opt` methods have been renamed to `send` and `recv`. This means that all send/receive operations return a `Result` now indicating whether the operation was successful or not. * The error type of `send` is now a `SendError` to implement a custom error message and allow for `unwrap()`. The error type contains an `into_inner` method to extract the value. * The error type of `recv` is now `RecvError` for the same reasons as `send`. * The `TryRecvError` and `TrySendError` types have had public reexports removed of their variants and the variant names have been tweaked with enum namespacing rules. * The `Messages` iterator is renamed to `Iter` This functionality is now all `#[stable]`: * `Sender` * `SyncSender` * `Receiver` * `std::sync::mpsc` * `channel` * `sync_channel` * `Iter` * `Sender::send` * `Sender::clone` * `SyncSender::send` * `SyncSender::try_send` * `SyncSender::clone` * `Receiver::recv` * `Receiver::try_recv` * `Receiver::iter` * `SendError` * `RecvError` * `TrySendError::{mod, Full, Disconnected}` * `TryRecvError::{mod, Empty, Disconnected}` * `SendError::into_inner` * `TrySendError::into_inner` This is a breaking change due to the modification of where this module is located, as well as the changing of the semantics of `send` and `recv`. Most programs just need to rename imports of `std::comm` to `std::sync::mpsc` and add calls to `unwrap` after a send or a receive operation. [breaking-change]
2014-12-23 13:53:35 -06:00
let path = rx.recv().unwrap();
assert!(!path.exists());
let tmp = TempDir::new("test_rm_tempdir").unwrap();
let path = tmp.path().clone();
let f = move|:| -> () {
let tmp = tmp;
tmp.close();
panic!("panic when unwinding past `tmp`");
};
2015-01-05 23:59:45 -06:00
let _ = Thread::scoped(f).join();
assert!(!path.exists());
let path;
{
let f = move|:| {
TempDir::new("test_rm_tempdir").unwrap()
};
2015-01-05 23:59:45 -06:00
let tmp = Thread::scoped(f).join().ok().expect("test_rm_tmdir");
path = tmp.path().clone();
assert!(path.exists());
tmp.close();
}
assert!(!path.exists());
let path;
{
let tmp = TempDir::new("test_rm_tempdir").unwrap();
path = tmp.into_inner();
}
assert!(path.exists());
fs::rmdir_recursive(&path);
assert!(!path.exists());
}
// Ideally these would be in std::os but then core would need
// to depend on std
fn recursive_mkdir_rel() {
let path = Path::new("frob");
let cwd = os::getcwd().unwrap();
2014-10-14 20:07:11 -05:00
println!("recursive_mkdir_rel: Making: {} in cwd {} [{}]", path.display(),
cwd.display(), path.exists());
fs::mkdir_recursive(&path, io::USER_RWX);
assert!(path.is_dir());
fs::mkdir_recursive(&path, io::USER_RWX);
assert!(path.is_dir());
}
fn recursive_mkdir_dot() {
let dot = Path::new(".");
fs::mkdir_recursive(&dot, io::USER_RWX);
let dotdot = Path::new("..");
fs::mkdir_recursive(&dotdot, io::USER_RWX);
}
fn recursive_mkdir_rel_2() {
let path = Path::new("./frob/baz");
let cwd = os::getcwd().unwrap();
2014-10-14 20:07:11 -05:00
println!("recursive_mkdir_rel_2: Making: {} in cwd {} [{}]", path.display(),
cwd.display(), path.exists());
fs::mkdir_recursive(&path, io::USER_RWX);
assert!(path.is_dir());
assert!(path.dir_path().is_dir());
let path2 = Path::new("quux/blat");
log: Introduce liblog, the old std::logging This commit moves all logging out of the standard library into an external crate. This crate is the new crate which is responsible for all logging macros and logging implementation. A few reasons for this change are: * The crate map has always been a bit of a code smell among rust programs. It has difficulty being loaded on almost all platforms, and it's used almost exclusively for logging and only logging. Removing the crate map is one of the end goals of this movement. * The compiler has a fair bit of special support for logging. It has the __log_level() expression as well as generating a global word per module specifying the log level. This is unfairly favoring the built-in logging system, and is much better done purely in libraries instead of the compiler itself. * Initialization of logging is much easier to do if there is no reliance on a magical crate map being available to set module log levels. * If the logging library can be written outside of the standard library, there's no reason that it shouldn't be. It's likely that we're not going to build the highest quality logging library of all time, so third-party libraries should be able to provide just as high-quality logging systems as the default one provided in the rust distribution. With a migration such as this, the change does not come for free. There are some subtle changes in the behavior of liblog vs the previous logging macros: * The core change of this migration is that there is no longer a physical log-level per module. This concept is still emulated (it is quite useful), but there is now only a global log level, not a local one. This global log level is a reflection of the maximum of all log levels specified. The previously generated logging code looked like: if specified_level <= __module_log_level() { println!(...) } The newly generated code looks like: if specified_level <= ::log::LOG_LEVEL { if ::log::module_enabled(module_path!()) { println!(...) } } Notably, the first layer of checking is still intended to be "super fast" in that it's just a load of a global word and a compare. The second layer of checking is executed to determine if the current module does indeed have logging turned on. This means that if any module has a debug log level turned on, all modules with debug log levels get a little bit slower (they all do more expensive dynamic checks to determine if they're turned on or not). Semantically, this migration brings no change in this respect, but runtime-wise, this will have a perf impact on some code. * A `RUST_LOG=::help` directive will no longer print out a list of all modules that can be logged. This is because the crate map will no longer specify the log levels of all modules, so the list of modules is not known. Additionally, warnings can no longer be provided if a malformed logging directive was supplied. The new "hello world" for logging looks like: #[phase(syntax, link)] extern crate log; fn main() { debug!("Hello, world!"); }
2014-03-09 00:11:44 -06:00
println!("recursive_mkdir_rel_2: Making: {} in cwd {}", path2.display(),
cwd.display());
fs::mkdir_recursive(&path2, io::USER_RWX);
assert!(path2.is_dir());
assert!(path2.dir_path().is_dir());
}
// Ideally this would be in core, but needs TempFile
pub fn test_rmdir_recursive_ok() {
let rwx = io::USER_RWX;
let tmpdir = TempDir::new("test").ok().expect("test_rmdir_recursive_ok: \
couldn't create temp dir");
let tmpdir = tmpdir.path();
let root = tmpdir.join("foo");
log: Introduce liblog, the old std::logging This commit moves all logging out of the standard library into an external crate. This crate is the new crate which is responsible for all logging macros and logging implementation. A few reasons for this change are: * The crate map has always been a bit of a code smell among rust programs. It has difficulty being loaded on almost all platforms, and it's used almost exclusively for logging and only logging. Removing the crate map is one of the end goals of this movement. * The compiler has a fair bit of special support for logging. It has the __log_level() expression as well as generating a global word per module specifying the log level. This is unfairly favoring the built-in logging system, and is much better done purely in libraries instead of the compiler itself. * Initialization of logging is much easier to do if there is no reliance on a magical crate map being available to set module log levels. * If the logging library can be written outside of the standard library, there's no reason that it shouldn't be. It's likely that we're not going to build the highest quality logging library of all time, so third-party libraries should be able to provide just as high-quality logging systems as the default one provided in the rust distribution. With a migration such as this, the change does not come for free. There are some subtle changes in the behavior of liblog vs the previous logging macros: * The core change of this migration is that there is no longer a physical log-level per module. This concept is still emulated (it is quite useful), but there is now only a global log level, not a local one. This global log level is a reflection of the maximum of all log levels specified. The previously generated logging code looked like: if specified_level <= __module_log_level() { println!(...) } The newly generated code looks like: if specified_level <= ::log::LOG_LEVEL { if ::log::module_enabled(module_path!()) { println!(...) } } Notably, the first layer of checking is still intended to be "super fast" in that it's just a load of a global word and a compare. The second layer of checking is executed to determine if the current module does indeed have logging turned on. This means that if any module has a debug log level turned on, all modules with debug log levels get a little bit slower (they all do more expensive dynamic checks to determine if they're turned on or not). Semantically, this migration brings no change in this respect, but runtime-wise, this will have a perf impact on some code. * A `RUST_LOG=::help` directive will no longer print out a list of all modules that can be logged. This is because the crate map will no longer specify the log levels of all modules, so the list of modules is not known. Additionally, warnings can no longer be provided if a malformed logging directive was supplied. The new "hello world" for logging looks like: #[phase(syntax, link)] extern crate log; fn main() { debug!("Hello, world!"); }
2014-03-09 00:11:44 -06:00
println!("making {}", root.display());
fs::mkdir(&root, rwx);
fs::mkdir(&root.join("foo"), rwx);
fs::mkdir(&root.join("foo").join("bar"), rwx);
fs::mkdir(&root.join("foo").join("bar").join("blat"), rwx);
fs::rmdir_recursive(&root);
assert!(!root.exists());
assert!(!root.join("bar").exists());
assert!(!root.join("bar").join("blat").exists());
}
pub fn dont_double_panic() {
2015-01-05 23:59:45 -06:00
let r: Result<(), _> = Thread::scoped(move|| {
let tmpdir = TempDir::new("test").unwrap();
// Remove the temporary directory so that TempDir sees
// an error on drop
fs::rmdir(tmpdir.path());
// Panic. If TempDir panics *again* due to the rmdir
// error then the process will abort.
panic!();
}).join();
assert!(r.is_err());
}
2015-01-02 16:32:54 -06:00
fn in_tmpdir<F>(f: F) where F: FnOnce() {
let tmpdir = TempDir::new("test").ok().expect("can't make tmpdir");
assert!(os::change_dir(tmpdir.path()).is_ok());
f();
}
pub fn main() {
in_tmpdir(test_tempdir);
in_tmpdir(test_rm_tempdir);
in_tmpdir(test_rm_tempdir_close);
in_tmpdir(recursive_mkdir_rel);
in_tmpdir(recursive_mkdir_dot);
in_tmpdir(recursive_mkdir_rel_2);
in_tmpdir(test_rmdir_recursive_ok);
in_tmpdir(dont_double_panic);
}