1 | use std::error; |
2 | use std::ffi::OsStr; |
3 | use std::fmt; |
4 | use std::fs::{self, File, OpenOptions}; |
5 | use std::io::{self, Read, Seek, SeekFrom, Write}; |
6 | use std::mem; |
7 | use std::ops::Deref; |
8 | #[cfg (unix)] |
9 | use std::os::unix::io::{AsFd, AsRawFd, BorrowedFd, RawFd}; |
10 | #[cfg (target_os = "wasi" )] |
11 | use std::os::wasi::io::{AsFd, AsRawFd, BorrowedFd, RawFd}; |
12 | #[cfg (windows)] |
13 | use std::os::windows::io::{AsHandle, AsRawHandle, BorrowedHandle, RawHandle}; |
14 | use std::path::{Path, PathBuf}; |
15 | |
16 | use crate::env; |
17 | use crate::error::IoResultExt; |
18 | use crate::Builder; |
19 | |
20 | mod imp; |
21 | |
22 | /// Create a new temporary file. |
23 | /// |
24 | /// The file will be created in the location returned by [`env::temp_dir()`]. |
25 | /// |
26 | /// # Security |
27 | /// |
28 | /// This variant is secure/reliable in the presence of a pathological temporary file cleaner. |
29 | /// |
30 | /// # Resource Leaking |
31 | /// |
32 | /// The temporary file will be automatically removed by the OS when the last handle to it is closed. |
33 | /// This doesn't rely on Rust destructors being run, so will (almost) never fail to clean up the temporary file. |
34 | /// |
35 | /// # Errors |
36 | /// |
37 | /// If the file can not be created, `Err` is returned. |
38 | /// |
39 | /// # Examples |
40 | /// |
41 | /// ``` |
42 | /// use tempfile::tempfile; |
43 | /// use std::io::Write; |
44 | /// |
45 | /// // Create a file inside of `env::temp_dir()`. |
46 | /// let mut file = tempfile()?; |
47 | /// |
48 | /// writeln!(file, "Brian was here. Briefly." )?; |
49 | /// # Ok::<(), std::io::Error>(()) |
50 | /// ``` |
51 | pub fn tempfile() -> io::Result<File> { |
52 | tempfile_in(dir:env::temp_dir()) |
53 | } |
54 | |
55 | /// Create a new temporary file in the specified directory. |
56 | /// |
57 | /// # Security |
58 | /// |
59 | /// This variant is secure/reliable in the presence of a pathological temporary file cleaner. |
60 | /// If the temporary file isn't created in [`env::temp_dir()`] then temporary file cleaners aren't an issue. |
61 | /// |
62 | /// # Resource Leaking |
63 | /// |
64 | /// The temporary file will be automatically removed by the OS when the last handle to it is closed. |
65 | /// This doesn't rely on Rust destructors being run, so will (almost) never fail to clean up the temporary file. |
66 | /// |
67 | /// # Errors |
68 | /// |
69 | /// If the file can not be created, `Err` is returned. |
70 | /// |
71 | /// # Examples |
72 | /// |
73 | /// ``` |
74 | /// use tempfile::tempfile_in; |
75 | /// use std::io::Write; |
76 | /// |
77 | /// // Create a file inside of the current working directory |
78 | /// let mut file = tempfile_in("./" )?; |
79 | /// |
80 | /// writeln!(file, "Brian was here. Briefly." )?; |
81 | /// # Ok::<(), std::io::Error>(()) |
82 | /// ``` |
83 | pub fn tempfile_in<P: AsRef<Path>>(dir: P) -> io::Result<File> { |
84 | imp::create(dir.as_ref()) |
85 | } |
86 | |
87 | /// Error returned when persisting a temporary file path fails. |
88 | #[derive (Debug)] |
89 | pub struct PathPersistError { |
90 | /// The underlying IO error. |
91 | pub error: io::Error, |
92 | /// The temporary file path that couldn't be persisted. |
93 | pub path: TempPath, |
94 | } |
95 | |
96 | impl From<PathPersistError> for io::Error { |
97 | #[inline ] |
98 | fn from(error: PathPersistError) -> io::Error { |
99 | error.error |
100 | } |
101 | } |
102 | |
103 | impl From<PathPersistError> for TempPath { |
104 | #[inline ] |
105 | fn from(error: PathPersistError) -> TempPath { |
106 | error.path |
107 | } |
108 | } |
109 | |
110 | impl fmt::Display for PathPersistError { |
111 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
112 | write!(f, "failed to persist temporary file path: {}" , self.error) |
113 | } |
114 | } |
115 | |
116 | impl error::Error for PathPersistError { |
117 | fn source(&self) -> Option<&(dyn error::Error + 'static)> { |
118 | Some(&self.error) |
119 | } |
120 | } |
121 | |
122 | /// A path to a named temporary file without an open file handle. |
123 | /// |
124 | /// This is useful when the temporary file needs to be used by a child process, |
125 | /// for example. |
126 | /// |
127 | /// When dropped, the temporary file is deleted unless `keep(true)` was called |
128 | /// on the builder that constructed this value. |
129 | pub struct TempPath { |
130 | path: Box<Path>, |
131 | keep: bool, |
132 | } |
133 | |
134 | impl TempPath { |
135 | /// Close and remove the temporary file. |
136 | /// |
137 | /// Use this if you want to detect errors in deleting the file. |
138 | /// |
139 | /// # Errors |
140 | /// |
141 | /// If the file cannot be deleted, `Err` is returned. |
142 | /// |
143 | /// # Examples |
144 | /// |
145 | /// ```no_run |
146 | /// use tempfile::NamedTempFile; |
147 | /// |
148 | /// let file = NamedTempFile::new()?; |
149 | /// |
150 | /// // Close the file, but keep the path to it around. |
151 | /// let path = file.into_temp_path(); |
152 | /// |
153 | /// // By closing the `TempPath` explicitly, we can check that it has |
154 | /// // been deleted successfully. If we don't close it explicitly, the |
155 | /// // file will still be deleted when `file` goes out of scope, but we |
156 | /// // won't know whether deleting the file succeeded. |
157 | /// path.close()?; |
158 | /// # Ok::<(), std::io::Error>(()) |
159 | /// ``` |
160 | pub fn close(mut self) -> io::Result<()> { |
161 | let result = fs::remove_file(&self.path).with_err_path(|| &*self.path); |
162 | self.path = PathBuf::new().into_boxed_path(); |
163 | mem::forget(self); |
164 | result |
165 | } |
166 | |
167 | /// Persist the temporary file at the target path. |
168 | /// |
169 | /// If a file exists at the target path, persist will atomically replace it. |
170 | /// If this method fails, it will return `self` in the resulting |
171 | /// [`PathPersistError`]. |
172 | /// |
173 | /// Note: Temporary files cannot be persisted across filesystems. Also |
174 | /// neither the file contents nor the containing directory are |
175 | /// synchronized, so the update may not yet have reached the disk when |
176 | /// `persist` returns. |
177 | /// |
178 | /// # Security |
179 | /// |
180 | /// Only use this method if you're positive that a temporary file cleaner |
181 | /// won't have deleted your file. Otherwise, you might end up persisting an |
182 | /// attacker controlled file. |
183 | /// |
184 | /// # Errors |
185 | /// |
186 | /// If the file cannot be moved to the new location, `Err` is returned. |
187 | /// |
188 | /// # Examples |
189 | /// |
190 | /// ```no_run |
191 | /// use std::io::Write; |
192 | /// use tempfile::NamedTempFile; |
193 | /// |
194 | /// let mut file = NamedTempFile::new()?; |
195 | /// writeln!(file, "Brian was here. Briefly." )?; |
196 | /// |
197 | /// let path = file.into_temp_path(); |
198 | /// path.persist("./saved_file.txt" )?; |
199 | /// # Ok::<(), std::io::Error>(()) |
200 | /// ``` |
201 | /// |
202 | /// [`PathPersistError`]: struct.PathPersistError.html |
203 | pub fn persist<P: AsRef<Path>>(mut self, new_path: P) -> Result<(), PathPersistError> { |
204 | match imp::persist(&self.path, new_path.as_ref(), true) { |
205 | Ok(_) => { |
206 | // Don't drop `self`. We don't want to try deleting the old |
207 | // temporary file path. (It'll fail, but the failure is never |
208 | // seen.) |
209 | self.path = PathBuf::new().into_boxed_path(); |
210 | mem::forget(self); |
211 | Ok(()) |
212 | } |
213 | Err(e) => Err(PathPersistError { |
214 | error: e, |
215 | path: self, |
216 | }), |
217 | } |
218 | } |
219 | |
220 | /// Persist the temporary file at the target path if and only if no file exists there. |
221 | /// |
222 | /// If a file exists at the target path, fail. If this method fails, it will |
223 | /// return `self` in the resulting [`PathPersistError`]. |
224 | /// |
225 | /// Note: Temporary files cannot be persisted across filesystems. Also Note: |
226 | /// This method is not atomic. It can leave the original link to the |
227 | /// temporary file behind. |
228 | /// |
229 | /// # Security |
230 | /// |
231 | /// Only use this method if you're positive that a temporary file cleaner |
232 | /// won't have deleted your file. Otherwise, you might end up persisting an |
233 | /// attacker controlled file. |
234 | /// |
235 | /// # Errors |
236 | /// |
237 | /// If the file cannot be moved to the new location or a file already exists |
238 | /// there, `Err` is returned. |
239 | /// |
240 | /// # Examples |
241 | /// |
242 | /// ```no_run |
243 | /// use tempfile::NamedTempFile; |
244 | /// use std::io::Write; |
245 | /// |
246 | /// let mut file = NamedTempFile::new()?; |
247 | /// writeln!(file, "Brian was here. Briefly." )?; |
248 | /// |
249 | /// let path = file.into_temp_path(); |
250 | /// path.persist_noclobber("./saved_file.txt" )?; |
251 | /// # Ok::<(), std::io::Error>(()) |
252 | /// ``` |
253 | /// |
254 | /// [`PathPersistError`]: struct.PathPersistError.html |
255 | pub fn persist_noclobber<P: AsRef<Path>>( |
256 | mut self, |
257 | new_path: P, |
258 | ) -> Result<(), PathPersistError> { |
259 | match imp::persist(&self.path, new_path.as_ref(), false) { |
260 | Ok(_) => { |
261 | // Don't drop `self`. We don't want to try deleting the old |
262 | // temporary file path. (It'll fail, but the failure is never |
263 | // seen.) |
264 | self.path = PathBuf::new().into_boxed_path(); |
265 | mem::forget(self); |
266 | Ok(()) |
267 | } |
268 | Err(e) => Err(PathPersistError { |
269 | error: e, |
270 | path: self, |
271 | }), |
272 | } |
273 | } |
274 | |
275 | /// Keep the temporary file from being deleted. This function will turn the |
276 | /// temporary file into a non-temporary file without moving it. |
277 | /// |
278 | /// # Errors |
279 | /// |
280 | /// On some platforms (e.g., Windows), we need to mark the file as |
281 | /// non-temporary. This operation could fail. |
282 | /// |
283 | /// # Examples |
284 | /// |
285 | /// ```no_run |
286 | /// use std::io::Write; |
287 | /// use tempfile::NamedTempFile; |
288 | /// |
289 | /// let mut file = NamedTempFile::new()?; |
290 | /// writeln!(file, "Brian was here. Briefly." )?; |
291 | /// |
292 | /// let path = file.into_temp_path(); |
293 | /// let path = path.keep()?; |
294 | /// # Ok::<(), std::io::Error>(()) |
295 | /// ``` |
296 | /// |
297 | /// [`PathPersistError`]: struct.PathPersistError.html |
298 | pub fn keep(mut self) -> Result<PathBuf, PathPersistError> { |
299 | match imp::keep(&self.path) { |
300 | Ok(_) => { |
301 | // Don't drop `self`. We don't want to try deleting the old |
302 | // temporary file path. (It'll fail, but the failure is never |
303 | // seen.) |
304 | let path = mem::replace(&mut self.path, PathBuf::new().into_boxed_path()); |
305 | mem::forget(self); |
306 | Ok(path.into()) |
307 | } |
308 | Err(e) => Err(PathPersistError { |
309 | error: e, |
310 | path: self, |
311 | }), |
312 | } |
313 | } |
314 | |
315 | /// Create a new TempPath from an existing path. This can be done even if no |
316 | /// file exists at the given path. |
317 | /// |
318 | /// This is mostly useful for interacting with libraries and external |
319 | /// components that provide files to be consumed or expect a path with no |
320 | /// existing file to be given. |
321 | pub fn from_path(path: impl Into<PathBuf>) -> Self { |
322 | Self { |
323 | path: path.into().into_boxed_path(), |
324 | keep: false, |
325 | } |
326 | } |
327 | |
328 | pub(crate) fn new(path: PathBuf, keep: bool) -> Self { |
329 | Self { |
330 | path: path.into_boxed_path(), |
331 | keep, |
332 | } |
333 | } |
334 | } |
335 | |
336 | impl fmt::Debug for TempPath { |
337 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
338 | self.path.fmt(f) |
339 | } |
340 | } |
341 | |
342 | impl Drop for TempPath { |
343 | fn drop(&mut self) { |
344 | if !self.keep { |
345 | let _ = fs::remove_file(&self.path); |
346 | } |
347 | } |
348 | } |
349 | |
350 | impl Deref for TempPath { |
351 | type Target = Path; |
352 | |
353 | fn deref(&self) -> &Path { |
354 | &self.path |
355 | } |
356 | } |
357 | |
358 | impl AsRef<Path> for TempPath { |
359 | fn as_ref(&self) -> &Path { |
360 | &self.path |
361 | } |
362 | } |
363 | |
364 | impl AsRef<OsStr> for TempPath { |
365 | fn as_ref(&self) -> &OsStr { |
366 | self.path.as_os_str() |
367 | } |
368 | } |
369 | |
370 | /// A named temporary file. |
371 | /// |
372 | /// The default constructor, [`NamedTempFile::new()`], creates files in |
373 | /// the location returned by [`env::temp_dir()`], but `NamedTempFile` |
374 | /// can be configured to manage a temporary file in any location |
375 | /// by constructing with [`NamedTempFile::new_in()`]. |
376 | /// |
377 | /// # Security |
378 | /// |
379 | /// Most operating systems employ temporary file cleaners to delete old |
380 | /// temporary files. Unfortunately these temporary file cleaners don't always |
381 | /// reliably _detect_ whether the temporary file is still being used. |
382 | /// |
383 | /// Specifically, the following sequence of events can happen: |
384 | /// |
385 | /// 1. A user creates a temporary file with `NamedTempFile::new()`. |
386 | /// 2. Time passes. |
387 | /// 3. The temporary file cleaner deletes (unlinks) the temporary file from the |
388 | /// filesystem. |
389 | /// 4. Some other program creates a new file to replace this deleted temporary |
390 | /// file. |
391 | /// 5. The user tries to re-open the temporary file (in the same program or in a |
392 | /// different program) by path. Unfortunately, they'll end up opening the |
393 | /// file created by the other program, not the original file. |
394 | /// |
395 | /// ## Operating System Specific Concerns |
396 | /// |
397 | /// The behavior of temporary files and temporary file cleaners differ by |
398 | /// operating system. |
399 | /// |
400 | /// ### Windows |
401 | /// |
402 | /// On Windows, temporary files are, by default, created in per-user temporary |
403 | /// file directories so only an application running as the same user would be |
404 | /// able to interfere (which they could do anyways). However, an application |
405 | /// running as the same user can still _accidentally_ re-create deleted |
406 | /// temporary files if the number of random bytes in the temporary file name is |
407 | /// too small. |
408 | /// |
409 | /// ### MacOS |
410 | /// |
411 | /// Like on Windows, temporary files are created in per-user temporary file |
412 | /// directories by default so calling `NamedTempFile::new()` should be |
413 | /// relatively safe. |
414 | /// |
415 | /// ### Linux |
416 | /// |
417 | /// Unfortunately, most _Linux_ distributions don't create per-user temporary |
418 | /// file directories. Worse, systemd's tmpfiles daemon (a common temporary file |
419 | /// cleaner) will happily remove open temporary files if they haven't been |
420 | /// modified within the last 10 days. |
421 | /// |
422 | /// # Resource Leaking |
423 | /// |
424 | /// If the program exits before the `NamedTempFile` destructor is |
425 | /// run, the temporary file will not be deleted. This can happen |
426 | /// if the process exits using [`std::process::exit()`], a segfault occurs, |
427 | /// receiving an interrupt signal like `SIGINT` that is not handled, or by using |
428 | /// a statically declared `NamedTempFile` instance (like with [`lazy_static`]). |
429 | /// |
430 | /// Use the [`tempfile()`] function unless you need a named file path. |
431 | /// |
432 | /// [`tempfile()`]: fn.tempfile.html |
433 | /// [`NamedTempFile::new()`]: #method.new |
434 | /// [`NamedTempFile::new_in()`]: #method.new_in |
435 | /// [`std::process::exit()`]: http://doc.rust-lang.org/std/process/fn.exit.html |
436 | /// [`lazy_static`]: https://github.com/rust-lang-nursery/lazy-static.rs/issues/62 |
437 | pub struct NamedTempFile<F = File> { |
438 | path: TempPath, |
439 | file: F, |
440 | } |
441 | |
442 | impl<F> fmt::Debug for NamedTempFile<F> { |
443 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
444 | write!(f, "NamedTempFile( {:?})" , self.path) |
445 | } |
446 | } |
447 | |
448 | impl<F> AsRef<Path> for NamedTempFile<F> { |
449 | #[inline ] |
450 | fn as_ref(&self) -> &Path { |
451 | self.path() |
452 | } |
453 | } |
454 | |
455 | /// Error returned when persisting a temporary file fails. |
456 | pub struct PersistError<F = File> { |
457 | /// The underlying IO error. |
458 | pub error: io::Error, |
459 | /// The temporary file that couldn't be persisted. |
460 | pub file: NamedTempFile<F>, |
461 | } |
462 | |
463 | impl<F> fmt::Debug for PersistError<F> { |
464 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
465 | write!(f, "PersistError( {:?})" , self.error) |
466 | } |
467 | } |
468 | |
469 | impl<F> From<PersistError<F>> for io::Error { |
470 | #[inline ] |
471 | fn from(error: PersistError<F>) -> io::Error { |
472 | error.error |
473 | } |
474 | } |
475 | |
476 | impl<F> From<PersistError<F>> for NamedTempFile<F> { |
477 | #[inline ] |
478 | fn from(error: PersistError<F>) -> NamedTempFile<F> { |
479 | error.file |
480 | } |
481 | } |
482 | |
483 | impl<F> fmt::Display for PersistError<F> { |
484 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
485 | write!(f, "failed to persist temporary file: {}" , self.error) |
486 | } |
487 | } |
488 | |
489 | impl<F> error::Error for PersistError<F> { |
490 | fn source(&self) -> Option<&(dyn error::Error + 'static)> { |
491 | Some(&self.error) |
492 | } |
493 | } |
494 | |
495 | impl NamedTempFile<File> { |
496 | /// Create a new named temporary file. |
497 | /// |
498 | /// See [`Builder`] for more configuration. |
499 | /// |
500 | /// # Security |
501 | /// |
502 | /// This will create a temporary file in the default temporary file |
503 | /// directory (platform dependent). This has security implications on many |
504 | /// platforms so please read the security section of this type's |
505 | /// documentation. |
506 | /// |
507 | /// Reasons to use this method: |
508 | /// |
509 | /// 1. The file has a short lifetime and your temporary file cleaner is |
510 | /// sane (doesn't delete recently accessed files). |
511 | /// |
512 | /// 2. You trust every user on your system (i.e. you are the only user). |
513 | /// |
514 | /// 3. You have disabled your system's temporary file cleaner or verified |
515 | /// that your system doesn't have a temporary file cleaner. |
516 | /// |
517 | /// Reasons not to use this method: |
518 | /// |
519 | /// 1. You'll fix it later. No you won't. |
520 | /// |
521 | /// 2. You don't care about the security of the temporary file. If none of |
522 | /// the "reasons to use this method" apply, referring to a temporary |
523 | /// file by name may allow an attacker to create/overwrite your |
524 | /// non-temporary files. There are exceptions but if you don't already |
525 | /// know them, don't use this method. |
526 | /// |
527 | /// # Errors |
528 | /// |
529 | /// If the file can not be created, `Err` is returned. |
530 | /// |
531 | /// # Examples |
532 | /// |
533 | /// Create a named temporary file and write some data to it: |
534 | /// |
535 | /// ```no_run |
536 | /// use std::io::Write; |
537 | /// use tempfile::NamedTempFile; |
538 | /// |
539 | /// let mut file = NamedTempFile::new()?; |
540 | /// |
541 | /// writeln!(file, "Brian was here. Briefly." )?; |
542 | /// # Ok::<(), std::io::Error>(()) |
543 | /// ``` |
544 | /// |
545 | /// [`Builder`]: struct.Builder.html |
546 | pub fn new() -> io::Result<NamedTempFile> { |
547 | Builder::new().tempfile() |
548 | } |
549 | |
550 | /// Create a new named temporary file in the specified directory. |
551 | /// |
552 | /// This is equivalent to: |
553 | /// |
554 | /// ```ignore |
555 | /// Builder::new().tempfile_in(dir) |
556 | /// ``` |
557 | /// |
558 | /// See [`NamedTempFile::new()`] for details. |
559 | /// |
560 | /// [`NamedTempFile::new()`]: #method.new |
561 | pub fn new_in<P: AsRef<Path>>(dir: P) -> io::Result<NamedTempFile> { |
562 | Builder::new().tempfile_in(dir) |
563 | } |
564 | |
565 | /// Create a new named temporary file with the specified filename suffix. |
566 | /// |
567 | /// See [`NamedTempFile::new()`] for details. |
568 | /// |
569 | /// [`NamedTempFile::new()`]: #method.new |
570 | pub fn with_suffix<S: AsRef<OsStr>>(suffix: S) -> io::Result<NamedTempFile> { |
571 | Builder::new().suffix(&suffix).tempfile() |
572 | } |
573 | /// Create a new named temporary file with the specified filename suffix, |
574 | /// in the specified directory. |
575 | /// |
576 | /// This is equivalent to: |
577 | /// |
578 | /// ```ignore |
579 | /// Builder::new().suffix(&suffix).tempfile_in(directory) |
580 | /// ``` |
581 | /// |
582 | /// See [`NamedTempFile::new()`] for details. |
583 | /// |
584 | /// [`NamedTempFile::new()`]: #method.new |
585 | pub fn with_suffix_in<S: AsRef<OsStr>, P: AsRef<Path>>( |
586 | suffix: S, |
587 | dir: P, |
588 | ) -> io::Result<NamedTempFile> { |
589 | Builder::new().suffix(&suffix).tempfile_in(dir) |
590 | } |
591 | |
592 | /// Create a new named temporary file with the specified filename prefix. |
593 | /// |
594 | /// See [`NamedTempFile::new()`] for details. |
595 | /// |
596 | /// [`NamedTempFile::new()`]: #method.new |
597 | pub fn with_prefix<S: AsRef<OsStr>>(prefix: S) -> io::Result<NamedTempFile> { |
598 | Builder::new().prefix(&prefix).tempfile() |
599 | } |
600 | /// Create a new named temporary file with the specified filename prefix, |
601 | /// in the specified directory. |
602 | /// |
603 | /// This is equivalent to: |
604 | /// |
605 | /// ```ignore |
606 | /// Builder::new().prefix(&prefix).tempfile_in(directory) |
607 | /// ``` |
608 | /// |
609 | /// See [`NamedTempFile::new()`] for details. |
610 | /// |
611 | /// [`NamedTempFile::new()`]: #method.new |
612 | pub fn with_prefix_in<S: AsRef<OsStr>, P: AsRef<Path>>( |
613 | prefix: S, |
614 | dir: P, |
615 | ) -> io::Result<NamedTempFile> { |
616 | Builder::new().prefix(&prefix).tempfile_in(dir) |
617 | } |
618 | } |
619 | |
620 | impl<F> NamedTempFile<F> { |
621 | /// Get the temporary file's path. |
622 | /// |
623 | /// # Security |
624 | /// |
625 | /// Referring to a temporary file's path may not be secure in all cases. |
626 | /// Please read the security section on the top level documentation of this |
627 | /// type for details. |
628 | /// |
629 | /// # Examples |
630 | /// |
631 | /// ```no_run |
632 | /// use tempfile::NamedTempFile; |
633 | /// |
634 | /// let file = NamedTempFile::new()?; |
635 | /// |
636 | /// println!("{:?}" , file.path()); |
637 | /// # Ok::<(), std::io::Error>(()) |
638 | /// ``` |
639 | #[inline ] |
640 | pub fn path(&self) -> &Path { |
641 | &self.path |
642 | } |
643 | |
644 | /// Close and remove the temporary file. |
645 | /// |
646 | /// Use this if you want to detect errors in deleting the file. |
647 | /// |
648 | /// # Errors |
649 | /// |
650 | /// If the file cannot be deleted, `Err` is returned. |
651 | /// |
652 | /// # Examples |
653 | /// |
654 | /// ```no_run |
655 | /// use tempfile::NamedTempFile; |
656 | /// |
657 | /// let file = NamedTempFile::new()?; |
658 | /// |
659 | /// // By closing the `NamedTempFile` explicitly, we can check that it has |
660 | /// // been deleted successfully. If we don't close it explicitly, |
661 | /// // the file will still be deleted when `file` goes out |
662 | /// // of scope, but we won't know whether deleting the file |
663 | /// // succeeded. |
664 | /// file.close()?; |
665 | /// # Ok::<(), std::io::Error>(()) |
666 | /// ``` |
667 | pub fn close(self) -> io::Result<()> { |
668 | let NamedTempFile { path, .. } = self; |
669 | path.close() |
670 | } |
671 | |
672 | /// Persist the temporary file at the target path. |
673 | /// |
674 | /// If a file exists at the target path, persist will atomically replace it. |
675 | /// If this method fails, it will return `self` in the resulting |
676 | /// [`PersistError`]. |
677 | /// |
678 | /// **Note:** Temporary files cannot be persisted across filesystems. Also |
679 | /// neither the file contents nor the containing directory are |
680 | /// synchronized, so the update may not yet have reached the disk when |
681 | /// `persist` returns. |
682 | /// |
683 | /// # Security |
684 | /// |
685 | /// This method persists the temporary file using its path and may not be |
686 | /// secure in all cases. Please read the security section on the top |
687 | /// level documentation of this type for details. |
688 | /// |
689 | /// # Errors |
690 | /// |
691 | /// If the file cannot be moved to the new location, `Err` is returned. |
692 | /// |
693 | /// # Examples |
694 | /// |
695 | /// ```no_run |
696 | /// use std::io::Write; |
697 | /// use tempfile::NamedTempFile; |
698 | /// |
699 | /// let file = NamedTempFile::new()?; |
700 | /// |
701 | /// let mut persisted_file = file.persist("./saved_file.txt" )?; |
702 | /// writeln!(persisted_file, "Brian was here. Briefly." )?; |
703 | /// # Ok::<(), std::io::Error>(()) |
704 | /// ``` |
705 | /// |
706 | /// [`PersistError`]: struct.PersistError.html |
707 | pub fn persist<P: AsRef<Path>>(self, new_path: P) -> Result<F, PersistError<F>> { |
708 | let NamedTempFile { path, file } = self; |
709 | match path.persist(new_path) { |
710 | Ok(_) => Ok(file), |
711 | Err(err) => { |
712 | let PathPersistError { error, path } = err; |
713 | Err(PersistError { |
714 | file: NamedTempFile { path, file }, |
715 | error, |
716 | }) |
717 | } |
718 | } |
719 | } |
720 | |
721 | /// Persist the temporary file at the target path if and only if no file exists there. |
722 | /// |
723 | /// If a file exists at the target path, fail. If this method fails, it will |
724 | /// return `self` in the resulting PersistError. |
725 | /// |
726 | /// **Note:** Temporary files cannot be persisted across filesystems. |
727 | /// |
728 | /// **Atomicity:** This method is not guaranteed to be atomic on all platforms, although it will |
729 | /// generally be atomic on Windows and modern Linux filesystems. While it will never overwrite a |
730 | /// file at the target path, it may leave the original link to the temporary file behind leaving |
731 | /// you with two [hard links][hardlink] in your filesystem pointing at the same underlying file. |
732 | /// This can happen if either (a) we lack permission to "unlink" the original filename; (b) this |
733 | /// program crashes while persisting the temporary file; or (c) the filesystem is removed, |
734 | /// unmounted, etc. while we're performing this operation. |
735 | /// |
736 | /// # Security |
737 | /// |
738 | /// This method persists the temporary file using its path and may not be |
739 | /// secure in all cases. Please read the security section on the top |
740 | /// level documentation of this type for details. |
741 | /// |
742 | /// # Errors |
743 | /// |
744 | /// If the file cannot be moved to the new location or a file already exists there, |
745 | /// `Err` is returned. |
746 | /// |
747 | /// # Examples |
748 | /// |
749 | /// ```no_run |
750 | /// use std::io::Write; |
751 | /// use tempfile::NamedTempFile; |
752 | /// |
753 | /// let file = NamedTempFile::new()?; |
754 | /// |
755 | /// let mut persisted_file = file.persist_noclobber("./saved_file.txt" )?; |
756 | /// writeln!(persisted_file, "Brian was here. Briefly." )?; |
757 | /// # Ok::<(), std::io::Error>(()) |
758 | /// ``` |
759 | /// |
760 | /// [hardlink]: https://en.wikipedia.org/wiki/Hard_link |
761 | pub fn persist_noclobber<P: AsRef<Path>>(self, new_path: P) -> Result<F, PersistError<F>> { |
762 | let NamedTempFile { path, file } = self; |
763 | match path.persist_noclobber(new_path) { |
764 | Ok(_) => Ok(file), |
765 | Err(err) => { |
766 | let PathPersistError { error, path } = err; |
767 | Err(PersistError { |
768 | file: NamedTempFile { path, file }, |
769 | error, |
770 | }) |
771 | } |
772 | } |
773 | } |
774 | |
775 | /// Keep the temporary file from being deleted. This function will turn the |
776 | /// temporary file into a non-temporary file without moving it. |
777 | /// |
778 | /// |
779 | /// # Errors |
780 | /// |
781 | /// On some platforms (e.g., Windows), we need to mark the file as |
782 | /// non-temporary. This operation could fail. |
783 | /// |
784 | /// # Examples |
785 | /// |
786 | /// ```no_run |
787 | /// use std::io::Write; |
788 | /// use tempfile::NamedTempFile; |
789 | /// |
790 | /// let mut file = NamedTempFile::new()?; |
791 | /// writeln!(file, "Brian was here. Briefly." )?; |
792 | /// |
793 | /// let (file, path) = file.keep()?; |
794 | /// # Ok::<(), std::io::Error>(()) |
795 | /// ``` |
796 | /// |
797 | /// [`PathPersistError`]: struct.PathPersistError.html |
798 | pub fn keep(self) -> Result<(F, PathBuf), PersistError<F>> { |
799 | let (file, path) = (self.file, self.path); |
800 | match path.keep() { |
801 | Ok(path) => Ok((file, path)), |
802 | Err(PathPersistError { error, path }) => Err(PersistError { |
803 | file: NamedTempFile { path, file }, |
804 | error, |
805 | }), |
806 | } |
807 | } |
808 | |
809 | /// Get a reference to the underlying file. |
810 | pub fn as_file(&self) -> &F { |
811 | &self.file |
812 | } |
813 | |
814 | /// Get a mutable reference to the underlying file. |
815 | pub fn as_file_mut(&mut self) -> &mut F { |
816 | &mut self.file |
817 | } |
818 | |
819 | /// Turn this named temporary file into an "unnamed" temporary file as if you |
820 | /// had constructed it with [`tempfile()`]. |
821 | /// |
822 | /// The underlying file will be removed from the filesystem but the returned [`File`] |
823 | /// can still be read/written. |
824 | pub fn into_file(self) -> F { |
825 | self.file |
826 | } |
827 | |
828 | /// Closes the file, leaving only the temporary file path. |
829 | /// |
830 | /// This is useful when another process must be able to open the temporary |
831 | /// file. |
832 | pub fn into_temp_path(self) -> TempPath { |
833 | self.path |
834 | } |
835 | |
836 | /// Converts the named temporary file into its constituent parts. |
837 | /// |
838 | /// Note: When the path is dropped, the underlying file will be removed from the filesystem but |
839 | /// the returned [`File`] can still be read/written. |
840 | pub fn into_parts(self) -> (F, TempPath) { |
841 | (self.file, self.path) |
842 | } |
843 | |
844 | /// Creates a `NamedTempFile` from its constituent parts. |
845 | /// |
846 | /// This can be used with [`NamedTempFile::into_parts`] to reconstruct the |
847 | /// `NamedTempFile`. |
848 | pub fn from_parts(file: F, path: TempPath) -> Self { |
849 | Self { file, path } |
850 | } |
851 | } |
852 | |
853 | impl NamedTempFile<File> { |
854 | /// Securely reopen the temporary file. |
855 | /// |
856 | /// This function is useful when you need multiple independent handles to |
857 | /// the same file. It's perfectly fine to drop the original `NamedTempFile` |
858 | /// while holding on to `File`s returned by this function; the `File`s will |
859 | /// remain usable. However, they may not be nameable. |
860 | /// |
861 | /// # Errors |
862 | /// |
863 | /// If the file cannot be reopened, `Err` is returned. |
864 | /// |
865 | /// # Security |
866 | /// |
867 | /// Unlike `File::open(my_temp_file.path())`, `NamedTempFile::reopen()` |
868 | /// guarantees that the re-opened file is the _same_ file, even in the |
869 | /// presence of pathological temporary file cleaners. |
870 | /// |
871 | /// # Examples |
872 | /// |
873 | /// ```no_run |
874 | /// use tempfile::NamedTempFile; |
875 | /// |
876 | /// let file = NamedTempFile::new()?; |
877 | /// |
878 | /// let another_handle = file.reopen()?; |
879 | /// # Ok::<(), std::io::Error>(()) |
880 | /// ``` |
881 | pub fn reopen(&self) -> io::Result<File> { |
882 | imp::reopen(self.as_file(), NamedTempFile::path(self)) |
883 | .with_err_path(|| NamedTempFile::path(self)) |
884 | } |
885 | } |
886 | |
887 | impl<F: Read> Read for NamedTempFile<F> { |
888 | fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { |
889 | self.as_file_mut().read(buf).with_err_path(|| self.path()) |
890 | } |
891 | |
892 | fn read_vectored(&mut self, bufs: &mut [io::IoSliceMut<'_>]) -> io::Result<usize> { |
893 | self.as_file_mut() |
894 | .read_vectored(bufs) |
895 | .with_err_path(|| self.path()) |
896 | } |
897 | |
898 | fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> { |
899 | self.as_file_mut() |
900 | .read_to_end(buf) |
901 | .with_err_path(|| self.path()) |
902 | } |
903 | |
904 | fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> { |
905 | self.as_file_mut() |
906 | .read_to_string(buf) |
907 | .with_err_path(|| self.path()) |
908 | } |
909 | |
910 | fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> { |
911 | self.as_file_mut() |
912 | .read_exact(buf) |
913 | .with_err_path(|| self.path()) |
914 | } |
915 | } |
916 | |
917 | impl Read for &NamedTempFile<File> { |
918 | fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { |
919 | self.as_file().read(buf).with_err_path(|| self.path()) |
920 | } |
921 | |
922 | fn read_vectored(&mut self, bufs: &mut [io::IoSliceMut<'_>]) -> io::Result<usize> { |
923 | self.as_file() |
924 | .read_vectored(bufs) |
925 | .with_err_path(|| self.path()) |
926 | } |
927 | |
928 | fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> { |
929 | self.as_file() |
930 | .read_to_end(buf) |
931 | .with_err_path(|| self.path()) |
932 | } |
933 | |
934 | fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> { |
935 | self.as_file() |
936 | .read_to_string(buf) |
937 | .with_err_path(|| self.path()) |
938 | } |
939 | |
940 | fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> { |
941 | self.as_file().read_exact(buf).with_err_path(|| self.path()) |
942 | } |
943 | } |
944 | |
945 | impl<F: Write> Write for NamedTempFile<F> { |
946 | fn write(&mut self, buf: &[u8]) -> io::Result<usize> { |
947 | self.as_file_mut().write(buf).with_err_path(|| self.path()) |
948 | } |
949 | #[inline ] |
950 | fn flush(&mut self) -> io::Result<()> { |
951 | self.as_file_mut().flush().with_err_path(|| self.path()) |
952 | } |
953 | |
954 | fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result<usize> { |
955 | self.as_file_mut() |
956 | .write_vectored(bufs) |
957 | .with_err_path(|| self.path()) |
958 | } |
959 | |
960 | fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { |
961 | self.as_file_mut() |
962 | .write_all(buf) |
963 | .with_err_path(|| self.path()) |
964 | } |
965 | |
966 | fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> { |
967 | self.as_file_mut() |
968 | .write_fmt(fmt) |
969 | .with_err_path(|| self.path()) |
970 | } |
971 | } |
972 | |
973 | impl Write for &NamedTempFile<File> { |
974 | fn write(&mut self, buf: &[u8]) -> io::Result<usize> { |
975 | self.as_file().write(buf).with_err_path(|| self.path()) |
976 | } |
977 | #[inline ] |
978 | fn flush(&mut self) -> io::Result<()> { |
979 | self.as_file().flush().with_err_path(|| self.path()) |
980 | } |
981 | |
982 | fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result<usize> { |
983 | self.as_file() |
984 | .write_vectored(bufs) |
985 | .with_err_path(|| self.path()) |
986 | } |
987 | |
988 | fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { |
989 | self.as_file().write_all(buf).with_err_path(|| self.path()) |
990 | } |
991 | |
992 | fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> { |
993 | self.as_file().write_fmt(args:fmt).with_err_path(|| self.path()) |
994 | } |
995 | } |
996 | |
997 | impl<F: Seek> Seek for NamedTempFile<F> { |
998 | fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> { |
999 | self.as_file_mut().seek(pos).with_err_path(|| self.path()) |
1000 | } |
1001 | } |
1002 | |
1003 | impl Seek for &NamedTempFile<File> { |
1004 | fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> { |
1005 | self.as_file().seek(pos).with_err_path(|| self.path()) |
1006 | } |
1007 | } |
1008 | |
1009 | #[cfg (any(unix, target_os = "wasi" ))] |
1010 | impl<F: AsFd> AsFd for NamedTempFile<F> { |
1011 | fn as_fd(&self) -> BorrowedFd<'_> { |
1012 | self.as_file().as_fd() |
1013 | } |
1014 | } |
1015 | |
1016 | #[cfg (any(unix, target_os = "wasi" ))] |
1017 | impl<F: AsRawFd> AsRawFd for NamedTempFile<F> { |
1018 | #[inline ] |
1019 | fn as_raw_fd(&self) -> RawFd { |
1020 | self.as_file().as_raw_fd() |
1021 | } |
1022 | } |
1023 | |
1024 | #[cfg (windows)] |
1025 | impl<F: AsHandle> AsHandle for NamedTempFile<F> { |
1026 | #[inline ] |
1027 | fn as_handle(&self) -> BorrowedHandle<'_> { |
1028 | self.as_file().as_handle() |
1029 | } |
1030 | } |
1031 | |
1032 | #[cfg (windows)] |
1033 | impl<F: AsRawHandle> AsRawHandle for NamedTempFile<F> { |
1034 | #[inline ] |
1035 | fn as_raw_handle(&self) -> RawHandle { |
1036 | self.as_file().as_raw_handle() |
1037 | } |
1038 | } |
1039 | |
1040 | pub(crate) fn create_named( |
1041 | path: PathBuf, |
1042 | open_options: &mut OpenOptions, |
1043 | permissions: Option<&std::fs::Permissions>, |
1044 | keep: bool, |
1045 | ) -> io::Result<NamedTempFile> { |
1046 | imp::create_named(&path, open_options, permissions) |
1047 | .with_err_path(|| path.clone()) |
1048 | .map(|file: File| NamedTempFile { |
1049 | path: TempPath { |
1050 | path: path.into_boxed_path(), |
1051 | keep, |
1052 | }, |
1053 | file, |
1054 | }) |
1055 | } |
1056 | |