Debian Codegraph @

third_party/rust/tempfile/src/lib.rs

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