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