Commit | Line | Data |
262eb13a |
1 | package File::Temp; |
2 | |
3 | =head1 NAME |
4 | |
5 | File::Temp - return name and handle of a temporary file safely |
6 | |
e77f578c |
7 | =begin __INTERNALS |
8 | |
9 | =head1 PORTABILITY |
10 | |
05fb677a |
11 | This section is at the top in order to provide easier access to |
12 | porters. It is not expected to be rendered by a standard pod |
13 | formatting tool. Please skip straight to the SYNOPSIS section if you |
14 | are not trying to port this module to a new platform. |
15 | |
16 | This module is designed to be portable across operating systems and it |
17 | currently supports Unix, VMS, DOS, OS/2, Windows and Mac OS |
18 | (Classic). When porting to a new OS there are generally three main |
19 | issues that have to be solved: |
e77f578c |
20 | |
21 | =over 4 |
22 | |
23 | =item * |
24 | |
28d6a1e0 |
25 | Can the OS unlink an open file? If it can not then the |
e77f578c |
26 | C<_can_unlink_opened_file> method should be modified. |
27 | |
28 | =item * |
29 | |
30 | Are the return values from C<stat> reliable? By default all the |
31 | return values from C<stat> are compared when unlinking a temporary |
32 | file using the filename and the handle. Operating systems other than |
33 | unix do not always have valid entries in all fields. If C<unlink0> fails |
34 | then the C<stat> comparison should be modified accordingly. |
35 | |
36 | =item * |
37 | |
38 | Security. Systems that can not support a test for the sticky bit |
39 | on a directory can not use the MEDIUM and HIGH security tests. |
40 | The C<_can_do_level> method should be modified accordingly. |
41 | |
42 | =back |
43 | |
44 | =end __INTERNALS |
45 | |
262eb13a |
46 | =head1 SYNOPSIS |
47 | |
be708cc0 |
48 | use File::Temp qw/ tempfile tempdir /; |
262eb13a |
49 | |
05fb677a |
50 | $fh = tempfile(); |
51 | ($fh, $filename) = tempfile(); |
262eb13a |
52 | |
53 | ($fh, $filename) = tempfile( $template, DIR => $dir); |
54 | ($fh, $filename) = tempfile( $template, SUFFIX => '.dat'); |
55 | |
05fb677a |
56 | |
57 | $dir = tempdir( CLEANUP => 1 ); |
58 | ($fh, $filename) = tempfile( DIR => $dir ); |
262eb13a |
59 | |
4a094b80 |
60 | Object interface: |
61 | |
62 | require File::Temp; |
63 | use File::Temp (); |
5d0b10e0 |
64 | use File::Temp qw/ :seekable /; |
4a094b80 |
65 | |
5d0b10e0 |
66 | $fh = new File::Temp(); |
67 | $fname = $fh->filename; |
68 | |
69 | $fh = new File::Temp(TEMPLATE => $template); |
4a094b80 |
70 | $fname = $fh->filename; |
71 | |
72 | $tmp = new File::Temp( UNLINK => 0, SUFFIX => '.dat' ); |
73 | print $tmp "Some data\n"; |
74 | print "Filename is $tmp\n"; |
5d0b10e0 |
75 | $tmp->seek( 0, SEEK_END ); |
4a094b80 |
76 | |
05fb677a |
77 | The following interfaces are provided for compatibility with |
78 | existing APIs. They should not be used in new code. |
4a094b80 |
79 | |
262eb13a |
80 | MkTemp family: |
81 | |
82 | use File::Temp qw/ :mktemp /; |
83 | |
84 | ($fh, $file) = mkstemp( "tmpfileXXXXX" ); |
85 | ($fh, $file) = mkstemps( "tmpfileXXXXXX", $suffix); |
86 | |
87 | $tmpdir = mkdtemp( $template ); |
88 | |
89 | $unopened_file = mktemp( $template ); |
90 | |
91 | POSIX functions: |
92 | |
93 | use File::Temp qw/ :POSIX /; |
94 | |
95 | $file = tmpnam(); |
96 | $fh = tmpfile(); |
97 | |
98 | ($fh, $file) = tmpnam(); |
262eb13a |
99 | |
100 | Compatibility functions: |
101 | |
102 | $unopened_file = File::Temp::tempnam( $dir, $pfx ); |
103 | |
262eb13a |
104 | =head1 DESCRIPTION |
105 | |
4a094b80 |
106 | C<File::Temp> can be used to create and open temporary files in a safe |
107 | way. There is both a function interface and an object-oriented |
108 | interface. The File::Temp constructor or the tempfile() function can |
109 | be used to return the name and the open filehandle of a temporary |
110 | file. The tempdir() function can be used to create a temporary |
111 | directory. |
262eb13a |
112 | |
113 | The security aspect of temporary file creation is emphasized such that |
781948c1 |
114 | a filehandle and filename are returned together. This helps guarantee |
115 | that a race condition can not occur where the temporary file is |
116 | created by another process between checking for the existence of the |
117 | file and its opening. Additional security levels are provided to |
118 | check, for example, that the sticky bit is set on world writable |
119 | directories. See L<"safe_level"> for more information. |
262eb13a |
120 | |
121 | For compatibility with popular C library functions, Perl implementations of |
122 | the mkstemp() family of functions are provided. These are, mkstemp(), |
123 | mkstemps(), mkdtemp() and mktemp(). |
124 | |
125 | Additionally, implementations of the standard L<POSIX|POSIX> |
126 | tmpnam() and tmpfile() functions are provided if required. |
127 | |
128 | Implementations of mktemp(), tmpnam(), and tempnam() are provided, |
129 | but should be used with caution since they return only a filename |
130 | that was valid when function was called, so cannot guarantee |
131 | that the file will not exist by the time the caller opens the filename. |
132 | |
133 | =cut |
134 | |
135 | # 5.6.0 gives us S_IWOTH, S_IWGRP, our and auto-vivifying filehandls |
5d0b10e0 |
136 | # People would like a version on 5.004 so give them what they want :-) |
137 | use 5.004; |
262eb13a |
138 | use strict; |
139 | use Carp; |
140 | use File::Spec 0.8; |
141 | use File::Path qw/ rmtree /; |
142 | use Fcntl 1.03; |
11d7f64f |
143 | use Errno; |
51fc852f |
144 | require VMS::Stdio if $^O eq 'VMS'; |
262eb13a |
145 | |
5d0b10e0 |
146 | # pre-emptively load Carp::Heavy. If we don't when we run out of file |
147 | # handles and attempt to call croak() we get an error message telling |
148 | # us that Carp::Heavy won't load rather than an error telling us we |
149 | # have run out of file handles. We either preload croak() or we |
150 | # switch the calls to croak from _gettemp() to use die. |
151 | require Carp::Heavy; |
152 | |
51fc852f |
153 | # Need the Symbol package if we are running older perl |
1c19c868 |
154 | require Symbol if $] < 5.006; |
155 | |
4a094b80 |
156 | ### For the OO interface |
5d0b10e0 |
157 | use base qw/ IO::Handle IO::Seekable /; |
4a094b80 |
158 | use overload '""' => "STRINGIFY"; |
159 | |
1c19c868 |
160 | |
262eb13a |
161 | # use 'our' on v5.6.0 |
05fb677a |
162 | use vars qw($VERSION @EXPORT_OK %EXPORT_TAGS $DEBUG $KEEP_ALL); |
262eb13a |
163 | |
164 | $DEBUG = 0; |
05fb677a |
165 | $KEEP_ALL = 0; |
262eb13a |
166 | |
167 | # We are exporting functions |
168 | |
262eb13a |
169 | use base qw/Exporter/; |
170 | |
171 | # Export list - to allow fine tuning of export table |
172 | |
173 | @EXPORT_OK = qw{ |
174 | tempfile |
175 | tempdir |
176 | tmpnam |
177 | tmpfile |
178 | mktemp |
669b450a |
179 | mkstemp |
262eb13a |
180 | mkstemps |
181 | mkdtemp |
182 | unlink0 |
05fb677a |
183 | cleanup |
5d0b10e0 |
184 | SEEK_SET |
185 | SEEK_CUR |
186 | SEEK_END |
262eb13a |
187 | }; |
188 | |
189 | # Groups of functions for export |
190 | |
191 | %EXPORT_TAGS = ( |
192 | 'POSIX' => [qw/ tmpnam tmpfile /], |
193 | 'mktemp' => [qw/ mktemp mkstemp mkstemps mkdtemp/], |
5d0b10e0 |
194 | 'seekable' => [qw/ SEEK_SET SEEK_CUR SEEK_END /], |
262eb13a |
195 | ); |
196 | |
197 | # add contents of these tags to @EXPORT |
5d0b10e0 |
198 | Exporter::export_tags('POSIX','mktemp','seekable'); |
262eb13a |
199 | |
be708cc0 |
200 | # Version number |
262eb13a |
201 | |
5d0b10e0 |
202 | $VERSION = '0.17'; |
262eb13a |
203 | |
204 | # This is a list of characters that can be used in random filenames |
205 | |
206 | my @CHARS = (qw/ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z |
207 | a b c d e f g h i j k l m n o p q r s t u v w x y z |
669b450a |
208 | 0 1 2 3 4 5 6 7 8 9 _ |
262eb13a |
209 | /); |
210 | |
211 | # Maximum number of tries to make a temp file before failing |
212 | |
05fb677a |
213 | use constant MAX_TRIES => 1000; |
262eb13a |
214 | |
215 | # Minimum number of X characters that should be in a template |
216 | use constant MINX => 4; |
217 | |
218 | # Default template when no template supplied |
219 | |
220 | use constant TEMPXXX => 'X' x 10; |
221 | |
222 | # Constants for the security level |
223 | |
224 | use constant STANDARD => 0; |
225 | use constant MEDIUM => 1; |
226 | use constant HIGH => 2; |
227 | |
1c19c868 |
228 | # OPENFLAGS. If we defined the flag to use with Sysopen here this gives |
229 | # us an optimisation when many temporary files are requested |
230 | |
231 | my $OPENFLAGS = O_CREAT | O_EXCL | O_RDWR; |
232 | |
be708cc0 |
233 | unless ($^O eq 'MacOS') { |
05fb677a |
234 | for my $oflag (qw/ NOFOLLOW BINARY LARGEFILE EXLOCK NOINHERIT /) { |
be708cc0 |
235 | my ($bit, $func) = (0, "Fcntl::O_" . $oflag); |
236 | no strict 'refs'; |
237 | $OPENFLAGS |= $bit if eval { |
238 | # Make sure that redefined die handlers do not cause problems |
5d0b10e0 |
239 | # e.g. CGI::Carp |
be708cc0 |
240 | local $SIG{__DIE__} = sub {}; |
241 | local $SIG{__WARN__} = sub {}; |
242 | $bit = &$func(); |
243 | 1; |
244 | }; |
245 | } |
1c19c868 |
246 | } |
247 | |
51fc852f |
248 | # On some systems the O_TEMPORARY flag can be used to tell the OS |
249 | # to automatically remove the file when it is closed. This is fine |
250 | # in most cases but not if tempfile is called with UNLINK=>0 and |
251 | # the filename is requested -- in the case where the filename is to |
252 | # be passed to another routine. This happens on windows. We overcome |
253 | # this by using a second open flags variable |
254 | |
255 | my $OPENTEMPFLAGS = $OPENFLAGS; |
be708cc0 |
256 | unless ($^O eq 'MacOS') { |
257 | for my $oflag (qw/ TEMPORARY /) { |
258 | my ($bit, $func) = (0, "Fcntl::O_" . $oflag); |
259 | no strict 'refs'; |
260 | $OPENTEMPFLAGS |= $bit if eval { |
261 | # Make sure that redefined die handlers do not cause problems |
5d0b10e0 |
262 | # e.g. CGI::Carp |
be708cc0 |
263 | local $SIG{__DIE__} = sub {}; |
264 | local $SIG{__WARN__} = sub {}; |
265 | $bit = &$func(); |
266 | 1; |
267 | }; |
268 | } |
51fc852f |
269 | } |
1c19c868 |
270 | |
262eb13a |
271 | # INTERNAL ROUTINES - not to be used outside of package |
272 | |
273 | # Generic routine for getting a temporary filename |
274 | # modelled on OpenBSD _gettemp() in mktemp.c |
275 | |
669b450a |
276 | # The template must contain X's that are to be replaced |
262eb13a |
277 | # with the random values |
278 | |
279 | # Arguments: |
280 | |
281 | # TEMPLATE - string containing the XXXXX's that is converted |
282 | # to a random filename and opened if required |
283 | |
284 | # Optionally, a hash can also be supplied containing specific options |
285 | # "open" => if true open the temp file, else just return the name |
286 | # default is 0 |
287 | # "mkdir"=> if true, we are creating a temp directory rather than tempfile |
288 | # default is 0 |
289 | # "suffixlen" => number of characters at end of PATH to be ignored. |
290 | # default is 0. |
51fc852f |
291 | # "unlink_on_close" => indicates that, if possible, the OS should remove |
292 | # the file as soon as it is closed. Usually indicates |
be708cc0 |
293 | # use of the O_TEMPORARY flag to sysopen. |
51fc852f |
294 | # Usually irrelevant on unix |
295 | |
28d6a1e0 |
296 | # Optionally a reference to a scalar can be passed into the function |
297 | # On error this will be used to store the reason for the error |
298 | # "ErrStr" => \$errstr |
0e939f40 |
299 | |
262eb13a |
300 | # "open" and "mkdir" can not both be true |
51fc852f |
301 | # "unlink_on_close" is not used when "mkdir" is true. |
262eb13a |
302 | |
303 | # The default options are equivalent to mktemp(). |
304 | |
305 | # Returns: |
306 | # filehandle - open file handle (if called with doopen=1, else undef) |
307 | # temp name - name of the temp file or directory |
308 | |
309 | # For example: |
310 | # ($fh, $name) = _gettemp($template, "open" => 1); |
311 | |
312 | # for the current version, failures are associated with |
28d6a1e0 |
313 | # stored in an error string and returned to give the reason whilst debugging |
314 | # This routine is not called by any external function |
262eb13a |
315 | sub _gettemp { |
316 | |
317 | croak 'Usage: ($fh, $name) = _gettemp($template, OPTIONS);' |
318 | unless scalar(@_) >= 1; |
319 | |
28d6a1e0 |
320 | # the internal error string - expect it to be overridden |
321 | # Need this in case the caller decides not to supply us a value |
322 | # need an anonymous scalar |
323 | my $tempErrStr; |
0e939f40 |
324 | |
262eb13a |
325 | # Default options |
326 | my %options = ( |
327 | "open" => 0, |
328 | "mkdir" => 0, |
329 | "suffixlen" => 0, |
51fc852f |
330 | "unlink_on_close" => 0, |
28d6a1e0 |
331 | "ErrStr" => \$tempErrStr, |
262eb13a |
332 | ); |
333 | |
334 | # Read the template |
335 | my $template = shift; |
336 | if (ref($template)) { |
28d6a1e0 |
337 | # Use a warning here since we have not yet merged ErrStr |
262eb13a |
338 | carp "File::Temp::_gettemp: template must not be a reference"; |
339 | return (); |
340 | } |
341 | |
342 | # Check that the number of entries on stack are even |
343 | if (scalar(@_) % 2 != 0) { |
28d6a1e0 |
344 | # Use a warning here since we have not yet merged ErrStr |
262eb13a |
345 | carp "File::Temp::_gettemp: Must have even number of options"; |
346 | return (); |
347 | } |
348 | |
349 | # Read the options and merge with defaults |
350 | %options = (%options, @_) if @_; |
669b450a |
351 | |
28d6a1e0 |
352 | # Make sure the error string is set to undef |
353 | ${$options{ErrStr}} = undef; |
0e939f40 |
354 | |
262eb13a |
355 | # Can not open the file and make a directory in a single call |
356 | if ($options{"open"} && $options{"mkdir"}) { |
28d6a1e0 |
357 | ${$options{ErrStr}} = "doopen and domkdir can not both be true\n"; |
262eb13a |
358 | return (); |
359 | } |
360 | |
361 | # Find the start of the end of the Xs (position of last X) |
362 | # Substr starts from 0 |
363 | my $start = length($template) - 1 - $options{"suffixlen"}; |
364 | |
5d0b10e0 |
365 | # Check that we have at least MINX x X (e.g. 'XXXX") at the end of the string |
262eb13a |
366 | # (taking suffixlen into account). Any fewer is insecure. |
367 | |
368 | # Do it using substr - no reason to use a pattern match since |
369 | # we know where we are looking and what we are looking for |
370 | |
371 | if (substr($template, $start - MINX + 1, MINX) ne 'X' x MINX) { |
05fb677a |
372 | ${$options{ErrStr}} = "The template must end with at least ". |
28d6a1e0 |
373 | MINX . " 'X' characters\n"; |
262eb13a |
374 | return (); |
375 | } |
376 | |
377 | # Replace all the X at the end of the substring with a |
378 | # random character or just all the XX at the end of a full string. |
379 | # Do it as an if, since the suffix adjusts which section to replace |
380 | # and suffixlen=0 returns nothing if used in the substr directly |
381 | # and generate a full path from the template |
382 | |
383 | my $path = _replace_XX($template, $options{"suffixlen"}); |
384 | |
385 | |
386 | # Split the path into constituent parts - eventually we need to check |
387 | # whether the directory exists |
388 | # We need to know whether we are making a temp directory |
389 | # or a tempfile |
390 | |
391 | my ($volume, $directories, $file); |
392 | my $parent; # parent directory |
393 | if ($options{"mkdir"}) { |
394 | # There is no filename at the end |
395 | ($volume, $directories, $file) = File::Spec->splitpath( $path, 1); |
396 | |
397 | # The parent is then $directories without the last directory |
398 | # Split the directory and put it back together again |
399 | my @dirs = File::Spec->splitdir($directories); |
400 | |
be708cc0 |
401 | # If @dirs only has one entry (i.e. the directory template) that means |
402 | # we are in the current directory |
262eb13a |
403 | if ($#dirs == 0) { |
404 | $parent = File::Spec->curdir; |
405 | } else { |
406 | |
669b450a |
407 | if ($^O eq 'VMS') { # need volume to avoid relative dir spec |
408 | $parent = File::Spec->catdir($volume, @dirs[0..$#dirs-1]); |
e4dfc136 |
409 | $parent = 'sys$disk:[]' if $parent eq ''; |
669b450a |
410 | } else { |
411 | |
412 | # Put it back together without the last one |
413 | $parent = File::Spec->catdir(@dirs[0..$#dirs-1]); |
262eb13a |
414 | |
669b450a |
415 | # ...and attach the volume (no filename) |
416 | $parent = File::Spec->catpath($volume, $parent, ''); |
417 | } |
262eb13a |
418 | |
419 | } |
420 | |
421 | } else { |
422 | |
423 | # Get rid of the last filename (use File::Basename for this?) |
424 | ($volume, $directories, $file) = File::Spec->splitpath( $path ); |
425 | |
426 | # Join up without the file part |
427 | $parent = File::Spec->catpath($volume,$directories,''); |
428 | |
429 | # If $parent is empty replace with curdir |
430 | $parent = File::Spec->curdir |
431 | unless $directories ne ''; |
432 | |
433 | } |
434 | |
be708cc0 |
435 | # Check that the parent directories exist |
262eb13a |
436 | # Do this even for the case where we are simply returning a name |
437 | # not a file -- no point returning a name that includes a directory |
438 | # that does not exist or is not writable |
439 | |
28d6a1e0 |
440 | unless (-d $parent) { |
441 | ${$options{ErrStr}} = "Parent directory ($parent) is not a directory"; |
442 | return (); |
443 | } |
05fb677a |
444 | unless (-w $parent) { |
28d6a1e0 |
445 | ${$options{ErrStr}} = "Parent directory ($parent) is not writable\n"; |
262eb13a |
446 | return (); |
447 | } |
448 | |
0e939f40 |
449 | |
262eb13a |
450 | # Check the stickiness of the directory and chown giveaway if required |
451 | # If the directory is world writable the sticky bit |
452 | # must be set |
453 | |
454 | if (File::Temp->safe_level == MEDIUM) { |
28d6a1e0 |
455 | my $safeerr; |
456 | unless (_is_safe($parent,\$safeerr)) { |
457 | ${$options{ErrStr}} = "Parent directory ($parent) is not safe ($safeerr)"; |
262eb13a |
458 | return (); |
459 | } |
460 | } elsif (File::Temp->safe_level == HIGH) { |
28d6a1e0 |
461 | my $safeerr; |
462 | unless (_is_verysafe($parent, \$safeerr)) { |
463 | ${$options{ErrStr}} = "Parent directory ($parent) is not safe ($safeerr)"; |
262eb13a |
464 | return (); |
465 | } |
466 | } |
467 | |
468 | |
262eb13a |
469 | # Now try MAX_TRIES time to open the file |
470 | for (my $i = 0; $i < MAX_TRIES; $i++) { |
471 | |
472 | # Try to open the file if requested |
473 | if ($options{"open"}) { |
474 | my $fh; |
475 | |
476 | # If we are running before perl5.6.0 we can not auto-vivify |
477 | if ($] < 5.006) { |
262eb13a |
478 | $fh = &Symbol::gensym; |
479 | } |
480 | |
481 | # Try to make sure this will be marked close-on-exec |
482 | # XXX: Win32 doesn't respect this, nor the proper fcntl, |
483 | # but may have O_NOINHERIT. This may or may not be in Fcntl. |
28d6a1e0 |
484 | local $^F = 2; |
262eb13a |
485 | |
486 | # Store callers umask |
97c10e77 |
487 | my $umask = umask(); |
262eb13a |
488 | |
489 | # Set a known umask |
97c10e77 |
490 | umask(066); |
262eb13a |
491 | |
492 | # Attempt to open the file |
51fc852f |
493 | my $open_success = undef; |
05fb677a |
494 | if ( $^O eq 'VMS' and $options{"unlink_on_close"} && !$KEEP_ALL) { |
f826e675 |
495 | # make it auto delete on close by setting FAB$V_DLT bit |
51fc852f |
496 | $fh = VMS::Stdio::vmssysopen($path, $OPENFLAGS, 0600, 'fop=dlt'); |
497 | $open_success = $fh; |
498 | } else { |
05fb677a |
499 | my $flags = ( ($options{"unlink_on_close"} && !$KEEP_ALL) ? |
51fc852f |
500 | $OPENTEMPFLAGS : |
501 | $OPENFLAGS ); |
502 | $open_success = sysopen($fh, $path, $flags, 0600); |
503 | } |
504 | if ( $open_success ) { |
262eb13a |
505 | |
506 | # Reset umask |
d5201bd2 |
507 | umask($umask) if defined $umask; |
be708cc0 |
508 | |
262eb13a |
509 | # Opened successfully - return file handle and name |
510 | return ($fh, $path); |
511 | |
512 | } else { |
513 | # Reset umask |
d5201bd2 |
514 | umask($umask) if defined $umask; |
262eb13a |
515 | |
516 | # Error opening file - abort with error |
517 | # if the reason was anything but EEXIST |
11d7f64f |
518 | unless ($!{EEXIST}) { |
28d6a1e0 |
519 | ${$options{ErrStr}} = "Could not create temp file $path: $!"; |
262eb13a |
520 | return (); |
521 | } |
522 | |
523 | # Loop round for another try |
be708cc0 |
524 | |
262eb13a |
525 | } |
526 | } elsif ($options{"mkdir"}) { |
527 | |
528 | # Store callers umask |
97c10e77 |
529 | my $umask = umask(); |
262eb13a |
530 | |
531 | # Set a known umask |
97c10e77 |
532 | umask(066); |
262eb13a |
533 | |
534 | # Open the temp directory |
535 | if (mkdir( $path, 0700)) { |
536 | # created okay |
537 | # Reset umask |
d5201bd2 |
538 | umask($umask) if defined $umask; |
262eb13a |
539 | |
540 | return undef, $path; |
541 | } else { |
542 | |
543 | # Reset umask |
d5201bd2 |
544 | umask($umask) if defined $umask; |
262eb13a |
545 | |
546 | # Abort with error if the reason for failure was anything |
547 | # except EEXIST |
11d7f64f |
548 | unless ($!{EEXIST}) { |
28d6a1e0 |
549 | ${$options{ErrStr}} = "Could not create directory $path: $!"; |
262eb13a |
550 | return (); |
551 | } |
552 | |
553 | # Loop round for another try |
554 | |
555 | } |
556 | |
557 | } else { |
558 | |
559 | # Return true if the file can not be found |
560 | # Directory has been checked previously |
561 | |
562 | return (undef, $path) unless -e $path; |
563 | |
669b450a |
564 | # Try again until MAX_TRIES |
262eb13a |
565 | |
566 | } |
669b450a |
567 | |
262eb13a |
568 | # Did not successfully open the tempfile/dir |
569 | # so try again with a different set of random letters |
570 | # No point in trying to increment unless we have only |
571 | # 1 X say and the randomness could come up with the same |
572 | # file MAX_TRIES in a row. |
573 | |
574 | # Store current attempt - in principal this implies that the |
575 | # 3rd time around the open attempt that the first temp file |
576 | # name could be generated again. Probably should store each |
577 | # attempt and make sure that none are repeated |
578 | |
579 | my $original = $path; |
580 | my $counter = 0; # Stop infinite loop |
581 | my $MAX_GUESS = 50; |
582 | |
583 | do { |
584 | |
585 | # Generate new name from original template |
586 | $path = _replace_XX($template, $options{"suffixlen"}); |
587 | |
588 | $counter++; |
589 | |
590 | } until ($path ne $original || $counter > $MAX_GUESS); |
591 | |
592 | # Check for out of control looping |
593 | if ($counter > $MAX_GUESS) { |
28d6a1e0 |
594 | ${$options{ErrStr}} = "Tried to get a new temp name different to the previous value $MAX_GUESS times.\nSomething wrong with template?? ($template)"; |
262eb13a |
595 | return (); |
596 | } |
597 | |
598 | } |
599 | |
600 | # If we get here, we have run out of tries |
28d6a1e0 |
601 | ${ $options{ErrStr} } = "Have exceeded the maximum number of attempts (" |
602 | . MAX_TRIES . ") to open temp file/dir"; |
262eb13a |
603 | |
604 | return (); |
605 | |
606 | } |
607 | |
608 | # Internal routine to return a random character from the |
609 | # character list. Does not do an srand() since rand() |
610 | # will do one automatically |
611 | |
612 | # No arguments. Return value is the random character |
613 | |
1c19c868 |
614 | # No longer called since _replace_XX runs a few percent faster if |
615 | # I inline the code. This is important if we are creating thousands of |
616 | # temporary files. |
617 | |
262eb13a |
618 | sub _randchar { |
619 | |
620 | $CHARS[ int( rand( $#CHARS ) ) ]; |
621 | |
622 | } |
623 | |
624 | # Internal routine to replace the XXXX... with random characters |
be708cc0 |
625 | # This has to be done by _gettemp() every time it fails to |
262eb13a |
626 | # open a temp file/dir |
627 | |
be708cc0 |
628 | # Arguments: $template (the template with XXX), |
262eb13a |
629 | # $ignore (number of characters at end to ignore) |
630 | |
631 | # Returns: modified template |
632 | |
633 | sub _replace_XX { |
634 | |
635 | croak 'Usage: _replace_XX($template, $ignore)' |
636 | unless scalar(@_) == 2; |
637 | |
638 | my ($path, $ignore) = @_; |
639 | |
640 | # Do it as an if, since the suffix adjusts which section to replace |
641 | # and suffixlen=0 returns nothing if used in the substr directly |
642 | # Alternatively, could simply set $ignore to length($path)-1 |
643 | # Don't want to always use substr when not required though. |
644 | |
645 | if ($ignore) { |
1c19c868 |
646 | substr($path, 0, - $ignore) =~ s/X(?=X*\z)/$CHARS[ int( rand( $#CHARS ) ) ]/ge; |
262eb13a |
647 | } else { |
1c19c868 |
648 | $path =~ s/X(?=X*\z)/$CHARS[ int( rand( $#CHARS ) ) ]/ge; |
262eb13a |
649 | } |
262eb13a |
650 | return $path; |
651 | } |
652 | |
05fb677a |
653 | # Internal routine to force a temp file to be writable after |
654 | # it is created so that we can unlink it. Windows seems to occassionally |
655 | # force a file to be readonly when written to certain temp locations |
656 | sub _force_writable { |
657 | my $file = shift; |
658 | my $umask = umask(); |
659 | umask(066); |
660 | chmod 0600, $file; |
661 | umask($umask) if defined $umask; |
662 | } |
663 | |
664 | |
262eb13a |
665 | # internal routine to check to see if the directory is safe |
669b450a |
666 | # First checks to see if the directory is not owned by the |
262eb13a |
667 | # current user or root. Then checks to see if anyone else |
669b450a |
668 | # can write to the directory and if so, checks to see if |
262eb13a |
669 | # it has the sticky bit set |
670 | |
671 | # Will not work on systems that do not support sticky bit |
672 | |
673 | #Args: directory path to check |
28d6a1e0 |
674 | # Optionally: reference to scalar to contain error message |
262eb13a |
675 | # Returns true if the path is safe and false otherwise. |
676 | # Returns undef if can not even run stat() on the path |
677 | |
678 | # This routine based on version written by Tom Christiansen |
679 | |
680 | # Presumably, by the time we actually attempt to create the |
681 | # file or directory in this directory, it may not be safe |
682 | # anymore... Have to run _is_safe directly after the open. |
683 | |
684 | sub _is_safe { |
685 | |
686 | my $path = shift; |
28d6a1e0 |
687 | my $err_ref = shift; |
262eb13a |
688 | |
689 | # Stat path |
690 | my @info = stat($path); |
28d6a1e0 |
691 | unless (scalar(@info)) { |
692 | $$err_ref = "stat(path) returned no values"; |
693 | return 0; |
694 | }; |
669b450a |
695 | return 1 if $^O eq 'VMS'; # owner delete control at file level |
262eb13a |
696 | |
697 | # Check to see whether owner is neither superuser (or a system uid) nor me |
5d0b10e0 |
698 | # Use the effective uid from the $> variable |
262eb13a |
699 | # UID is in [4] |
5d0b10e0 |
700 | if ($info[4] > File::Temp->top_system_uid() && $info[4] != $>) { |
73f754d1 |
701 | |
5d0b10e0 |
702 | Carp::cluck(sprintf "uid=$info[4] topuid=%s euid=$< path='$path'", |
73f754d1 |
703 | File::Temp->top_system_uid()); |
704 | |
28d6a1e0 |
705 | $$err_ref = "Directory owned neither by root nor the current user" |
706 | if ref($err_ref); |
262eb13a |
707 | return 0; |
708 | } |
709 | |
710 | # check whether group or other can write file |
711 | # use 066 to detect either reading or writing |
712 | # use 022 to check writability |
713 | # Do it with S_IWOTH and S_IWGRP for portability (maybe) |
714 | # mode is in info[2] |
715 | if (($info[2] & &Fcntl::S_IWGRP) || # Is group writable? |
716 | ($info[2] & &Fcntl::S_IWOTH) ) { # Is world writable? |
28d6a1e0 |
717 | # Must be a directory |
05fb677a |
718 | unless (-d $path) { |
28d6a1e0 |
719 | $$err_ref = "Path ($path) is not a directory" |
720 | if ref($err_ref); |
721 | return 0; |
722 | } |
723 | # Must have sticky bit set |
05fb677a |
724 | unless (-k $path) { |
28d6a1e0 |
725 | $$err_ref = "Sticky bit not set on $path when dir is group|world writable" |
726 | if ref($err_ref); |
727 | return 0; |
728 | } |
262eb13a |
729 | } |
730 | |
731 | return 1; |
732 | } |
733 | |
734 | # Internal routine to check whether a directory is safe |
be708cc0 |
735 | # for temp files. Safer than _is_safe since it checks for |
262eb13a |
736 | # the possibility of chown giveaway and if that is a possibility |
737 | # checks each directory in the path to see if it is safe (with _is_safe) |
738 | |
739 | # If _PC_CHOWN_RESTRICTED is not set, does the full test of each |
740 | # directory anyway. |
741 | |
28d6a1e0 |
742 | # Takes optional second arg as scalar ref to error reason |
0e939f40 |
743 | |
262eb13a |
744 | sub _is_verysafe { |
745 | |
746 | # Need POSIX - but only want to bother if really necessary due to overhead |
747 | require POSIX; |
748 | |
749 | my $path = shift; |
28d6a1e0 |
750 | print "_is_verysafe testing $path\n" if $DEBUG; |
669b450a |
751 | return 1 if $^O eq 'VMS'; # owner delete control at file level |
262eb13a |
752 | |
28d6a1e0 |
753 | my $err_ref = shift; |
0e939f40 |
754 | |
262eb13a |
755 | # Should Get the value of _PC_CHOWN_RESTRICTED if it is defined |
756 | # and If it is not there do the extensive test |
757 | my $chown_restricted; |
758 | $chown_restricted = &POSIX::_PC_CHOWN_RESTRICTED() |
759 | if eval { &POSIX::_PC_CHOWN_RESTRICTED(); 1}; |
760 | |
761 | # If chown_resticted is set to some value we should test it |
762 | if (defined $chown_restricted) { |
763 | |
764 | # Return if the current directory is safe |
28d6a1e0 |
765 | return _is_safe($path,$err_ref) if POSIX::sysconf( $chown_restricted ); |
262eb13a |
766 | |
767 | } |
768 | |
769 | # To reach this point either, the _PC_CHOWN_RESTRICTED symbol |
770 | # was not avialable or the symbol was there but chown giveaway |
771 | # is allowed. Either way, we now have to test the entire tree for |
772 | # safety. |
773 | |
774 | # Convert path to an absolute directory if required |
775 | unless (File::Spec->file_name_is_absolute($path)) { |
776 | $path = File::Spec->rel2abs($path); |
777 | } |
778 | |
779 | # Split directory into components - assume no file |
780 | my ($volume, $directories, undef) = File::Spec->splitpath( $path, 1); |
781 | |
d1be9408 |
782 | # Slightly less efficient than having a function in File::Spec |
262eb13a |
783 | # to chop off the end of a directory or even a function that |
784 | # can handle ../ in a directory tree |
785 | # Sometimes splitdir() returns a blank at the end |
786 | # so we will probably check the bottom directory twice in some cases |
787 | my @dirs = File::Spec->splitdir($directories); |
788 | |
789 | # Concatenate one less directory each time around |
790 | foreach my $pos (0.. $#dirs) { |
791 | # Get a directory name |
792 | my $dir = File::Spec->catpath($volume, |
793 | File::Spec->catdir(@dirs[0.. $#dirs - $pos]), |
794 | '' |
795 | ); |
796 | |
797 | print "TESTING DIR $dir\n" if $DEBUG; |
798 | |
799 | # Check the directory |
28d6a1e0 |
800 | return 0 unless _is_safe($dir,$err_ref); |
262eb13a |
801 | |
802 | } |
803 | |
804 | return 1; |
805 | } |
806 | |
807 | |
808 | |
809 | # internal routine to determine whether unlink works on this |
810 | # platform for files that are currently open. |
811 | # Returns true if we can, false otherwise. |
812 | |
669b450a |
813 | # Currently WinNT, OS/2 and VMS can not unlink an opened file |
814 | # On VMS this is because the O_EXCL flag is used to open the |
815 | # temporary file. Currently I do not know enough about the issues |
816 | # on VMS to decide whether O_EXCL is a requirement. |
262eb13a |
817 | |
818 | sub _can_unlink_opened_file { |
819 | |
be708cc0 |
820 | if ($^O eq 'MSWin32' || $^O eq 'os2' || $^O eq 'VMS' || $^O eq 'dos' || $^O eq 'MacOS') { |
1c19c868 |
821 | return 0; |
822 | } else { |
823 | return 1; |
824 | } |
262eb13a |
825 | |
826 | } |
827 | |
1c19c868 |
828 | # internal routine to decide which security levels are allowed |
829 | # see safe_level() for more information on this |
830 | |
831 | # Controls whether the supplied security level is allowed |
832 | |
833 | # $cando = _can_do_level( $level ) |
834 | |
835 | sub _can_do_level { |
836 | |
837 | # Get security level |
838 | my $level = shift; |
839 | |
840 | # Always have to be able to do STANDARD |
841 | return 1 if $level == STANDARD; |
842 | |
843 | # Currently, the systems that can do HIGH or MEDIUM are identical |
4a094b80 |
844 | if ( $^O eq 'MSWin32' || $^O eq 'os2' || $^O eq 'cygwin' || $^O eq 'dos' || $^O eq 'MacOS' || $^O eq 'mpeix') { |
1c19c868 |
845 | return 0; |
846 | } else { |
847 | return 1; |
848 | } |
849 | |
850 | } |
262eb13a |
851 | |
852 | # This routine sets up a deferred unlinking of a specified |
853 | # filename and filehandle. It is used in the following cases: |
669b450a |
854 | # - Called by unlink0 if an opened file can not be unlinked |
262eb13a |
855 | # - Called by tempfile() if files are to be removed on shutdown |
856 | # - Called by tempdir() if directories are to be removed on shutdown |
857 | |
858 | # Arguments: |
859 | # _deferred_unlink( $fh, $fname, $isdir ); |
860 | # |
861 | # - filehandle (so that it can be expclicitly closed if open |
862 | # - filename (the thing we want to remove) |
863 | # - isdir (flag to indicate that we are being given a directory) |
864 | # [and hence no filehandle] |
865 | |
51fc852f |
866 | # Status is not referred to since all the magic is done with an END block |
262eb13a |
867 | |
1c19c868 |
868 | { |
869 | # Will set up two lexical variables to contain all the files to be |
05fb677a |
870 | # removed. One array for files, another for directories They will |
871 | # only exist in this block. |
872 | |
873 | # This means we only have to set up a single END block to remove |
874 | # all files. |
875 | |
876 | # in order to prevent child processes inadvertently deleting the parent |
877 | # temp files we use a hash to store the temp files and directories |
878 | # created by a particular process id. |
879 | |
880 | # %files_to_unlink contains values that are references to an array of |
881 | # array references containing the filehandle and filename associated with |
882 | # the temp file. |
883 | my (%files_to_unlink, %dirs_to_unlink); |
1c19c868 |
884 | |
885 | # Set up an end block to use these arrays |
886 | END { |
05fb677a |
887 | cleanup(); |
888 | } |
889 | |
890 | # Cleanup function. Always triggered on END but can be invoked |
891 | # manually. |
892 | sub cleanup { |
893 | if (!$KEEP_ALL) { |
894 | # Files |
895 | my @files = (exists $files_to_unlink{$$} ? |
896 | @{ $files_to_unlink{$$} } : () ); |
897 | foreach my $file (@files) { |
898 | # close the filehandle without checking its state |
899 | # in order to make real sure that this is closed |
900 | # if its already closed then I dont care about the answer |
901 | # probably a better way to do this |
902 | close($file->[0]); # file handle is [0] |
903 | |
904 | if (-f $file->[1]) { # file name is [1] |
905 | _force_writable( $file->[1] ); # for windows |
906 | unlink $file->[1] or warn "Error removing ".$file->[1]; |
907 | } |
1c19c868 |
908 | } |
05fb677a |
909 | # Dirs |
910 | my @dirs = (exists $dirs_to_unlink{$$} ? |
911 | @{ $dirs_to_unlink{$$} } : () ); |
912 | foreach my $dir (@dirs) { |
913 | if (-d $dir) { |
914 | rmtree($dir, $DEBUG, 0); |
915 | } |
1c19c868 |
916 | } |
262eb13a |
917 | |
05fb677a |
918 | # clear the arrays |
919 | @{ $files_to_unlink{$$} } = () |
920 | if exists $files_to_unlink{$$}; |
921 | @{ $dirs_to_unlink{$$} } = () |
922 | if exists $dirs_to_unlink{$$}; |
923 | } |
1c19c868 |
924 | } |
262eb13a |
925 | |
05fb677a |
926 | |
1c19c868 |
927 | # This is the sub called to register a file for deferred unlinking |
928 | # This could simply store the input parameters and defer everything |
929 | # until the END block. For now we do a bit of checking at this |
930 | # point in order to make sure that (1) we have a file/dir to delete |
931 | # and (2) we have been called with the correct arguments. |
932 | sub _deferred_unlink { |
933 | |
934 | croak 'Usage: _deferred_unlink($fh, $fname, $isdir)' |
935 | unless scalar(@_) == 3; |
669b450a |
936 | |
1c19c868 |
937 | my ($fh, $fname, $isdir) = @_; |
262eb13a |
938 | |
1c19c868 |
939 | warn "Setting up deferred removal of $fname\n" |
940 | if $DEBUG; |
669b450a |
941 | |
1c19c868 |
942 | # If we have a directory, check that it is a directory |
943 | if ($isdir) { |
262eb13a |
944 | |
1c19c868 |
945 | if (-d $fname) { |
262eb13a |
946 | |
1c19c868 |
947 | # Directory exists so store it |
51fc852f |
948 | # first on VMS turn []foo into [.foo] for rmtree |
949 | $fname = VMS::Filespec::vmspath($fname) if $^O eq 'VMS'; |
05fb677a |
950 | $dirs_to_unlink{$$} = [] |
951 | unless exists $dirs_to_unlink{$$}; |
952 | push (@{ $dirs_to_unlink{$$} }, $fname); |
262eb13a |
953 | |
1c19c868 |
954 | } else { |
28d6a1e0 |
955 | carp "Request to remove directory $fname could not be completed since it does not exist!\n" if $^W; |
1c19c868 |
956 | } |
957 | |
262eb13a |
958 | } else { |
262eb13a |
959 | |
1c19c868 |
960 | if (-f $fname) { |
262eb13a |
961 | |
1c19c868 |
962 | # file exists so store handle and name for later removal |
05fb677a |
963 | $files_to_unlink{$$} = [] |
964 | unless exists $files_to_unlink{$$}; |
965 | push(@{ $files_to_unlink{$$} }, [$fh, $fname]); |
262eb13a |
966 | |
1c19c868 |
967 | } else { |
28d6a1e0 |
968 | carp "Request to remove file $fname could not be completed since it is not there!\n" if $^W; |
1c19c868 |
969 | } |
262eb13a |
970 | |
262eb13a |
971 | } |
972 | |
262eb13a |
973 | } |
974 | |
262eb13a |
975 | |
1c19c868 |
976 | } |
262eb13a |
977 | |
05fb677a |
978 | =head1 OBJECT-ORIENTED INTERFACE |
4a094b80 |
979 | |
980 | This is the primary interface for interacting with |
981 | C<File::Temp>. Using the OO interface a temporary file can be created |
982 | when the object is constructed and the file can be removed when the |
983 | object is no longer required. |
984 | |
985 | Note that there is no method to obtain the filehandle from the |
986 | C<File::Temp> object. The object itself acts as a filehandle. Also, |
987 | the object is configured such that it stringifies to the name of the |
5d0b10e0 |
988 | temporary file. The object isa C<IO::Handle> and isa C<IO::Seekable> |
989 | so all those methods are available. |
4a094b80 |
990 | |
991 | =over 4 |
992 | |
993 | =item B<new> |
994 | |
995 | Create a temporary file object. |
996 | |
997 | my $tmp = new File::Temp(); |
998 | |
999 | by default the object is constructed as if C<tempfile> |
1000 | was called without options, but with the additional behaviour |
1001 | that the temporary file is removed by the object destructor |
1002 | if UNLINK is set to true (the default). |
1003 | |
1004 | Supported arguments are the same as for C<tempfile>: UNLINK |
1005 | (defaulting to true), DIR and SUFFIX. Additionally, the filename |
1006 | template is specified using the TEMPLATE option. The OPEN option |
1007 | is not supported (the file is always opened). |
1008 | |
1009 | $tmp = new File::Temp( TEMPLATE => 'tempXXXXX', |
1010 | DIR => 'mydir', |
1011 | SUFFIX => '.dat'); |
1012 | |
1013 | Arguments are case insensitive. |
1014 | |
5d0b10e0 |
1015 | Can call croak() if an error occurs. |
1016 | |
4a094b80 |
1017 | =cut |
1018 | |
1019 | sub new { |
1020 | my $proto = shift; |
1021 | my $class = ref($proto) || $proto; |
1022 | |
1023 | # read arguments and convert keys to upper case |
1024 | my %args = @_; |
1025 | %args = map { uc($_), $args{$_} } keys %args; |
1026 | |
1027 | # see if they are unlinking (defaulting to yes) |
1028 | my $unlink = (exists $args{UNLINK} ? $args{UNLINK} : 1 ); |
1029 | delete $args{UNLINK}; |
1030 | |
1031 | # template (store it in an error so that it will |
1032 | # disappear from the arg list of tempfile |
1033 | my @template = ( exists $args{TEMPLATE} ? $args{TEMPLATE} : () ); |
1034 | delete $args{TEMPLATE}; |
1035 | |
1036 | # Protect OPEN |
1037 | delete $args{OPEN}; |
1038 | |
1039 | # Open the file and retain file handle and file name |
1040 | my ($fh, $path) = tempfile( @template, %args ); |
1041 | |
1042 | print "Tmp: $fh - $path\n" if $DEBUG; |
1043 | |
1044 | # Store the filename in the scalar slot |
1045 | ${*$fh} = $path; |
1046 | |
1047 | # Store unlink information in hash slot (plus other constructor info) |
1048 | %{*$fh} = %args; |
4a094b80 |
1049 | |
05fb677a |
1050 | # create the object |
4a094b80 |
1051 | bless $fh, $class; |
1052 | |
05fb677a |
1053 | # final method-based configuration |
1054 | $fh->unlink_on_destroy( $unlink ); |
1055 | |
4a094b80 |
1056 | return $fh; |
1057 | } |
1058 | |
1059 | =item B<filename> |
1060 | |
1061 | Return the name of the temporary file associated with this object. |
1062 | |
1063 | $filename = $tmp->filename; |
1064 | |
1065 | This method is called automatically when the object is used as |
1066 | a string. |
1067 | |
1068 | =cut |
1069 | |
1070 | sub filename { |
1071 | my $self = shift; |
1072 | return ${*$self}; |
1073 | } |
1074 | |
1075 | sub STRINGIFY { |
1076 | my $self = shift; |
1077 | return $self->filename; |
1078 | } |
1079 | |
05fb677a |
1080 | =item B<unlink_on_destroy> |
1081 | |
1082 | Control whether the file is unlinked when the object goes out of scope. |
1083 | The file is removed if this value is true and $KEEP_ALL is not. |
1084 | |
1085 | $fh->unlink_on_destroy( 1 ); |
1086 | |
1087 | Default is for the file to be removed. |
1088 | |
1089 | =cut |
1090 | |
1091 | sub unlink_on_destroy { |
1092 | my $self = shift; |
1093 | if (@_) { |
1094 | ${*$self}{UNLINK} = shift; |
1095 | } |
1096 | return ${*$self}{UNLINK}; |
1097 | } |
1098 | |
4a094b80 |
1099 | =item B<DESTROY> |
1100 | |
1101 | When the object goes out of scope, the destructor is called. This |
1102 | destructor will attempt to unlink the file (using C<unlink1>) |
1103 | if the constructor was called with UNLINK set to 1 (the default state |
1104 | if UNLINK is not specified). |
1105 | |
1106 | No error is given if the unlink fails. |
1107 | |
05fb677a |
1108 | If the global variable $KEEP_ALL is true, the file will not be removed. |
1109 | |
4a094b80 |
1110 | =cut |
1111 | |
1112 | sub DESTROY { |
1113 | my $self = shift; |
05fb677a |
1114 | if (${*$self}{UNLINK} && !$KEEP_ALL) { |
4a094b80 |
1115 | print "# ---------> Unlinking $self\n" if $DEBUG; |
1116 | |
1117 | # The unlink1 may fail if the file has been closed |
1118 | # by the caller. This leaves us with the decision |
1119 | # of whether to refuse to remove the file or simply |
1120 | # do an unlink without test. Seems to be silly |
1121 | # to do this when we are trying to be careful |
1122 | # about security |
05fb677a |
1123 | _force_writable( $self->filename ); # for windows |
4a094b80 |
1124 | unlink1( $self, $self->filename ) |
1125 | or unlink($self->filename); |
1126 | } |
1127 | } |
1128 | |
1129 | =back |
1130 | |
262eb13a |
1131 | =head1 FUNCTIONS |
1132 | |
1133 | This section describes the recommended interface for generating |
1134 | temporary files and directories. |
1135 | |
1136 | =over 4 |
1137 | |
1138 | =item B<tempfile> |
1139 | |
1140 | This is the basic function to generate temporary files. |
1141 | The behaviour of the file can be changed using various options: |
1142 | |
05fb677a |
1143 | $fh = tempfile(); |
262eb13a |
1144 | ($fh, $filename) = tempfile(); |
1145 | |
1146 | Create a temporary file in the directory specified for temporary |
1147 | files, as specified by the tmpdir() function in L<File::Spec>. |
1148 | |
1149 | ($fh, $filename) = tempfile($template); |
1150 | |
1151 | Create a temporary file in the current directory using the supplied |
1152 | template. Trailing `X' characters are replaced with random letters to |
1153 | generate the filename. At least four `X' characters must be present |
4a094b80 |
1154 | at the end of the template. |
262eb13a |
1155 | |
1156 | ($fh, $filename) = tempfile($template, SUFFIX => $suffix) |
1157 | |
1158 | Same as previously, except that a suffix is added to the template |
1159 | after the `X' translation. Useful for ensuring that a temporary |
1160 | filename has a particular extension when needed by other applications. |
1161 | But see the WARNING at the end. |
1162 | |
1163 | ($fh, $filename) = tempfile($template, DIR => $dir); |
1164 | |
1165 | Translates the template as before except that a directory name |
1166 | is specified. |
1167 | |
51fc852f |
1168 | ($fh, $filename) = tempfile($template, UNLINK => 1); |
1169 | |
1170 | Return the filename and filehandle as before except that the file is |
05fb677a |
1171 | automatically removed when the program exits (dependent on |
1172 | $KEEP_ALL). Default is for the file to be removed if a file handle is |
1173 | requested and to be kept if the filename is requested. In a scalar |
1174 | context (where no filename is returned) the file is always deleted |
1175 | either (depending on the operating system) on exit or when it is |
1176 | closed (unless $KEEP_ALL is true when the temp file is created). |
1177 | |
1178 | Use the object-oriented interface if fine-grained control of when |
1179 | a file is removed is required. |
51fc852f |
1180 | |
262eb13a |
1181 | If the template is not specified, a template is always |
1182 | automatically generated. This temporary file is placed in tmpdir() |
be708cc0 |
1183 | (L<File::Spec>) unless a directory is specified explicitly with the |
262eb13a |
1184 | DIR option. |
1185 | |
1186 | $fh = tempfile( $template, DIR => $dir ); |
1187 | |
05fb677a |
1188 | If called in scalar context, only the filehandle is returned and the |
1189 | file will automatically be deleted when closed on operating systems |
1190 | that support this (see the description of tmpfile() elsewhere in this |
1191 | document). This is the preferred mode of operation, as if you only |
1192 | have a filehandle, you can never create a race condition by fumbling |
1193 | with the filename. On systems that can not unlink an open file or can |
1194 | not mark a file as temporary when it is opened (for example, Windows |
1195 | NT uses the C<O_TEMPORARY> flag) the file is marked for deletion when |
1196 | the program ends (equivalent to setting UNLINK to 1). The C<UNLINK> |
1197 | flag is ignored if present. |
09d7a2f9 |
1198 | |
262eb13a |
1199 | (undef, $filename) = tempfile($template, OPEN => 0); |
1200 | |
1201 | This will return the filename based on the template but |
1202 | will not open this file. Cannot be used in conjunction with |
be708cc0 |
1203 | UNLINK set to true. Default is to always open the file |
262eb13a |
1204 | to protect from possible race conditions. A warning is issued |
1205 | if warnings are turned on. Consider using the tmpnam() |
1206 | and mktemp() functions described elsewhere in this document |
1207 | if opening the file is not required. |
1208 | |
51fc852f |
1209 | Options can be combined as required. |
1210 | |
5d0b10e0 |
1211 | Will croak() if there is an error. |
1212 | |
262eb13a |
1213 | =cut |
1214 | |
1215 | sub tempfile { |
1216 | |
1217 | # Can not check for argument count since we can have any |
1218 | # number of args |
1219 | |
1220 | # Default options |
1221 | my %options = ( |
1222 | "DIR" => undef, # Directory prefix |
f826e675 |
1223 | "SUFFIX" => '', # Template suffix |
1224 | "UNLINK" => 0, # Do not unlink file on exit |
1225 | "OPEN" => 1, # Open file |
262eb13a |
1226 | ); |
1227 | |
1228 | # Check to see whether we have an odd or even number of arguments |
1229 | my $template = (scalar(@_) % 2 == 1 ? shift(@_) : undef); |
1230 | |
1231 | # Read the options and merge with defaults |
1232 | %options = (%options, @_) if @_; |
1233 | |
1234 | # First decision is whether or not to open the file |
1235 | if (! $options{"OPEN"}) { |
1236 | |
1237 | warn "tempfile(): temporary filename requested but not opened.\nPossibly unsafe, consider using tempfile() with OPEN set to true\n" |
1238 | if $^W; |
1239 | |
1240 | } |
1241 | |
f826e675 |
1242 | if ($options{"DIR"} and $^O eq 'VMS') { |
1243 | |
1244 | # on VMS turn []foo into [.foo] for concatenation |
1245 | $options{"DIR"} = VMS::Filespec::vmspath($options{"DIR"}); |
1246 | } |
1247 | |
669b450a |
1248 | # Construct the template |
262eb13a |
1249 | |
1250 | # Have a choice of trying to work around the mkstemp/mktemp/tmpnam etc |
1251 | # functions or simply constructing a template and using _gettemp() |
1252 | # explicitly. Go for the latter |
1253 | |
1254 | # First generate a template if not defined and prefix the directory |
1255 | # If no template must prefix the temp directory |
1256 | if (defined $template) { |
1257 | if ($options{"DIR"}) { |
1258 | |
1259 | $template = File::Spec->catfile($options{"DIR"}, $template); |
1260 | |
1261 | } |
1262 | |
1263 | } else { |
1264 | |
1265 | if ($options{"DIR"}) { |
1266 | |
1267 | $template = File::Spec->catfile($options{"DIR"}, TEMPXXX); |
1268 | |
1269 | } else { |
669b450a |
1270 | |
262eb13a |
1271 | $template = File::Spec->catfile(File::Spec->tmpdir, TEMPXXX); |
1272 | |
1273 | } |
669b450a |
1274 | |
262eb13a |
1275 | } |
1276 | |
1277 | # Now add a suffix |
1278 | $template .= $options{"SUFFIX"}; |
1279 | |
09d7a2f9 |
1280 | # Determine whether we should tell _gettemp to unlink the file |
1281 | # On unix this is irrelevant and can be worked out after the file is |
1282 | # opened (simply by unlinking the open filehandle). On Windows or VMS |
1283 | # we have to indicate temporary-ness when we open the file. In general |
be708cc0 |
1284 | # we only want a true temporary file if we are returning just the |
09d7a2f9 |
1285 | # filehandle - if the user wants the filename they probably do not |
05fb677a |
1286 | # want the file to disappear as soon as they close it (which may be |
1287 | # important if they want a child process to use the file) |
09d7a2f9 |
1288 | # For this reason, tie unlink_on_close to the return context regardless |
1289 | # of OS. |
1290 | my $unlink_on_close = ( wantarray ? 0 : 1); |
1291 | |
262eb13a |
1292 | # Create the file |
28d6a1e0 |
1293 | my ($fh, $path, $errstr); |
1294 | croak "Error in tempfile() using $template: $errstr" |
262eb13a |
1295 | unless (($fh, $path) = _gettemp($template, |
51fc852f |
1296 | "open" => $options{'OPEN'}, |
262eb13a |
1297 | "mkdir"=> 0 , |
09d7a2f9 |
1298 | "unlink_on_close" => $unlink_on_close, |
262eb13a |
1299 | "suffixlen" => length($options{'SUFFIX'}), |
28d6a1e0 |
1300 | "ErrStr" => \$errstr, |
669b450a |
1301 | ) ); |
262eb13a |
1302 | |
1303 | # Set up an exit handler that can do whatever is right for the |
09d7a2f9 |
1304 | # system. This removes files at exit when requested explicitly or when |
1305 | # system is asked to unlink_on_close but is unable to do so because |
1306 | # of OS limitations. |
1307 | # The latter should be achieved by using a tied filehandle. |
1308 | # Do not check return status since this is all done with END blocks. |
262eb13a |
1309 | _deferred_unlink($fh, $path, 0) if $options{"UNLINK"}; |
669b450a |
1310 | |
262eb13a |
1311 | # Return |
1312 | if (wantarray()) { |
1313 | |
1314 | if ($options{'OPEN'}) { |
1315 | return ($fh, $path); |
1316 | } else { |
1317 | return (undef, $path); |
1318 | } |
1319 | |
1320 | } else { |
1321 | |
1322 | # Unlink the file. It is up to unlink0 to decide what to do with |
1323 | # this (whether to unlink now or to defer until later) |
1324 | unlink0($fh, $path) or croak "Error unlinking file $path using unlink0"; |
669b450a |
1325 | |
262eb13a |
1326 | # Return just the filehandle. |
1327 | return $fh; |
1328 | } |
1329 | |
1330 | |
1331 | } |
1332 | |
1333 | =item B<tempdir> |
1334 | |
1335 | This is the recommended interface for creation of temporary directories. |
1336 | The behaviour of the function depends on the arguments: |
1337 | |
1338 | $tempdir = tempdir(); |
1339 | |
1340 | Create a directory in tmpdir() (see L<File::Spec|File::Spec>). |
1341 | |
1342 | $tempdir = tempdir( $template ); |
1343 | |
1344 | Create a directory from the supplied template. This template is |
1345 | similar to that described for tempfile(). `X' characters at the end |
1346 | of the template are replaced with random letters to construct the |
1347 | directory name. At least four `X' characters must be in the template. |
1348 | |
1349 | $tempdir = tempdir ( DIR => $dir ); |
1350 | |
1351 | Specifies the directory to use for the temporary directory. |
1352 | The temporary directory name is derived from an internal template. |
1353 | |
1354 | $tempdir = tempdir ( $template, DIR => $dir ); |
1355 | |
1356 | Prepend the supplied directory name to the template. The template |
1357 | should not include parent directory specifications itself. Any parent |
1358 | directory specifications are removed from the template before |
1359 | prepending the supplied directory. |
1360 | |
1361 | $tempdir = tempdir ( $template, TMPDIR => 1 ); |
1362 | |
be708cc0 |
1363 | Using the supplied template, create the temporary directory in |
262eb13a |
1364 | a standard location for temporary files. Equivalent to doing |
1365 | |
1366 | $tempdir = tempdir ( $template, DIR => File::Spec->tmpdir); |
1367 | |
1368 | but shorter. Parent directory specifications are stripped from the |
1369 | template itself. The C<TMPDIR> option is ignored if C<DIR> is set |
1370 | explicitly. Additionally, C<TMPDIR> is implied if neither a template |
1371 | nor a directory are supplied. |
1372 | |
1373 | $tempdir = tempdir( $template, CLEANUP => 1); |
1374 | |
be708cc0 |
1375 | Create a temporary directory using the supplied template, but |
262eb13a |
1376 | attempt to remove it (and all files inside it) when the program |
1377 | exits. Note that an attempt will be made to remove all files from |
1378 | the directory even if they were not created by this module (otherwise |
1379 | why ask to clean it up?). The directory removal is made with |
1380 | the rmtree() function from the L<File::Path|File::Path> module. |
1381 | Of course, if the template is not specified, the temporary directory |
1382 | will be created in tmpdir() and will also be removed at program exit. |
1383 | |
5d0b10e0 |
1384 | Will croak() if there is an error. |
1385 | |
262eb13a |
1386 | =cut |
1387 | |
1388 | # ' |
1389 | |
1390 | sub tempdir { |
1391 | |
1392 | # Can not check for argument count since we can have any |
1393 | # number of args |
1394 | |
1395 | # Default options |
1396 | my %options = ( |
1397 | "CLEANUP" => 0, # Remove directory on exit |
1398 | "DIR" => '', # Root directory |
1399 | "TMPDIR" => 0, # Use tempdir with template |
1400 | ); |
1401 | |
1402 | # Check to see whether we have an odd or even number of arguments |
1403 | my $template = (scalar(@_) % 2 == 1 ? shift(@_) : undef ); |
1404 | |
1405 | # Read the options and merge with defaults |
1406 | %options = (%options, @_) if @_; |
1407 | |
1408 | # Modify or generate the template |
1409 | |
1410 | # Deal with the DIR and TMPDIR options |
1411 | if (defined $template) { |
1412 | |
1413 | # Need to strip directory path if using DIR or TMPDIR |
1414 | if ($options{'TMPDIR'} || $options{'DIR'}) { |
1415 | |
1416 | # Strip parent directory from the filename |
51fc852f |
1417 | # |
262eb13a |
1418 | # There is no filename at the end |
51fc852f |
1419 | $template = VMS::Filespec::vmspath($template) if $^O eq 'VMS'; |
262eb13a |
1420 | my ($volume, $directories, undef) = File::Spec->splitpath( $template, 1); |
1421 | |
1422 | # Last directory is then our template |
1423 | $template = (File::Spec->splitdir($directories))[-1]; |
1424 | |
1425 | # Prepend the supplied directory or temp dir |
1426 | if ($options{"DIR"}) { |
1427 | |
e4dfc136 |
1428 | $template = File::Spec->catdir($options{"DIR"}, $template); |
262eb13a |
1429 | |
1430 | } elsif ($options{TMPDIR}) { |
1431 | |
1432 | # Prepend tmpdir |
1433 | $template = File::Spec->catdir(File::Spec->tmpdir, $template); |
1434 | |
1435 | } |
1436 | |
1437 | } |
1438 | |
1439 | } else { |
1440 | |
1441 | if ($options{"DIR"}) { |
1442 | |
1443 | $template = File::Spec->catdir($options{"DIR"}, TEMPXXX); |
1444 | |
1445 | } else { |
669b450a |
1446 | |
262eb13a |
1447 | $template = File::Spec->catdir(File::Spec->tmpdir, TEMPXXX); |
1448 | |
1449 | } |
669b450a |
1450 | |
262eb13a |
1451 | } |
1452 | |
1453 | # Create the directory |
1454 | my $tempdir; |
669b450a |
1455 | my $suffixlen = 0; |
1456 | if ($^O eq 'VMS') { # dir names can end in delimiters |
1457 | $template =~ m/([\.\]:>]+)$/; |
1458 | $suffixlen = length($1); |
1459 | } |
be708cc0 |
1460 | if ( ($^O eq 'MacOS') && (substr($template, -1) eq ':') ) { |
1461 | # dir name has a trailing ':' |
1462 | ++$suffixlen; |
1463 | } |
0e939f40 |
1464 | |
28d6a1e0 |
1465 | my $errstr; |
1466 | croak "Error in tempdir() using $template: $errstr" |
262eb13a |
1467 | unless ((undef, $tempdir) = _gettemp($template, |
669b450a |
1468 | "open" => 0, |
262eb13a |
1469 | "mkdir"=> 1 , |
669b450a |
1470 | "suffixlen" => $suffixlen, |
28d6a1e0 |
1471 | "ErrStr" => \$errstr, |
669b450a |
1472 | ) ); |
1473 | |
262eb13a |
1474 | # Install exit handler; must be dynamic to get lexical |
669b450a |
1475 | if ( $options{'CLEANUP'} && -d $tempdir) { |
262eb13a |
1476 | _deferred_unlink(undef, $tempdir, 1); |
669b450a |
1477 | } |
262eb13a |
1478 | |
1479 | # Return the dir name |
1480 | return $tempdir; |
1481 | |
1482 | } |
1483 | |
1484 | =back |
1485 | |
1486 | =head1 MKTEMP FUNCTIONS |
1487 | |
be708cc0 |
1488 | The following functions are Perl implementations of the |
262eb13a |
1489 | mktemp() family of temp file generation system calls. |
1490 | |
1491 | =over 4 |
1492 | |
1493 | =item B<mkstemp> |
1494 | |
1495 | Given a template, returns a filehandle to the temporary file and the name |
1496 | of the file. |
1497 | |
1498 | ($fh, $name) = mkstemp( $template ); |
1499 | |
1500 | In scalar context, just the filehandle is returned. |
1501 | |
1502 | The template may be any filename with some number of X's appended |
1503 | to it, for example F</tmp/temp.XXXX>. The trailing X's are replaced |
1504 | with unique alphanumeric combinations. |
1505 | |
5d0b10e0 |
1506 | Will croak() if there is an error. |
1507 | |
262eb13a |
1508 | =cut |
1509 | |
1510 | |
1511 | |
1512 | sub mkstemp { |
1513 | |
1514 | croak "Usage: mkstemp(template)" |
1515 | if scalar(@_) != 1; |
1516 | |
1517 | my $template = shift; |
1518 | |
28d6a1e0 |
1519 | my ($fh, $path, $errstr); |
1520 | croak "Error in mkstemp using $template: $errstr" |
669b450a |
1521 | unless (($fh, $path) = _gettemp($template, |
1522 | "open" => 1, |
262eb13a |
1523 | "mkdir"=> 0 , |
1524 | "suffixlen" => 0, |
28d6a1e0 |
1525 | "ErrStr" => \$errstr, |
262eb13a |
1526 | ) ); |
1527 | |
1528 | if (wantarray()) { |
1529 | return ($fh, $path); |
1530 | } else { |
1531 | return $fh; |
1532 | } |
1533 | |
1534 | } |
1535 | |
1536 | |
1537 | =item B<mkstemps> |
1538 | |
1539 | Similar to mkstemp(), except that an extra argument can be supplied |
1540 | with a suffix to be appended to the template. |
1541 | |
1542 | ($fh, $name) = mkstemps( $template, $suffix ); |
1543 | |
1544 | For example a template of C<testXXXXXX> and suffix of C<.dat> |
1545 | would generate a file similar to F<testhGji_w.dat>. |
1546 | |
1547 | Returns just the filehandle alone when called in scalar context. |
1548 | |
5d0b10e0 |
1549 | Will croak() if there is an error. |
1550 | |
262eb13a |
1551 | =cut |
1552 | |
1553 | sub mkstemps { |
1554 | |
1555 | croak "Usage: mkstemps(template, suffix)" |
1556 | if scalar(@_) != 2; |
1557 | |
1558 | |
1559 | my $template = shift; |
1560 | my $suffix = shift; |
1561 | |
1562 | $template .= $suffix; |
669b450a |
1563 | |
28d6a1e0 |
1564 | my ($fh, $path, $errstr); |
1565 | croak "Error in mkstemps using $template: $errstr" |
262eb13a |
1566 | unless (($fh, $path) = _gettemp($template, |
28d6a1e0 |
1567 | "open" => 1, |
262eb13a |
1568 | "mkdir"=> 0 , |
1569 | "suffixlen" => length($suffix), |
28d6a1e0 |
1570 | "ErrStr" => \$errstr, |
262eb13a |
1571 | ) ); |
1572 | |
1573 | if (wantarray()) { |
1574 | return ($fh, $path); |
1575 | } else { |
1576 | return $fh; |
1577 | } |
1578 | |
1579 | } |
1580 | |
1581 | =item B<mkdtemp> |
1582 | |
1583 | Create a directory from a template. The template must end in |
1584 | X's that are replaced by the routine. |
1585 | |
1586 | $tmpdir_name = mkdtemp($template); |
1587 | |
1588 | Returns the name of the temporary directory created. |
262eb13a |
1589 | |
1590 | Directory must be removed by the caller. |
1591 | |
5d0b10e0 |
1592 | Will croak() if there is an error. |
1593 | |
262eb13a |
1594 | =cut |
1595 | |
1596 | #' # for emacs |
1597 | |
1598 | sub mkdtemp { |
1599 | |
1600 | croak "Usage: mkdtemp(template)" |
1601 | if scalar(@_) != 1; |
262eb13a |
1602 | |
669b450a |
1603 | my $template = shift; |
1604 | my $suffixlen = 0; |
1605 | if ($^O eq 'VMS') { # dir names can end in delimiters |
1606 | $template =~ m/([\.\]:>]+)$/; |
1607 | $suffixlen = length($1); |
1608 | } |
be708cc0 |
1609 | if ( ($^O eq 'MacOS') && (substr($template, -1) eq ':') ) { |
1610 | # dir name has a trailing ':' |
1611 | ++$suffixlen; |
1612 | } |
28d6a1e0 |
1613 | my ($junk, $tmpdir, $errstr); |
1614 | croak "Error creating temp directory from template $template\: $errstr" |
262eb13a |
1615 | unless (($junk, $tmpdir) = _gettemp($template, |
669b450a |
1616 | "open" => 0, |
262eb13a |
1617 | "mkdir"=> 1 , |
669b450a |
1618 | "suffixlen" => $suffixlen, |
28d6a1e0 |
1619 | "ErrStr" => \$errstr, |
262eb13a |
1620 | ) ); |
1621 | |
1622 | return $tmpdir; |
1623 | |
1624 | } |
1625 | |
1626 | =item B<mktemp> |
1627 | |
1628 | Returns a valid temporary filename but does not guarantee |
1629 | that the file will not be opened by someone else. |
1630 | |
1631 | $unopened_file = mktemp($template); |
1632 | |
1633 | Template is the same as that required by mkstemp(). |
1634 | |
5d0b10e0 |
1635 | Will croak() if there is an error. |
1636 | |
262eb13a |
1637 | =cut |
1638 | |
1639 | sub mktemp { |
1640 | |
1641 | croak "Usage: mktemp(template)" |
1642 | if scalar(@_) != 1; |
1643 | |
1644 | my $template = shift; |
1645 | |
28d6a1e0 |
1646 | my ($tmpname, $junk, $errstr); |
1647 | croak "Error getting name to temp file from template $template: $errstr" |
262eb13a |
1648 | unless (($junk, $tmpname) = _gettemp($template, |
669b450a |
1649 | "open" => 0, |
262eb13a |
1650 | "mkdir"=> 0 , |
1651 | "suffixlen" => 0, |
28d6a1e0 |
1652 | "ErrStr" => \$errstr, |
262eb13a |
1653 | ) ); |
1654 | |
1655 | return $tmpname; |
1656 | } |
1657 | |
1658 | =back |
1659 | |
1660 | =head1 POSIX FUNCTIONS |
1661 | |
1662 | This section describes the re-implementation of the tmpnam() |
be708cc0 |
1663 | and tmpfile() functions described in L<POSIX> |
262eb13a |
1664 | using the mkstemp() from this module. |
1665 | |
1666 | Unlike the L<POSIX|POSIX> implementations, the directory used |
1667 | for the temporary file is not specified in a system include |
1668 | file (C<P_tmpdir>) but simply depends on the choice of tmpdir() |
1669 | returned by L<File::Spec|File::Spec>. On some implementations this |
1670 | location can be set using the C<TMPDIR> environment variable, which |
1671 | may not be secure. |
1672 | If this is a problem, simply use mkstemp() and specify a template. |
1673 | |
1674 | =over 4 |
1675 | |
1676 | =item B<tmpnam> |
1677 | |
1678 | When called in scalar context, returns the full name (including path) |
1679 | of a temporary file (uses mktemp()). The only check is that the file does |
1680 | not already exist, but there is no guarantee that that condition will |
1681 | continue to apply. |
1682 | |
1683 | $file = tmpnam(); |
1684 | |
1685 | When called in list context, a filehandle to the open file and |
1686 | a filename are returned. This is achieved by calling mkstemp() |
1687 | after constructing a suitable template. |
1688 | |
1689 | ($fh, $file) = tmpnam(); |
1690 | |
1691 | If possible, this form should be used to prevent possible |
1692 | race conditions. |
1693 | |
1694 | See L<File::Spec/tmpdir> for information on the choice of temporary |
1695 | directory for a particular operating system. |
1696 | |
5d0b10e0 |
1697 | Will croak() if there is an error. |
1698 | |
262eb13a |
1699 | =cut |
1700 | |
1701 | sub tmpnam { |
1702 | |
1703 | # Retrieve the temporary directory name |
1704 | my $tmpdir = File::Spec->tmpdir; |
1705 | |
1706 | croak "Error temporary directory is not writable" |
1707 | if $tmpdir eq ''; |
1708 | |
1709 | # Use a ten character template and append to tmpdir |
1710 | my $template = File::Spec->catfile($tmpdir, TEMPXXX); |
669b450a |
1711 | |
262eb13a |
1712 | if (wantarray() ) { |
1713 | return mkstemp($template); |
1714 | } else { |
1715 | return mktemp($template); |
1716 | } |
1717 | |
1718 | } |
1719 | |
1720 | =item B<tmpfile> |
1721 | |
c6d63c67 |
1722 | Returns the filehandle of a temporary file. |
262eb13a |
1723 | |
1724 | $fh = tmpfile(); |
1725 | |
1726 | The file is removed when the filehandle is closed or when the program |
1727 | exits. No access to the filename is provided. |
1728 | |
0e939f40 |
1729 | If the temporary file can not be created undef is returned. |
1730 | Currently this command will probably not work when the temporary |
1731 | directory is on an NFS file system. |
1732 | |
5d0b10e0 |
1733 | Will croak() if there is an error. |
1734 | |
262eb13a |
1735 | =cut |
1736 | |
1737 | sub tmpfile { |
1738 | |
91e74348 |
1739 | # Simply call tmpnam() in a list context |
262eb13a |
1740 | my ($fh, $file) = tmpnam(); |
1741 | |
1742 | # Make sure file is removed when filehandle is closed |
0e939f40 |
1743 | # This will fail on NFS |
1744 | unlink0($fh, $file) |
1745 | or return undef; |
262eb13a |
1746 | |
1747 | return $fh; |
1748 | |
1749 | } |
1750 | |
1751 | =back |
1752 | |
1753 | =head1 ADDITIONAL FUNCTIONS |
1754 | |
1755 | These functions are provided for backwards compatibility |
1756 | with common tempfile generation C library functions. |
1757 | |
1758 | They are not exported and must be addressed using the full package |
be708cc0 |
1759 | name. |
262eb13a |
1760 | |
1761 | =over 4 |
1762 | |
1763 | =item B<tempnam> |
1764 | |
1765 | Return the name of a temporary file in the specified directory |
1766 | using a prefix. The file is guaranteed not to exist at the time |
be708cc0 |
1767 | the function was called, but such guarantees are good for one |
262eb13a |
1768 | clock tick only. Always use the proper form of C<sysopen> |
1769 | with C<O_CREAT | O_EXCL> if you must open such a filename. |
1770 | |
1771 | $filename = File::Temp::tempnam( $dir, $prefix ); |
1772 | |
1773 | Equivalent to running mktemp() with $dir/$prefixXXXXXXXX |
be708cc0 |
1774 | (using unix file convention as an example) |
262eb13a |
1775 | |
1776 | Because this function uses mktemp(), it can suffer from race conditions. |
1777 | |
5d0b10e0 |
1778 | Will croak() if there is an error. |
1779 | |
262eb13a |
1780 | =cut |
1781 | |
1782 | sub tempnam { |
1783 | |
1784 | croak 'Usage tempnam($dir, $prefix)' unless scalar(@_) == 2; |
1785 | |
1786 | my ($dir, $prefix) = @_; |
1787 | |
1788 | # Add a string to the prefix |
1789 | $prefix .= 'XXXXXXXX'; |
1790 | |
1791 | # Concatenate the directory to the file |
1792 | my $template = File::Spec->catfile($dir, $prefix); |
1793 | |
1794 | return mktemp($template); |
1795 | |
1796 | } |
1797 | |
1798 | =back |
1799 | |
1800 | =head1 UTILITY FUNCTIONS |
1801 | |
1802 | Useful functions for dealing with the filehandle and filename. |
1803 | |
1804 | =over 4 |
1805 | |
1806 | =item B<unlink0> |
1807 | |
1808 | Given an open filehandle and the associated filename, make a safe |
1809 | unlink. This is achieved by first checking that the filename and |
1810 | filehandle initially point to the same file and that the number of |
1811 | links to the file is 1 (all fields returned by stat() are compared). |
1812 | Then the filename is unlinked and the filehandle checked once again to |
1813 | verify that the number of links on that file is now 0. This is the |
1814 | closest you can come to making sure that the filename unlinked was the |
1815 | same as the file whose descriptor you hold. |
1816 | |
05fb677a |
1817 | unlink0($fh, $path) |
1818 | or die "Error unlinking file $path safely"; |
262eb13a |
1819 | |
5d0b10e0 |
1820 | Returns false on error but croaks() if there is a security |
1821 | anomaly. The filehandle is not closed since on some occasions this is |
1822 | not required. |
262eb13a |
1823 | |
1824 | On some platforms, for example Windows NT, it is not possible to |
1825 | unlink an open file (the file must be closed first). On those |
1c19c868 |
1826 | platforms, the actual unlinking is deferred until the program ends and |
1827 | good status is returned. A check is still performed to make sure that |
1828 | the filehandle and filename are pointing to the same thing (but not at |
1829 | the time the end block is executed since the deferred removal may not |
1830 | have access to the filehandle). |
262eb13a |
1831 | |
1832 | Additionally, on Windows NT not all the fields returned by stat() can |
51fc852f |
1833 | be compared. For example, the C<dev> and C<rdev> fields seem to be |
1834 | different. Also, it seems that the size of the file returned by stat() |
262eb13a |
1835 | does not always agree, with C<stat(FH)> being more accurate than |
1836 | C<stat(filename)>, presumably because of caching issues even when |
1837 | using autoflush (this is usually overcome by waiting a while after |
1838 | writing to the tempfile before attempting to C<unlink0> it). |
1839 | |
1c19c868 |
1840 | Finally, on NFS file systems the link count of the file handle does |
1841 | not always go to zero immediately after unlinking. Currently, this |
1842 | command is expected to fail on NFS disks. |
1843 | |
05fb677a |
1844 | This function is disabled if the global variable $KEEP_ALL is true |
1845 | and an unlink on open file is supported. If the unlink is to be deferred |
1846 | to the END block, the file is still registered for removal. |
1847 | |
5d0b10e0 |
1848 | This function should not be called if you are using the object oriented |
1849 | interface since the it will interfere with the object destructor deleting |
1850 | the file. |
1851 | |
262eb13a |
1852 | =cut |
1853 | |
1854 | sub unlink0 { |
1855 | |
1856 | croak 'Usage: unlink0(filehandle, filename)' |
1857 | unless scalar(@_) == 2; |
1858 | |
1859 | # Read args |
1860 | my ($fh, $path) = @_; |
1861 | |
4a094b80 |
1862 | cmpstat($fh, $path) or return 0; |
1863 | |
1864 | # attempt remove the file (does not work on some platforms) |
1865 | if (_can_unlink_opened_file()) { |
05fb677a |
1866 | |
1867 | # return early (Without unlink) if we have been instructed to retain files. |
1868 | return 1 if $KEEP_ALL; |
1869 | |
4a094b80 |
1870 | # XXX: do *not* call this on a directory; possible race |
1871 | # resulting in recursive removal |
1872 | croak "unlink0: $path has become a directory!" if -d $path; |
1873 | unlink($path) or return 0; |
1874 | |
1875 | # Stat the filehandle |
1876 | my @fh = stat $fh; |
1877 | |
1878 | print "Link count = $fh[3] \n" if $DEBUG; |
1879 | |
1880 | # Make sure that the link count is zero |
1881 | # - Cygwin provides deferred unlinking, however, |
1882 | # on Win9x the link count remains 1 |
1883 | # On NFS the link count may still be 1 but we cant know that |
1884 | # we are on NFS |
1885 | return ( $fh[3] == 0 or $^O eq 'cygwin' ? 1 : 0); |
1886 | |
1887 | } else { |
1888 | _deferred_unlink($fh, $path, 0); |
1889 | return 1; |
1890 | } |
1891 | |
1892 | } |
1893 | |
1894 | =item B<cmpstat> |
1895 | |
1896 | Compare C<stat> of filehandle with C<stat> of provided filename. This |
1897 | can be used to check that the filename and filehandle initially point |
1898 | to the same file and that the number of links to the file is 1 (all |
1899 | fields returned by stat() are compared). |
1900 | |
05fb677a |
1901 | cmpstat($fh, $path) |
1902 | or die "Error comparing handle with file"; |
4a094b80 |
1903 | |
1904 | Returns false if the stat information differs or if the link count is |
5d0b10e0 |
1905 | greater than 1. Calls croak if there is a security anomaly. |
4a094b80 |
1906 | |
5d0b10e0 |
1907 | On certain platforms, for example Windows, not all the fields returned by stat() |
4a094b80 |
1908 | can be compared. For example, the C<dev> and C<rdev> fields seem to be |
1909 | different in Windows. Also, it seems that the size of the file |
1910 | returned by stat() does not always agree, with C<stat(FH)> being more |
1911 | accurate than C<stat(filename)>, presumably because of caching issues |
1912 | even when using autoflush (this is usually overcome by waiting a while |
1913 | after writing to the tempfile before attempting to C<unlink0> it). |
1914 | |
1915 | Not exported by default. |
1916 | |
1917 | =cut |
1918 | |
1919 | sub cmpstat { |
1920 | |
1921 | croak 'Usage: cmpstat(filehandle, filename)' |
1922 | unless scalar(@_) == 2; |
1923 | |
1924 | # Read args |
1925 | my ($fh, $path) = @_; |
1926 | |
1927 | warn "Comparing stat\n" |
262eb13a |
1928 | if $DEBUG; |
1929 | |
4a094b80 |
1930 | # Stat the filehandle - which may be closed if someone has manually |
1931 | # closed the file. Can not turn off warnings without using $^W |
1932 | # unless we upgrade to 5.006 minimum requirement |
1933 | my @fh; |
1934 | { |
1935 | local ($^W) = 0; |
1936 | @fh = stat $fh; |
1937 | } |
1938 | return unless @fh; |
262eb13a |
1939 | |
1940 | if ($fh[3] > 1 && $^W) { |
28d6a1e0 |
1941 | carp "unlink0: fstat found too many links; SB=@fh" if $^W; |
669b450a |
1942 | } |
262eb13a |
1943 | |
1944 | # Stat the path |
1945 | my @path = stat $path; |
1946 | |
1947 | unless (@path) { |
1948 | carp "unlink0: $path is gone already" if $^W; |
1949 | return; |
669b450a |
1950 | } |
262eb13a |
1951 | |
1952 | # this is no longer a file, but may be a directory, or worse |
05fb677a |
1953 | unless (-f $path) { |
262eb13a |
1954 | confess "panic: $path is no longer a file: SB=@fh"; |
669b450a |
1955 | } |
262eb13a |
1956 | |
1957 | # Do comparison of each member of the array |
1958 | # On WinNT dev and rdev seem to be different |
1959 | # depending on whether it is a file or a handle. |
1960 | # Cannot simply compare all members of the stat return |
1961 | # Select the ones we can use |
1962 | my @okstat = (0..$#fh); # Use all by default |
1963 | if ($^O eq 'MSWin32') { |
1964 | @okstat = (1,2,3,4,5,7,8,9,10); |
669b450a |
1965 | } elsif ($^O eq 'os2') { |
d62e1b7f |
1966 | @okstat = (0, 2..$#fh); |
51fc852f |
1967 | } elsif ($^O eq 'VMS') { # device and file ID are sufficient |
1968 | @okstat = (0, 1); |
6bbf1b34 |
1969 | } elsif ($^O eq 'dos') { |
4a094b80 |
1970 | @okstat = (0,2..7,11..$#fh); |
1971 | } elsif ($^O eq 'mpeix') { |
1972 | @okstat = (0..4,8..10); |
262eb13a |
1973 | } |
1974 | |
1975 | # Now compare each entry explicitly by number |
1976 | for (@okstat) { |
1977 | print "Comparing: $_ : $fh[$_] and $path[$_]\n" if $DEBUG; |
d62e1b7f |
1978 | # Use eq rather than == since rdev, blksize, and blocks (6, 11, |
1979 | # and 12) will be '' on platforms that do not support them. This |
1980 | # is fine since we are only comparing integers. |
669b450a |
1981 | unless ($fh[$_] eq $path[$_]) { |
262eb13a |
1982 | warn "Did not match $_ element of stat\n" if $DEBUG; |
1983 | return 0; |
1984 | } |
1985 | } |
669b450a |
1986 | |
4a094b80 |
1987 | return 1; |
1988 | } |
262eb13a |
1989 | |
4a094b80 |
1990 | =item B<unlink1> |
262eb13a |
1991 | |
4a094b80 |
1992 | Similar to C<unlink0> except after file comparison using cmpstat, the |
1993 | filehandle is closed prior to attempting to unlink the file. This |
1994 | allows the file to be removed without using an END block, but does |
1995 | mean that the post-unlink comparison of the filehandle state provided |
1996 | by C<unlink0> is not available. |
262eb13a |
1997 | |
05fb677a |
1998 | unlink1($fh, $path) |
1999 | or die "Error closing and unlinking file"; |
262eb13a |
2000 | |
4a094b80 |
2001 | Usually called from the object destructor when using the OO interface. |
2002 | |
2003 | Not exported by default. |
2004 | |
05fb677a |
2005 | This function is disabled if the global variable $KEEP_ALL is true. |
2006 | |
5d0b10e0 |
2007 | Can call croak() if there is a security anomaly during the stat() |
2008 | comparison. |
2009 | |
4a094b80 |
2010 | =cut |
262eb13a |
2011 | |
4a094b80 |
2012 | sub unlink1 { |
2013 | croak 'Usage: unlink1(filehandle, filename)' |
2014 | unless scalar(@_) == 2; |
2015 | |
2016 | # Read args |
2017 | my ($fh, $path) = @_; |
2018 | |
2019 | cmpstat($fh, $path) or return 0; |
2020 | |
2021 | # Close the file |
2022 | close( $fh ) or return 0; |
2023 | |
05fb677a |
2024 | # Make sure the file is writable (for windows) |
2025 | _force_writable( $path ); |
2026 | |
2027 | # return early (without unlink) if we have been instructed to retain files. |
2028 | return 1 if $KEEP_ALL; |
2029 | |
4a094b80 |
2030 | # remove the file |
2031 | return unlink($path); |
262eb13a |
2032 | } |
2033 | |
05fb677a |
2034 | =item B<cleanup> |
2035 | |
2036 | Calling this function will cause any temp files or temp directories |
2037 | that are registered for removal to be removed. This happens automatically |
2038 | when the process exits but can be triggered manually if the caller is sure |
2039 | that none of the temp files are required. This method can be registered as |
2040 | an Apache callback. |
2041 | |
2042 | On OSes where temp files are automatically removed when the temp file |
2043 | is closed, calling this function will have no effect other than to remove |
2044 | temporary directories (which may include temporary files). |
2045 | |
2046 | File::Temp::cleanup(); |
2047 | |
2048 | Not exported by default. |
2049 | |
262eb13a |
2050 | =back |
2051 | |
2052 | =head1 PACKAGE VARIABLES |
2053 | |
2054 | These functions control the global state of the package. |
2055 | |
2056 | =over 4 |
2057 | |
2058 | =item B<safe_level> |
2059 | |
2060 | Controls the lengths to which the module will go to check the safety of the |
2061 | temporary file or directory before proceeding. |
2062 | Options are: |
2063 | |
2064 | =over 8 |
2065 | |
2066 | =item STANDARD |
2067 | |
2068 | Do the basic security measures to ensure the directory exists and |
2069 | is writable, that the umask() is fixed before opening of the file, |
2070 | that temporary files are opened only if they do not already exist, and |
2071 | that possible race conditions are avoided. Finally the L<unlink0|"unlink0"> |
2072 | function is used to remove files safely. |
2073 | |
2074 | =item MEDIUM |
2075 | |
2076 | In addition to the STANDARD security, the output directory is checked |
2077 | to make sure that it is owned either by root or the user running the |
2078 | program. If the directory is writable by group or by other, it is then |
2079 | checked to make sure that the sticky bit is set. |
2080 | |
2081 | Will not work on platforms that do not support the C<-k> test |
2082 | for sticky bit. |
2083 | |
2084 | =item HIGH |
2085 | |
2086 | In addition to the MEDIUM security checks, also check for the |
2087 | possibility of ``chown() giveaway'' using the L<POSIX|POSIX> |
2088 | sysconf() function. If this is a possibility, each directory in the |
be708cc0 |
2089 | path is checked in turn for safeness, recursively walking back to the |
262eb13a |
2090 | root directory. |
2091 | |
2092 | For platforms that do not support the L<POSIX|POSIX> |
be708cc0 |
2093 | C<_PC_CHOWN_RESTRICTED> symbol (for example, Windows NT) it is |
262eb13a |
2094 | assumed that ``chown() giveaway'' is possible and the recursive test |
2095 | is performed. |
2096 | |
2097 | =back |
2098 | |
2099 | The level can be changed as follows: |
2100 | |
2101 | File::Temp->safe_level( File::Temp::HIGH ); |
2102 | |
2103 | The level constants are not exported by the module. |
2104 | |
2105 | Currently, you must be running at least perl v5.6.0 in order to |
be708cc0 |
2106 | run with MEDIUM or HIGH security. This is simply because the |
262eb13a |
2107 | safety tests use functions from L<Fcntl|Fcntl> that are not |
2108 | available in older versions of perl. The problem is that the version |
2109 | number for Fcntl is the same in perl 5.6.0 and in 5.005_03 even though |
1c19c868 |
2110 | they are different versions. |
2111 | |
2112 | On systems that do not support the HIGH or MEDIUM safety levels |
2113 | (for example Win NT or OS/2) any attempt to change the level will |
2114 | be ignored. The decision to ignore rather than raise an exception |
2115 | allows portable programs to be written with high security in mind |
2116 | for the systems that can support this without those programs failing |
2117 | on systems where the extra tests are irrelevant. |
2118 | |
2119 | If you really need to see whether the change has been accepted |
2120 | simply examine the return value of C<safe_level>. |
2121 | |
2122 | $newlevel = File::Temp->safe_level( File::Temp::HIGH ); |
be708cc0 |
2123 | die "Could not change to high security" |
1c19c868 |
2124 | if $newlevel != File::Temp::HIGH; |
262eb13a |
2125 | |
2126 | =cut |
2127 | |
2128 | { |
2129 | # protect from using the variable itself |
2130 | my $LEVEL = STANDARD; |
2131 | sub safe_level { |
2132 | my $self = shift; |
be708cc0 |
2133 | if (@_) { |
262eb13a |
2134 | my $level = shift; |
2135 | if (($level != STANDARD) && ($level != MEDIUM) && ($level != HIGH)) { |
28d6a1e0 |
2136 | carp "safe_level: Specified level ($level) not STANDARD, MEDIUM or HIGH - ignoring\n" if $^W; |
262eb13a |
2137 | } else { |
1c19c868 |
2138 | # Dont allow this on perl 5.005 or earlier |
262eb13a |
2139 | if ($] < 5.006 && $level != STANDARD) { |
2140 | # Cant do MEDIUM or HIGH checks |
2141 | croak "Currently requires perl 5.006 or newer to do the safe checks"; |
2142 | } |
1c19c868 |
2143 | # Check that we are allowed to change level |
2144 | # Silently ignore if we can not. |
2145 | $LEVEL = $level if _can_do_level($level); |
262eb13a |
2146 | } |
2147 | } |
2148 | return $LEVEL; |
2149 | } |
2150 | } |
2151 | |
2152 | =item TopSystemUID |
2153 | |
2154 | This is the highest UID on the current system that refers to a root |
be708cc0 |
2155 | UID. This is used to make sure that the temporary directory is |
2156 | owned by a system UID (C<root>, C<bin>, C<sys> etc) rather than |
262eb13a |
2157 | simply by root. |
2158 | |
2159 | This is required since on many unix systems C</tmp> is not owned |
2160 | by root. |
2161 | |
2162 | Default is to assume that any UID less than or equal to 10 is a root |
2163 | UID. |
2164 | |
2165 | File::Temp->top_system_uid(10); |
2166 | my $topid = File::Temp->top_system_uid; |
2167 | |
2168 | This value can be adjusted to reduce security checking if required. |
2169 | The value is only relevant when C<safe_level> is set to MEDIUM or higher. |
2170 | |
262eb13a |
2171 | =cut |
2172 | |
2173 | { |
2174 | my $TopSystemUID = 10; |
0c52c6a9 |
2175 | $TopSystemUID = 197108 if $^O eq 'interix'; # "Administrator" |
262eb13a |
2176 | sub top_system_uid { |
2177 | my $self = shift; |
2178 | if (@_) { |
2179 | my $newuid = shift; |
2180 | croak "top_system_uid: UIDs should be numeric" |
2181 | unless $newuid =~ /^\d+$/s; |
2182 | $TopSystemUID = $newuid; |
2183 | } |
2184 | return $TopSystemUID; |
2185 | } |
2186 | } |
2187 | |
05fb677a |
2188 | =item B<$KEEP_ALL> |
2189 | |
2190 | Controls whether temporary files and directories should be retained |
2191 | regardless of any instructions in the program to remove them |
2192 | automatically. This is useful for debugging but should not be used in |
2193 | production code. |
2194 | |
2195 | $File::Temp::KEEP_ALL = 1; |
2196 | |
2197 | Default is for files to be removed as requested by the caller. |
2198 | |
2199 | In some cases, files will only be retained if this variable is true |
2200 | when the file is created. This means that you can not create a temporary |
2201 | file, set this variable and expect the temp file to still be around |
2202 | when the program exits. |
2203 | |
2204 | =item B<$DEBUG> |
2205 | |
2206 | Controls whether debugging messages should be enabled. |
2207 | |
2208 | $File::Temp::DEBUG = 1; |
2209 | |
2210 | Default is for debugging mode to be disabled. |
2211 | |
2212 | =back |
2213 | |
262eb13a |
2214 | =head1 WARNING |
2215 | |
2216 | For maximum security, endeavour always to avoid ever looking at, |
2217 | touching, or even imputing the existence of the filename. You do not |
2218 | know that that filename is connected to the same file as the handle |
2219 | you have, and attempts to check this can only trigger more race |
2220 | conditions. It's far more secure to use the filehandle alone and |
2221 | dispense with the filename altogether. |
2222 | |
2223 | If you need to pass the handle to something that expects a filename |
2224 | then, on a unix system, use C<"/dev/fd/" . fileno($fh)> for arbitrary |
2225 | programs, or more generally C<< "+<=&" . fileno($fh) >> for Perl |
2226 | programs. You will have to clear the close-on-exec bit on that file |
2227 | descriptor before passing it to another process. |
2228 | |
2229 | use Fcntl qw/F_SETFD F_GETFD/; |
2230 | fcntl($tmpfh, F_SETFD, 0) |
2231 | or die "Can't clear close-on-exec flag on temp fh: $!\n"; |
2232 | |
09d7a2f9 |
2233 | =head2 Temporary files and NFS |
2234 | |
2235 | Some problems are associated with using temporary files that reside |
2236 | on NFS file systems and it is recommended that a local filesystem |
2237 | is used whenever possible. Some of the security tests will most probably |
2238 | fail when the temp file is not local. Additionally, be aware that |
2239 | the performance of I/O operations over NFS will not be as good as for |
2240 | a local disk. |
2241 | |
05fb677a |
2242 | =head2 Forking |
2243 | |
2244 | In some cases files created by File::Temp are removed from within an |
2245 | END block. Since END blocks are triggered when a child process exits |
2246 | (unless C<POSIX::_exit()> is used by the child) File::Temp takes care |
2247 | to only remove those temp files created by a particular process ID. This |
2248 | means that a child will not attempt to remove temp files created by the |
2249 | parent process. |
2250 | |
5d0b10e0 |
2251 | If you are forking many processes in parallel that are all creating |
2252 | temporary files, you may need to reset the random number seed using |
2253 | srand(EXPR) in each child else all the children will attempt to walk |
2254 | through the same set of random file names and may well cause |
2255 | themselves to give up if they exceed the number of retry attempts. |
2256 | |
05fb677a |
2257 | =head2 BINMODE |
2258 | |
2259 | The file returned by File::Temp will have been opened in binary mode |
2260 | if such a mode is available. If that is not correct, use the binmode() |
2261 | function to change the mode of the filehandle. |
2262 | |
262eb13a |
2263 | =head1 HISTORY |
2264 | |
2265 | Originally began life in May 1999 as an XS interface to the system |
e77f578c |
2266 | mkstemp() function. In March 2000, the OpenBSD mkstemp() code was |
262eb13a |
2267 | translated to Perl for total control of the code's |
2268 | security checking, to ensure the presence of the function regardless of |
05fb677a |
2269 | operating system and to help with portability. The module was shipped |
2270 | as a standard part of perl from v5.6.1. |
262eb13a |
2271 | |
2272 | =head1 SEE ALSO |
2273 | |
2274 | L<POSIX/tmpnam>, L<POSIX/tmpfile>, L<File::Spec>, L<File::Path> |
2275 | |
05fb677a |
2276 | See L<IO::File> and L<File::MkTemp>, L<Apachae::TempFile> for |
2277 | different implementations of temporary file handling. |
262eb13a |
2278 | |
2279 | =head1 AUTHOR |
2280 | |
21cc0ee1 |
2281 | Tim Jenness E<lt>tjenness@cpan.orgE<gt> |
262eb13a |
2282 | |
5d0b10e0 |
2283 | Copyright (C) 1999-2006 Tim Jenness and the UK Particle Physics and |
262eb13a |
2284 | Astronomy Research Council. All Rights Reserved. This program is free |
2285 | software; you can redistribute it and/or modify it under the same |
2286 | terms as Perl itself. |
2287 | |
be708cc0 |
2288 | Original Perl implementation loosely based on the OpenBSD C code for |
262eb13a |
2289 | mkstemp(). Thanks to Tom Christiansen for suggesting that this module |
2290 | should be written and providing ideas for code improvements and |
2291 | security enhancements. |
2292 | |
2293 | =cut |
2294 | |
262eb13a |
2295 | 1; |