tempfile/lib.rs
1//! Temporary files and directories.
2//!
3//! - Use the [`tempfile()`] function for temporary files
4//! - Use the [`tempdir()`] function for temporary directories.
5//!
6//! # Design
7//!
8//! This crate provides several approaches to creating temporary files and directories.
9//! [`tempfile()`] relies on the OS to remove the temporary file once the last handle is closed.
10//! [`TempDir`] and [`NamedTempFile`] both rely on Rust destructors for cleanup.
11//!
12//! When choosing between the temporary file variants, prefer `tempfile`
13//! unless you either need to know the file's path or to be able to persist it.
14//!
15//! ## Resource Leaking
16//!
17//! `tempfile` will (almost) never fail to cleanup temporary resources. However `TempDir` and `NamedTempFile` will
18//! fail if their destructors don't run. This is because `tempfile` relies on the OS to cleanup the
19//! underlying file, while `TempDir` and `NamedTempFile` rely on rust destructors to do so.
20//! Destructors may fail to run if the process exits through an unhandled signal interrupt (like `SIGINT`),
21//! or if the instance is declared statically (like with [`lazy_static`]), among other possible
22//! reasons.
23//!
24//! ## Security
25//!
26//! In the presence of pathological temporary file cleaner, relying on file paths is unsafe because
27//! a temporary file cleaner could delete the temporary file which an attacker could then replace.
28//!
29//! `tempfile` doesn't rely on file paths so this isn't an issue. However, `NamedTempFile` does
30//! rely on file paths for _some_ operations. See the security documentation on
31//! the `NamedTempFile` type for more information.
32//!
33//! ## Early drop pitfall
34//!
35//! Because `TempDir` and `NamedTempFile` rely on their destructors for cleanup, this can lead
36//! to an unexpected early removal of the directory/file, usually when working with APIs which are
37//! generic over `AsRef<Path>`. Consider the following example:
38//!
39//! ```no_run
40//! use tempfile::tempdir;
41//! use std::process::Command;
42//!
43//! // Create a directory inside of `env::temp_dir()`.
44//! let temp_dir = tempdir()?;
45//!
46//! // Spawn the `touch` command inside the temporary directory and collect the exit status
47//! // Note that `temp_dir` is **not** moved into `current_dir`, but passed as a reference
48//! let exit_status = Command::new("touch").arg("tmp").current_dir(&temp_dir).status()?;
49//! assert!(exit_status.success());
50//!
51//! # Ok::<(), std::io::Error>(())
52//! ```
53//!
54//! This works because a reference to `temp_dir` is passed to `current_dir`, resulting in the
55//! destructor of `temp_dir` being run after the `Command` has finished execution. Moving the
56//! `TempDir` into the `current_dir` call would result in the `TempDir` being converted into
57//! an internal representation, with the original value being dropped and the directory thus
58//! being deleted, before the command can be executed.
59//!
60//! The `touch` command would fail with an `No such file or directory` error.
61//!
62//! ## Examples
63//!
64//! Create a temporary file and write some data into it:
65//!
66//! ```
67//! use tempfile::tempfile;
68//! use std::io::Write;
69//!
70//! // Create a file inside of `env::temp_dir()`.
71//! let mut file = tempfile()?;
72//!
73//! writeln!(file, "Brian was here. Briefly.")?;
74//! # Ok::<(), std::io::Error>(())
75//! ```
76//!
77//! Create a named temporary file and open an independent file handle:
78//!
79//! ```
80//! use tempfile::NamedTempFile;
81//! use std::io::{Write, Read};
82//!
83//! let text = "Brian was here. Briefly.";
84//!
85//! // Create a file inside of `env::temp_dir()`.
86//! let mut file1 = NamedTempFile::new()?;
87//!
88//! // Re-open it.
89//! let mut file2 = file1.reopen()?;
90//!
91//! // Write some test data to the first handle.
92//! file1.write_all(text.as_bytes())?;
93//!
94//! // Read the test data using the second handle.
95//! let mut buf = String::new();
96//! file2.read_to_string(&mut buf)?;
97//! assert_eq!(buf, text);
98//! # Ok::<(), std::io::Error>(())
99//! ```
100//!
101//! Create a temporary directory and add a file to it:
102//!
103//! ```
104//! use tempfile::tempdir;
105//! use std::fs::File;
106//! use std::io::Write;
107//!
108//! // Create a directory inside of `env::temp_dir()`.
109//! let dir = tempdir()?;
110//!
111//! let file_path = dir.path().join("my-temporary-note.txt");
112//! let mut file = File::create(file_path)?;
113//! writeln!(file, "Brian was here. Briefly.")?;
114//!
115//! // By closing the `TempDir` explicitly, we can check that it has
116//! // been deleted successfully. If we don't close it explicitly,
117//! // the directory will still be deleted when `dir` goes out
118//! // of scope, but we won't know whether deleting the directory
119//! // succeeded.
120//! drop(file);
121//! dir.close()?;
122//! # Ok::<(), std::io::Error>(())
123//! ```
124//!
125//! [`tempfile()`]: fn.tempfile.html
126//! [`tempdir()`]: fn.tempdir.html
127//! [`TempDir`]: struct.TempDir.html
128//! [`NamedTempFile`]: struct.NamedTempFile.html
129//! [`lazy_static`]: https://github.com/rust-lang-nursery/lazy-static.rs/issues/62
130
131#![doc(
132 html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
133 html_favicon_url = "https://www.rust-lang.org/favicon.ico",
134 html_root_url = "https://docs.rs/tempfile/latest"
135)]
136#![cfg_attr(test, deny(warnings))]
137#![deny(rust_2018_idioms)]
138#![allow(clippy::redundant_field_names)]
139// wasip2 conditionally gates stdlib APIs.
140// https://github.com/rust-lang/rust/issues/130323
141#![cfg_attr(
142 all(feature = "nightly", target_os = "wasi", target_env = "p2"),
143 feature(wasip2)
144)]
145#![cfg_attr(all(feature = "nightly", target_os = "wasi"), feature(wasi_ext))]
146
147#[cfg(doctest)]
148doc_comment::doctest!("../README.md");
149
150const NUM_RETRIES: u32 = 1 << 31;
151const NUM_RAND_CHARS: usize = 6;
152
153use std::ffi::OsStr;
154use std::fs::OpenOptions;
155use std::io;
156use std::path::Path;
157
158mod dir;
159mod error;
160mod file;
161mod spooled;
162mod util;
163
164pub mod env;
165
166pub use crate::dir::{tempdir, tempdir_in, TempDir};
167pub use crate::file::{
168 tempfile, tempfile_in, NamedTempFile, PathPersistError, PersistError, TempPath,
169};
170pub use crate::spooled::{spooled_tempfile, SpooledData, SpooledTempFile};
171
172/// Create a new temporary file or directory with custom parameters.
173#[derive(Debug, Clone, Eq, PartialEq)]
174pub struct Builder<'a, 'b> {
175 random_len: usize,
176 prefix: &'a OsStr,
177 suffix: &'b OsStr,
178 append: bool,
179 permissions: Option<std::fs::Permissions>,
180 keep: bool,
181}
182
183impl<'a, 'b> Default for Builder<'a, 'b> {
184 fn default() -> Self {
185 Builder {
186 random_len: crate::NUM_RAND_CHARS,
187 prefix: OsStr::new(".tmp"),
188 suffix: OsStr::new(""),
189 append: false,
190 permissions: None,
191 keep: false,
192 }
193 }
194}
195
196impl<'a, 'b> Builder<'a, 'b> {
197 /// Create a new `Builder`.
198 ///
199 /// # Examples
200 ///
201 /// Create a named temporary file and write some data into it:
202 ///
203 /// ```
204 /// use std::ffi::OsStr;
205 /// use tempfile::Builder;
206 ///
207 /// let named_tempfile = Builder::new()
208 /// .prefix("my-temporary-note")
209 /// .suffix(".txt")
210 /// .rand_bytes(5)
211 /// .tempfile()?;
212 ///
213 /// let name = named_tempfile
214 /// .path()
215 /// .file_name().and_then(OsStr::to_str);
216 ///
217 /// if let Some(name) = name {
218 /// assert!(name.starts_with("my-temporary-note"));
219 /// assert!(name.ends_with(".txt"));
220 /// assert_eq!(name.len(), "my-temporary-note.txt".len() + 5);
221 /// }
222 /// # Ok::<(), std::io::Error>(())
223 /// ```
224 ///
225 /// Create a temporary directory and add a file to it:
226 ///
227 /// ```
228 /// use std::io::Write;
229 /// use std::fs::File;
230 /// use std::ffi::OsStr;
231 /// use tempfile::Builder;
232 ///
233 /// let dir = Builder::new()
234 /// .prefix("my-temporary-dir")
235 /// .rand_bytes(5)
236 /// .tempdir()?;
237 ///
238 /// let file_path = dir.path().join("my-temporary-note.txt");
239 /// let mut file = File::create(file_path)?;
240 /// writeln!(file, "Brian was here. Briefly.")?;
241 ///
242 /// // By closing the `TempDir` explicitly, we can check that it has
243 /// // been deleted successfully. If we don't close it explicitly,
244 /// // the directory will still be deleted when `dir` goes out
245 /// // of scope, but we won't know whether deleting the directory
246 /// // succeeded.
247 /// drop(file);
248 /// dir.close()?;
249 /// # Ok::<(), std::io::Error>(())
250 /// ```
251 ///
252 /// Create a temporary directory with a chosen prefix under a chosen folder:
253 ///
254 /// ```no_run
255 /// use tempfile::Builder;
256 ///
257 /// let dir = Builder::new()
258 /// .prefix("my-temporary-dir")
259 /// .tempdir_in("folder-with-tempdirs")?;
260 /// # Ok::<(), std::io::Error>(())
261 /// ```
262 #[must_use]
263 pub fn new() -> Self {
264 Self::default()
265 }
266
267 /// Set a custom filename prefix.
268 ///
269 /// Path separators are legal but not advisable.
270 /// Default: `.tmp`.
271 ///
272 /// # Examples
273 ///
274 /// ```
275 /// use tempfile::Builder;
276 ///
277 /// let named_tempfile = Builder::new()
278 /// .prefix("my-temporary-note")
279 /// .tempfile()?;
280 /// # Ok::<(), std::io::Error>(())
281 /// ```
282 pub fn prefix<S: AsRef<OsStr> + ?Sized>(&mut self, prefix: &'a S) -> &mut Self {
283 self.prefix = prefix.as_ref();
284 self
285 }
286
287 /// Set a custom filename suffix.
288 ///
289 /// Path separators are legal but not advisable.
290 /// Default: empty.
291 ///
292 /// # Examples
293 ///
294 /// ```
295 /// use tempfile::Builder;
296 ///
297 /// let named_tempfile = Builder::new()
298 /// .suffix(".txt")
299 /// .tempfile()?;
300 /// # Ok::<(), std::io::Error>(())
301 /// ```
302 pub fn suffix<S: AsRef<OsStr> + ?Sized>(&mut self, suffix: &'b S) -> &mut Self {
303 self.suffix = suffix.as_ref();
304 self
305 }
306
307 /// Set the number of random bytes.
308 ///
309 /// Default: `6`.
310 ///
311 /// # Examples
312 ///
313 /// ```
314 /// use tempfile::Builder;
315 ///
316 /// let named_tempfile = Builder::new()
317 /// .rand_bytes(5)
318 /// .tempfile()?;
319 /// # Ok::<(), std::io::Error>(())
320 /// ```
321 pub fn rand_bytes(&mut self, rand: usize) -> &mut Self {
322 self.random_len = rand;
323 self
324 }
325
326 /// Set the file to be opened in append mode.
327 ///
328 /// Default: `false`.
329 ///
330 /// # Examples
331 ///
332 /// ```
333 /// use tempfile::Builder;
334 ///
335 /// let named_tempfile = Builder::new()
336 /// .append(true)
337 /// .tempfile()?;
338 /// # Ok::<(), std::io::Error>(())
339 /// ```
340 pub fn append(&mut self, append: bool) -> &mut Self {
341 self.append = append;
342 self
343 }
344
345 /// The permissions to create the tempfile or [tempdir](Self::tempdir) with.
346 ///
347 /// # Security
348 ///
349 /// By default, the permissions of tempfiles on unix are set for it to be
350 /// readable and writable by the owner only, yielding the greatest amount
351 /// of security.
352 /// As this method allows to widen the permissions, security would be
353 /// reduced in such cases.
354 ///
355 /// # Platform Notes
356 /// ## Unix
357 ///
358 /// The actual permission bits set on the tempfile or tempdir will be affected by the `umask`
359 /// applied by the underlying syscall. The actual permission bits are calculated via
360 /// `permissions & !umask`.
361 ///
362 /// Permissions default to `0o600` for tempfiles and `0o777` for tempdirs. Note, this doesn't
363 /// include effects of the current `umask`. For example, combined with the standard umask
364 /// `0o022`, the defaults yield `0o600` for tempfiles and `0o755` for tempdirs.
365 ///
366 /// ## Windows and others
367 ///
368 /// This setting is unsupported and trying to set a file or directory read-only
369 /// will cause an error to be returned..
370 ///
371 /// # Examples
372 ///
373 /// Create a named temporary file that is world-readable.
374 ///
375 /// ```
376 /// # #[cfg(unix)]
377 /// # {
378 /// use tempfile::Builder;
379 /// use std::os::unix::fs::PermissionsExt;
380 ///
381 /// let all_read_write = std::fs::Permissions::from_mode(0o666);
382 /// let tempfile = Builder::new().permissions(all_read_write).tempfile()?;
383 /// let actual_permissions = tempfile.path().metadata()?.permissions();
384 /// assert_ne!(
385 /// actual_permissions.mode() & !0o170000,
386 /// 0o600,
387 /// "we get broader permissions than the default despite umask"
388 /// );
389 /// # }
390 /// # Ok::<(), std::io::Error>(())
391 /// ```
392 ///
393 /// Create a named temporary directory that is restricted to the owner.
394 ///
395 /// ```
396 /// # #[cfg(unix)]
397 /// # {
398 /// use tempfile::Builder;
399 /// use std::os::unix::fs::PermissionsExt;
400 ///
401 /// let owner_rwx = std::fs::Permissions::from_mode(0o700);
402 /// let tempdir = Builder::new().permissions(owner_rwx).tempdir()?;
403 /// let actual_permissions = tempdir.path().metadata()?.permissions();
404 /// assert_eq!(
405 /// actual_permissions.mode() & !0o170000,
406 /// 0o700,
407 /// "we get the narrow permissions we asked for"
408 /// );
409 /// # }
410 /// # Ok::<(), std::io::Error>(())
411 /// ```
412 pub fn permissions(&mut self, permissions: std::fs::Permissions) -> &mut Self {
413 self.permissions = Some(permissions);
414 self
415 }
416
417 /// Set the file/folder to be kept even when the [`NamedTempFile`]/[`TempDir`] goes out of
418 /// scope.
419 ///
420 /// By default, the file/folder is automatically cleaned up in the destructor of
421 /// [`NamedTempFile`]/[`TempDir`]. When `keep` is set to `true`, this behavior is supressed.
422 ///
423 /// # Examples
424 ///
425 /// ```
426 /// use tempfile::Builder;
427 ///
428 /// let named_tempfile = Builder::new()
429 /// .keep(true)
430 /// .tempfile()?;
431 /// # Ok::<(), std::io::Error>(())
432 /// ```
433 pub fn keep(&mut self, keep: bool) -> &mut Self {
434 self.keep = keep;
435 self
436 }
437
438 /// Create the named temporary file.
439 ///
440 /// # Security
441 ///
442 /// See [the security][security] docs on `NamedTempFile`.
443 ///
444 /// # Resource leaking
445 ///
446 /// See [the resource leaking][resource-leaking] docs on `NamedTempFile`.
447 ///
448 /// # Errors
449 ///
450 /// If the file cannot be created, `Err` is returned.
451 ///
452 /// # Examples
453 ///
454 /// ```
455 /// use tempfile::Builder;
456 ///
457 /// let tempfile = Builder::new().tempfile()?;
458 /// # Ok::<(), std::io::Error>(())
459 /// ```
460 ///
461 /// [security]: struct.NamedTempFile.html#security
462 /// [resource-leaking]: struct.NamedTempFile.html#resource-leaking
463 pub fn tempfile(&self) -> io::Result<NamedTempFile> {
464 self.tempfile_in(env::temp_dir())
465 }
466
467 /// Create the named temporary file in the specified directory.
468 ///
469 /// # Security
470 ///
471 /// See [the security][security] docs on `NamedTempFile`.
472 ///
473 /// # Resource leaking
474 ///
475 /// See [the resource leaking][resource-leaking] docs on `NamedTempFile`.
476 ///
477 /// # Errors
478 ///
479 /// If the file cannot be created, `Err` is returned.
480 ///
481 /// # Examples
482 ///
483 /// ```
484 /// use tempfile::Builder;
485 ///
486 /// let tempfile = Builder::new().tempfile_in("./")?;
487 /// # Ok::<(), std::io::Error>(())
488 /// ```
489 ///
490 /// [security]: struct.NamedTempFile.html#security
491 /// [resource-leaking]: struct.NamedTempFile.html#resource-leaking
492 pub fn tempfile_in<P: AsRef<Path>>(&self, dir: P) -> io::Result<NamedTempFile> {
493 util::create_helper(
494 dir.as_ref(),
495 self.prefix,
496 self.suffix,
497 self.random_len,
498 |path| {
499 file::create_named(
500 path,
501 OpenOptions::new().append(self.append),
502 self.permissions.as_ref(),
503 self.keep,
504 )
505 },
506 )
507 }
508
509 /// Attempts to make a temporary directory inside of [`env::temp_dir()`] whose
510 /// name will have the prefix, `prefix`. The directory and
511 /// everything inside it will be automatically deleted once the
512 /// returned `TempDir` is destroyed.
513 ///
514 /// # Resource leaking
515 ///
516 /// See [the resource leaking][resource-leaking] docs on `TempDir`.
517 ///
518 /// # Errors
519 ///
520 /// If the directory can not be created, `Err` is returned.
521 ///
522 /// # Examples
523 ///
524 /// ```
525 /// use tempfile::Builder;
526 ///
527 /// let tmp_dir = Builder::new().tempdir()?;
528 /// # Ok::<(), std::io::Error>(())
529 /// ```
530 ///
531 /// [resource-leaking]: struct.TempDir.html#resource-leaking
532 pub fn tempdir(&self) -> io::Result<TempDir> {
533 self.tempdir_in(env::temp_dir())
534 }
535
536 /// Attempts to make a temporary directory inside of `dir`.
537 /// The directory and everything inside it will be automatically
538 /// deleted once the returned `TempDir` is destroyed.
539 ///
540 /// # Resource leaking
541 ///
542 /// See [the resource leaking][resource-leaking] docs on `TempDir`.
543 ///
544 /// # Errors
545 ///
546 /// If the directory can not be created, `Err` is returned.
547 ///
548 /// # Examples
549 ///
550 /// ```
551 /// use tempfile::Builder;
552 ///
553 /// let tmp_dir = Builder::new().tempdir_in("./")?;
554 /// # Ok::<(), std::io::Error>(())
555 /// ```
556 ///
557 /// [resource-leaking]: struct.TempDir.html#resource-leaking
558 pub fn tempdir_in<P: AsRef<Path>>(&self, dir: P) -> io::Result<TempDir> {
559 let storage;
560 let mut dir = dir.as_ref();
561 if !dir.is_absolute() {
562 let cur_dir = std::env::current_dir()?;
563 storage = cur_dir.join(dir);
564 dir = &storage;
565 }
566
567 util::create_helper(dir, self.prefix, self.suffix, self.random_len, |path| {
568 dir::create(path, self.permissions.as_ref(), self.keep)
569 })
570 }
571
572 /// Attempts to create a temporary file (or file-like object) using the
573 /// provided closure. The closure is passed a temporary file path and
574 /// returns an [`std::io::Result`]. The path provided to the closure will be
575 /// inside of [`env::temp_dir()`]. Use [`Builder::make_in`] to provide
576 /// a custom temporary directory. If the closure returns one of the
577 /// following errors, then another randomized file path is tried:
578 /// - [`std::io::ErrorKind::AlreadyExists`]
579 /// - [`std::io::ErrorKind::AddrInUse`]
580 ///
581 /// This can be helpful for taking full control over the file creation, but
582 /// leaving the temporary file path construction up to the library. This
583 /// also enables creating a temporary UNIX domain socket, since it is not
584 /// possible to bind to a socket that already exists.
585 ///
586 /// Note that [`Builder::append`] is ignored when using [`Builder::make`].
587 ///
588 /// # Security
589 ///
590 /// This has the same [security implications][security] as
591 /// [`NamedTempFile`], but with additional caveats. Specifically, it is up
592 /// to the closure to ensure that the file does not exist and that such a
593 /// check is *atomic*. Otherwise, a [time-of-check to time-of-use
594 /// bug][TOCTOU] could be introduced.
595 ///
596 /// For example, the following is **not** secure:
597 ///
598 /// ```
599 /// use std::fs::File;
600 /// use tempfile::Builder;
601 ///
602 /// // This is NOT secure!
603 /// let tempfile = Builder::new().make(|path| {
604 /// if path.is_file() {
605 /// return Err(std::io::ErrorKind::AlreadyExists.into());
606 /// }
607 ///
608 /// // Between the check above and the usage below, an attacker could
609 /// // have replaced `path` with another file, which would get truncated
610 /// // by `File::create`.
611 ///
612 /// File::create(path)
613 /// })?;
614 /// # Ok::<(), std::io::Error>(())
615 /// ```
616 ///
617 /// Note that simply using [`std::fs::File::create`] alone is not correct
618 /// because it does not fail if the file already exists:
619 ///
620 /// ```
621 /// use tempfile::Builder;
622 /// use std::fs::File;
623 ///
624 /// // This could overwrite an existing file!
625 /// let tempfile = Builder::new().make(|path| File::create(path))?;
626 /// # Ok::<(), std::io::Error>(())
627 /// ```
628 /// For creating regular temporary files, use [`Builder::tempfile`] instead
629 /// to avoid these problems. This function is meant to enable more exotic
630 /// use-cases.
631 ///
632 /// # Resource leaking
633 ///
634 /// See [the resource leaking][resource-leaking] docs on `NamedTempFile`.
635 ///
636 /// # Errors
637 ///
638 /// If the closure returns any error besides
639 /// [`std::io::ErrorKind::AlreadyExists`] or
640 /// [`std::io::ErrorKind::AddrInUse`], then `Err` is returned.
641 ///
642 /// # Examples
643 /// ```
644 /// # #[cfg(unix)]
645 /// # {
646 /// use std::os::unix::net::UnixListener;
647 /// use tempfile::Builder;
648 ///
649 /// let tempsock = Builder::new().make(|path| UnixListener::bind(path))?;
650 /// # }
651 /// # Ok::<(), std::io::Error>(())
652 /// ```
653 ///
654 /// [TOCTOU]: https://en.wikipedia.org/wiki/Time-of-check_to_time-of-use
655 /// [security]: struct.NamedTempFile.html#security
656 /// [resource-leaking]: struct.NamedTempFile.html#resource-leaking
657 pub fn make<F, R>(&self, f: F) -> io::Result<NamedTempFile<R>>
658 where
659 F: FnMut(&Path) -> io::Result<R>,
660 {
661 self.make_in(env::temp_dir(), f)
662 }
663
664 /// This is the same as [`Builder::make`], except `dir` is used as the base
665 /// directory for the temporary file path.
666 ///
667 /// See [`Builder::make`] for more details and security implications.
668 ///
669 /// # Examples
670 /// ```
671 /// # #[cfg(unix)]
672 /// # {
673 /// use tempfile::Builder;
674 /// use std::os::unix::net::UnixListener;
675 ///
676 /// let tempsock = Builder::new().make_in("./", |path| UnixListener::bind(path))?;
677 /// # }
678 /// # Ok::<(), std::io::Error>(())
679 /// ```
680 pub fn make_in<F, R, P>(&self, dir: P, mut f: F) -> io::Result<NamedTempFile<R>>
681 where
682 F: FnMut(&Path) -> io::Result<R>,
683 P: AsRef<Path>,
684 {
685 util::create_helper(
686 dir.as_ref(),
687 self.prefix,
688 self.suffix,
689 self.random_len,
690 move |path| {
691 Ok(NamedTempFile::from_parts(
692 f(&path)?,
693 TempPath::new(path, self.keep),
694 ))
695 },
696 )
697 }
698}