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