1*256a93a4Safresh1package File::Temp; # git description: v0.2310-3-gc7148fe 26fb12b70Safresh1# ABSTRACT: return name and handle of a temporary file safely 391f110e0Safresh1 4*256a93a4Safresh1our $VERSION = '0.2311'; 5f3efcd01Safresh1 6f3efcd01Safresh1#pod =begin :__INTERNALS 7f3efcd01Safresh1#pod 8f3efcd01Safresh1#pod =head1 PORTABILITY 9f3efcd01Safresh1#pod 10f3efcd01Safresh1#pod This section is at the top in order to provide easier access to 11f3efcd01Safresh1#pod porters. It is not expected to be rendered by a standard pod 12f3efcd01Safresh1#pod formatting tool. Please skip straight to the SYNOPSIS section if you 13f3efcd01Safresh1#pod are not trying to port this module to a new platform. 14f3efcd01Safresh1#pod 15f3efcd01Safresh1#pod This module is designed to be portable across operating systems and it 16f3efcd01Safresh1#pod currently supports Unix, VMS, DOS, OS/2, Windows and Mac OS 17f3efcd01Safresh1#pod (Classic). When porting to a new OS there are generally three main 18f3efcd01Safresh1#pod issues that have to be solved: 19f3efcd01Safresh1#pod 20f3efcd01Safresh1#pod =over 4 21f3efcd01Safresh1#pod 22f3efcd01Safresh1#pod =item * 23f3efcd01Safresh1#pod 24f3efcd01Safresh1#pod Can the OS unlink an open file? If it can not then the 25f3efcd01Safresh1#pod C<_can_unlink_opened_file> method should be modified. 26f3efcd01Safresh1#pod 27f3efcd01Safresh1#pod =item * 28f3efcd01Safresh1#pod 29f3efcd01Safresh1#pod Are the return values from C<stat> reliable? By default all the 30f3efcd01Safresh1#pod return values from C<stat> are compared when unlinking a temporary 31f3efcd01Safresh1#pod file using the filename and the handle. Operating systems other than 32f3efcd01Safresh1#pod unix do not always have valid entries in all fields. If utility function 33f3efcd01Safresh1#pod C<File::Temp::unlink0> fails then the C<stat> comparison should be 34f3efcd01Safresh1#pod modified accordingly. 35f3efcd01Safresh1#pod 36f3efcd01Safresh1#pod =item * 37f3efcd01Safresh1#pod 38f3efcd01Safresh1#pod Security. Systems that can not support a test for the sticky bit 39f3efcd01Safresh1#pod on a directory can not use the MEDIUM and HIGH security tests. 40f3efcd01Safresh1#pod The C<_can_do_level> method should be modified accordingly. 41f3efcd01Safresh1#pod 42f3efcd01Safresh1#pod =back 43f3efcd01Safresh1#pod 44f3efcd01Safresh1#pod =end :__INTERNALS 45f3efcd01Safresh1#pod 46f3efcd01Safresh1#pod =head1 SYNOPSIS 47f3efcd01Safresh1#pod 48f3efcd01Safresh1#pod use File::Temp qw/ tempfile tempdir /; 49f3efcd01Safresh1#pod 50f3efcd01Safresh1#pod $fh = tempfile(); 51f3efcd01Safresh1#pod ($fh, $filename) = tempfile(); 52f3efcd01Safresh1#pod 53f3efcd01Safresh1#pod ($fh, $filename) = tempfile( $template, DIR => $dir); 54f3efcd01Safresh1#pod ($fh, $filename) = tempfile( $template, SUFFIX => '.dat'); 55f3efcd01Safresh1#pod ($fh, $filename) = tempfile( $template, TMPDIR => 1 ); 56f3efcd01Safresh1#pod 57f3efcd01Safresh1#pod binmode( $fh, ":utf8" ); 58f3efcd01Safresh1#pod 59f3efcd01Safresh1#pod $dir = tempdir( CLEANUP => 1 ); 60f3efcd01Safresh1#pod ($fh, $filename) = tempfile( DIR => $dir ); 61f3efcd01Safresh1#pod 62f3efcd01Safresh1#pod Object interface: 63f3efcd01Safresh1#pod 64f3efcd01Safresh1#pod require File::Temp; 65f3efcd01Safresh1#pod use File::Temp (); 66f3efcd01Safresh1#pod use File::Temp qw/ :seekable /; 67f3efcd01Safresh1#pod 68f3efcd01Safresh1#pod $fh = File::Temp->new(); 69f3efcd01Safresh1#pod $fname = $fh->filename; 70f3efcd01Safresh1#pod 71f3efcd01Safresh1#pod $fh = File::Temp->new(TEMPLATE => $template); 72f3efcd01Safresh1#pod $fname = $fh->filename; 73f3efcd01Safresh1#pod 74f3efcd01Safresh1#pod $tmp = File::Temp->new( UNLINK => 0, SUFFIX => '.dat' ); 75f3efcd01Safresh1#pod print $tmp "Some data\n"; 76f3efcd01Safresh1#pod print "Filename is $tmp\n"; 77f3efcd01Safresh1#pod $tmp->seek( 0, SEEK_END ); 78f3efcd01Safresh1#pod 79f3efcd01Safresh1#pod $dir = File::Temp->newdir(); # CLEANUP => 1 by default 80f3efcd01Safresh1#pod 81f3efcd01Safresh1#pod The following interfaces are provided for compatibility with 82f3efcd01Safresh1#pod existing APIs. They should not be used in new code. 83f3efcd01Safresh1#pod 84f3efcd01Safresh1#pod MkTemp family: 85f3efcd01Safresh1#pod 86f3efcd01Safresh1#pod use File::Temp qw/ :mktemp /; 87f3efcd01Safresh1#pod 88f3efcd01Safresh1#pod ($fh, $file) = mkstemp( "tmpfileXXXXX" ); 89f3efcd01Safresh1#pod ($fh, $file) = mkstemps( "tmpfileXXXXXX", $suffix); 90f3efcd01Safresh1#pod 91f3efcd01Safresh1#pod $tmpdir = mkdtemp( $template ); 92f3efcd01Safresh1#pod 93f3efcd01Safresh1#pod $unopened_file = mktemp( $template ); 94f3efcd01Safresh1#pod 95f3efcd01Safresh1#pod POSIX functions: 96f3efcd01Safresh1#pod 97f3efcd01Safresh1#pod use File::Temp qw/ :POSIX /; 98f3efcd01Safresh1#pod 99f3efcd01Safresh1#pod $file = tmpnam(); 100f3efcd01Safresh1#pod $fh = tmpfile(); 101f3efcd01Safresh1#pod 102f3efcd01Safresh1#pod ($fh, $file) = tmpnam(); 103f3efcd01Safresh1#pod 104f3efcd01Safresh1#pod Compatibility functions: 105f3efcd01Safresh1#pod 106f3efcd01Safresh1#pod $unopened_file = File::Temp::tempnam( $dir, $pfx ); 107f3efcd01Safresh1#pod 108f3efcd01Safresh1#pod =head1 DESCRIPTION 109f3efcd01Safresh1#pod 110f3efcd01Safresh1#pod C<File::Temp> can be used to create and open temporary files in a safe 111f3efcd01Safresh1#pod way. There is both a function interface and an object-oriented 112f3efcd01Safresh1#pod interface. The File::Temp constructor or the tempfile() function can 113f3efcd01Safresh1#pod be used to return the name and the open filehandle of a temporary 114f3efcd01Safresh1#pod file. The tempdir() function can be used to create a temporary 115f3efcd01Safresh1#pod directory. 116f3efcd01Safresh1#pod 117f3efcd01Safresh1#pod The security aspect of temporary file creation is emphasized such that 118f3efcd01Safresh1#pod a filehandle and filename are returned together. This helps guarantee 119f3efcd01Safresh1#pod that a race condition can not occur where the temporary file is 120f3efcd01Safresh1#pod created by another process between checking for the existence of the 121f3efcd01Safresh1#pod file and its opening. Additional security levels are provided to 122f3efcd01Safresh1#pod check, for example, that the sticky bit is set on world writable 123f3efcd01Safresh1#pod directories. See L<"safe_level"> for more information. 124f3efcd01Safresh1#pod 125f3efcd01Safresh1#pod For compatibility with popular C library functions, Perl implementations of 126f3efcd01Safresh1#pod the mkstemp() family of functions are provided. These are, mkstemp(), 127f3efcd01Safresh1#pod mkstemps(), mkdtemp() and mktemp(). 128f3efcd01Safresh1#pod 129f3efcd01Safresh1#pod Additionally, implementations of the standard L<POSIX|POSIX> 130f3efcd01Safresh1#pod tmpnam() and tmpfile() functions are provided if required. 131f3efcd01Safresh1#pod 132f3efcd01Safresh1#pod Implementations of mktemp(), tmpnam(), and tempnam() are provided, 133f3efcd01Safresh1#pod but should be used with caution since they return only a filename 134f3efcd01Safresh1#pod that was valid when function was called, so cannot guarantee 135f3efcd01Safresh1#pod that the file will not exist by the time the caller opens the filename. 136f3efcd01Safresh1#pod 137f3efcd01Safresh1#pod Filehandles returned by these functions support the seekable methods. 138f3efcd01Safresh1#pod 139f3efcd01Safresh1#pod =cut 14091f110e0Safresh1 1416fb12b70Safresh1# Toolchain targets v5.8.1, but we'll try to support back to v5.6 anyway. 1426fb12b70Safresh1# It might be possible to make this v5.5, but many v5.6isms are creeping 1436fb12b70Safresh1# into the code and tests. 1446fb12b70Safresh1use 5.006; 14591f110e0Safresh1use strict; 14691f110e0Safresh1use Carp; 14791f110e0Safresh1use File::Spec 0.8; 14891f110e0Safresh1use Cwd (); 1496fb12b70Safresh1use File::Path 2.06 qw/ rmtree /; 15091f110e0Safresh1use Fcntl 1.03; 15191f110e0Safresh1use IO::Seekable; # For SEEK_* 15291f110e0Safresh1use Errno; 15391f110e0Safresh1use Scalar::Util 'refaddr'; 15491f110e0Safresh1require VMS::Stdio if $^O eq 'VMS'; 15591f110e0Safresh1 15691f110e0Safresh1# pre-emptively load Carp::Heavy. If we don't when we run out of file 15791f110e0Safresh1# handles and attempt to call croak() we get an error message telling 15891f110e0Safresh1# us that Carp::Heavy won't load rather than an error telling us we 15991f110e0Safresh1# have run out of file handles. We either preload croak() or we 16091f110e0Safresh1# switch the calls to croak from _gettemp() to use die. 16191f110e0Safresh1eval { require Carp::Heavy; }; 16291f110e0Safresh1 16391f110e0Safresh1# Need the Symbol package if we are running older perl 16491f110e0Safresh1require Symbol if $] < 5.006; 16591f110e0Safresh1 16691f110e0Safresh1### For the OO interface 1676fb12b70Safresh1use parent 0.221 qw/ IO::Handle IO::Seekable /; 16891f110e0Safresh1use overload '""' => "STRINGIFY", '0+' => "NUMIFY", 16991f110e0Safresh1 fallback => 1; 17091f110e0Safresh1 171f3efcd01Safresh1our $DEBUG = 0; 172f3efcd01Safresh1our $KEEP_ALL = 0; 17391f110e0Safresh1 17491f110e0Safresh1# We are exporting functions 17591f110e0Safresh1 1766fb12b70Safresh1use Exporter 5.57 'import'; # 5.57 lets us import 'import' 17791f110e0Safresh1 17891f110e0Safresh1# Export list - to allow fine tuning of export table 17991f110e0Safresh1 180f3efcd01Safresh1our @EXPORT_OK = qw{ 18191f110e0Safresh1 tempfile 18291f110e0Safresh1 tempdir 18391f110e0Safresh1 tmpnam 18491f110e0Safresh1 tmpfile 18591f110e0Safresh1 mktemp 18691f110e0Safresh1 mkstemp 18791f110e0Safresh1 mkstemps 18891f110e0Safresh1 mkdtemp 18991f110e0Safresh1 unlink0 19091f110e0Safresh1 cleanup 19191f110e0Safresh1 SEEK_SET 19291f110e0Safresh1 SEEK_CUR 19391f110e0Safresh1 SEEK_END 19491f110e0Safresh1 }; 19591f110e0Safresh1 19691f110e0Safresh1# Groups of functions for export 19791f110e0Safresh1 198f3efcd01Safresh1our %EXPORT_TAGS = ( 19991f110e0Safresh1 'POSIX' => [qw/ tmpnam tmpfile /], 20091f110e0Safresh1 'mktemp' => [qw/ mktemp mkstemp mkstemps mkdtemp/], 20191f110e0Safresh1 'seekable' => [qw/ SEEK_SET SEEK_CUR SEEK_END /], 20291f110e0Safresh1 ); 20391f110e0Safresh1 20491f110e0Safresh1# add contents of these tags to @EXPORT 20591f110e0Safresh1Exporter::export_tags('POSIX','mktemp','seekable'); 20691f110e0Safresh1 20791f110e0Safresh1# This is a list of characters that can be used in random filenames 20891f110e0Safresh1 20991f110e0Safresh1my @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 21091f110e0Safresh1 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 21191f110e0Safresh1 0 1 2 3 4 5 6 7 8 9 _ 21291f110e0Safresh1 /); 21391f110e0Safresh1 21491f110e0Safresh1# Maximum number of tries to make a temp file before failing 21591f110e0Safresh1 21691f110e0Safresh1use constant MAX_TRIES => 1000; 21791f110e0Safresh1 21891f110e0Safresh1# Minimum number of X characters that should be in a template 21991f110e0Safresh1use constant MINX => 4; 22091f110e0Safresh1 22191f110e0Safresh1# Default template when no template supplied 22291f110e0Safresh1 22391f110e0Safresh1use constant TEMPXXX => 'X' x 10; 22491f110e0Safresh1 22591f110e0Safresh1# Constants for the security level 22691f110e0Safresh1 22791f110e0Safresh1use constant STANDARD => 0; 22891f110e0Safresh1use constant MEDIUM => 1; 22991f110e0Safresh1use constant HIGH => 2; 23091f110e0Safresh1 23191f110e0Safresh1# OPENFLAGS. If we defined the flag to use with Sysopen here this gives 23291f110e0Safresh1# us an optimisation when many temporary files are requested 23391f110e0Safresh1 23491f110e0Safresh1my $OPENFLAGS = O_CREAT | O_EXCL | O_RDWR; 23591f110e0Safresh1my $LOCKFLAG; 23691f110e0Safresh1 23791f110e0Safresh1unless ($^O eq 'MacOS') { 23891f110e0Safresh1 for my $oflag (qw/ NOFOLLOW BINARY LARGEFILE NOINHERIT /) { 23991f110e0Safresh1 my ($bit, $func) = (0, "Fcntl::O_" . $oflag); 24091f110e0Safresh1 no strict 'refs'; 24191f110e0Safresh1 $OPENFLAGS |= $bit if eval { 24291f110e0Safresh1 # Make sure that redefined die handlers do not cause problems 24391f110e0Safresh1 # e.g. CGI::Carp 24491f110e0Safresh1 local $SIG{__DIE__} = sub {}; 24591f110e0Safresh1 local $SIG{__WARN__} = sub {}; 24691f110e0Safresh1 $bit = &$func(); 24791f110e0Safresh1 1; 24891f110e0Safresh1 }; 24991f110e0Safresh1 } 25091f110e0Safresh1 # Special case O_EXLOCK 25191f110e0Safresh1 $LOCKFLAG = eval { 25291f110e0Safresh1 local $SIG{__DIE__} = sub {}; 25391f110e0Safresh1 local $SIG{__WARN__} = sub {}; 25491f110e0Safresh1 &Fcntl::O_EXLOCK(); 25591f110e0Safresh1 }; 25691f110e0Safresh1} 25791f110e0Safresh1 25891f110e0Safresh1# On some systems the O_TEMPORARY flag can be used to tell the OS 25991f110e0Safresh1# to automatically remove the file when it is closed. This is fine 26091f110e0Safresh1# in most cases but not if tempfile is called with UNLINK=>0 and 26191f110e0Safresh1# the filename is requested -- in the case where the filename is to 26291f110e0Safresh1# be passed to another routine. This happens on windows. We overcome 26391f110e0Safresh1# this by using a second open flags variable 26491f110e0Safresh1 26591f110e0Safresh1my $OPENTEMPFLAGS = $OPENFLAGS; 26691f110e0Safresh1unless ($^O eq 'MacOS') { 26791f110e0Safresh1 for my $oflag (qw/ TEMPORARY /) { 26891f110e0Safresh1 my ($bit, $func) = (0, "Fcntl::O_" . $oflag); 26991f110e0Safresh1 local($@); 27091f110e0Safresh1 no strict 'refs'; 27191f110e0Safresh1 $OPENTEMPFLAGS |= $bit if eval { 27291f110e0Safresh1 # Make sure that redefined die handlers do not cause problems 27391f110e0Safresh1 # e.g. CGI::Carp 27491f110e0Safresh1 local $SIG{__DIE__} = sub {}; 27591f110e0Safresh1 local $SIG{__WARN__} = sub {}; 27691f110e0Safresh1 $bit = &$func(); 27791f110e0Safresh1 1; 27891f110e0Safresh1 }; 27991f110e0Safresh1 } 28091f110e0Safresh1} 28191f110e0Safresh1 28291f110e0Safresh1# Private hash tracking which files have been created by each process id via the OO interface 28391f110e0Safresh1my %FILES_CREATED_BY_OBJECT; 28491f110e0Safresh1 28591f110e0Safresh1# INTERNAL ROUTINES - not to be used outside of package 28691f110e0Safresh1 28791f110e0Safresh1# Generic routine for getting a temporary filename 28891f110e0Safresh1# modelled on OpenBSD _gettemp() in mktemp.c 28991f110e0Safresh1 29091f110e0Safresh1# The template must contain X's that are to be replaced 29191f110e0Safresh1# with the random values 29291f110e0Safresh1 29391f110e0Safresh1# Arguments: 29491f110e0Safresh1 29591f110e0Safresh1# TEMPLATE - string containing the XXXXX's that is converted 29691f110e0Safresh1# to a random filename and opened if required 29791f110e0Safresh1 29891f110e0Safresh1# Optionally, a hash can also be supplied containing specific options 29991f110e0Safresh1# "open" => if true open the temp file, else just return the name 30091f110e0Safresh1# default is 0 30191f110e0Safresh1# "mkdir"=> if true, we are creating a temp directory rather than tempfile 30291f110e0Safresh1# default is 0 30391f110e0Safresh1# "suffixlen" => number of characters at end of PATH to be ignored. 30491f110e0Safresh1# default is 0. 30591f110e0Safresh1# "unlink_on_close" => indicates that, if possible, the OS should remove 30691f110e0Safresh1# the file as soon as it is closed. Usually indicates 30791f110e0Safresh1# use of the O_TEMPORARY flag to sysopen. 30891f110e0Safresh1# Usually irrelevant on unix 309f3efcd01Safresh1# "use_exlock" => Indicates that O_EXLOCK should be used. Default is false. 310*256a93a4Safresh1# "file_permissions" => file permissions for sysopen(). Default is 0600. 31191f110e0Safresh1 31291f110e0Safresh1# Optionally a reference to a scalar can be passed into the function 31391f110e0Safresh1# On error this will be used to store the reason for the error 31491f110e0Safresh1# "ErrStr" => \$errstr 31591f110e0Safresh1 31691f110e0Safresh1# "open" and "mkdir" can not both be true 31791f110e0Safresh1# "unlink_on_close" is not used when "mkdir" is true. 31891f110e0Safresh1 31991f110e0Safresh1# The default options are equivalent to mktemp(). 32091f110e0Safresh1 32191f110e0Safresh1# Returns: 32291f110e0Safresh1# filehandle - open file handle (if called with doopen=1, else undef) 32391f110e0Safresh1# temp name - name of the temp file or directory 32491f110e0Safresh1 32591f110e0Safresh1# For example: 32691f110e0Safresh1# ($fh, $name) = _gettemp($template, "open" => 1); 32791f110e0Safresh1 32891f110e0Safresh1# for the current version, failures are associated with 32991f110e0Safresh1# stored in an error string and returned to give the reason whilst debugging 33091f110e0Safresh1# This routine is not called by any external function 33191f110e0Safresh1sub _gettemp { 33291f110e0Safresh1 33391f110e0Safresh1 croak 'Usage: ($fh, $name) = _gettemp($template, OPTIONS);' 33491f110e0Safresh1 unless scalar(@_) >= 1; 33591f110e0Safresh1 33691f110e0Safresh1 # the internal error string - expect it to be overridden 33791f110e0Safresh1 # Need this in case the caller decides not to supply us a value 33891f110e0Safresh1 # need an anonymous scalar 33991f110e0Safresh1 my $tempErrStr; 34091f110e0Safresh1 34191f110e0Safresh1 # Default options 34291f110e0Safresh1 my %options = ( 34391f110e0Safresh1 "open" => 0, 34491f110e0Safresh1 "mkdir" => 0, 34591f110e0Safresh1 "suffixlen" => 0, 34691f110e0Safresh1 "unlink_on_close" => 0, 347f3efcd01Safresh1 "use_exlock" => 0, 34891f110e0Safresh1 "ErrStr" => \$tempErrStr, 349*256a93a4Safresh1 "file_permissions" => undef, 35091f110e0Safresh1 ); 35191f110e0Safresh1 35291f110e0Safresh1 # Read the template 35391f110e0Safresh1 my $template = shift; 35491f110e0Safresh1 if (ref($template)) { 35591f110e0Safresh1 # Use a warning here since we have not yet merged ErrStr 35691f110e0Safresh1 carp "File::Temp::_gettemp: template must not be a reference"; 35791f110e0Safresh1 return (); 35891f110e0Safresh1 } 35991f110e0Safresh1 36091f110e0Safresh1 # Check that the number of entries on stack are even 36191f110e0Safresh1 if (scalar(@_) % 2 != 0) { 36291f110e0Safresh1 # Use a warning here since we have not yet merged ErrStr 36391f110e0Safresh1 carp "File::Temp::_gettemp: Must have even number of options"; 36491f110e0Safresh1 return (); 36591f110e0Safresh1 } 36691f110e0Safresh1 36791f110e0Safresh1 # Read the options and merge with defaults 36891f110e0Safresh1 %options = (%options, @_) if @_; 36991f110e0Safresh1 37091f110e0Safresh1 # Make sure the error string is set to undef 37191f110e0Safresh1 ${$options{ErrStr}} = undef; 37291f110e0Safresh1 37391f110e0Safresh1 # Can not open the file and make a directory in a single call 37491f110e0Safresh1 if ($options{"open"} && $options{"mkdir"}) { 37591f110e0Safresh1 ${$options{ErrStr}} = "doopen and domkdir can not both be true\n"; 37691f110e0Safresh1 return (); 37791f110e0Safresh1 } 37891f110e0Safresh1 37991f110e0Safresh1 # Find the start of the end of the Xs (position of last X) 38091f110e0Safresh1 # Substr starts from 0 38191f110e0Safresh1 my $start = length($template) - 1 - $options{"suffixlen"}; 38291f110e0Safresh1 38391f110e0Safresh1 # Check that we have at least MINX x X (e.g. 'XXXX") at the end of the string 38491f110e0Safresh1 # (taking suffixlen into account). Any fewer is insecure. 38591f110e0Safresh1 38691f110e0Safresh1 # Do it using substr - no reason to use a pattern match since 38791f110e0Safresh1 # we know where we are looking and what we are looking for 38891f110e0Safresh1 38991f110e0Safresh1 if (substr($template, $start - MINX + 1, MINX) ne 'X' x MINX) { 39091f110e0Safresh1 ${$options{ErrStr}} = "The template must end with at least ". 39191f110e0Safresh1 MINX . " 'X' characters\n"; 39291f110e0Safresh1 return (); 39391f110e0Safresh1 } 39491f110e0Safresh1 39591f110e0Safresh1 # Replace all the X at the end of the substring with a 39691f110e0Safresh1 # random character or just all the XX at the end of a full string. 39791f110e0Safresh1 # Do it as an if, since the suffix adjusts which section to replace 39891f110e0Safresh1 # and suffixlen=0 returns nothing if used in the substr directly 39991f110e0Safresh1 # and generate a full path from the template 40091f110e0Safresh1 40191f110e0Safresh1 my $path = _replace_XX($template, $options{"suffixlen"}); 40291f110e0Safresh1 40391f110e0Safresh1 40491f110e0Safresh1 # Split the path into constituent parts - eventually we need to check 40591f110e0Safresh1 # whether the directory exists 40691f110e0Safresh1 # We need to know whether we are making a temp directory 40791f110e0Safresh1 # or a tempfile 40891f110e0Safresh1 40991f110e0Safresh1 my ($volume, $directories, $file); 41091f110e0Safresh1 my $parent; # parent directory 41191f110e0Safresh1 if ($options{"mkdir"}) { 41291f110e0Safresh1 # There is no filename at the end 41391f110e0Safresh1 ($volume, $directories, $file) = File::Spec->splitpath( $path, 1); 41491f110e0Safresh1 41591f110e0Safresh1 # The parent is then $directories without the last directory 41691f110e0Safresh1 # Split the directory and put it back together again 41791f110e0Safresh1 my @dirs = File::Spec->splitdir($directories); 41891f110e0Safresh1 41991f110e0Safresh1 # If @dirs only has one entry (i.e. the directory template) that means 42091f110e0Safresh1 # we are in the current directory 42191f110e0Safresh1 if ($#dirs == 0) { 42291f110e0Safresh1 $parent = File::Spec->curdir; 42391f110e0Safresh1 } else { 42491f110e0Safresh1 42591f110e0Safresh1 if ($^O eq 'VMS') { # need volume to avoid relative dir spec 42691f110e0Safresh1 $parent = File::Spec->catdir($volume, @dirs[0..$#dirs-1]); 42791f110e0Safresh1 $parent = 'sys$disk:[]' if $parent eq ''; 42891f110e0Safresh1 } else { 42991f110e0Safresh1 43091f110e0Safresh1 # Put it back together without the last one 43191f110e0Safresh1 $parent = File::Spec->catdir(@dirs[0..$#dirs-1]); 43291f110e0Safresh1 43391f110e0Safresh1 # ...and attach the volume (no filename) 43491f110e0Safresh1 $parent = File::Spec->catpath($volume, $parent, ''); 43591f110e0Safresh1 } 43691f110e0Safresh1 43791f110e0Safresh1 } 43891f110e0Safresh1 43991f110e0Safresh1 } else { 44091f110e0Safresh1 44191f110e0Safresh1 # Get rid of the last filename (use File::Basename for this?) 44291f110e0Safresh1 ($volume, $directories, $file) = File::Spec->splitpath( $path ); 44391f110e0Safresh1 44491f110e0Safresh1 # Join up without the file part 44591f110e0Safresh1 $parent = File::Spec->catpath($volume,$directories,''); 44691f110e0Safresh1 44791f110e0Safresh1 # If $parent is empty replace with curdir 44891f110e0Safresh1 $parent = File::Spec->curdir 44991f110e0Safresh1 unless $directories ne ''; 45091f110e0Safresh1 45191f110e0Safresh1 } 45291f110e0Safresh1 45391f110e0Safresh1 # Check that the parent directories exist 45491f110e0Safresh1 # Do this even for the case where we are simply returning a name 45591f110e0Safresh1 # not a file -- no point returning a name that includes a directory 45691f110e0Safresh1 # that does not exist or is not writable 45791f110e0Safresh1 45891f110e0Safresh1 unless (-e $parent) { 45991f110e0Safresh1 ${$options{ErrStr}} = "Parent directory ($parent) does not exist"; 46091f110e0Safresh1 return (); 46191f110e0Safresh1 } 46291f110e0Safresh1 unless (-d $parent) { 46391f110e0Safresh1 ${$options{ErrStr}} = "Parent directory ($parent) is not a directory"; 46491f110e0Safresh1 return (); 46591f110e0Safresh1 } 46691f110e0Safresh1 46791f110e0Safresh1 # Check the stickiness of the directory and chown giveaway if required 46891f110e0Safresh1 # If the directory is world writable the sticky bit 46991f110e0Safresh1 # must be set 47091f110e0Safresh1 47191f110e0Safresh1 if (File::Temp->safe_level == MEDIUM) { 47291f110e0Safresh1 my $safeerr; 47391f110e0Safresh1 unless (_is_safe($parent,\$safeerr)) { 47491f110e0Safresh1 ${$options{ErrStr}} = "Parent directory ($parent) is not safe ($safeerr)"; 47591f110e0Safresh1 return (); 47691f110e0Safresh1 } 47791f110e0Safresh1 } elsif (File::Temp->safe_level == HIGH) { 47891f110e0Safresh1 my $safeerr; 47991f110e0Safresh1 unless (_is_verysafe($parent, \$safeerr)) { 48091f110e0Safresh1 ${$options{ErrStr}} = "Parent directory ($parent) is not safe ($safeerr)"; 48191f110e0Safresh1 return (); 48291f110e0Safresh1 } 48391f110e0Safresh1 } 48491f110e0Safresh1 485*256a93a4Safresh1 my $perms = $options{file_permissions}; 486*256a93a4Safresh1 my $has_perms = defined $perms; 487*256a93a4Safresh1 $perms = 0600 unless $has_perms; 48891f110e0Safresh1 48991f110e0Safresh1 # Now try MAX_TRIES time to open the file 49091f110e0Safresh1 for (my $i = 0; $i < MAX_TRIES; $i++) { 49191f110e0Safresh1 49291f110e0Safresh1 # Try to open the file if requested 49391f110e0Safresh1 if ($options{"open"}) { 49491f110e0Safresh1 my $fh; 49591f110e0Safresh1 49691f110e0Safresh1 # If we are running before perl5.6.0 we can not auto-vivify 49791f110e0Safresh1 if ($] < 5.006) { 49891f110e0Safresh1 $fh = &Symbol::gensym; 49991f110e0Safresh1 } 50091f110e0Safresh1 50191f110e0Safresh1 # Try to make sure this will be marked close-on-exec 50291f110e0Safresh1 # XXX: Win32 doesn't respect this, nor the proper fcntl, 50391f110e0Safresh1 # but may have O_NOINHERIT. This may or may not be in Fcntl. 50491f110e0Safresh1 local $^F = 2; 50591f110e0Safresh1 50691f110e0Safresh1 # Attempt to open the file 50791f110e0Safresh1 my $open_success = undef; 50891f110e0Safresh1 if ( $^O eq 'VMS' and $options{"unlink_on_close"} && !$KEEP_ALL) { 50991f110e0Safresh1 # make it auto delete on close by setting FAB$V_DLT bit 510*256a93a4Safresh1 $fh = VMS::Stdio::vmssysopen($path, $OPENFLAGS, $perms, 'fop=dlt'); 51191f110e0Safresh1 $open_success = $fh; 51291f110e0Safresh1 } else { 51391f110e0Safresh1 my $flags = ( ($options{"unlink_on_close"} && !$KEEP_ALL) ? 51491f110e0Safresh1 $OPENTEMPFLAGS : 51591f110e0Safresh1 $OPENFLAGS ); 51691f110e0Safresh1 $flags |= $LOCKFLAG if (defined $LOCKFLAG && $options{use_exlock}); 517*256a93a4Safresh1 $open_success = sysopen($fh, $path, $flags, $perms); 51891f110e0Safresh1 } 51991f110e0Safresh1 if ( $open_success ) { 52091f110e0Safresh1 52191f110e0Safresh1 # in case of odd umask force rw 522*256a93a4Safresh1 chmod($perms, $path) unless $has_perms; 52391f110e0Safresh1 52491f110e0Safresh1 # Opened successfully - return file handle and name 52591f110e0Safresh1 return ($fh, $path); 52691f110e0Safresh1 52791f110e0Safresh1 } else { 52891f110e0Safresh1 52991f110e0Safresh1 # Error opening file - abort with error 53091f110e0Safresh1 # if the reason was anything but EEXIST 53191f110e0Safresh1 unless ($!{EEXIST}) { 53291f110e0Safresh1 ${$options{ErrStr}} = "Could not create temp file $path: $!"; 53391f110e0Safresh1 return (); 53491f110e0Safresh1 } 53591f110e0Safresh1 53691f110e0Safresh1 # Loop round for another try 53791f110e0Safresh1 53891f110e0Safresh1 } 53991f110e0Safresh1 } elsif ($options{"mkdir"}) { 54091f110e0Safresh1 54191f110e0Safresh1 # Open the temp directory 54291f110e0Safresh1 if (mkdir( $path, 0700)) { 54391f110e0Safresh1 # in case of odd umask 54491f110e0Safresh1 chmod(0700, $path); 54591f110e0Safresh1 54691f110e0Safresh1 return undef, $path; 54791f110e0Safresh1 } else { 54891f110e0Safresh1 54991f110e0Safresh1 # Abort with error if the reason for failure was anything 55091f110e0Safresh1 # except EEXIST 55191f110e0Safresh1 unless ($!{EEXIST}) { 55291f110e0Safresh1 ${$options{ErrStr}} = "Could not create directory $path: $!"; 55391f110e0Safresh1 return (); 55491f110e0Safresh1 } 55591f110e0Safresh1 55691f110e0Safresh1 # Loop round for another try 55791f110e0Safresh1 55891f110e0Safresh1 } 55991f110e0Safresh1 56091f110e0Safresh1 } else { 56191f110e0Safresh1 56291f110e0Safresh1 # Return true if the file can not be found 56391f110e0Safresh1 # Directory has been checked previously 56491f110e0Safresh1 56591f110e0Safresh1 return (undef, $path) unless -e $path; 56691f110e0Safresh1 56791f110e0Safresh1 # Try again until MAX_TRIES 56891f110e0Safresh1 56991f110e0Safresh1 } 57091f110e0Safresh1 57191f110e0Safresh1 # Did not successfully open the tempfile/dir 57291f110e0Safresh1 # so try again with a different set of random letters 57391f110e0Safresh1 # No point in trying to increment unless we have only 57491f110e0Safresh1 # 1 X say and the randomness could come up with the same 57591f110e0Safresh1 # file MAX_TRIES in a row. 57691f110e0Safresh1 577f3efcd01Safresh1 # Store current attempt - in principle this implies that the 57891f110e0Safresh1 # 3rd time around the open attempt that the first temp file 57991f110e0Safresh1 # name could be generated again. Probably should store each 58091f110e0Safresh1 # attempt and make sure that none are repeated 58191f110e0Safresh1 58291f110e0Safresh1 my $original = $path; 58391f110e0Safresh1 my $counter = 0; # Stop infinite loop 58491f110e0Safresh1 my $MAX_GUESS = 50; 58591f110e0Safresh1 58691f110e0Safresh1 do { 58791f110e0Safresh1 58891f110e0Safresh1 # Generate new name from original template 58991f110e0Safresh1 $path = _replace_XX($template, $options{"suffixlen"}); 59091f110e0Safresh1 59191f110e0Safresh1 $counter++; 59291f110e0Safresh1 59391f110e0Safresh1 } until ($path ne $original || $counter > $MAX_GUESS); 59491f110e0Safresh1 59591f110e0Safresh1 # Check for out of control looping 59691f110e0Safresh1 if ($counter > $MAX_GUESS) { 59791f110e0Safresh1 ${$options{ErrStr}} = "Tried to get a new temp name different to the previous value $MAX_GUESS times.\nSomething wrong with template?? ($template)"; 59891f110e0Safresh1 return (); 59991f110e0Safresh1 } 60091f110e0Safresh1 60191f110e0Safresh1 } 60291f110e0Safresh1 60391f110e0Safresh1 # If we get here, we have run out of tries 60491f110e0Safresh1 ${ $options{ErrStr} } = "Have exceeded the maximum number of attempts (" 60591f110e0Safresh1 . MAX_TRIES . ") to open temp file/dir"; 60691f110e0Safresh1 60791f110e0Safresh1 return (); 60891f110e0Safresh1 60991f110e0Safresh1} 61091f110e0Safresh1 61191f110e0Safresh1# Internal routine to replace the XXXX... with random characters 61291f110e0Safresh1# This has to be done by _gettemp() every time it fails to 61391f110e0Safresh1# open a temp file/dir 61491f110e0Safresh1 61591f110e0Safresh1# Arguments: $template (the template with XXX), 61691f110e0Safresh1# $ignore (number of characters at end to ignore) 61791f110e0Safresh1 61891f110e0Safresh1# Returns: modified template 61991f110e0Safresh1 62091f110e0Safresh1sub _replace_XX { 62191f110e0Safresh1 62291f110e0Safresh1 croak 'Usage: _replace_XX($template, $ignore)' 62391f110e0Safresh1 unless scalar(@_) == 2; 62491f110e0Safresh1 62591f110e0Safresh1 my ($path, $ignore) = @_; 62691f110e0Safresh1 62791f110e0Safresh1 # Do it as an if, since the suffix adjusts which section to replace 62891f110e0Safresh1 # and suffixlen=0 returns nothing if used in the substr directly 62991f110e0Safresh1 # Alternatively, could simply set $ignore to length($path)-1 63091f110e0Safresh1 # Don't want to always use substr when not required though. 63191f110e0Safresh1 my $end = ( $] >= 5.006 ? "\\z" : "\\Z" ); 63291f110e0Safresh1 63391f110e0Safresh1 if ($ignore) { 63491f110e0Safresh1 substr($path, 0, - $ignore) =~ s/X(?=X*$end)/$CHARS[ int( rand( @CHARS ) ) ]/ge; 63591f110e0Safresh1 } else { 63691f110e0Safresh1 $path =~ s/X(?=X*$end)/$CHARS[ int( rand( @CHARS ) ) ]/ge; 63791f110e0Safresh1 } 63891f110e0Safresh1 return $path; 63991f110e0Safresh1} 64091f110e0Safresh1 64191f110e0Safresh1# Internal routine to force a temp file to be writable after 64291f110e0Safresh1# it is created so that we can unlink it. Windows seems to occasionally 64391f110e0Safresh1# force a file to be readonly when written to certain temp locations 64491f110e0Safresh1sub _force_writable { 64591f110e0Safresh1 my $file = shift; 64691f110e0Safresh1 chmod 0600, $file; 64791f110e0Safresh1} 64891f110e0Safresh1 64991f110e0Safresh1 65091f110e0Safresh1# internal routine to check to see if the directory is safe 65191f110e0Safresh1# First checks to see if the directory is not owned by the 65291f110e0Safresh1# current user or root. Then checks to see if anyone else 65391f110e0Safresh1# can write to the directory and if so, checks to see if 65491f110e0Safresh1# it has the sticky bit set 65591f110e0Safresh1 65691f110e0Safresh1# Will not work on systems that do not support sticky bit 65791f110e0Safresh1 65891f110e0Safresh1#Args: directory path to check 65991f110e0Safresh1# Optionally: reference to scalar to contain error message 66091f110e0Safresh1# Returns true if the path is safe and false otherwise. 66191f110e0Safresh1# Returns undef if can not even run stat() on the path 66291f110e0Safresh1 66391f110e0Safresh1# This routine based on version written by Tom Christiansen 66491f110e0Safresh1 66591f110e0Safresh1# Presumably, by the time we actually attempt to create the 66691f110e0Safresh1# file or directory in this directory, it may not be safe 66791f110e0Safresh1# anymore... Have to run _is_safe directly after the open. 66891f110e0Safresh1 66991f110e0Safresh1sub _is_safe { 67091f110e0Safresh1 67191f110e0Safresh1 my $path = shift; 67291f110e0Safresh1 my $err_ref = shift; 67391f110e0Safresh1 67491f110e0Safresh1 # Stat path 67591f110e0Safresh1 my @info = stat($path); 67691f110e0Safresh1 unless (scalar(@info)) { 67791f110e0Safresh1 $$err_ref = "stat(path) returned no values"; 67891f110e0Safresh1 return 0; 67991f110e0Safresh1 } 68091f110e0Safresh1 ; 68191f110e0Safresh1 return 1 if $^O eq 'VMS'; # owner delete control at file level 68291f110e0Safresh1 68391f110e0Safresh1 # Check to see whether owner is neither superuser (or a system uid) nor me 68491f110e0Safresh1 # Use the effective uid from the $> variable 68591f110e0Safresh1 # UID is in [4] 68691f110e0Safresh1 if ($info[4] > File::Temp->top_system_uid() && $info[4] != $>) { 68791f110e0Safresh1 68891f110e0Safresh1 Carp::cluck(sprintf "uid=$info[4] topuid=%s euid=$> path='$path'", 68991f110e0Safresh1 File::Temp->top_system_uid()); 69091f110e0Safresh1 69191f110e0Safresh1 $$err_ref = "Directory owned neither by root nor the current user" 69291f110e0Safresh1 if ref($err_ref); 69391f110e0Safresh1 return 0; 69491f110e0Safresh1 } 69591f110e0Safresh1 69691f110e0Safresh1 # check whether group or other can write file 69791f110e0Safresh1 # use 066 to detect either reading or writing 69891f110e0Safresh1 # use 022 to check writability 69991f110e0Safresh1 # Do it with S_IWOTH and S_IWGRP for portability (maybe) 70091f110e0Safresh1 # mode is in info[2] 70191f110e0Safresh1 if (($info[2] & &Fcntl::S_IWGRP) || # Is group writable? 70291f110e0Safresh1 ($info[2] & &Fcntl::S_IWOTH) ) { # Is world writable? 70391f110e0Safresh1 # Must be a directory 70491f110e0Safresh1 unless (-d $path) { 70591f110e0Safresh1 $$err_ref = "Path ($path) is not a directory" 70691f110e0Safresh1 if ref($err_ref); 70791f110e0Safresh1 return 0; 70891f110e0Safresh1 } 70991f110e0Safresh1 # Must have sticky bit set 71091f110e0Safresh1 unless (-k $path) { 71191f110e0Safresh1 $$err_ref = "Sticky bit not set on $path when dir is group|world writable" 71291f110e0Safresh1 if ref($err_ref); 71391f110e0Safresh1 return 0; 71491f110e0Safresh1 } 71591f110e0Safresh1 } 71691f110e0Safresh1 71791f110e0Safresh1 return 1; 71891f110e0Safresh1} 71991f110e0Safresh1 72091f110e0Safresh1# Internal routine to check whether a directory is safe 72191f110e0Safresh1# for temp files. Safer than _is_safe since it checks for 72291f110e0Safresh1# the possibility of chown giveaway and if that is a possibility 72391f110e0Safresh1# checks each directory in the path to see if it is safe (with _is_safe) 72491f110e0Safresh1 72591f110e0Safresh1# If _PC_CHOWN_RESTRICTED is not set, does the full test of each 72691f110e0Safresh1# directory anyway. 72791f110e0Safresh1 72891f110e0Safresh1# Takes optional second arg as scalar ref to error reason 72991f110e0Safresh1 73091f110e0Safresh1sub _is_verysafe { 73191f110e0Safresh1 73291f110e0Safresh1 # Need POSIX - but only want to bother if really necessary due to overhead 73391f110e0Safresh1 require POSIX; 73491f110e0Safresh1 73591f110e0Safresh1 my $path = shift; 73691f110e0Safresh1 print "_is_verysafe testing $path\n" if $DEBUG; 73791f110e0Safresh1 return 1 if $^O eq 'VMS'; # owner delete control at file level 73891f110e0Safresh1 73991f110e0Safresh1 my $err_ref = shift; 74091f110e0Safresh1 74191f110e0Safresh1 # Should Get the value of _PC_CHOWN_RESTRICTED if it is defined 74291f110e0Safresh1 # and If it is not there do the extensive test 74391f110e0Safresh1 local($@); 74491f110e0Safresh1 my $chown_restricted; 74591f110e0Safresh1 $chown_restricted = &POSIX::_PC_CHOWN_RESTRICTED() 74691f110e0Safresh1 if eval { &POSIX::_PC_CHOWN_RESTRICTED(); 1}; 74791f110e0Safresh1 74891f110e0Safresh1 # If chown_resticted is set to some value we should test it 74991f110e0Safresh1 if (defined $chown_restricted) { 75091f110e0Safresh1 75191f110e0Safresh1 # Return if the current directory is safe 75291f110e0Safresh1 return _is_safe($path,$err_ref) if POSIX::sysconf( $chown_restricted ); 75391f110e0Safresh1 75491f110e0Safresh1 } 75591f110e0Safresh1 75691f110e0Safresh1 # To reach this point either, the _PC_CHOWN_RESTRICTED symbol 75791f110e0Safresh1 # was not available or the symbol was there but chown giveaway 75891f110e0Safresh1 # is allowed. Either way, we now have to test the entire tree for 75991f110e0Safresh1 # safety. 76091f110e0Safresh1 76191f110e0Safresh1 # Convert path to an absolute directory if required 76291f110e0Safresh1 unless (File::Spec->file_name_is_absolute($path)) { 76391f110e0Safresh1 $path = File::Spec->rel2abs($path); 76491f110e0Safresh1 } 76591f110e0Safresh1 76691f110e0Safresh1 # Split directory into components - assume no file 76791f110e0Safresh1 my ($volume, $directories, undef) = File::Spec->splitpath( $path, 1); 76891f110e0Safresh1 76991f110e0Safresh1 # Slightly less efficient than having a function in File::Spec 77091f110e0Safresh1 # to chop off the end of a directory or even a function that 77191f110e0Safresh1 # can handle ../ in a directory tree 77291f110e0Safresh1 # Sometimes splitdir() returns a blank at the end 77391f110e0Safresh1 # so we will probably check the bottom directory twice in some cases 77491f110e0Safresh1 my @dirs = File::Spec->splitdir($directories); 77591f110e0Safresh1 77691f110e0Safresh1 # Concatenate one less directory each time around 77791f110e0Safresh1 foreach my $pos (0.. $#dirs) { 77891f110e0Safresh1 # Get a directory name 77991f110e0Safresh1 my $dir = File::Spec->catpath($volume, 78091f110e0Safresh1 File::Spec->catdir(@dirs[0.. $#dirs - $pos]), 78191f110e0Safresh1 '' 78291f110e0Safresh1 ); 78391f110e0Safresh1 78491f110e0Safresh1 print "TESTING DIR $dir\n" if $DEBUG; 78591f110e0Safresh1 78691f110e0Safresh1 # Check the directory 78791f110e0Safresh1 return 0 unless _is_safe($dir,$err_ref); 78891f110e0Safresh1 78991f110e0Safresh1 } 79091f110e0Safresh1 79191f110e0Safresh1 return 1; 79291f110e0Safresh1} 79391f110e0Safresh1 79491f110e0Safresh1 79591f110e0Safresh1 79691f110e0Safresh1# internal routine to determine whether unlink works on this 79791f110e0Safresh1# platform for files that are currently open. 79891f110e0Safresh1# Returns true if we can, false otherwise. 79991f110e0Safresh1 80091f110e0Safresh1# Currently WinNT, OS/2 and VMS can not unlink an opened file 80191f110e0Safresh1# On VMS this is because the O_EXCL flag is used to open the 80291f110e0Safresh1# temporary file. Currently I do not know enough about the issues 80391f110e0Safresh1# on VMS to decide whether O_EXCL is a requirement. 80491f110e0Safresh1 80591f110e0Safresh1sub _can_unlink_opened_file { 80691f110e0Safresh1 807*256a93a4Safresh1 if (grep $^O eq $_, qw/MSWin32 os2 VMS dos MacOS haiku/) { 80891f110e0Safresh1 return 0; 80991f110e0Safresh1 } else { 81091f110e0Safresh1 return 1; 81191f110e0Safresh1 } 81291f110e0Safresh1 81391f110e0Safresh1} 81491f110e0Safresh1 81591f110e0Safresh1# internal routine to decide which security levels are allowed 81691f110e0Safresh1# see safe_level() for more information on this 81791f110e0Safresh1 81891f110e0Safresh1# Controls whether the supplied security level is allowed 81991f110e0Safresh1 82091f110e0Safresh1# $cando = _can_do_level( $level ) 82191f110e0Safresh1 82291f110e0Safresh1sub _can_do_level { 82391f110e0Safresh1 82491f110e0Safresh1 # Get security level 82591f110e0Safresh1 my $level = shift; 82691f110e0Safresh1 82791f110e0Safresh1 # Always have to be able to do STANDARD 82891f110e0Safresh1 return 1 if $level == STANDARD; 82991f110e0Safresh1 83091f110e0Safresh1 # Currently, the systems that can do HIGH or MEDIUM are identical 83191f110e0Safresh1 if ( $^O eq 'MSWin32' || $^O eq 'os2' || $^O eq 'cygwin' || $^O eq 'dos' || $^O eq 'MacOS' || $^O eq 'mpeix') { 83291f110e0Safresh1 return 0; 83391f110e0Safresh1 } else { 83491f110e0Safresh1 return 1; 83591f110e0Safresh1 } 83691f110e0Safresh1 83791f110e0Safresh1} 83891f110e0Safresh1 83991f110e0Safresh1# This routine sets up a deferred unlinking of a specified 84091f110e0Safresh1# filename and filehandle. It is used in the following cases: 84191f110e0Safresh1# - Called by unlink0 if an opened file can not be unlinked 84291f110e0Safresh1# - Called by tempfile() if files are to be removed on shutdown 84391f110e0Safresh1# - Called by tempdir() if directories are to be removed on shutdown 84491f110e0Safresh1 84591f110e0Safresh1# Arguments: 84691f110e0Safresh1# _deferred_unlink( $fh, $fname, $isdir ); 84791f110e0Safresh1# 84891f110e0Safresh1# - filehandle (so that it can be explicitly closed if open 84991f110e0Safresh1# - filename (the thing we want to remove) 85091f110e0Safresh1# - isdir (flag to indicate that we are being given a directory) 85191f110e0Safresh1# [and hence no filehandle] 85291f110e0Safresh1 85391f110e0Safresh1# Status is not referred to since all the magic is done with an END block 85491f110e0Safresh1 85591f110e0Safresh1{ 85691f110e0Safresh1 # Will set up two lexical variables to contain all the files to be 85791f110e0Safresh1 # removed. One array for files, another for directories They will 85891f110e0Safresh1 # only exist in this block. 85991f110e0Safresh1 86091f110e0Safresh1 # This means we only have to set up a single END block to remove 86191f110e0Safresh1 # all files. 86291f110e0Safresh1 86391f110e0Safresh1 # in order to prevent child processes inadvertently deleting the parent 86491f110e0Safresh1 # temp files we use a hash to store the temp files and directories 86591f110e0Safresh1 # created by a particular process id. 86691f110e0Safresh1 86791f110e0Safresh1 # %files_to_unlink contains values that are references to an array of 86891f110e0Safresh1 # array references containing the filehandle and filename associated with 86991f110e0Safresh1 # the temp file. 87091f110e0Safresh1 my (%files_to_unlink, %dirs_to_unlink); 87191f110e0Safresh1 87291f110e0Safresh1 # Set up an end block to use these arrays 87391f110e0Safresh1 END { 87491f110e0Safresh1 local($., $@, $!, $^E, $?); 87591f110e0Safresh1 cleanup(at_exit => 1); 87691f110e0Safresh1 } 87791f110e0Safresh1 87891f110e0Safresh1 # Cleanup function. Always triggered on END (with at_exit => 1) but 87991f110e0Safresh1 # can be invoked manually. 88091f110e0Safresh1 sub cleanup { 88191f110e0Safresh1 my %h = @_; 88291f110e0Safresh1 my $at_exit = delete $h{at_exit}; 88391f110e0Safresh1 $at_exit = 0 if not defined $at_exit; 88491f110e0Safresh1 { my @k = sort keys %h; die "unrecognized parameters: @k" if @k } 88591f110e0Safresh1 88691f110e0Safresh1 if (!$KEEP_ALL) { 88791f110e0Safresh1 # Files 88891f110e0Safresh1 my @files = (exists $files_to_unlink{$$} ? 88991f110e0Safresh1 @{ $files_to_unlink{$$} } : () ); 89091f110e0Safresh1 foreach my $file (@files) { 89191f110e0Safresh1 # close the filehandle without checking its state 89291f110e0Safresh1 # in order to make real sure that this is closed 8936fb12b70Safresh1 # if its already closed then I don't care about the answer 89491f110e0Safresh1 # probably a better way to do this 89591f110e0Safresh1 close($file->[0]); # file handle is [0] 89691f110e0Safresh1 89791f110e0Safresh1 if (-f $file->[1]) { # file name is [1] 89891f110e0Safresh1 _force_writable( $file->[1] ); # for windows 89991f110e0Safresh1 unlink $file->[1] or warn "Error removing ".$file->[1]; 90091f110e0Safresh1 } 90191f110e0Safresh1 } 90291f110e0Safresh1 # Dirs 90391f110e0Safresh1 my @dirs = (exists $dirs_to_unlink{$$} ? 90491f110e0Safresh1 @{ $dirs_to_unlink{$$} } : () ); 90591f110e0Safresh1 my ($cwd, $cwd_to_remove); 90691f110e0Safresh1 foreach my $dir (@dirs) { 90791f110e0Safresh1 if (-d $dir) { 90891f110e0Safresh1 # Some versions of rmtree will abort if you attempt to remove 90991f110e0Safresh1 # the directory you are sitting in. For automatic cleanup 91091f110e0Safresh1 # at program exit, we avoid this by chdir()ing out of the way 91191f110e0Safresh1 # first. If not at program exit, it's best not to mess with the 91291f110e0Safresh1 # current directory, so just let it fail with a warning. 91391f110e0Safresh1 if ($at_exit) { 91491f110e0Safresh1 $cwd = Cwd::abs_path(File::Spec->curdir) if not defined $cwd; 91591f110e0Safresh1 my $abs = Cwd::abs_path($dir); 91691f110e0Safresh1 if ($abs eq $cwd) { 91791f110e0Safresh1 $cwd_to_remove = $dir; 91891f110e0Safresh1 next; 91991f110e0Safresh1 } 92091f110e0Safresh1 } 92191f110e0Safresh1 eval { rmtree($dir, $DEBUG, 0); }; 92291f110e0Safresh1 warn $@ if ($@ && $^W); 92391f110e0Safresh1 } 92491f110e0Safresh1 } 92591f110e0Safresh1 92691f110e0Safresh1 if (defined $cwd_to_remove) { 92791f110e0Safresh1 # We do need to clean up the current directory, and everything 92891f110e0Safresh1 # else is done, so get out of there and remove it. 92991f110e0Safresh1 chdir $cwd_to_remove or die "cannot chdir to $cwd_to_remove: $!"; 93091f110e0Safresh1 my $updir = File::Spec->updir; 93191f110e0Safresh1 chdir $updir or die "cannot chdir to $updir: $!"; 93291f110e0Safresh1 eval { rmtree($cwd_to_remove, $DEBUG, 0); }; 93391f110e0Safresh1 warn $@ if ($@ && $^W); 93491f110e0Safresh1 } 93591f110e0Safresh1 93691f110e0Safresh1 # clear the arrays 93791f110e0Safresh1 @{ $files_to_unlink{$$} } = () 93891f110e0Safresh1 if exists $files_to_unlink{$$}; 93991f110e0Safresh1 @{ $dirs_to_unlink{$$} } = () 94091f110e0Safresh1 if exists $dirs_to_unlink{$$}; 94191f110e0Safresh1 } 94291f110e0Safresh1 } 94391f110e0Safresh1 94491f110e0Safresh1 94591f110e0Safresh1 # This is the sub called to register a file for deferred unlinking 94691f110e0Safresh1 # This could simply store the input parameters and defer everything 94791f110e0Safresh1 # until the END block. For now we do a bit of checking at this 94891f110e0Safresh1 # point in order to make sure that (1) we have a file/dir to delete 94991f110e0Safresh1 # and (2) we have been called with the correct arguments. 95091f110e0Safresh1 sub _deferred_unlink { 95191f110e0Safresh1 95291f110e0Safresh1 croak 'Usage: _deferred_unlink($fh, $fname, $isdir)' 95391f110e0Safresh1 unless scalar(@_) == 3; 95491f110e0Safresh1 95591f110e0Safresh1 my ($fh, $fname, $isdir) = @_; 95691f110e0Safresh1 95791f110e0Safresh1 warn "Setting up deferred removal of $fname\n" 95891f110e0Safresh1 if $DEBUG; 95991f110e0Safresh1 96091f110e0Safresh1 # make sure we save the absolute path for later cleanup 96191f110e0Safresh1 # OK to untaint because we only ever use this internally 96291f110e0Safresh1 # as a file path, never interpolating into the shell 96391f110e0Safresh1 $fname = Cwd::abs_path($fname); 96491f110e0Safresh1 ($fname) = $fname =~ /^(.*)$/; 96591f110e0Safresh1 96691f110e0Safresh1 # If we have a directory, check that it is a directory 96791f110e0Safresh1 if ($isdir) { 96891f110e0Safresh1 96991f110e0Safresh1 if (-d $fname) { 97091f110e0Safresh1 97191f110e0Safresh1 # Directory exists so store it 97291f110e0Safresh1 # first on VMS turn []foo into [.foo] for rmtree 97391f110e0Safresh1 $fname = VMS::Filespec::vmspath($fname) if $^O eq 'VMS'; 97491f110e0Safresh1 $dirs_to_unlink{$$} = [] 97591f110e0Safresh1 unless exists $dirs_to_unlink{$$}; 97691f110e0Safresh1 push (@{ $dirs_to_unlink{$$} }, $fname); 97791f110e0Safresh1 97891f110e0Safresh1 } else { 97991f110e0Safresh1 carp "Request to remove directory $fname could not be completed since it does not exist!\n" if $^W; 98091f110e0Safresh1 } 98191f110e0Safresh1 98291f110e0Safresh1 } else { 98391f110e0Safresh1 98491f110e0Safresh1 if (-f $fname) { 98591f110e0Safresh1 98691f110e0Safresh1 # file exists so store handle and name for later removal 98791f110e0Safresh1 $files_to_unlink{$$} = [] 98891f110e0Safresh1 unless exists $files_to_unlink{$$}; 98991f110e0Safresh1 push(@{ $files_to_unlink{$$} }, [$fh, $fname]); 99091f110e0Safresh1 99191f110e0Safresh1 } else { 99291f110e0Safresh1 carp "Request to remove file $fname could not be completed since it is not there!\n" if $^W; 99391f110e0Safresh1 } 99491f110e0Safresh1 99591f110e0Safresh1 } 99691f110e0Safresh1 99791f110e0Safresh1 } 99891f110e0Safresh1 99991f110e0Safresh1 100091f110e0Safresh1} 100191f110e0Safresh1 100291f110e0Safresh1# normalize argument keys to upper case and do consistent handling 100391f110e0Safresh1# of leading template vs TEMPLATE 100491f110e0Safresh1sub _parse_args { 100591f110e0Safresh1 my $leading_template = (scalar(@_) % 2 == 1 ? shift(@_) : '' ); 100691f110e0Safresh1 my %args = @_; 1007*256a93a4Safresh1 %args = map +(uc($_) => $args{$_}), keys %args; 100891f110e0Safresh1 100991f110e0Safresh1 # template (store it in an array so that it will 101091f110e0Safresh1 # disappear from the arg list of tempfile) 101191f110e0Safresh1 my @template = ( 101291f110e0Safresh1 exists $args{TEMPLATE} ? $args{TEMPLATE} : 101391f110e0Safresh1 $leading_template ? $leading_template : () 101491f110e0Safresh1 ); 101591f110e0Safresh1 delete $args{TEMPLATE}; 101691f110e0Safresh1 101791f110e0Safresh1 return( \@template, \%args ); 101891f110e0Safresh1} 101991f110e0Safresh1 1020f3efcd01Safresh1#pod =head1 OBJECT-ORIENTED INTERFACE 1021f3efcd01Safresh1#pod 1022f3efcd01Safresh1#pod This is the primary interface for interacting with 1023f3efcd01Safresh1#pod C<File::Temp>. Using the OO interface a temporary file can be created 1024f3efcd01Safresh1#pod when the object is constructed and the file can be removed when the 1025f3efcd01Safresh1#pod object is no longer required. 1026f3efcd01Safresh1#pod 1027f3efcd01Safresh1#pod Note that there is no method to obtain the filehandle from the 1028f3efcd01Safresh1#pod C<File::Temp> object. The object itself acts as a filehandle. The object 1029f3efcd01Safresh1#pod isa C<IO::Handle> and isa C<IO::Seekable> so all those methods are 1030f3efcd01Safresh1#pod available. 1031f3efcd01Safresh1#pod 1032f3efcd01Safresh1#pod Also, the object is configured such that it stringifies to the name of the 1033f3efcd01Safresh1#pod temporary file and so can be compared to a filename directly. It numifies 1034f3efcd01Safresh1#pod to the C<refaddr> the same as other handles and so can be compared to other 1035f3efcd01Safresh1#pod handles with C<==>. 1036f3efcd01Safresh1#pod 1037f3efcd01Safresh1#pod $fh eq $filename # as a string 1038f3efcd01Safresh1#pod $fh != \*STDOUT # as a number 1039f3efcd01Safresh1#pod 1040f3efcd01Safresh1#pod Available since 0.14. 1041f3efcd01Safresh1#pod 1042f3efcd01Safresh1#pod =over 4 1043f3efcd01Safresh1#pod 1044f3efcd01Safresh1#pod =item B<new> 1045f3efcd01Safresh1#pod 1046f3efcd01Safresh1#pod Create a temporary file object. 1047f3efcd01Safresh1#pod 1048f3efcd01Safresh1#pod my $tmp = File::Temp->new(); 1049f3efcd01Safresh1#pod 1050f3efcd01Safresh1#pod by default the object is constructed as if C<tempfile> 1051f3efcd01Safresh1#pod was called without options, but with the additional behaviour 1052f3efcd01Safresh1#pod that the temporary file is removed by the object destructor 1053f3efcd01Safresh1#pod if UNLINK is set to true (the default). 1054f3efcd01Safresh1#pod 1055f3efcd01Safresh1#pod Supported arguments are the same as for C<tempfile>: UNLINK 1056*256a93a4Safresh1#pod (defaulting to true), DIR, EXLOCK, PERMS and SUFFIX. 1057*256a93a4Safresh1#pod Additionally, the filename 1058f3efcd01Safresh1#pod template is specified using the TEMPLATE option. The OPEN option 1059f3efcd01Safresh1#pod is not supported (the file is always opened). 1060f3efcd01Safresh1#pod 1061f3efcd01Safresh1#pod $tmp = File::Temp->new( TEMPLATE => 'tempXXXXX', 1062f3efcd01Safresh1#pod DIR => 'mydir', 1063f3efcd01Safresh1#pod SUFFIX => '.dat'); 1064f3efcd01Safresh1#pod 1065f3efcd01Safresh1#pod Arguments are case insensitive. 1066f3efcd01Safresh1#pod 1067f3efcd01Safresh1#pod Can call croak() if an error occurs. 1068f3efcd01Safresh1#pod 1069f3efcd01Safresh1#pod Available since 0.14. 1070f3efcd01Safresh1#pod 1071f3efcd01Safresh1#pod TEMPLATE available since 0.23 1072f3efcd01Safresh1#pod 1073f3efcd01Safresh1#pod =cut 107491f110e0Safresh1 107591f110e0Safresh1sub new { 107691f110e0Safresh1 my $proto = shift; 107791f110e0Safresh1 my $class = ref($proto) || $proto; 107891f110e0Safresh1 107991f110e0Safresh1 my ($maybe_template, $args) = _parse_args(@_); 108091f110e0Safresh1 108191f110e0Safresh1 # see if they are unlinking (defaulting to yes) 108291f110e0Safresh1 my $unlink = (exists $args->{UNLINK} ? $args->{UNLINK} : 1 ); 108391f110e0Safresh1 delete $args->{UNLINK}; 108491f110e0Safresh1 108591f110e0Safresh1 # Protect OPEN 108691f110e0Safresh1 delete $args->{OPEN}; 108791f110e0Safresh1 108891f110e0Safresh1 # Open the file and retain file handle and file name 108991f110e0Safresh1 my ($fh, $path) = tempfile( @$maybe_template, %$args ); 109091f110e0Safresh1 109191f110e0Safresh1 print "Tmp: $fh - $path\n" if $DEBUG; 109291f110e0Safresh1 109391f110e0Safresh1 # Store the filename in the scalar slot 109491f110e0Safresh1 ${*$fh} = $path; 109591f110e0Safresh1 109691f110e0Safresh1 # Cache the filename by pid so that the destructor can decide whether to remove it 109791f110e0Safresh1 $FILES_CREATED_BY_OBJECT{$$}{$path} = 1; 109891f110e0Safresh1 109991f110e0Safresh1 # Store unlink information in hash slot (plus other constructor info) 110091f110e0Safresh1 %{*$fh} = %$args; 110191f110e0Safresh1 110291f110e0Safresh1 # create the object 110391f110e0Safresh1 bless $fh, $class; 110491f110e0Safresh1 110591f110e0Safresh1 # final method-based configuration 110691f110e0Safresh1 $fh->unlink_on_destroy( $unlink ); 110791f110e0Safresh1 110891f110e0Safresh1 return $fh; 110991f110e0Safresh1} 111091f110e0Safresh1 1111f3efcd01Safresh1#pod =item B<newdir> 1112f3efcd01Safresh1#pod 1113f3efcd01Safresh1#pod Create a temporary directory using an object oriented interface. 1114f3efcd01Safresh1#pod 1115f3efcd01Safresh1#pod $dir = File::Temp->newdir(); 1116f3efcd01Safresh1#pod 1117f3efcd01Safresh1#pod By default the directory is deleted when the object goes out of scope. 1118f3efcd01Safresh1#pod 1119f3efcd01Safresh1#pod Supports the same options as the C<tempdir> function. Note that directories 1120f3efcd01Safresh1#pod created with this method default to CLEANUP => 1. 1121f3efcd01Safresh1#pod 1122f3efcd01Safresh1#pod $dir = File::Temp->newdir( $template, %options ); 1123f3efcd01Safresh1#pod 1124f3efcd01Safresh1#pod A template may be specified either with a leading template or 1125f3efcd01Safresh1#pod with a TEMPLATE argument. 1126f3efcd01Safresh1#pod 1127f3efcd01Safresh1#pod Available since 0.19. 1128f3efcd01Safresh1#pod 1129f3efcd01Safresh1#pod TEMPLATE available since 0.23. 1130f3efcd01Safresh1#pod 1131f3efcd01Safresh1#pod =cut 113291f110e0Safresh1 113391f110e0Safresh1sub newdir { 113491f110e0Safresh1 my $self = shift; 113591f110e0Safresh1 113691f110e0Safresh1 my ($maybe_template, $args) = _parse_args(@_); 113791f110e0Safresh1 113891f110e0Safresh1 # handle CLEANUP without passing CLEANUP to tempdir 113991f110e0Safresh1 my $cleanup = (exists $args->{CLEANUP} ? $args->{CLEANUP} : 1 ); 114091f110e0Safresh1 delete $args->{CLEANUP}; 114191f110e0Safresh1 114291f110e0Safresh1 my $tempdir = tempdir( @$maybe_template, %$args); 114391f110e0Safresh1 114491f110e0Safresh1 # get a safe absolute path for cleanup, just like 114591f110e0Safresh1 # happens in _deferred_unlink 114691f110e0Safresh1 my $real_dir = Cwd::abs_path( $tempdir ); 114791f110e0Safresh1 ($real_dir) = $real_dir =~ /^(.*)$/; 114891f110e0Safresh1 114991f110e0Safresh1 return bless { DIRNAME => $tempdir, 115091f110e0Safresh1 REALNAME => $real_dir, 115191f110e0Safresh1 CLEANUP => $cleanup, 115291f110e0Safresh1 LAUNCHPID => $$, 115391f110e0Safresh1 }, "File::Temp::Dir"; 115491f110e0Safresh1} 115591f110e0Safresh1 1156f3efcd01Safresh1#pod =item B<filename> 1157f3efcd01Safresh1#pod 1158f3efcd01Safresh1#pod Return the name of the temporary file associated with this object 1159f3efcd01Safresh1#pod (if the object was created using the "new" constructor). 1160f3efcd01Safresh1#pod 1161f3efcd01Safresh1#pod $filename = $tmp->filename; 1162f3efcd01Safresh1#pod 1163f3efcd01Safresh1#pod This method is called automatically when the object is used as 1164f3efcd01Safresh1#pod a string. 1165f3efcd01Safresh1#pod 1166f3efcd01Safresh1#pod Current API available since 0.14 1167f3efcd01Safresh1#pod 1168f3efcd01Safresh1#pod =cut 116991f110e0Safresh1 117091f110e0Safresh1sub filename { 117191f110e0Safresh1 my $self = shift; 117291f110e0Safresh1 return ${*$self}; 117391f110e0Safresh1} 117491f110e0Safresh1 117591f110e0Safresh1sub STRINGIFY { 117691f110e0Safresh1 my $self = shift; 117791f110e0Safresh1 return $self->filename; 117891f110e0Safresh1} 117991f110e0Safresh1 118091f110e0Safresh1# For reference, can't use '0+'=>\&Scalar::Util::refaddr directly because 118191f110e0Safresh1# refaddr() demands one parameter only, whereas overload.pm calls with three 118291f110e0Safresh1# even for unary operations like '0+'. 118391f110e0Safresh1sub NUMIFY { 118491f110e0Safresh1 return refaddr($_[0]); 118591f110e0Safresh1} 118691f110e0Safresh1 1187f3efcd01Safresh1#pod =item B<dirname> 1188f3efcd01Safresh1#pod 1189f3efcd01Safresh1#pod Return the name of the temporary directory associated with this 1190f3efcd01Safresh1#pod object (if the object was created using the "newdir" constructor). 1191f3efcd01Safresh1#pod 1192f3efcd01Safresh1#pod $dirname = $tmpdir->dirname; 1193f3efcd01Safresh1#pod 1194f3efcd01Safresh1#pod This method is called automatically when the object is used in string context. 1195f3efcd01Safresh1#pod 1196f3efcd01Safresh1#pod =item B<unlink_on_destroy> 1197f3efcd01Safresh1#pod 1198f3efcd01Safresh1#pod Control whether the file is unlinked when the object goes out of scope. 1199f3efcd01Safresh1#pod The file is removed if this value is true and $KEEP_ALL is not. 1200f3efcd01Safresh1#pod 1201f3efcd01Safresh1#pod $fh->unlink_on_destroy( 1 ); 1202f3efcd01Safresh1#pod 1203f3efcd01Safresh1#pod Default is for the file to be removed. 1204f3efcd01Safresh1#pod 1205f3efcd01Safresh1#pod Current API available since 0.15 1206f3efcd01Safresh1#pod 1207f3efcd01Safresh1#pod =cut 120891f110e0Safresh1 120991f110e0Safresh1sub unlink_on_destroy { 121091f110e0Safresh1 my $self = shift; 121191f110e0Safresh1 if (@_) { 121291f110e0Safresh1 ${*$self}{UNLINK} = shift; 121391f110e0Safresh1 } 121491f110e0Safresh1 return ${*$self}{UNLINK}; 121591f110e0Safresh1} 121691f110e0Safresh1 1217f3efcd01Safresh1#pod =item B<DESTROY> 1218f3efcd01Safresh1#pod 1219f3efcd01Safresh1#pod When the object goes out of scope, the destructor is called. This 1220f3efcd01Safresh1#pod destructor will attempt to unlink the file (using L<unlink1|"unlink1">) 1221f3efcd01Safresh1#pod if the constructor was called with UNLINK set to 1 (the default state 1222f3efcd01Safresh1#pod if UNLINK is not specified). 1223f3efcd01Safresh1#pod 1224f3efcd01Safresh1#pod No error is given if the unlink fails. 1225f3efcd01Safresh1#pod 1226f3efcd01Safresh1#pod If the object has been passed to a child process during a fork, the 1227f3efcd01Safresh1#pod file will be deleted when the object goes out of scope in the parent. 1228f3efcd01Safresh1#pod 1229f3efcd01Safresh1#pod For a temporary directory object the directory will be removed unless 1230f3efcd01Safresh1#pod the CLEANUP argument was used in the constructor (and set to false) or 1231f3efcd01Safresh1#pod C<unlink_on_destroy> was modified after creation. Note that if a temp 1232f3efcd01Safresh1#pod directory is your current directory, it cannot be removed - a warning 1233f3efcd01Safresh1#pod will be given in this case. C<chdir()> out of the directory before 1234f3efcd01Safresh1#pod letting the object go out of scope. 1235f3efcd01Safresh1#pod 1236f3efcd01Safresh1#pod If the global variable $KEEP_ALL is true, the file or directory 1237f3efcd01Safresh1#pod will not be removed. 1238f3efcd01Safresh1#pod 1239f3efcd01Safresh1#pod =cut 124091f110e0Safresh1 124191f110e0Safresh1sub DESTROY { 124291f110e0Safresh1 local($., $@, $!, $^E, $?); 124391f110e0Safresh1 my $self = shift; 124491f110e0Safresh1 124591f110e0Safresh1 # Make sure we always remove the file from the global hash 124691f110e0Safresh1 # on destruction. This prevents the hash from growing uncontrollably 124791f110e0Safresh1 # and post-destruction there is no reason to know about the file. 124891f110e0Safresh1 my $file = $self->filename; 124991f110e0Safresh1 my $was_created_by_proc; 125091f110e0Safresh1 if (exists $FILES_CREATED_BY_OBJECT{$$}{$file}) { 125191f110e0Safresh1 $was_created_by_proc = 1; 125291f110e0Safresh1 delete $FILES_CREATED_BY_OBJECT{$$}{$file}; 125391f110e0Safresh1 } 125491f110e0Safresh1 125591f110e0Safresh1 if (${*$self}{UNLINK} && !$KEEP_ALL) { 125691f110e0Safresh1 print "# ---------> Unlinking $self\n" if $DEBUG; 125791f110e0Safresh1 125891f110e0Safresh1 # only delete if this process created it 125991f110e0Safresh1 return unless $was_created_by_proc; 126091f110e0Safresh1 126191f110e0Safresh1 # The unlink1 may fail if the file has been closed 126291f110e0Safresh1 # by the caller. This leaves us with the decision 126391f110e0Safresh1 # of whether to refuse to remove the file or simply 126491f110e0Safresh1 # do an unlink without test. Seems to be silly 126591f110e0Safresh1 # to do this when we are trying to be careful 126691f110e0Safresh1 # about security 126791f110e0Safresh1 _force_writable( $file ); # for windows 126891f110e0Safresh1 unlink1( $self, $file ) 126991f110e0Safresh1 or unlink($file); 127091f110e0Safresh1 } 127191f110e0Safresh1} 127291f110e0Safresh1 1273f3efcd01Safresh1#pod =back 1274f3efcd01Safresh1#pod 1275f3efcd01Safresh1#pod =head1 FUNCTIONS 1276f3efcd01Safresh1#pod 1277f3efcd01Safresh1#pod This section describes the recommended interface for generating 1278f3efcd01Safresh1#pod temporary files and directories. 1279f3efcd01Safresh1#pod 1280f3efcd01Safresh1#pod =over 4 1281f3efcd01Safresh1#pod 1282f3efcd01Safresh1#pod =item B<tempfile> 1283f3efcd01Safresh1#pod 1284f3efcd01Safresh1#pod This is the basic function to generate temporary files. 1285f3efcd01Safresh1#pod The behaviour of the file can be changed using various options: 1286f3efcd01Safresh1#pod 1287f3efcd01Safresh1#pod $fh = tempfile(); 1288f3efcd01Safresh1#pod ($fh, $filename) = tempfile(); 1289f3efcd01Safresh1#pod 1290f3efcd01Safresh1#pod Create a temporary file in the directory specified for temporary 1291f3efcd01Safresh1#pod files, as specified by the tmpdir() function in L<File::Spec>. 1292f3efcd01Safresh1#pod 1293f3efcd01Safresh1#pod ($fh, $filename) = tempfile($template); 1294f3efcd01Safresh1#pod 1295f3efcd01Safresh1#pod Create a temporary file in the current directory using the supplied 1296f3efcd01Safresh1#pod template. Trailing `X' characters are replaced with random letters to 1297f3efcd01Safresh1#pod generate the filename. At least four `X' characters must be present 1298f3efcd01Safresh1#pod at the end of the template. 1299f3efcd01Safresh1#pod 1300f3efcd01Safresh1#pod ($fh, $filename) = tempfile($template, SUFFIX => $suffix) 1301f3efcd01Safresh1#pod 1302f3efcd01Safresh1#pod Same as previously, except that a suffix is added to the template 1303f3efcd01Safresh1#pod after the `X' translation. Useful for ensuring that a temporary 1304f3efcd01Safresh1#pod filename has a particular extension when needed by other applications. 1305f3efcd01Safresh1#pod But see the WARNING at the end. 1306f3efcd01Safresh1#pod 1307f3efcd01Safresh1#pod ($fh, $filename) = tempfile($template, DIR => $dir); 1308f3efcd01Safresh1#pod 1309f3efcd01Safresh1#pod Translates the template as before except that a directory name 1310f3efcd01Safresh1#pod is specified. 1311f3efcd01Safresh1#pod 1312f3efcd01Safresh1#pod ($fh, $filename) = tempfile($template, TMPDIR => 1); 1313f3efcd01Safresh1#pod 1314f3efcd01Safresh1#pod Equivalent to specifying a DIR of "File::Spec->tmpdir", writing the file 1315f3efcd01Safresh1#pod into the same temporary directory as would be used if no template was 1316f3efcd01Safresh1#pod specified at all. 1317f3efcd01Safresh1#pod 1318f3efcd01Safresh1#pod ($fh, $filename) = tempfile($template, UNLINK => 1); 1319f3efcd01Safresh1#pod 1320f3efcd01Safresh1#pod Return the filename and filehandle as before except that the file is 1321f3efcd01Safresh1#pod automatically removed when the program exits (dependent on 1322f3efcd01Safresh1#pod $KEEP_ALL). Default is for the file to be removed if a file handle is 1323f3efcd01Safresh1#pod requested and to be kept if the filename is requested. In a scalar 1324f3efcd01Safresh1#pod context (where no filename is returned) the file is always deleted 1325f3efcd01Safresh1#pod either (depending on the operating system) on exit or when it is 1326f3efcd01Safresh1#pod closed (unless $KEEP_ALL is true when the temp file is created). 1327f3efcd01Safresh1#pod 1328f3efcd01Safresh1#pod Use the object-oriented interface if fine-grained control of when 1329f3efcd01Safresh1#pod a file is removed is required. 1330f3efcd01Safresh1#pod 1331f3efcd01Safresh1#pod If the template is not specified, a template is always 1332f3efcd01Safresh1#pod automatically generated. This temporary file is placed in tmpdir() 1333f3efcd01Safresh1#pod (L<File::Spec>) unless a directory is specified explicitly with the 1334f3efcd01Safresh1#pod DIR option. 1335f3efcd01Safresh1#pod 1336f3efcd01Safresh1#pod $fh = tempfile( DIR => $dir ); 1337f3efcd01Safresh1#pod 1338f3efcd01Safresh1#pod If called in scalar context, only the filehandle is returned and the 1339f3efcd01Safresh1#pod file will automatically be deleted when closed on operating systems 1340f3efcd01Safresh1#pod that support this (see the description of tmpfile() elsewhere in this 1341f3efcd01Safresh1#pod document). This is the preferred mode of operation, as if you only 1342f3efcd01Safresh1#pod have a filehandle, you can never create a race condition by fumbling 1343f3efcd01Safresh1#pod with the filename. On systems that can not unlink an open file or can 1344f3efcd01Safresh1#pod not mark a file as temporary when it is opened (for example, Windows 1345f3efcd01Safresh1#pod NT uses the C<O_TEMPORARY> flag) the file is marked for deletion when 1346f3efcd01Safresh1#pod the program ends (equivalent to setting UNLINK to 1). The C<UNLINK> 1347f3efcd01Safresh1#pod flag is ignored if present. 1348f3efcd01Safresh1#pod 1349f3efcd01Safresh1#pod (undef, $filename) = tempfile($template, OPEN => 0); 1350f3efcd01Safresh1#pod 1351f3efcd01Safresh1#pod This will return the filename based on the template but 1352f3efcd01Safresh1#pod will not open this file. Cannot be used in conjunction with 1353f3efcd01Safresh1#pod UNLINK set to true. Default is to always open the file 1354f3efcd01Safresh1#pod to protect from possible race conditions. A warning is issued 1355f3efcd01Safresh1#pod if warnings are turned on. Consider using the tmpnam() 1356f3efcd01Safresh1#pod and mktemp() functions described elsewhere in this document 1357f3efcd01Safresh1#pod if opening the file is not required. 1358f3efcd01Safresh1#pod 1359f3efcd01Safresh1#pod To open the temporary filehandle with O_EXLOCK (open with exclusive 1360f3efcd01Safresh1#pod file lock) use C<< EXLOCK=>1 >>. This is supported only by some 1361f3efcd01Safresh1#pod operating systems (most notably BSD derived systems). By default 1362f3efcd01Safresh1#pod EXLOCK will be false. Former C<File::Temp> versions set EXLOCK to 1363f3efcd01Safresh1#pod true, so to be sure to get an unlocked filehandle also with older 1364f3efcd01Safresh1#pod versions, explicitly set C<< EXLOCK=>0 >>. 1365f3efcd01Safresh1#pod 1366f3efcd01Safresh1#pod ($fh, $filename) = tempfile($template, EXLOCK => 1); 1367f3efcd01Safresh1#pod 1368*256a93a4Safresh1#pod By default, the temp file is created with 0600 file permissions. 1369*256a93a4Safresh1#pod Use C<PERMS> to change this: 1370*256a93a4Safresh1#pod 1371*256a93a4Safresh1#pod ($fh, $filename) = tempfile($template, PERMS => 0666); 1372*256a93a4Safresh1#pod 1373f3efcd01Safresh1#pod Options can be combined as required. 1374f3efcd01Safresh1#pod 1375f3efcd01Safresh1#pod Will croak() if there is an error. 1376f3efcd01Safresh1#pod 1377f3efcd01Safresh1#pod Available since 0.05. 1378f3efcd01Safresh1#pod 1379f3efcd01Safresh1#pod UNLINK flag available since 0.10. 1380f3efcd01Safresh1#pod 1381f3efcd01Safresh1#pod TMPDIR flag available since 0.19. 1382f3efcd01Safresh1#pod 1383f3efcd01Safresh1#pod EXLOCK flag available since 0.19. 1384f3efcd01Safresh1#pod 1385*256a93a4Safresh1#pod PERMS flag available since 0.2310. 1386*256a93a4Safresh1#pod 1387f3efcd01Safresh1#pod =cut 138891f110e0Safresh1 138991f110e0Safresh1sub tempfile { 139091f110e0Safresh1 if ( @_ && $_[0] eq 'File::Temp' ) { 139191f110e0Safresh1 croak "'tempfile' can't be called as a method"; 139291f110e0Safresh1 } 139391f110e0Safresh1 # Can not check for argument count since we can have any 139491f110e0Safresh1 # number of args 139591f110e0Safresh1 139691f110e0Safresh1 # Default options 139791f110e0Safresh1 my %options = ( 139891f110e0Safresh1 "DIR" => undef, # Directory prefix 139991f110e0Safresh1 "SUFFIX" => '', # Template suffix 140091f110e0Safresh1 "UNLINK" => 0, # Do not unlink file on exit 140191f110e0Safresh1 "OPEN" => 1, # Open file 140291f110e0Safresh1 "TMPDIR" => 0, # Place tempfile in tempdir if template specified 1403f3efcd01Safresh1 "EXLOCK" => 0, # Open file with O_EXLOCK 1404*256a93a4Safresh1 "PERMS" => undef, # File permissions 140591f110e0Safresh1 ); 140691f110e0Safresh1 140791f110e0Safresh1 # Check to see whether we have an odd or even number of arguments 140891f110e0Safresh1 my ($maybe_template, $args) = _parse_args(@_); 140991f110e0Safresh1 my $template = @$maybe_template ? $maybe_template->[0] : undef; 141091f110e0Safresh1 141191f110e0Safresh1 # Read the options and merge with defaults 141291f110e0Safresh1 %options = (%options, %$args); 141391f110e0Safresh1 141491f110e0Safresh1 # First decision is whether or not to open the file 141591f110e0Safresh1 if (! $options{"OPEN"}) { 141691f110e0Safresh1 141791f110e0Safresh1 warn "tempfile(): temporary filename requested but not opened.\nPossibly unsafe, consider using tempfile() with OPEN set to true\n" 141891f110e0Safresh1 if $^W; 141991f110e0Safresh1 142091f110e0Safresh1 } 142191f110e0Safresh1 142291f110e0Safresh1 if ($options{"DIR"} and $^O eq 'VMS') { 142391f110e0Safresh1 142491f110e0Safresh1 # on VMS turn []foo into [.foo] for concatenation 142591f110e0Safresh1 $options{"DIR"} = VMS::Filespec::vmspath($options{"DIR"}); 142691f110e0Safresh1 } 142791f110e0Safresh1 142891f110e0Safresh1 # Construct the template 142991f110e0Safresh1 143091f110e0Safresh1 # Have a choice of trying to work around the mkstemp/mktemp/tmpnam etc 143191f110e0Safresh1 # functions or simply constructing a template and using _gettemp() 143291f110e0Safresh1 # explicitly. Go for the latter 143391f110e0Safresh1 143491f110e0Safresh1 # First generate a template if not defined and prefix the directory 143591f110e0Safresh1 # If no template must prefix the temp directory 143691f110e0Safresh1 if (defined $template) { 143791f110e0Safresh1 # End up with current directory if neither DIR not TMPDIR are set 143891f110e0Safresh1 if ($options{"DIR"}) { 143991f110e0Safresh1 144091f110e0Safresh1 $template = File::Spec->catfile($options{"DIR"}, $template); 144191f110e0Safresh1 144291f110e0Safresh1 } elsif ($options{TMPDIR}) { 144391f110e0Safresh1 1444f3efcd01Safresh1 $template = File::Spec->catfile(_wrap_file_spec_tmpdir(), $template ); 144591f110e0Safresh1 144691f110e0Safresh1 } 144791f110e0Safresh1 144891f110e0Safresh1 } else { 144991f110e0Safresh1 145091f110e0Safresh1 if ($options{"DIR"}) { 145191f110e0Safresh1 145291f110e0Safresh1 $template = File::Spec->catfile($options{"DIR"}, TEMPXXX); 145391f110e0Safresh1 145491f110e0Safresh1 } else { 145591f110e0Safresh1 1456f3efcd01Safresh1 $template = File::Spec->catfile(_wrap_file_spec_tmpdir(), TEMPXXX); 145791f110e0Safresh1 145891f110e0Safresh1 } 145991f110e0Safresh1 146091f110e0Safresh1 } 146191f110e0Safresh1 146291f110e0Safresh1 # Now add a suffix 146391f110e0Safresh1 $template .= $options{"SUFFIX"}; 146491f110e0Safresh1 146591f110e0Safresh1 # Determine whether we should tell _gettemp to unlink the file 146691f110e0Safresh1 # On unix this is irrelevant and can be worked out after the file is 146791f110e0Safresh1 # opened (simply by unlinking the open filehandle). On Windows or VMS 146891f110e0Safresh1 # we have to indicate temporary-ness when we open the file. In general 146991f110e0Safresh1 # we only want a true temporary file if we are returning just the 147091f110e0Safresh1 # filehandle - if the user wants the filename they probably do not 147191f110e0Safresh1 # want the file to disappear as soon as they close it (which may be 147291f110e0Safresh1 # important if they want a child process to use the file) 147391f110e0Safresh1 # For this reason, tie unlink_on_close to the return context regardless 147491f110e0Safresh1 # of OS. 147591f110e0Safresh1 my $unlink_on_close = ( wantarray ? 0 : 1); 147691f110e0Safresh1 147791f110e0Safresh1 # Create the file 147891f110e0Safresh1 my ($fh, $path, $errstr); 147991f110e0Safresh1 croak "Error in tempfile() using template $template: $errstr" 148091f110e0Safresh1 unless (($fh, $path) = _gettemp($template, 1481*256a93a4Safresh1 "open" => $options{OPEN}, 148291f110e0Safresh1 "mkdir" => 0, 148391f110e0Safresh1 "unlink_on_close" => $unlink_on_close, 1484*256a93a4Safresh1 "suffixlen" => length($options{SUFFIX}), 148591f110e0Safresh1 "ErrStr" => \$errstr, 148691f110e0Safresh1 "use_exlock" => $options{EXLOCK}, 1487*256a93a4Safresh1 "file_permissions" => $options{PERMS}, 148891f110e0Safresh1 ) ); 148991f110e0Safresh1 149091f110e0Safresh1 # Set up an exit handler that can do whatever is right for the 149191f110e0Safresh1 # system. This removes files at exit when requested explicitly or when 149291f110e0Safresh1 # system is asked to unlink_on_close but is unable to do so because 149391f110e0Safresh1 # of OS limitations. 149491f110e0Safresh1 # The latter should be achieved by using a tied filehandle. 149591f110e0Safresh1 # Do not check return status since this is all done with END blocks. 149691f110e0Safresh1 _deferred_unlink($fh, $path, 0) if $options{"UNLINK"}; 149791f110e0Safresh1 149891f110e0Safresh1 # Return 149991f110e0Safresh1 if (wantarray()) { 150091f110e0Safresh1 150191f110e0Safresh1 if ($options{'OPEN'}) { 150291f110e0Safresh1 return ($fh, $path); 150391f110e0Safresh1 } else { 150491f110e0Safresh1 return (undef, $path); 150591f110e0Safresh1 } 150691f110e0Safresh1 150791f110e0Safresh1 } else { 150891f110e0Safresh1 150991f110e0Safresh1 # Unlink the file. It is up to unlink0 to decide what to do with 151091f110e0Safresh1 # this (whether to unlink now or to defer until later) 151191f110e0Safresh1 unlink0($fh, $path) or croak "Error unlinking file $path using unlink0"; 151291f110e0Safresh1 151391f110e0Safresh1 # Return just the filehandle. 151491f110e0Safresh1 return $fh; 151591f110e0Safresh1 } 151691f110e0Safresh1 151791f110e0Safresh1 151891f110e0Safresh1} 151991f110e0Safresh1 1520f3efcd01Safresh1# On Windows under taint mode, File::Spec could suggest "C:\" as a tempdir 1521f3efcd01Safresh1# which might not be writable. If that is the case, we fallback to a 1522f3efcd01Safresh1# user directory. See https://rt.cpan.org/Ticket/Display.html?id=60340 1523f3efcd01Safresh1 1524f3efcd01Safresh1{ 1525f3efcd01Safresh1 my ($alt_tmpdir, $checked); 1526f3efcd01Safresh1 1527f3efcd01Safresh1 sub _wrap_file_spec_tmpdir { 1528f3efcd01Safresh1 return File::Spec->tmpdir unless $^O eq "MSWin32" && ${^TAINT}; 1529f3efcd01Safresh1 1530f3efcd01Safresh1 if ( $checked ) { 1531f3efcd01Safresh1 return $alt_tmpdir ? $alt_tmpdir : File::Spec->tmpdir; 1532f3efcd01Safresh1 } 1533f3efcd01Safresh1 1534f3efcd01Safresh1 # probe what File::Spec gives and find a fallback 1535f3efcd01Safresh1 my $xxpath = _replace_XX( "X" x 10, 0 ); 1536f3efcd01Safresh1 1537f3efcd01Safresh1 # First, see if File::Spec->tmpdir is writable 1538f3efcd01Safresh1 my $tmpdir = File::Spec->tmpdir; 1539f3efcd01Safresh1 my $testpath = File::Spec->catdir( $tmpdir, $xxpath ); 1540f3efcd01Safresh1 if (mkdir( $testpath, 0700) ) { 1541f3efcd01Safresh1 $checked = 1; 1542f3efcd01Safresh1 rmdir $testpath; 1543f3efcd01Safresh1 return $tmpdir; 1544f3efcd01Safresh1 } 1545f3efcd01Safresh1 1546f3efcd01Safresh1 # Next, see if CSIDL_LOCAL_APPDATA is writable 1547f3efcd01Safresh1 require Win32; 1548f3efcd01Safresh1 my $local_app = File::Spec->catdir( 1549f3efcd01Safresh1 Win32::GetFolderPath( Win32::CSIDL_LOCAL_APPDATA() ), 'Temp' 1550f3efcd01Safresh1 ); 1551f3efcd01Safresh1 $testpath = File::Spec->catdir( $local_app, $xxpath ); 1552f3efcd01Safresh1 if ( -e $local_app or mkdir( $local_app, 0700 ) ) { 1553f3efcd01Safresh1 if (mkdir( $testpath, 0700) ) { 1554f3efcd01Safresh1 $checked = 1; 1555f3efcd01Safresh1 rmdir $testpath; 1556f3efcd01Safresh1 return $alt_tmpdir = $local_app; 1557f3efcd01Safresh1 } 1558f3efcd01Safresh1 } 1559f3efcd01Safresh1 1560f3efcd01Safresh1 # Can't find something writable 1561f3efcd01Safresh1 croak << "HERE"; 1562f3efcd01Safresh1Couldn't find a writable temp directory in taint mode. Tried: 1563f3efcd01Safresh1 $tmpdir 1564f3efcd01Safresh1 $local_app 1565f3efcd01Safresh1 1566f3efcd01Safresh1Try setting and untainting the TMPDIR environment variable. 1567f3efcd01Safresh1HERE 1568f3efcd01Safresh1 1569f3efcd01Safresh1 } 1570f3efcd01Safresh1} 1571f3efcd01Safresh1 1572f3efcd01Safresh1#pod =item B<tempdir> 1573f3efcd01Safresh1#pod 1574f3efcd01Safresh1#pod This is the recommended interface for creation of temporary 1575f3efcd01Safresh1#pod directories. By default the directory will not be removed on exit 1576f3efcd01Safresh1#pod (that is, it won't be temporary; this behaviour can not be changed 1577f3efcd01Safresh1#pod because of issues with backwards compatibility). To enable removal 1578f3efcd01Safresh1#pod either use the CLEANUP option which will trigger removal on program 1579f3efcd01Safresh1#pod exit, or consider using the "newdir" method in the object interface which 1580f3efcd01Safresh1#pod will allow the directory to be cleaned up when the object goes out of 1581f3efcd01Safresh1#pod scope. 1582f3efcd01Safresh1#pod 1583f3efcd01Safresh1#pod The behaviour of the function depends on the arguments: 1584f3efcd01Safresh1#pod 1585f3efcd01Safresh1#pod $tempdir = tempdir(); 1586f3efcd01Safresh1#pod 1587f3efcd01Safresh1#pod Create a directory in tmpdir() (see L<File::Spec|File::Spec>). 1588f3efcd01Safresh1#pod 1589f3efcd01Safresh1#pod $tempdir = tempdir( $template ); 1590f3efcd01Safresh1#pod 1591f3efcd01Safresh1#pod Create a directory from the supplied template. This template is 1592f3efcd01Safresh1#pod similar to that described for tempfile(). `X' characters at the end 1593f3efcd01Safresh1#pod of the template are replaced with random letters to construct the 1594f3efcd01Safresh1#pod directory name. At least four `X' characters must be in the template. 1595f3efcd01Safresh1#pod 1596f3efcd01Safresh1#pod $tempdir = tempdir ( DIR => $dir ); 1597f3efcd01Safresh1#pod 1598f3efcd01Safresh1#pod Specifies the directory to use for the temporary directory. 1599f3efcd01Safresh1#pod The temporary directory name is derived from an internal template. 1600f3efcd01Safresh1#pod 1601f3efcd01Safresh1#pod $tempdir = tempdir ( $template, DIR => $dir ); 1602f3efcd01Safresh1#pod 1603f3efcd01Safresh1#pod Prepend the supplied directory name to the template. The template 1604f3efcd01Safresh1#pod should not include parent directory specifications itself. Any parent 1605f3efcd01Safresh1#pod directory specifications are removed from the template before 1606f3efcd01Safresh1#pod prepending the supplied directory. 1607f3efcd01Safresh1#pod 1608f3efcd01Safresh1#pod $tempdir = tempdir ( $template, TMPDIR => 1 ); 1609f3efcd01Safresh1#pod 1610f3efcd01Safresh1#pod Using the supplied template, create the temporary directory in 1611f3efcd01Safresh1#pod a standard location for temporary files. Equivalent to doing 1612f3efcd01Safresh1#pod 1613f3efcd01Safresh1#pod $tempdir = tempdir ( $template, DIR => File::Spec->tmpdir); 1614f3efcd01Safresh1#pod 1615f3efcd01Safresh1#pod but shorter. Parent directory specifications are stripped from the 1616f3efcd01Safresh1#pod template itself. The C<TMPDIR> option is ignored if C<DIR> is set 1617f3efcd01Safresh1#pod explicitly. Additionally, C<TMPDIR> is implied if neither a template 1618f3efcd01Safresh1#pod nor a directory are supplied. 1619f3efcd01Safresh1#pod 1620f3efcd01Safresh1#pod $tempdir = tempdir( $template, CLEANUP => 1); 1621f3efcd01Safresh1#pod 1622f3efcd01Safresh1#pod Create a temporary directory using the supplied template, but 1623f3efcd01Safresh1#pod attempt to remove it (and all files inside it) when the program 1624f3efcd01Safresh1#pod exits. Note that an attempt will be made to remove all files from 1625f3efcd01Safresh1#pod the directory even if they were not created by this module (otherwise 1626f3efcd01Safresh1#pod why ask to clean it up?). The directory removal is made with 1627f3efcd01Safresh1#pod the rmtree() function from the L<File::Path|File::Path> module. 1628f3efcd01Safresh1#pod Of course, if the template is not specified, the temporary directory 1629f3efcd01Safresh1#pod will be created in tmpdir() and will also be removed at program exit. 1630f3efcd01Safresh1#pod 1631f3efcd01Safresh1#pod Will croak() if there is an error. 1632f3efcd01Safresh1#pod 1633f3efcd01Safresh1#pod Current API available since 0.05. 1634f3efcd01Safresh1#pod 1635f3efcd01Safresh1#pod =cut 163691f110e0Safresh1 163791f110e0Safresh1# ' 163891f110e0Safresh1 163991f110e0Safresh1sub tempdir { 164091f110e0Safresh1 if ( @_ && $_[0] eq 'File::Temp' ) { 164191f110e0Safresh1 croak "'tempdir' can't be called as a method"; 164291f110e0Safresh1 } 164391f110e0Safresh1 164491f110e0Safresh1 # Can not check for argument count since we can have any 164591f110e0Safresh1 # number of args 164691f110e0Safresh1 164791f110e0Safresh1 # Default options 164891f110e0Safresh1 my %options = ( 164991f110e0Safresh1 "CLEANUP" => 0, # Remove directory on exit 165091f110e0Safresh1 "DIR" => '', # Root directory 165191f110e0Safresh1 "TMPDIR" => 0, # Use tempdir with template 165291f110e0Safresh1 ); 165391f110e0Safresh1 165491f110e0Safresh1 # Check to see whether we have an odd or even number of arguments 165591f110e0Safresh1 my ($maybe_template, $args) = _parse_args(@_); 165691f110e0Safresh1 my $template = @$maybe_template ? $maybe_template->[0] : undef; 165791f110e0Safresh1 165891f110e0Safresh1 # Read the options and merge with defaults 165991f110e0Safresh1 %options = (%options, %$args); 166091f110e0Safresh1 166191f110e0Safresh1 # Modify or generate the template 166291f110e0Safresh1 166391f110e0Safresh1 # Deal with the DIR and TMPDIR options 166491f110e0Safresh1 if (defined $template) { 166591f110e0Safresh1 166691f110e0Safresh1 # Need to strip directory path if using DIR or TMPDIR 166791f110e0Safresh1 if ($options{'TMPDIR'} || $options{'DIR'}) { 166891f110e0Safresh1 166991f110e0Safresh1 # Strip parent directory from the filename 167091f110e0Safresh1 # 167191f110e0Safresh1 # There is no filename at the end 167291f110e0Safresh1 $template = VMS::Filespec::vmspath($template) if $^O eq 'VMS'; 167391f110e0Safresh1 my ($volume, $directories, undef) = File::Spec->splitpath( $template, 1); 167491f110e0Safresh1 167591f110e0Safresh1 # Last directory is then our template 167691f110e0Safresh1 $template = (File::Spec->splitdir($directories))[-1]; 167791f110e0Safresh1 167891f110e0Safresh1 # Prepend the supplied directory or temp dir 167991f110e0Safresh1 if ($options{"DIR"}) { 168091f110e0Safresh1 168191f110e0Safresh1 $template = File::Spec->catdir($options{"DIR"}, $template); 168291f110e0Safresh1 168391f110e0Safresh1 } elsif ($options{TMPDIR}) { 168491f110e0Safresh1 168591f110e0Safresh1 # Prepend tmpdir 1686f3efcd01Safresh1 $template = File::Spec->catdir(_wrap_file_spec_tmpdir(), $template); 168791f110e0Safresh1 168891f110e0Safresh1 } 168991f110e0Safresh1 169091f110e0Safresh1 } 169191f110e0Safresh1 169291f110e0Safresh1 } else { 169391f110e0Safresh1 169491f110e0Safresh1 if ($options{"DIR"}) { 169591f110e0Safresh1 169691f110e0Safresh1 $template = File::Spec->catdir($options{"DIR"}, TEMPXXX); 169791f110e0Safresh1 169891f110e0Safresh1 } else { 169991f110e0Safresh1 1700f3efcd01Safresh1 $template = File::Spec->catdir(_wrap_file_spec_tmpdir(), TEMPXXX); 170191f110e0Safresh1 170291f110e0Safresh1 } 170391f110e0Safresh1 170491f110e0Safresh1 } 170591f110e0Safresh1 170691f110e0Safresh1 # Create the directory 170791f110e0Safresh1 my $tempdir; 170891f110e0Safresh1 my $suffixlen = 0; 170991f110e0Safresh1 if ($^O eq 'VMS') { # dir names can end in delimiters 171091f110e0Safresh1 $template =~ m/([\.\]:>]+)$/; 171191f110e0Safresh1 $suffixlen = length($1); 171291f110e0Safresh1 } 171391f110e0Safresh1 if ( ($^O eq 'MacOS') && (substr($template, -1) eq ':') ) { 171491f110e0Safresh1 # dir name has a trailing ':' 171591f110e0Safresh1 ++$suffixlen; 171691f110e0Safresh1 } 171791f110e0Safresh1 171891f110e0Safresh1 my $errstr; 171991f110e0Safresh1 croak "Error in tempdir() using $template: $errstr" 172091f110e0Safresh1 unless ((undef, $tempdir) = _gettemp($template, 172191f110e0Safresh1 "open" => 0, 172291f110e0Safresh1 "mkdir"=> 1 , 172391f110e0Safresh1 "suffixlen" => $suffixlen, 172491f110e0Safresh1 "ErrStr" => \$errstr, 172591f110e0Safresh1 ) ); 172691f110e0Safresh1 172791f110e0Safresh1 # Install exit handler; must be dynamic to get lexical 172891f110e0Safresh1 if ( $options{'CLEANUP'} && -d $tempdir) { 172991f110e0Safresh1 _deferred_unlink(undef, $tempdir, 1); 173091f110e0Safresh1 } 173191f110e0Safresh1 173291f110e0Safresh1 # Return the dir name 173391f110e0Safresh1 return $tempdir; 173491f110e0Safresh1 173591f110e0Safresh1} 173691f110e0Safresh1 1737f3efcd01Safresh1#pod =back 1738f3efcd01Safresh1#pod 1739f3efcd01Safresh1#pod =head1 MKTEMP FUNCTIONS 1740f3efcd01Safresh1#pod 1741f3efcd01Safresh1#pod The following functions are Perl implementations of the 1742f3efcd01Safresh1#pod mktemp() family of temp file generation system calls. 1743f3efcd01Safresh1#pod 1744f3efcd01Safresh1#pod =over 4 1745f3efcd01Safresh1#pod 1746f3efcd01Safresh1#pod =item B<mkstemp> 1747f3efcd01Safresh1#pod 1748f3efcd01Safresh1#pod Given a template, returns a filehandle to the temporary file and the name 1749f3efcd01Safresh1#pod of the file. 1750f3efcd01Safresh1#pod 1751f3efcd01Safresh1#pod ($fh, $name) = mkstemp( $template ); 1752f3efcd01Safresh1#pod 1753f3efcd01Safresh1#pod In scalar context, just the filehandle is returned. 1754f3efcd01Safresh1#pod 1755f3efcd01Safresh1#pod The template may be any filename with some number of X's appended 1756f3efcd01Safresh1#pod to it, for example F</tmp/temp.XXXX>. The trailing X's are replaced 1757f3efcd01Safresh1#pod with unique alphanumeric combinations. 1758f3efcd01Safresh1#pod 1759f3efcd01Safresh1#pod Will croak() if there is an error. 1760f3efcd01Safresh1#pod 1761f3efcd01Safresh1#pod Current API available since 0.05. 1762f3efcd01Safresh1#pod 1763f3efcd01Safresh1#pod =cut 176491f110e0Safresh1 176591f110e0Safresh1 176691f110e0Safresh1 176791f110e0Safresh1sub mkstemp { 176891f110e0Safresh1 176991f110e0Safresh1 croak "Usage: mkstemp(template)" 177091f110e0Safresh1 if scalar(@_) != 1; 177191f110e0Safresh1 177291f110e0Safresh1 my $template = shift; 177391f110e0Safresh1 177491f110e0Safresh1 my ($fh, $path, $errstr); 177591f110e0Safresh1 croak "Error in mkstemp using $template: $errstr" 177691f110e0Safresh1 unless (($fh, $path) = _gettemp($template, 177791f110e0Safresh1 "open" => 1, 177891f110e0Safresh1 "mkdir"=> 0 , 177991f110e0Safresh1 "suffixlen" => 0, 178091f110e0Safresh1 "ErrStr" => \$errstr, 178191f110e0Safresh1 ) ); 178291f110e0Safresh1 178391f110e0Safresh1 if (wantarray()) { 178491f110e0Safresh1 return ($fh, $path); 178591f110e0Safresh1 } else { 178691f110e0Safresh1 return $fh; 178791f110e0Safresh1 } 178891f110e0Safresh1 178991f110e0Safresh1} 179091f110e0Safresh1 179191f110e0Safresh1 1792f3efcd01Safresh1#pod =item B<mkstemps> 1793f3efcd01Safresh1#pod 1794f3efcd01Safresh1#pod Similar to mkstemp(), except that an extra argument can be supplied 1795f3efcd01Safresh1#pod with a suffix to be appended to the template. 1796f3efcd01Safresh1#pod 1797f3efcd01Safresh1#pod ($fh, $name) = mkstemps( $template, $suffix ); 1798f3efcd01Safresh1#pod 1799f3efcd01Safresh1#pod For example a template of C<testXXXXXX> and suffix of C<.dat> 1800f3efcd01Safresh1#pod would generate a file similar to F<testhGji_w.dat>. 1801f3efcd01Safresh1#pod 1802f3efcd01Safresh1#pod Returns just the filehandle alone when called in scalar context. 1803f3efcd01Safresh1#pod 1804f3efcd01Safresh1#pod Will croak() if there is an error. 1805f3efcd01Safresh1#pod 1806f3efcd01Safresh1#pod Current API available since 0.05. 1807f3efcd01Safresh1#pod 1808f3efcd01Safresh1#pod =cut 180991f110e0Safresh1 181091f110e0Safresh1sub mkstemps { 181191f110e0Safresh1 181291f110e0Safresh1 croak "Usage: mkstemps(template, suffix)" 181391f110e0Safresh1 if scalar(@_) != 2; 181491f110e0Safresh1 181591f110e0Safresh1 181691f110e0Safresh1 my $template = shift; 181791f110e0Safresh1 my $suffix = shift; 181891f110e0Safresh1 181991f110e0Safresh1 $template .= $suffix; 182091f110e0Safresh1 182191f110e0Safresh1 my ($fh, $path, $errstr); 182291f110e0Safresh1 croak "Error in mkstemps using $template: $errstr" 182391f110e0Safresh1 unless (($fh, $path) = _gettemp($template, 182491f110e0Safresh1 "open" => 1, 182591f110e0Safresh1 "mkdir"=> 0 , 182691f110e0Safresh1 "suffixlen" => length($suffix), 182791f110e0Safresh1 "ErrStr" => \$errstr, 182891f110e0Safresh1 ) ); 182991f110e0Safresh1 183091f110e0Safresh1 if (wantarray()) { 183191f110e0Safresh1 return ($fh, $path); 183291f110e0Safresh1 } else { 183391f110e0Safresh1 return $fh; 183491f110e0Safresh1 } 183591f110e0Safresh1 183691f110e0Safresh1} 183791f110e0Safresh1 1838f3efcd01Safresh1#pod =item B<mkdtemp> 1839f3efcd01Safresh1#pod 1840f3efcd01Safresh1#pod Create a directory from a template. The template must end in 1841f3efcd01Safresh1#pod X's that are replaced by the routine. 1842f3efcd01Safresh1#pod 1843f3efcd01Safresh1#pod $tmpdir_name = mkdtemp($template); 1844f3efcd01Safresh1#pod 1845f3efcd01Safresh1#pod Returns the name of the temporary directory created. 1846f3efcd01Safresh1#pod 1847f3efcd01Safresh1#pod Directory must be removed by the caller. 1848f3efcd01Safresh1#pod 1849f3efcd01Safresh1#pod Will croak() if there is an error. 1850f3efcd01Safresh1#pod 1851f3efcd01Safresh1#pod Current API available since 0.05. 1852f3efcd01Safresh1#pod 1853f3efcd01Safresh1#pod =cut 185491f110e0Safresh1 185591f110e0Safresh1#' # for emacs 185691f110e0Safresh1 185791f110e0Safresh1sub mkdtemp { 185891f110e0Safresh1 185991f110e0Safresh1 croak "Usage: mkdtemp(template)" 186091f110e0Safresh1 if scalar(@_) != 1; 186191f110e0Safresh1 186291f110e0Safresh1 my $template = shift; 186391f110e0Safresh1 my $suffixlen = 0; 186491f110e0Safresh1 if ($^O eq 'VMS') { # dir names can end in delimiters 186591f110e0Safresh1 $template =~ m/([\.\]:>]+)$/; 186691f110e0Safresh1 $suffixlen = length($1); 186791f110e0Safresh1 } 186891f110e0Safresh1 if ( ($^O eq 'MacOS') && (substr($template, -1) eq ':') ) { 186991f110e0Safresh1 # dir name has a trailing ':' 187091f110e0Safresh1 ++$suffixlen; 187191f110e0Safresh1 } 187291f110e0Safresh1 my ($junk, $tmpdir, $errstr); 187391f110e0Safresh1 croak "Error creating temp directory from template $template\: $errstr" 187491f110e0Safresh1 unless (($junk, $tmpdir) = _gettemp($template, 187591f110e0Safresh1 "open" => 0, 187691f110e0Safresh1 "mkdir"=> 1 , 187791f110e0Safresh1 "suffixlen" => $suffixlen, 187891f110e0Safresh1 "ErrStr" => \$errstr, 187991f110e0Safresh1 ) ); 188091f110e0Safresh1 188191f110e0Safresh1 return $tmpdir; 188291f110e0Safresh1 188391f110e0Safresh1} 188491f110e0Safresh1 1885f3efcd01Safresh1#pod =item B<mktemp> 1886f3efcd01Safresh1#pod 1887f3efcd01Safresh1#pod Returns a valid temporary filename but does not guarantee 1888f3efcd01Safresh1#pod that the file will not be opened by someone else. 1889f3efcd01Safresh1#pod 1890f3efcd01Safresh1#pod $unopened_file = mktemp($template); 1891f3efcd01Safresh1#pod 1892f3efcd01Safresh1#pod Template is the same as that required by mkstemp(). 1893f3efcd01Safresh1#pod 1894f3efcd01Safresh1#pod Will croak() if there is an error. 1895f3efcd01Safresh1#pod 1896f3efcd01Safresh1#pod Current API available since 0.05. 1897f3efcd01Safresh1#pod 1898f3efcd01Safresh1#pod =cut 189991f110e0Safresh1 190091f110e0Safresh1sub mktemp { 190191f110e0Safresh1 190291f110e0Safresh1 croak "Usage: mktemp(template)" 190391f110e0Safresh1 if scalar(@_) != 1; 190491f110e0Safresh1 190591f110e0Safresh1 my $template = shift; 190691f110e0Safresh1 190791f110e0Safresh1 my ($tmpname, $junk, $errstr); 190891f110e0Safresh1 croak "Error getting name to temp file from template $template: $errstr" 190991f110e0Safresh1 unless (($junk, $tmpname) = _gettemp($template, 191091f110e0Safresh1 "open" => 0, 191191f110e0Safresh1 "mkdir"=> 0 , 191291f110e0Safresh1 "suffixlen" => 0, 191391f110e0Safresh1 "ErrStr" => \$errstr, 191491f110e0Safresh1 ) ); 191591f110e0Safresh1 191691f110e0Safresh1 return $tmpname; 191791f110e0Safresh1} 191891f110e0Safresh1 1919f3efcd01Safresh1#pod =back 1920f3efcd01Safresh1#pod 1921f3efcd01Safresh1#pod =head1 POSIX FUNCTIONS 1922f3efcd01Safresh1#pod 1923f3efcd01Safresh1#pod This section describes the re-implementation of the tmpnam() 1924f3efcd01Safresh1#pod and tmpfile() functions described in L<POSIX> 1925f3efcd01Safresh1#pod using the mkstemp() from this module. 1926f3efcd01Safresh1#pod 1927f3efcd01Safresh1#pod Unlike the L<POSIX|POSIX> implementations, the directory used 1928f3efcd01Safresh1#pod for the temporary file is not specified in a system include 1929f3efcd01Safresh1#pod file (C<P_tmpdir>) but simply depends on the choice of tmpdir() 1930f3efcd01Safresh1#pod returned by L<File::Spec|File::Spec>. On some implementations this 1931f3efcd01Safresh1#pod location can be set using the C<TMPDIR> environment variable, which 1932f3efcd01Safresh1#pod may not be secure. 1933f3efcd01Safresh1#pod If this is a problem, simply use mkstemp() and specify a template. 1934f3efcd01Safresh1#pod 1935f3efcd01Safresh1#pod =over 4 1936f3efcd01Safresh1#pod 1937f3efcd01Safresh1#pod =item B<tmpnam> 1938f3efcd01Safresh1#pod 1939f3efcd01Safresh1#pod When called in scalar context, returns the full name (including path) 1940f3efcd01Safresh1#pod of a temporary file (uses mktemp()). The only check is that the file does 1941f3efcd01Safresh1#pod not already exist, but there is no guarantee that that condition will 1942f3efcd01Safresh1#pod continue to apply. 1943f3efcd01Safresh1#pod 1944f3efcd01Safresh1#pod $file = tmpnam(); 1945f3efcd01Safresh1#pod 1946f3efcd01Safresh1#pod When called in list context, a filehandle to the open file and 1947f3efcd01Safresh1#pod a filename are returned. This is achieved by calling mkstemp() 1948f3efcd01Safresh1#pod after constructing a suitable template. 1949f3efcd01Safresh1#pod 1950f3efcd01Safresh1#pod ($fh, $file) = tmpnam(); 1951f3efcd01Safresh1#pod 1952f3efcd01Safresh1#pod If possible, this form should be used to prevent possible 1953f3efcd01Safresh1#pod race conditions. 1954f3efcd01Safresh1#pod 1955f3efcd01Safresh1#pod See L<File::Spec/tmpdir> for information on the choice of temporary 1956f3efcd01Safresh1#pod directory for a particular operating system. 1957f3efcd01Safresh1#pod 1958f3efcd01Safresh1#pod Will croak() if there is an error. 1959f3efcd01Safresh1#pod 1960f3efcd01Safresh1#pod Current API available since 0.05. 1961f3efcd01Safresh1#pod 1962f3efcd01Safresh1#pod =cut 196391f110e0Safresh1 196491f110e0Safresh1sub tmpnam { 196591f110e0Safresh1 196691f110e0Safresh1 # Retrieve the temporary directory name 1967f3efcd01Safresh1 my $tmpdir = _wrap_file_spec_tmpdir(); 196891f110e0Safresh1 1969f3efcd01Safresh1 # XXX I don't know under what circumstances this occurs, -- xdg 2016-04-02 197091f110e0Safresh1 croak "Error temporary directory is not writable" 197191f110e0Safresh1 if $tmpdir eq ''; 197291f110e0Safresh1 197391f110e0Safresh1 # Use a ten character template and append to tmpdir 197491f110e0Safresh1 my $template = File::Spec->catfile($tmpdir, TEMPXXX); 197591f110e0Safresh1 197691f110e0Safresh1 if (wantarray() ) { 197791f110e0Safresh1 return mkstemp($template); 197891f110e0Safresh1 } else { 197991f110e0Safresh1 return mktemp($template); 198091f110e0Safresh1 } 198191f110e0Safresh1 198291f110e0Safresh1} 198391f110e0Safresh1 1984f3efcd01Safresh1#pod =item B<tmpfile> 1985f3efcd01Safresh1#pod 1986f3efcd01Safresh1#pod Returns the filehandle of a temporary file. 1987f3efcd01Safresh1#pod 1988f3efcd01Safresh1#pod $fh = tmpfile(); 1989f3efcd01Safresh1#pod 1990f3efcd01Safresh1#pod The file is removed when the filehandle is closed or when the program 1991f3efcd01Safresh1#pod exits. No access to the filename is provided. 1992f3efcd01Safresh1#pod 1993f3efcd01Safresh1#pod If the temporary file can not be created undef is returned. 1994f3efcd01Safresh1#pod Currently this command will probably not work when the temporary 1995f3efcd01Safresh1#pod directory is on an NFS file system. 1996f3efcd01Safresh1#pod 1997f3efcd01Safresh1#pod Will croak() if there is an error. 1998f3efcd01Safresh1#pod 1999f3efcd01Safresh1#pod Available since 0.05. 2000f3efcd01Safresh1#pod 2001f3efcd01Safresh1#pod Returning undef if unable to create file added in 0.12. 2002f3efcd01Safresh1#pod 2003f3efcd01Safresh1#pod =cut 200491f110e0Safresh1 200591f110e0Safresh1sub tmpfile { 200691f110e0Safresh1 200791f110e0Safresh1 # Simply call tmpnam() in a list context 200891f110e0Safresh1 my ($fh, $file) = tmpnam(); 200991f110e0Safresh1 201091f110e0Safresh1 # Make sure file is removed when filehandle is closed 201191f110e0Safresh1 # This will fail on NFS 201291f110e0Safresh1 unlink0($fh, $file) 201391f110e0Safresh1 or return undef; 201491f110e0Safresh1 201591f110e0Safresh1 return $fh; 201691f110e0Safresh1 201791f110e0Safresh1} 201891f110e0Safresh1 2019f3efcd01Safresh1#pod =back 2020f3efcd01Safresh1#pod 2021f3efcd01Safresh1#pod =head1 ADDITIONAL FUNCTIONS 2022f3efcd01Safresh1#pod 2023f3efcd01Safresh1#pod These functions are provided for backwards compatibility 2024f3efcd01Safresh1#pod with common tempfile generation C library functions. 2025f3efcd01Safresh1#pod 2026f3efcd01Safresh1#pod They are not exported and must be addressed using the full package 2027f3efcd01Safresh1#pod name. 2028f3efcd01Safresh1#pod 2029f3efcd01Safresh1#pod =over 4 2030f3efcd01Safresh1#pod 2031f3efcd01Safresh1#pod =item B<tempnam> 2032f3efcd01Safresh1#pod 2033f3efcd01Safresh1#pod Return the name of a temporary file in the specified directory 2034f3efcd01Safresh1#pod using a prefix. The file is guaranteed not to exist at the time 2035f3efcd01Safresh1#pod the function was called, but such guarantees are good for one 2036f3efcd01Safresh1#pod clock tick only. Always use the proper form of C<sysopen> 2037f3efcd01Safresh1#pod with C<O_CREAT | O_EXCL> if you must open such a filename. 2038f3efcd01Safresh1#pod 2039f3efcd01Safresh1#pod $filename = File::Temp::tempnam( $dir, $prefix ); 2040f3efcd01Safresh1#pod 2041f3efcd01Safresh1#pod Equivalent to running mktemp() with $dir/$prefixXXXXXXXX 2042f3efcd01Safresh1#pod (using unix file convention as an example) 2043f3efcd01Safresh1#pod 2044f3efcd01Safresh1#pod Because this function uses mktemp(), it can suffer from race conditions. 2045f3efcd01Safresh1#pod 2046f3efcd01Safresh1#pod Will croak() if there is an error. 2047f3efcd01Safresh1#pod 2048f3efcd01Safresh1#pod Current API available since 0.05. 2049f3efcd01Safresh1#pod 2050f3efcd01Safresh1#pod =cut 205191f110e0Safresh1 205291f110e0Safresh1sub tempnam { 205391f110e0Safresh1 205491f110e0Safresh1 croak 'Usage tempnam($dir, $prefix)' unless scalar(@_) == 2; 205591f110e0Safresh1 205691f110e0Safresh1 my ($dir, $prefix) = @_; 205791f110e0Safresh1 205891f110e0Safresh1 # Add a string to the prefix 205991f110e0Safresh1 $prefix .= 'XXXXXXXX'; 206091f110e0Safresh1 206191f110e0Safresh1 # Concatenate the directory to the file 206291f110e0Safresh1 my $template = File::Spec->catfile($dir, $prefix); 206391f110e0Safresh1 206491f110e0Safresh1 return mktemp($template); 206591f110e0Safresh1 206691f110e0Safresh1} 206791f110e0Safresh1 2068f3efcd01Safresh1#pod =back 2069f3efcd01Safresh1#pod 2070f3efcd01Safresh1#pod =head1 UTILITY FUNCTIONS 2071f3efcd01Safresh1#pod 2072f3efcd01Safresh1#pod Useful functions for dealing with the filehandle and filename. 2073f3efcd01Safresh1#pod 2074f3efcd01Safresh1#pod =over 4 2075f3efcd01Safresh1#pod 2076f3efcd01Safresh1#pod =item B<unlink0> 2077f3efcd01Safresh1#pod 2078f3efcd01Safresh1#pod Given an open filehandle and the associated filename, make a safe 2079f3efcd01Safresh1#pod unlink. This is achieved by first checking that the filename and 2080f3efcd01Safresh1#pod filehandle initially point to the same file and that the number of 2081f3efcd01Safresh1#pod links to the file is 1 (all fields returned by stat() are compared). 2082f3efcd01Safresh1#pod Then the filename is unlinked and the filehandle checked once again to 2083f3efcd01Safresh1#pod verify that the number of links on that file is now 0. This is the 2084f3efcd01Safresh1#pod closest you can come to making sure that the filename unlinked was the 2085f3efcd01Safresh1#pod same as the file whose descriptor you hold. 2086f3efcd01Safresh1#pod 2087f3efcd01Safresh1#pod unlink0($fh, $path) 2088f3efcd01Safresh1#pod or die "Error unlinking file $path safely"; 2089f3efcd01Safresh1#pod 2090f3efcd01Safresh1#pod Returns false on error but croaks() if there is a security 2091f3efcd01Safresh1#pod anomaly. The filehandle is not closed since on some occasions this is 2092f3efcd01Safresh1#pod not required. 2093f3efcd01Safresh1#pod 2094f3efcd01Safresh1#pod On some platforms, for example Windows NT, it is not possible to 2095f3efcd01Safresh1#pod unlink an open file (the file must be closed first). On those 2096f3efcd01Safresh1#pod platforms, the actual unlinking is deferred until the program ends and 2097f3efcd01Safresh1#pod good status is returned. A check is still performed to make sure that 2098f3efcd01Safresh1#pod the filehandle and filename are pointing to the same thing (but not at 2099f3efcd01Safresh1#pod the time the end block is executed since the deferred removal may not 2100f3efcd01Safresh1#pod have access to the filehandle). 2101f3efcd01Safresh1#pod 2102f3efcd01Safresh1#pod Additionally, on Windows NT not all the fields returned by stat() can 2103f3efcd01Safresh1#pod be compared. For example, the C<dev> and C<rdev> fields seem to be 2104f3efcd01Safresh1#pod different. Also, it seems that the size of the file returned by stat() 2105f3efcd01Safresh1#pod does not always agree, with C<stat(FH)> being more accurate than 2106f3efcd01Safresh1#pod C<stat(filename)>, presumably because of caching issues even when 2107f3efcd01Safresh1#pod using autoflush (this is usually overcome by waiting a while after 2108f3efcd01Safresh1#pod writing to the tempfile before attempting to C<unlink0> it). 2109f3efcd01Safresh1#pod 2110f3efcd01Safresh1#pod Finally, on NFS file systems the link count of the file handle does 2111f3efcd01Safresh1#pod not always go to zero immediately after unlinking. Currently, this 2112f3efcd01Safresh1#pod command is expected to fail on NFS disks. 2113f3efcd01Safresh1#pod 2114f3efcd01Safresh1#pod This function is disabled if the global variable $KEEP_ALL is true 2115f3efcd01Safresh1#pod and an unlink on open file is supported. If the unlink is to be deferred 2116f3efcd01Safresh1#pod to the END block, the file is still registered for removal. 2117f3efcd01Safresh1#pod 2118f3efcd01Safresh1#pod This function should not be called if you are using the object oriented 2119f3efcd01Safresh1#pod interface since the it will interfere with the object destructor deleting 2120f3efcd01Safresh1#pod the file. 2121f3efcd01Safresh1#pod 2122f3efcd01Safresh1#pod Available Since 0.05. 2123f3efcd01Safresh1#pod 2124f3efcd01Safresh1#pod If can not unlink open file, defer removal until later available since 0.06. 2125f3efcd01Safresh1#pod 2126f3efcd01Safresh1#pod =cut 212791f110e0Safresh1 212891f110e0Safresh1sub unlink0 { 212991f110e0Safresh1 213091f110e0Safresh1 croak 'Usage: unlink0(filehandle, filename)' 213191f110e0Safresh1 unless scalar(@_) == 2; 213291f110e0Safresh1 213391f110e0Safresh1 # Read args 213491f110e0Safresh1 my ($fh, $path) = @_; 213591f110e0Safresh1 213691f110e0Safresh1 cmpstat($fh, $path) or return 0; 213791f110e0Safresh1 213891f110e0Safresh1 # attempt remove the file (does not work on some platforms) 213991f110e0Safresh1 if (_can_unlink_opened_file()) { 214091f110e0Safresh1 214191f110e0Safresh1 # return early (Without unlink) if we have been instructed to retain files. 214291f110e0Safresh1 return 1 if $KEEP_ALL; 214391f110e0Safresh1 214491f110e0Safresh1 # XXX: do *not* call this on a directory; possible race 214591f110e0Safresh1 # resulting in recursive removal 214691f110e0Safresh1 croak "unlink0: $path has become a directory!" if -d $path; 214791f110e0Safresh1 unlink($path) or return 0; 214891f110e0Safresh1 214991f110e0Safresh1 # Stat the filehandle 215091f110e0Safresh1 my @fh = stat $fh; 215191f110e0Safresh1 215291f110e0Safresh1 print "Link count = $fh[3] \n" if $DEBUG; 215391f110e0Safresh1 215491f110e0Safresh1 # Make sure that the link count is zero 215591f110e0Safresh1 # - Cygwin provides deferred unlinking, however, 215691f110e0Safresh1 # on Win9x the link count remains 1 215791f110e0Safresh1 # On NFS the link count may still be 1 but we can't know that 215891f110e0Safresh1 # we are on NFS. Since we can't be sure, we'll defer it 215991f110e0Safresh1 216091f110e0Safresh1 return 1 if $fh[3] == 0 || $^O eq 'cygwin'; 216191f110e0Safresh1 } 216291f110e0Safresh1 # fall-through if we can't unlink now 216391f110e0Safresh1 _deferred_unlink($fh, $path, 0); 216491f110e0Safresh1 return 1; 216591f110e0Safresh1} 216691f110e0Safresh1 2167f3efcd01Safresh1#pod =item B<cmpstat> 2168f3efcd01Safresh1#pod 2169f3efcd01Safresh1#pod Compare C<stat> of filehandle with C<stat> of provided filename. This 2170f3efcd01Safresh1#pod can be used to check that the filename and filehandle initially point 2171f3efcd01Safresh1#pod to the same file and that the number of links to the file is 1 (all 2172f3efcd01Safresh1#pod fields returned by stat() are compared). 2173f3efcd01Safresh1#pod 2174f3efcd01Safresh1#pod cmpstat($fh, $path) 2175f3efcd01Safresh1#pod or die "Error comparing handle with file"; 2176f3efcd01Safresh1#pod 2177f3efcd01Safresh1#pod Returns false if the stat information differs or if the link count is 2178f3efcd01Safresh1#pod greater than 1. Calls croak if there is a security anomaly. 2179f3efcd01Safresh1#pod 2180f3efcd01Safresh1#pod On certain platforms, for example Windows, not all the fields returned by stat() 2181f3efcd01Safresh1#pod can be compared. For example, the C<dev> and C<rdev> fields seem to be 2182f3efcd01Safresh1#pod different in Windows. Also, it seems that the size of the file 2183f3efcd01Safresh1#pod returned by stat() does not always agree, with C<stat(FH)> being more 2184f3efcd01Safresh1#pod accurate than C<stat(filename)>, presumably because of caching issues 2185f3efcd01Safresh1#pod even when using autoflush (this is usually overcome by waiting a while 2186f3efcd01Safresh1#pod after writing to the tempfile before attempting to C<unlink0> it). 2187f3efcd01Safresh1#pod 2188f3efcd01Safresh1#pod Not exported by default. 2189f3efcd01Safresh1#pod 2190f3efcd01Safresh1#pod Current API available since 0.14. 2191f3efcd01Safresh1#pod 2192f3efcd01Safresh1#pod =cut 219391f110e0Safresh1 219491f110e0Safresh1sub cmpstat { 219591f110e0Safresh1 219691f110e0Safresh1 croak 'Usage: cmpstat(filehandle, filename)' 219791f110e0Safresh1 unless scalar(@_) == 2; 219891f110e0Safresh1 219991f110e0Safresh1 # Read args 220091f110e0Safresh1 my ($fh, $path) = @_; 220191f110e0Safresh1 220291f110e0Safresh1 warn "Comparing stat\n" 220391f110e0Safresh1 if $DEBUG; 220491f110e0Safresh1 220591f110e0Safresh1 # Stat the filehandle - which may be closed if someone has manually 220691f110e0Safresh1 # closed the file. Can not turn off warnings without using $^W 220791f110e0Safresh1 # unless we upgrade to 5.006 minimum requirement 220891f110e0Safresh1 my @fh; 220991f110e0Safresh1 { 221091f110e0Safresh1 local ($^W) = 0; 221191f110e0Safresh1 @fh = stat $fh; 221291f110e0Safresh1 } 221391f110e0Safresh1 return unless @fh; 221491f110e0Safresh1 221591f110e0Safresh1 if ($fh[3] > 1 && $^W) { 221691f110e0Safresh1 carp "unlink0: fstat found too many links; SB=@fh" if $^W; 221791f110e0Safresh1 } 221891f110e0Safresh1 221991f110e0Safresh1 # Stat the path 222091f110e0Safresh1 my @path = stat $path; 222191f110e0Safresh1 222291f110e0Safresh1 unless (@path) { 222391f110e0Safresh1 carp "unlink0: $path is gone already" if $^W; 222491f110e0Safresh1 return; 222591f110e0Safresh1 } 222691f110e0Safresh1 222791f110e0Safresh1 # this is no longer a file, but may be a directory, or worse 222891f110e0Safresh1 unless (-f $path) { 222991f110e0Safresh1 confess "panic: $path is no longer a file: SB=@fh"; 223091f110e0Safresh1 } 223191f110e0Safresh1 223291f110e0Safresh1 # Do comparison of each member of the array 223391f110e0Safresh1 # On WinNT dev and rdev seem to be different 223491f110e0Safresh1 # depending on whether it is a file or a handle. 223591f110e0Safresh1 # Cannot simply compare all members of the stat return 223691f110e0Safresh1 # Select the ones we can use 223791f110e0Safresh1 my @okstat = (0..$#fh); # Use all by default 223891f110e0Safresh1 if ($^O eq 'MSWin32') { 223991f110e0Safresh1 @okstat = (1,2,3,4,5,7,8,9,10); 224091f110e0Safresh1 } elsif ($^O eq 'os2') { 224191f110e0Safresh1 @okstat = (0, 2..$#fh); 224291f110e0Safresh1 } elsif ($^O eq 'VMS') { # device and file ID are sufficient 224391f110e0Safresh1 @okstat = (0, 1); 224491f110e0Safresh1 } elsif ($^O eq 'dos') { 224591f110e0Safresh1 @okstat = (0,2..7,11..$#fh); 224691f110e0Safresh1 } elsif ($^O eq 'mpeix') { 224791f110e0Safresh1 @okstat = (0..4,8..10); 224891f110e0Safresh1 } 224991f110e0Safresh1 225091f110e0Safresh1 # Now compare each entry explicitly by number 225191f110e0Safresh1 for (@okstat) { 225291f110e0Safresh1 print "Comparing: $_ : $fh[$_] and $path[$_]\n" if $DEBUG; 225391f110e0Safresh1 # Use eq rather than == since rdev, blksize, and blocks (6, 11, 225491f110e0Safresh1 # and 12) will be '' on platforms that do not support them. This 225591f110e0Safresh1 # is fine since we are only comparing integers. 225691f110e0Safresh1 unless ($fh[$_] eq $path[$_]) { 225791f110e0Safresh1 warn "Did not match $_ element of stat\n" if $DEBUG; 225891f110e0Safresh1 return 0; 225991f110e0Safresh1 } 226091f110e0Safresh1 } 226191f110e0Safresh1 226291f110e0Safresh1 return 1; 226391f110e0Safresh1} 226491f110e0Safresh1 2265f3efcd01Safresh1#pod =item B<unlink1> 2266f3efcd01Safresh1#pod 2267f3efcd01Safresh1#pod Similar to C<unlink0> except after file comparison using cmpstat, the 2268f3efcd01Safresh1#pod filehandle is closed prior to attempting to unlink the file. This 2269f3efcd01Safresh1#pod allows the file to be removed without using an END block, but does 2270f3efcd01Safresh1#pod mean that the post-unlink comparison of the filehandle state provided 2271f3efcd01Safresh1#pod by C<unlink0> is not available. 2272f3efcd01Safresh1#pod 2273f3efcd01Safresh1#pod unlink1($fh, $path) 2274f3efcd01Safresh1#pod or die "Error closing and unlinking file"; 2275f3efcd01Safresh1#pod 2276f3efcd01Safresh1#pod Usually called from the object destructor when using the OO interface. 2277f3efcd01Safresh1#pod 2278f3efcd01Safresh1#pod Not exported by default. 2279f3efcd01Safresh1#pod 2280f3efcd01Safresh1#pod This function is disabled if the global variable $KEEP_ALL is true. 2281f3efcd01Safresh1#pod 2282f3efcd01Safresh1#pod Can call croak() if there is a security anomaly during the stat() 2283f3efcd01Safresh1#pod comparison. 2284f3efcd01Safresh1#pod 2285f3efcd01Safresh1#pod Current API available since 0.14. 2286f3efcd01Safresh1#pod 2287f3efcd01Safresh1#pod =cut 228891f110e0Safresh1 228991f110e0Safresh1sub unlink1 { 229091f110e0Safresh1 croak 'Usage: unlink1(filehandle, filename)' 229191f110e0Safresh1 unless scalar(@_) == 2; 229291f110e0Safresh1 229391f110e0Safresh1 # Read args 229491f110e0Safresh1 my ($fh, $path) = @_; 229591f110e0Safresh1 229691f110e0Safresh1 cmpstat($fh, $path) or return 0; 229791f110e0Safresh1 229891f110e0Safresh1 # Close the file 229991f110e0Safresh1 close( $fh ) or return 0; 230091f110e0Safresh1 230191f110e0Safresh1 # Make sure the file is writable (for windows) 230291f110e0Safresh1 _force_writable( $path ); 230391f110e0Safresh1 230491f110e0Safresh1 # return early (without unlink) if we have been instructed to retain files. 230591f110e0Safresh1 return 1 if $KEEP_ALL; 230691f110e0Safresh1 230791f110e0Safresh1 # remove the file 230891f110e0Safresh1 return unlink($path); 230991f110e0Safresh1} 231091f110e0Safresh1 2311f3efcd01Safresh1#pod =item B<cleanup> 2312f3efcd01Safresh1#pod 2313f3efcd01Safresh1#pod Calling this function will cause any temp files or temp directories 2314f3efcd01Safresh1#pod that are registered for removal to be removed. This happens automatically 2315f3efcd01Safresh1#pod when the process exits but can be triggered manually if the caller is sure 2316f3efcd01Safresh1#pod that none of the temp files are required. This method can be registered as 2317f3efcd01Safresh1#pod an Apache callback. 2318f3efcd01Safresh1#pod 2319f3efcd01Safresh1#pod Note that if a temp directory is your current directory, it cannot be 2320f3efcd01Safresh1#pod removed. C<chdir()> out of the directory first before calling 2321f3efcd01Safresh1#pod C<cleanup()>. (For the cleanup at program exit when the CLEANUP flag 2322f3efcd01Safresh1#pod is set, this happens automatically.) 2323f3efcd01Safresh1#pod 2324f3efcd01Safresh1#pod On OSes where temp files are automatically removed when the temp file 2325f3efcd01Safresh1#pod is closed, calling this function will have no effect other than to remove 2326f3efcd01Safresh1#pod temporary directories (which may include temporary files). 2327f3efcd01Safresh1#pod 2328f3efcd01Safresh1#pod File::Temp::cleanup(); 2329f3efcd01Safresh1#pod 2330f3efcd01Safresh1#pod Not exported by default. 2331f3efcd01Safresh1#pod 2332f3efcd01Safresh1#pod Current API available since 0.15. 2333f3efcd01Safresh1#pod 2334f3efcd01Safresh1#pod =back 2335f3efcd01Safresh1#pod 2336f3efcd01Safresh1#pod =head1 PACKAGE VARIABLES 2337f3efcd01Safresh1#pod 2338f3efcd01Safresh1#pod These functions control the global state of the package. 2339f3efcd01Safresh1#pod 2340f3efcd01Safresh1#pod =over 4 2341f3efcd01Safresh1#pod 2342f3efcd01Safresh1#pod =item B<safe_level> 2343f3efcd01Safresh1#pod 2344f3efcd01Safresh1#pod Controls the lengths to which the module will go to check the safety of the 2345f3efcd01Safresh1#pod temporary file or directory before proceeding. 2346f3efcd01Safresh1#pod Options are: 2347f3efcd01Safresh1#pod 2348f3efcd01Safresh1#pod =over 8 2349f3efcd01Safresh1#pod 2350f3efcd01Safresh1#pod =item STANDARD 2351f3efcd01Safresh1#pod 2352f3efcd01Safresh1#pod Do the basic security measures to ensure the directory exists and is 2353f3efcd01Safresh1#pod writable, that temporary files are opened only if they do not already 2354f3efcd01Safresh1#pod exist, and that possible race conditions are avoided. Finally the 2355f3efcd01Safresh1#pod L<unlink0|"unlink0"> function is used to remove files safely. 2356f3efcd01Safresh1#pod 2357f3efcd01Safresh1#pod =item MEDIUM 2358f3efcd01Safresh1#pod 2359f3efcd01Safresh1#pod In addition to the STANDARD security, the output directory is checked 2360f3efcd01Safresh1#pod to make sure that it is owned either by root or the user running the 2361f3efcd01Safresh1#pod program. If the directory is writable by group or by other, it is then 2362f3efcd01Safresh1#pod checked to make sure that the sticky bit is set. 2363f3efcd01Safresh1#pod 2364f3efcd01Safresh1#pod Will not work on platforms that do not support the C<-k> test 2365f3efcd01Safresh1#pod for sticky bit. 2366f3efcd01Safresh1#pod 2367f3efcd01Safresh1#pod =item HIGH 2368f3efcd01Safresh1#pod 2369f3efcd01Safresh1#pod In addition to the MEDIUM security checks, also check for the 2370f3efcd01Safresh1#pod possibility of ``chown() giveaway'' using the L<POSIX|POSIX> 2371f3efcd01Safresh1#pod sysconf() function. If this is a possibility, each directory in the 2372f3efcd01Safresh1#pod path is checked in turn for safeness, recursively walking back to the 2373f3efcd01Safresh1#pod root directory. 2374f3efcd01Safresh1#pod 2375f3efcd01Safresh1#pod For platforms that do not support the L<POSIX|POSIX> 2376f3efcd01Safresh1#pod C<_PC_CHOWN_RESTRICTED> symbol (for example, Windows NT) it is 2377f3efcd01Safresh1#pod assumed that ``chown() giveaway'' is possible and the recursive test 2378f3efcd01Safresh1#pod is performed. 2379f3efcd01Safresh1#pod 2380f3efcd01Safresh1#pod =back 2381f3efcd01Safresh1#pod 2382f3efcd01Safresh1#pod The level can be changed as follows: 2383f3efcd01Safresh1#pod 2384f3efcd01Safresh1#pod File::Temp->safe_level( File::Temp::HIGH ); 2385f3efcd01Safresh1#pod 2386f3efcd01Safresh1#pod The level constants are not exported by the module. 2387f3efcd01Safresh1#pod 2388f3efcd01Safresh1#pod Currently, you must be running at least perl v5.6.0 in order to 2389f3efcd01Safresh1#pod run with MEDIUM or HIGH security. This is simply because the 2390f3efcd01Safresh1#pod safety tests use functions from L<Fcntl|Fcntl> that are not 2391f3efcd01Safresh1#pod available in older versions of perl. The problem is that the version 2392f3efcd01Safresh1#pod number for Fcntl is the same in perl 5.6.0 and in 5.005_03 even though 2393f3efcd01Safresh1#pod they are different versions. 2394f3efcd01Safresh1#pod 2395f3efcd01Safresh1#pod On systems that do not support the HIGH or MEDIUM safety levels 2396f3efcd01Safresh1#pod (for example Win NT or OS/2) any attempt to change the level will 2397f3efcd01Safresh1#pod be ignored. The decision to ignore rather than raise an exception 2398f3efcd01Safresh1#pod allows portable programs to be written with high security in mind 2399f3efcd01Safresh1#pod for the systems that can support this without those programs failing 2400f3efcd01Safresh1#pod on systems where the extra tests are irrelevant. 2401f3efcd01Safresh1#pod 2402f3efcd01Safresh1#pod If you really need to see whether the change has been accepted 2403f3efcd01Safresh1#pod simply examine the return value of C<safe_level>. 2404f3efcd01Safresh1#pod 2405f3efcd01Safresh1#pod $newlevel = File::Temp->safe_level( File::Temp::HIGH ); 2406f3efcd01Safresh1#pod die "Could not change to high security" 2407f3efcd01Safresh1#pod if $newlevel != File::Temp::HIGH; 2408f3efcd01Safresh1#pod 2409f3efcd01Safresh1#pod Available since 0.05. 2410f3efcd01Safresh1#pod 2411f3efcd01Safresh1#pod =cut 24126fb12b70Safresh1 24136fb12b70Safresh1{ 24146fb12b70Safresh1 # protect from using the variable itself 24156fb12b70Safresh1 my $LEVEL = STANDARD; 24166fb12b70Safresh1 sub safe_level { 24176fb12b70Safresh1 my $self = shift; 24186fb12b70Safresh1 if (@_) { 24196fb12b70Safresh1 my $level = shift; 24206fb12b70Safresh1 if (($level != STANDARD) && ($level != MEDIUM) && ($level != HIGH)) { 24216fb12b70Safresh1 carp "safe_level: Specified level ($level) not STANDARD, MEDIUM or HIGH - ignoring\n" if $^W; 24226fb12b70Safresh1 } else { 24236fb12b70Safresh1 # Don't allow this on perl 5.005 or earlier 24246fb12b70Safresh1 if ($] < 5.006 && $level != STANDARD) { 24256fb12b70Safresh1 # Cant do MEDIUM or HIGH checks 24266fb12b70Safresh1 croak "Currently requires perl 5.006 or newer to do the safe checks"; 24276fb12b70Safresh1 } 24286fb12b70Safresh1 # Check that we are allowed to change level 24296fb12b70Safresh1 # Silently ignore if we can not. 24306fb12b70Safresh1 $LEVEL = $level if _can_do_level($level); 24316fb12b70Safresh1 } 24326fb12b70Safresh1 } 24336fb12b70Safresh1 return $LEVEL; 24346fb12b70Safresh1 } 24356fb12b70Safresh1} 24366fb12b70Safresh1 2437f3efcd01Safresh1#pod =item TopSystemUID 2438f3efcd01Safresh1#pod 2439f3efcd01Safresh1#pod This is the highest UID on the current system that refers to a root 2440f3efcd01Safresh1#pod UID. This is used to make sure that the temporary directory is 2441f3efcd01Safresh1#pod owned by a system UID (C<root>, C<bin>, C<sys> etc) rather than 2442f3efcd01Safresh1#pod simply by root. 2443f3efcd01Safresh1#pod 2444f3efcd01Safresh1#pod This is required since on many unix systems C</tmp> is not owned 2445f3efcd01Safresh1#pod by root. 2446f3efcd01Safresh1#pod 2447f3efcd01Safresh1#pod Default is to assume that any UID less than or equal to 10 is a root 2448f3efcd01Safresh1#pod UID. 2449f3efcd01Safresh1#pod 2450f3efcd01Safresh1#pod File::Temp->top_system_uid(10); 2451f3efcd01Safresh1#pod my $topid = File::Temp->top_system_uid; 2452f3efcd01Safresh1#pod 2453f3efcd01Safresh1#pod This value can be adjusted to reduce security checking if required. 2454f3efcd01Safresh1#pod The value is only relevant when C<safe_level> is set to MEDIUM or higher. 2455f3efcd01Safresh1#pod 2456f3efcd01Safresh1#pod Available since 0.05. 2457f3efcd01Safresh1#pod 2458f3efcd01Safresh1#pod =cut 24596fb12b70Safresh1 24606fb12b70Safresh1{ 24616fb12b70Safresh1 my $TopSystemUID = 10; 24626fb12b70Safresh1 $TopSystemUID = 197108 if $^O eq 'interix'; # "Administrator" 24636fb12b70Safresh1 sub top_system_uid { 24646fb12b70Safresh1 my $self = shift; 24656fb12b70Safresh1 if (@_) { 24666fb12b70Safresh1 my $newuid = shift; 24676fb12b70Safresh1 croak "top_system_uid: UIDs should be numeric" 24686fb12b70Safresh1 unless $newuid =~ /^\d+$/s; 24696fb12b70Safresh1 $TopSystemUID = $newuid; 24706fb12b70Safresh1 } 24716fb12b70Safresh1 return $TopSystemUID; 24726fb12b70Safresh1 } 24736fb12b70Safresh1} 24746fb12b70Safresh1 2475f3efcd01Safresh1#pod =item B<$KEEP_ALL> 2476f3efcd01Safresh1#pod 2477f3efcd01Safresh1#pod Controls whether temporary files and directories should be retained 2478f3efcd01Safresh1#pod regardless of any instructions in the program to remove them 2479f3efcd01Safresh1#pod automatically. This is useful for debugging but should not be used in 2480f3efcd01Safresh1#pod production code. 2481f3efcd01Safresh1#pod 2482f3efcd01Safresh1#pod $File::Temp::KEEP_ALL = 1; 2483f3efcd01Safresh1#pod 2484f3efcd01Safresh1#pod Default is for files to be removed as requested by the caller. 2485f3efcd01Safresh1#pod 2486f3efcd01Safresh1#pod In some cases, files will only be retained if this variable is true 2487f3efcd01Safresh1#pod when the file is created. This means that you can not create a temporary 2488f3efcd01Safresh1#pod file, set this variable and expect the temp file to still be around 2489f3efcd01Safresh1#pod when the program exits. 2490f3efcd01Safresh1#pod 2491f3efcd01Safresh1#pod =item B<$DEBUG> 2492f3efcd01Safresh1#pod 2493f3efcd01Safresh1#pod Controls whether debugging messages should be enabled. 2494f3efcd01Safresh1#pod 2495f3efcd01Safresh1#pod $File::Temp::DEBUG = 1; 2496f3efcd01Safresh1#pod 2497f3efcd01Safresh1#pod Default is for debugging mode to be disabled. 2498f3efcd01Safresh1#pod 2499f3efcd01Safresh1#pod Available since 0.15. 2500f3efcd01Safresh1#pod 2501f3efcd01Safresh1#pod =back 2502f3efcd01Safresh1#pod 2503f3efcd01Safresh1#pod =head1 WARNING 2504f3efcd01Safresh1#pod 2505f3efcd01Safresh1#pod For maximum security, endeavour always to avoid ever looking at, 2506f3efcd01Safresh1#pod touching, or even imputing the existence of the filename. You do not 2507f3efcd01Safresh1#pod know that that filename is connected to the same file as the handle 2508f3efcd01Safresh1#pod you have, and attempts to check this can only trigger more race 2509f3efcd01Safresh1#pod conditions. It's far more secure to use the filehandle alone and 2510f3efcd01Safresh1#pod dispense with the filename altogether. 2511f3efcd01Safresh1#pod 2512f3efcd01Safresh1#pod If you need to pass the handle to something that expects a filename 2513f3efcd01Safresh1#pod then on a unix system you can use C<"/dev/fd/" . fileno($fh)> for 2514f3efcd01Safresh1#pod arbitrary programs. Perl code that uses the 2-argument version of 2515f3efcd01Safresh1#pod C<< open >> can be passed C<< "+<=&" . fileno($fh) >>. Otherwise you 2516f3efcd01Safresh1#pod will need to pass the filename. You will have to clear the 2517f3efcd01Safresh1#pod close-on-exec bit on that file descriptor before passing it to another 2518f3efcd01Safresh1#pod process. 2519f3efcd01Safresh1#pod 2520f3efcd01Safresh1#pod use Fcntl qw/F_SETFD F_GETFD/; 2521f3efcd01Safresh1#pod fcntl($tmpfh, F_SETFD, 0) 2522f3efcd01Safresh1#pod or die "Can't clear close-on-exec flag on temp fh: $!\n"; 2523f3efcd01Safresh1#pod 2524f3efcd01Safresh1#pod =head2 Temporary files and NFS 2525f3efcd01Safresh1#pod 2526f3efcd01Safresh1#pod Some problems are associated with using temporary files that reside 2527f3efcd01Safresh1#pod on NFS file systems and it is recommended that a local filesystem 2528f3efcd01Safresh1#pod is used whenever possible. Some of the security tests will most probably 2529f3efcd01Safresh1#pod fail when the temp file is not local. Additionally, be aware that 2530f3efcd01Safresh1#pod the performance of I/O operations over NFS will not be as good as for 2531f3efcd01Safresh1#pod a local disk. 2532f3efcd01Safresh1#pod 2533f3efcd01Safresh1#pod =head2 Forking 2534f3efcd01Safresh1#pod 2535f3efcd01Safresh1#pod In some cases files created by File::Temp are removed from within an 2536f3efcd01Safresh1#pod END block. Since END blocks are triggered when a child process exits 2537f3efcd01Safresh1#pod (unless C<POSIX::_exit()> is used by the child) File::Temp takes care 2538f3efcd01Safresh1#pod to only remove those temp files created by a particular process ID. This 2539f3efcd01Safresh1#pod means that a child will not attempt to remove temp files created by the 2540f3efcd01Safresh1#pod parent process. 2541f3efcd01Safresh1#pod 2542f3efcd01Safresh1#pod If you are forking many processes in parallel that are all creating 2543f3efcd01Safresh1#pod temporary files, you may need to reset the random number seed using 2544f3efcd01Safresh1#pod srand(EXPR) in each child else all the children will attempt to walk 2545f3efcd01Safresh1#pod through the same set of random file names and may well cause 2546f3efcd01Safresh1#pod themselves to give up if they exceed the number of retry attempts. 2547f3efcd01Safresh1#pod 2548f3efcd01Safresh1#pod =head2 Directory removal 2549f3efcd01Safresh1#pod 2550f3efcd01Safresh1#pod Note that if you have chdir'ed into the temporary directory and it is 2551f3efcd01Safresh1#pod subsequently cleaned up (either in the END block or as part of object 2552f3efcd01Safresh1#pod destruction), then you will get a warning from File::Path::rmtree(). 2553f3efcd01Safresh1#pod 2554f3efcd01Safresh1#pod =head2 Taint mode 2555f3efcd01Safresh1#pod 2556f3efcd01Safresh1#pod If you need to run code under taint mode, updating to the latest 2557f3efcd01Safresh1#pod L<File::Spec> is highly recommended. On Windows, if the directory 2558f3efcd01Safresh1#pod given by L<File::Spec::tmpdir> isn't writable, File::Temp will attempt 2559f3efcd01Safresh1#pod to fallback to the user's local application data directory or croak 2560f3efcd01Safresh1#pod with an error. 2561f3efcd01Safresh1#pod 2562f3efcd01Safresh1#pod =head2 BINMODE 2563f3efcd01Safresh1#pod 2564f3efcd01Safresh1#pod The file returned by File::Temp will have been opened in binary mode 2565f3efcd01Safresh1#pod if such a mode is available. If that is not correct, use the C<binmode()> 2566f3efcd01Safresh1#pod function to change the mode of the filehandle. 2567f3efcd01Safresh1#pod 2568f3efcd01Safresh1#pod Note that you can modify the encoding of a file opened by File::Temp 2569f3efcd01Safresh1#pod also by using C<binmode()>. 2570f3efcd01Safresh1#pod 2571f3efcd01Safresh1#pod =head1 HISTORY 2572f3efcd01Safresh1#pod 2573f3efcd01Safresh1#pod Originally began life in May 1999 as an XS interface to the system 2574f3efcd01Safresh1#pod mkstemp() function. In March 2000, the OpenBSD mkstemp() code was 2575f3efcd01Safresh1#pod translated to Perl for total control of the code's 2576f3efcd01Safresh1#pod security checking, to ensure the presence of the function regardless of 2577f3efcd01Safresh1#pod operating system and to help with portability. The module was shipped 2578f3efcd01Safresh1#pod as a standard part of perl from v5.6.1. 2579f3efcd01Safresh1#pod 2580f3efcd01Safresh1#pod Thanks to Tom Christiansen for suggesting that this module 2581f3efcd01Safresh1#pod should be written and providing ideas for code improvements and 2582f3efcd01Safresh1#pod security enhancements. 2583f3efcd01Safresh1#pod 2584f3efcd01Safresh1#pod =head1 SEE ALSO 2585f3efcd01Safresh1#pod 2586f3efcd01Safresh1#pod L<POSIX/tmpnam>, L<POSIX/tmpfile>, L<File::Spec>, L<File::Path> 2587f3efcd01Safresh1#pod 2588f3efcd01Safresh1#pod See L<IO::File> and L<File::MkTemp>, L<Apache::TempFile> for 2589f3efcd01Safresh1#pod different implementations of temporary file handling. 2590f3efcd01Safresh1#pod 2591f3efcd01Safresh1#pod See L<File::Tempdir> for an alternative object-oriented wrapper for 2592f3efcd01Safresh1#pod the C<tempdir> function. 2593f3efcd01Safresh1#pod 2594f3efcd01Safresh1#pod =cut 25956fb12b70Safresh1 2596f3efcd01Safresh1package ## hide from PAUSE 2597f3efcd01Safresh1 File::Temp::Dir; 2598f3efcd01Safresh1 2599*256a93a4Safresh1our $VERSION = '0.2311'; 26006fb12b70Safresh1 26016fb12b70Safresh1use File::Path qw/ rmtree /; 26026fb12b70Safresh1use strict; 26036fb12b70Safresh1use overload '""' => "STRINGIFY", 26046fb12b70Safresh1 '0+' => \&File::Temp::NUMIFY, 26056fb12b70Safresh1 fallback => 1; 26066fb12b70Safresh1 26076fb12b70Safresh1# private class specifically to support tempdir objects 26086fb12b70Safresh1# created by File::Temp->newdir 26096fb12b70Safresh1 26106fb12b70Safresh1# ostensibly the same method interface as File::Temp but without 26116fb12b70Safresh1# inheriting all the IO::Seekable methods and other cruft 26126fb12b70Safresh1 26136fb12b70Safresh1# Read-only - returns the name of the temp directory 26146fb12b70Safresh1 26156fb12b70Safresh1sub dirname { 26166fb12b70Safresh1 my $self = shift; 26176fb12b70Safresh1 return $self->{DIRNAME}; 26186fb12b70Safresh1} 26196fb12b70Safresh1 26206fb12b70Safresh1sub STRINGIFY { 26216fb12b70Safresh1 my $self = shift; 26226fb12b70Safresh1 return $self->dirname; 26236fb12b70Safresh1} 26246fb12b70Safresh1 26256fb12b70Safresh1sub unlink_on_destroy { 26266fb12b70Safresh1 my $self = shift; 26276fb12b70Safresh1 if (@_) { 26286fb12b70Safresh1 $self->{CLEANUP} = shift; 26296fb12b70Safresh1 } 26306fb12b70Safresh1 return $self->{CLEANUP}; 26316fb12b70Safresh1} 26326fb12b70Safresh1 26336fb12b70Safresh1sub DESTROY { 26346fb12b70Safresh1 my $self = shift; 26356fb12b70Safresh1 local($., $@, $!, $^E, $?); 26366fb12b70Safresh1 if ($self->unlink_on_destroy && 26376fb12b70Safresh1 $$ == $self->{LAUNCHPID} && !$File::Temp::KEEP_ALL) { 26386fb12b70Safresh1 if (-d $self->{REALNAME}) { 26396fb12b70Safresh1 # Some versions of rmtree will abort if you attempt to remove 26406fb12b70Safresh1 # the directory you are sitting in. We protect that and turn it 26416fb12b70Safresh1 # into a warning. We do this because this occurs during object 26426fb12b70Safresh1 # destruction and so can not be caught by the user. 26436fb12b70Safresh1 eval { rmtree($self->{REALNAME}, $File::Temp::DEBUG, 0); }; 26446fb12b70Safresh1 warn $@ if ($@ && $^W); 26456fb12b70Safresh1 } 26466fb12b70Safresh1 } 26476fb12b70Safresh1} 26486fb12b70Safresh1 26496fb12b70Safresh11; 26506fb12b70Safresh1 2651f3efcd01Safresh1 2652f3efcd01Safresh1# vim: ts=2 sts=2 sw=2 et: 2653f3efcd01Safresh1 26546fb12b70Safresh1__END__ 26556fb12b70Safresh1 26566fb12b70Safresh1=pod 26576fb12b70Safresh1 2658f3efcd01Safresh1=encoding UTF-8 26596fb12b70Safresh1 26606fb12b70Safresh1=head1 NAME 26616fb12b70Safresh1 26626fb12b70Safresh1File::Temp - return name and handle of a temporary file safely 26636fb12b70Safresh1 26646fb12b70Safresh1=head1 VERSION 26656fb12b70Safresh1 2666*256a93a4Safresh1version 0.2311 26676fb12b70Safresh1 26686fb12b70Safresh1=head1 SYNOPSIS 26696fb12b70Safresh1 26706fb12b70Safresh1 use File::Temp qw/ tempfile tempdir /; 26716fb12b70Safresh1 26726fb12b70Safresh1 $fh = tempfile(); 26736fb12b70Safresh1 ($fh, $filename) = tempfile(); 26746fb12b70Safresh1 26756fb12b70Safresh1 ($fh, $filename) = tempfile( $template, DIR => $dir); 26766fb12b70Safresh1 ($fh, $filename) = tempfile( $template, SUFFIX => '.dat'); 26776fb12b70Safresh1 ($fh, $filename) = tempfile( $template, TMPDIR => 1 ); 26786fb12b70Safresh1 26796fb12b70Safresh1 binmode( $fh, ":utf8" ); 26806fb12b70Safresh1 26816fb12b70Safresh1 $dir = tempdir( CLEANUP => 1 ); 26826fb12b70Safresh1 ($fh, $filename) = tempfile( DIR => $dir ); 26836fb12b70Safresh1 26846fb12b70Safresh1Object interface: 26856fb12b70Safresh1 26866fb12b70Safresh1 require File::Temp; 26876fb12b70Safresh1 use File::Temp (); 26886fb12b70Safresh1 use File::Temp qw/ :seekable /; 26896fb12b70Safresh1 26906fb12b70Safresh1 $fh = File::Temp->new(); 26916fb12b70Safresh1 $fname = $fh->filename; 26926fb12b70Safresh1 26936fb12b70Safresh1 $fh = File::Temp->new(TEMPLATE => $template); 26946fb12b70Safresh1 $fname = $fh->filename; 26956fb12b70Safresh1 26966fb12b70Safresh1 $tmp = File::Temp->new( UNLINK => 0, SUFFIX => '.dat' ); 26976fb12b70Safresh1 print $tmp "Some data\n"; 26986fb12b70Safresh1 print "Filename is $tmp\n"; 26996fb12b70Safresh1 $tmp->seek( 0, SEEK_END ); 27006fb12b70Safresh1 2701f3efcd01Safresh1 $dir = File::Temp->newdir(); # CLEANUP => 1 by default 2702f3efcd01Safresh1 27036fb12b70Safresh1The following interfaces are provided for compatibility with 27046fb12b70Safresh1existing APIs. They should not be used in new code. 27056fb12b70Safresh1 27066fb12b70Safresh1MkTemp family: 27076fb12b70Safresh1 27086fb12b70Safresh1 use File::Temp qw/ :mktemp /; 27096fb12b70Safresh1 27106fb12b70Safresh1 ($fh, $file) = mkstemp( "tmpfileXXXXX" ); 27116fb12b70Safresh1 ($fh, $file) = mkstemps( "tmpfileXXXXXX", $suffix); 27126fb12b70Safresh1 27136fb12b70Safresh1 $tmpdir = mkdtemp( $template ); 27146fb12b70Safresh1 27156fb12b70Safresh1 $unopened_file = mktemp( $template ); 27166fb12b70Safresh1 27176fb12b70Safresh1POSIX functions: 27186fb12b70Safresh1 27196fb12b70Safresh1 use File::Temp qw/ :POSIX /; 27206fb12b70Safresh1 27216fb12b70Safresh1 $file = tmpnam(); 27226fb12b70Safresh1 $fh = tmpfile(); 27236fb12b70Safresh1 27246fb12b70Safresh1 ($fh, $file) = tmpnam(); 27256fb12b70Safresh1 27266fb12b70Safresh1Compatibility functions: 27276fb12b70Safresh1 27286fb12b70Safresh1 $unopened_file = File::Temp::tempnam( $dir, $pfx ); 27296fb12b70Safresh1 27306fb12b70Safresh1=head1 DESCRIPTION 27316fb12b70Safresh1 27326fb12b70Safresh1C<File::Temp> can be used to create and open temporary files in a safe 27336fb12b70Safresh1way. There is both a function interface and an object-oriented 27346fb12b70Safresh1interface. The File::Temp constructor or the tempfile() function can 27356fb12b70Safresh1be used to return the name and the open filehandle of a temporary 27366fb12b70Safresh1file. The tempdir() function can be used to create a temporary 27376fb12b70Safresh1directory. 27386fb12b70Safresh1 27396fb12b70Safresh1The security aspect of temporary file creation is emphasized such that 27406fb12b70Safresh1a filehandle and filename are returned together. This helps guarantee 27416fb12b70Safresh1that a race condition can not occur where the temporary file is 27426fb12b70Safresh1created by another process between checking for the existence of the 27436fb12b70Safresh1file and its opening. Additional security levels are provided to 27446fb12b70Safresh1check, for example, that the sticky bit is set on world writable 27456fb12b70Safresh1directories. See L<"safe_level"> for more information. 27466fb12b70Safresh1 27476fb12b70Safresh1For compatibility with popular C library functions, Perl implementations of 27486fb12b70Safresh1the mkstemp() family of functions are provided. These are, mkstemp(), 27496fb12b70Safresh1mkstemps(), mkdtemp() and mktemp(). 27506fb12b70Safresh1 27516fb12b70Safresh1Additionally, implementations of the standard L<POSIX|POSIX> 27526fb12b70Safresh1tmpnam() and tmpfile() functions are provided if required. 27536fb12b70Safresh1 27546fb12b70Safresh1Implementations of mktemp(), tmpnam(), and tempnam() are provided, 27556fb12b70Safresh1but should be used with caution since they return only a filename 27566fb12b70Safresh1that was valid when function was called, so cannot guarantee 27576fb12b70Safresh1that the file will not exist by the time the caller opens the filename. 27586fb12b70Safresh1 27596fb12b70Safresh1Filehandles returned by these functions support the seekable methods. 27606fb12b70Safresh1 2761f3efcd01Safresh1=begin :__INTERNALS 27626fb12b70Safresh1 27636fb12b70Safresh1=head1 PORTABILITY 27646fb12b70Safresh1 27656fb12b70Safresh1This section is at the top in order to provide easier access to 27666fb12b70Safresh1porters. It is not expected to be rendered by a standard pod 27676fb12b70Safresh1formatting tool. Please skip straight to the SYNOPSIS section if you 27686fb12b70Safresh1are not trying to port this module to a new platform. 27696fb12b70Safresh1 27706fb12b70Safresh1This module is designed to be portable across operating systems and it 27716fb12b70Safresh1currently supports Unix, VMS, DOS, OS/2, Windows and Mac OS 27726fb12b70Safresh1(Classic). When porting to a new OS there are generally three main 27736fb12b70Safresh1issues that have to be solved: 2774f3efcd01Safresh1 27756fb12b70Safresh1=over 4 27766fb12b70Safresh1 27776fb12b70Safresh1=item * 27786fb12b70Safresh1 27796fb12b70Safresh1Can the OS unlink an open file? If it can not then the 27806fb12b70Safresh1C<_can_unlink_opened_file> method should be modified. 27816fb12b70Safresh1 27826fb12b70Safresh1=item * 27836fb12b70Safresh1 27846fb12b70Safresh1Are the return values from C<stat> reliable? By default all the 27856fb12b70Safresh1return values from C<stat> are compared when unlinking a temporary 27866fb12b70Safresh1file using the filename and the handle. Operating systems other than 27876fb12b70Safresh1unix do not always have valid entries in all fields. If utility function 27886fb12b70Safresh1C<File::Temp::unlink0> fails then the C<stat> comparison should be 27896fb12b70Safresh1modified accordingly. 27906fb12b70Safresh1 27916fb12b70Safresh1=item * 27926fb12b70Safresh1 27936fb12b70Safresh1Security. Systems that can not support a test for the sticky bit 27946fb12b70Safresh1on a directory can not use the MEDIUM and HIGH security tests. 27956fb12b70Safresh1The C<_can_do_level> method should be modified accordingly. 27966fb12b70Safresh1 27976fb12b70Safresh1=back 27986fb12b70Safresh1 2799f3efcd01Safresh1=end :__INTERNALS 28006fb12b70Safresh1 28016fb12b70Safresh1=head1 OBJECT-ORIENTED INTERFACE 28026fb12b70Safresh1 28036fb12b70Safresh1This is the primary interface for interacting with 28046fb12b70Safresh1C<File::Temp>. Using the OO interface a temporary file can be created 28056fb12b70Safresh1when the object is constructed and the file can be removed when the 28066fb12b70Safresh1object is no longer required. 28076fb12b70Safresh1 28086fb12b70Safresh1Note that there is no method to obtain the filehandle from the 28096fb12b70Safresh1C<File::Temp> object. The object itself acts as a filehandle. The object 28106fb12b70Safresh1isa C<IO::Handle> and isa C<IO::Seekable> so all those methods are 28116fb12b70Safresh1available. 28126fb12b70Safresh1 28136fb12b70Safresh1Also, the object is configured such that it stringifies to the name of the 28146fb12b70Safresh1temporary file and so can be compared to a filename directly. It numifies 28156fb12b70Safresh1to the C<refaddr> the same as other handles and so can be compared to other 28166fb12b70Safresh1handles with C<==>. 28176fb12b70Safresh1 28186fb12b70Safresh1 $fh eq $filename # as a string 28196fb12b70Safresh1 $fh != \*STDOUT # as a number 28206fb12b70Safresh1 2821f3efcd01Safresh1Available since 0.14. 2822f3efcd01Safresh1 28236fb12b70Safresh1=over 4 28246fb12b70Safresh1 28256fb12b70Safresh1=item B<new> 28266fb12b70Safresh1 28276fb12b70Safresh1Create a temporary file object. 28286fb12b70Safresh1 28296fb12b70Safresh1 my $tmp = File::Temp->new(); 28306fb12b70Safresh1 28316fb12b70Safresh1by default the object is constructed as if C<tempfile> 28326fb12b70Safresh1was called without options, but with the additional behaviour 28336fb12b70Safresh1that the temporary file is removed by the object destructor 28346fb12b70Safresh1if UNLINK is set to true (the default). 28356fb12b70Safresh1 28366fb12b70Safresh1Supported arguments are the same as for C<tempfile>: UNLINK 2837*256a93a4Safresh1(defaulting to true), DIR, EXLOCK, PERMS and SUFFIX. 2838*256a93a4Safresh1Additionally, the filename 28396fb12b70Safresh1template is specified using the TEMPLATE option. The OPEN option 28406fb12b70Safresh1is not supported (the file is always opened). 28416fb12b70Safresh1 28426fb12b70Safresh1 $tmp = File::Temp->new( TEMPLATE => 'tempXXXXX', 28436fb12b70Safresh1 DIR => 'mydir', 28446fb12b70Safresh1 SUFFIX => '.dat'); 28456fb12b70Safresh1 28466fb12b70Safresh1Arguments are case insensitive. 28476fb12b70Safresh1 28486fb12b70Safresh1Can call croak() if an error occurs. 28496fb12b70Safresh1 2850f3efcd01Safresh1Available since 0.14. 2851f3efcd01Safresh1 2852f3efcd01Safresh1TEMPLATE available since 0.23 2853f3efcd01Safresh1 28546fb12b70Safresh1=item B<newdir> 28556fb12b70Safresh1 28566fb12b70Safresh1Create a temporary directory using an object oriented interface. 28576fb12b70Safresh1 28586fb12b70Safresh1 $dir = File::Temp->newdir(); 28596fb12b70Safresh1 28606fb12b70Safresh1By default the directory is deleted when the object goes out of scope. 28616fb12b70Safresh1 28626fb12b70Safresh1Supports the same options as the C<tempdir> function. Note that directories 28636fb12b70Safresh1created with this method default to CLEANUP => 1. 28646fb12b70Safresh1 28656fb12b70Safresh1 $dir = File::Temp->newdir( $template, %options ); 28666fb12b70Safresh1 28676fb12b70Safresh1A template may be specified either with a leading template or 28686fb12b70Safresh1with a TEMPLATE argument. 28696fb12b70Safresh1 2870f3efcd01Safresh1Available since 0.19. 2871f3efcd01Safresh1 2872f3efcd01Safresh1TEMPLATE available since 0.23. 2873f3efcd01Safresh1 28746fb12b70Safresh1=item B<filename> 28756fb12b70Safresh1 28766fb12b70Safresh1Return the name of the temporary file associated with this object 28776fb12b70Safresh1(if the object was created using the "new" constructor). 28786fb12b70Safresh1 28796fb12b70Safresh1 $filename = $tmp->filename; 28806fb12b70Safresh1 28816fb12b70Safresh1This method is called automatically when the object is used as 28826fb12b70Safresh1a string. 28836fb12b70Safresh1 2884f3efcd01Safresh1Current API available since 0.14 2885f3efcd01Safresh1 28866fb12b70Safresh1=item B<dirname> 28876fb12b70Safresh1 28886fb12b70Safresh1Return the name of the temporary directory associated with this 28896fb12b70Safresh1object (if the object was created using the "newdir" constructor). 28906fb12b70Safresh1 28916fb12b70Safresh1 $dirname = $tmpdir->dirname; 28926fb12b70Safresh1 28936fb12b70Safresh1This method is called automatically when the object is used in string context. 28946fb12b70Safresh1 28956fb12b70Safresh1=item B<unlink_on_destroy> 28966fb12b70Safresh1 28976fb12b70Safresh1Control whether the file is unlinked when the object goes out of scope. 28986fb12b70Safresh1The file is removed if this value is true and $KEEP_ALL is not. 28996fb12b70Safresh1 29006fb12b70Safresh1 $fh->unlink_on_destroy( 1 ); 29016fb12b70Safresh1 29026fb12b70Safresh1Default is for the file to be removed. 29036fb12b70Safresh1 2904f3efcd01Safresh1Current API available since 0.15 2905f3efcd01Safresh1 29066fb12b70Safresh1=item B<DESTROY> 29076fb12b70Safresh1 29086fb12b70Safresh1When the object goes out of scope, the destructor is called. This 29096fb12b70Safresh1destructor will attempt to unlink the file (using L<unlink1|"unlink1">) 29106fb12b70Safresh1if the constructor was called with UNLINK set to 1 (the default state 29116fb12b70Safresh1if UNLINK is not specified). 29126fb12b70Safresh1 29136fb12b70Safresh1No error is given if the unlink fails. 29146fb12b70Safresh1 29156fb12b70Safresh1If the object has been passed to a child process during a fork, the 29166fb12b70Safresh1file will be deleted when the object goes out of scope in the parent. 29176fb12b70Safresh1 29186fb12b70Safresh1For a temporary directory object the directory will be removed unless 29196fb12b70Safresh1the CLEANUP argument was used in the constructor (and set to false) or 29206fb12b70Safresh1C<unlink_on_destroy> was modified after creation. Note that if a temp 29216fb12b70Safresh1directory is your current directory, it cannot be removed - a warning 29226fb12b70Safresh1will be given in this case. C<chdir()> out of the directory before 29236fb12b70Safresh1letting the object go out of scope. 29246fb12b70Safresh1 29256fb12b70Safresh1If the global variable $KEEP_ALL is true, the file or directory 29266fb12b70Safresh1will not be removed. 29276fb12b70Safresh1 29286fb12b70Safresh1=back 29296fb12b70Safresh1 29306fb12b70Safresh1=head1 FUNCTIONS 29316fb12b70Safresh1 29326fb12b70Safresh1This section describes the recommended interface for generating 29336fb12b70Safresh1temporary files and directories. 29346fb12b70Safresh1 29356fb12b70Safresh1=over 4 29366fb12b70Safresh1 29376fb12b70Safresh1=item B<tempfile> 29386fb12b70Safresh1 29396fb12b70Safresh1This is the basic function to generate temporary files. 29406fb12b70Safresh1The behaviour of the file can be changed using various options: 29416fb12b70Safresh1 29426fb12b70Safresh1 $fh = tempfile(); 29436fb12b70Safresh1 ($fh, $filename) = tempfile(); 29446fb12b70Safresh1 29456fb12b70Safresh1Create a temporary file in the directory specified for temporary 29466fb12b70Safresh1files, as specified by the tmpdir() function in L<File::Spec>. 29476fb12b70Safresh1 29486fb12b70Safresh1 ($fh, $filename) = tempfile($template); 29496fb12b70Safresh1 29506fb12b70Safresh1Create a temporary file in the current directory using the supplied 29516fb12b70Safresh1template. Trailing `X' characters are replaced with random letters to 29526fb12b70Safresh1generate the filename. At least four `X' characters must be present 29536fb12b70Safresh1at the end of the template. 29546fb12b70Safresh1 29556fb12b70Safresh1 ($fh, $filename) = tempfile($template, SUFFIX => $suffix) 29566fb12b70Safresh1 29576fb12b70Safresh1Same as previously, except that a suffix is added to the template 29586fb12b70Safresh1after the `X' translation. Useful for ensuring that a temporary 29596fb12b70Safresh1filename has a particular extension when needed by other applications. 29606fb12b70Safresh1But see the WARNING at the end. 29616fb12b70Safresh1 29626fb12b70Safresh1 ($fh, $filename) = tempfile($template, DIR => $dir); 29636fb12b70Safresh1 29646fb12b70Safresh1Translates the template as before except that a directory name 29656fb12b70Safresh1is specified. 29666fb12b70Safresh1 29676fb12b70Safresh1 ($fh, $filename) = tempfile($template, TMPDIR => 1); 29686fb12b70Safresh1 29696fb12b70Safresh1Equivalent to specifying a DIR of "File::Spec->tmpdir", writing the file 29706fb12b70Safresh1into the same temporary directory as would be used if no template was 29716fb12b70Safresh1specified at all. 29726fb12b70Safresh1 29736fb12b70Safresh1 ($fh, $filename) = tempfile($template, UNLINK => 1); 29746fb12b70Safresh1 29756fb12b70Safresh1Return the filename and filehandle as before except that the file is 29766fb12b70Safresh1automatically removed when the program exits (dependent on 29776fb12b70Safresh1$KEEP_ALL). Default is for the file to be removed if a file handle is 29786fb12b70Safresh1requested and to be kept if the filename is requested. In a scalar 29796fb12b70Safresh1context (where no filename is returned) the file is always deleted 29806fb12b70Safresh1either (depending on the operating system) on exit or when it is 29816fb12b70Safresh1closed (unless $KEEP_ALL is true when the temp file is created). 29826fb12b70Safresh1 29836fb12b70Safresh1Use the object-oriented interface if fine-grained control of when 29846fb12b70Safresh1a file is removed is required. 29856fb12b70Safresh1 29866fb12b70Safresh1If the template is not specified, a template is always 29876fb12b70Safresh1automatically generated. This temporary file is placed in tmpdir() 29886fb12b70Safresh1(L<File::Spec>) unless a directory is specified explicitly with the 29896fb12b70Safresh1DIR option. 29906fb12b70Safresh1 29916fb12b70Safresh1 $fh = tempfile( DIR => $dir ); 29926fb12b70Safresh1 29936fb12b70Safresh1If called in scalar context, only the filehandle is returned and the 29946fb12b70Safresh1file will automatically be deleted when closed on operating systems 29956fb12b70Safresh1that support this (see the description of tmpfile() elsewhere in this 29966fb12b70Safresh1document). This is the preferred mode of operation, as if you only 29976fb12b70Safresh1have a filehandle, you can never create a race condition by fumbling 29986fb12b70Safresh1with the filename. On systems that can not unlink an open file or can 29996fb12b70Safresh1not mark a file as temporary when it is opened (for example, Windows 30006fb12b70Safresh1NT uses the C<O_TEMPORARY> flag) the file is marked for deletion when 30016fb12b70Safresh1the program ends (equivalent to setting UNLINK to 1). The C<UNLINK> 30026fb12b70Safresh1flag is ignored if present. 30036fb12b70Safresh1 30046fb12b70Safresh1 (undef, $filename) = tempfile($template, OPEN => 0); 30056fb12b70Safresh1 30066fb12b70Safresh1This will return the filename based on the template but 30076fb12b70Safresh1will not open this file. Cannot be used in conjunction with 30086fb12b70Safresh1UNLINK set to true. Default is to always open the file 30096fb12b70Safresh1to protect from possible race conditions. A warning is issued 30106fb12b70Safresh1if warnings are turned on. Consider using the tmpnam() 30116fb12b70Safresh1and mktemp() functions described elsewhere in this document 30126fb12b70Safresh1if opening the file is not required. 30136fb12b70Safresh1 3014f3efcd01Safresh1To open the temporary filehandle with O_EXLOCK (open with exclusive 3015f3efcd01Safresh1file lock) use C<< EXLOCK=>1 >>. This is supported only by some 3016f3efcd01Safresh1operating systems (most notably BSD derived systems). By default 3017f3efcd01Safresh1EXLOCK will be false. Former C<File::Temp> versions set EXLOCK to 3018f3efcd01Safresh1true, so to be sure to get an unlocked filehandle also with older 3019f3efcd01Safresh1versions, explicitly set C<< EXLOCK=>0 >>. 30206fb12b70Safresh1 3021f3efcd01Safresh1 ($fh, $filename) = tempfile($template, EXLOCK => 1); 30226fb12b70Safresh1 3023*256a93a4Safresh1By default, the temp file is created with 0600 file permissions. 3024*256a93a4Safresh1Use C<PERMS> to change this: 3025*256a93a4Safresh1 3026*256a93a4Safresh1 ($fh, $filename) = tempfile($template, PERMS => 0666); 3027*256a93a4Safresh1 30286fb12b70Safresh1Options can be combined as required. 30296fb12b70Safresh1 30306fb12b70Safresh1Will croak() if there is an error. 30316fb12b70Safresh1 3032f3efcd01Safresh1Available since 0.05. 3033f3efcd01Safresh1 3034f3efcd01Safresh1UNLINK flag available since 0.10. 3035f3efcd01Safresh1 3036f3efcd01Safresh1TMPDIR flag available since 0.19. 3037f3efcd01Safresh1 3038f3efcd01Safresh1EXLOCK flag available since 0.19. 3039f3efcd01Safresh1 3040*256a93a4Safresh1PERMS flag available since 0.2310. 3041*256a93a4Safresh1 30426fb12b70Safresh1=item B<tempdir> 30436fb12b70Safresh1 30446fb12b70Safresh1This is the recommended interface for creation of temporary 30456fb12b70Safresh1directories. By default the directory will not be removed on exit 30466fb12b70Safresh1(that is, it won't be temporary; this behaviour can not be changed 30476fb12b70Safresh1because of issues with backwards compatibility). To enable removal 30486fb12b70Safresh1either use the CLEANUP option which will trigger removal on program 30496fb12b70Safresh1exit, or consider using the "newdir" method in the object interface which 30506fb12b70Safresh1will allow the directory to be cleaned up when the object goes out of 30516fb12b70Safresh1scope. 30526fb12b70Safresh1 30536fb12b70Safresh1The behaviour of the function depends on the arguments: 30546fb12b70Safresh1 30556fb12b70Safresh1 $tempdir = tempdir(); 30566fb12b70Safresh1 30576fb12b70Safresh1Create a directory in tmpdir() (see L<File::Spec|File::Spec>). 30586fb12b70Safresh1 30596fb12b70Safresh1 $tempdir = tempdir( $template ); 30606fb12b70Safresh1 30616fb12b70Safresh1Create a directory from the supplied template. This template is 30626fb12b70Safresh1similar to that described for tempfile(). `X' characters at the end 30636fb12b70Safresh1of the template are replaced with random letters to construct the 30646fb12b70Safresh1directory name. At least four `X' characters must be in the template. 30656fb12b70Safresh1 30666fb12b70Safresh1 $tempdir = tempdir ( DIR => $dir ); 30676fb12b70Safresh1 30686fb12b70Safresh1Specifies the directory to use for the temporary directory. 30696fb12b70Safresh1The temporary directory name is derived from an internal template. 30706fb12b70Safresh1 30716fb12b70Safresh1 $tempdir = tempdir ( $template, DIR => $dir ); 30726fb12b70Safresh1 30736fb12b70Safresh1Prepend the supplied directory name to the template. The template 30746fb12b70Safresh1should not include parent directory specifications itself. Any parent 30756fb12b70Safresh1directory specifications are removed from the template before 30766fb12b70Safresh1prepending the supplied directory. 30776fb12b70Safresh1 30786fb12b70Safresh1 $tempdir = tempdir ( $template, TMPDIR => 1 ); 30796fb12b70Safresh1 30806fb12b70Safresh1Using the supplied template, create the temporary directory in 30816fb12b70Safresh1a standard location for temporary files. Equivalent to doing 30826fb12b70Safresh1 30836fb12b70Safresh1 $tempdir = tempdir ( $template, DIR => File::Spec->tmpdir); 30846fb12b70Safresh1 30856fb12b70Safresh1but shorter. Parent directory specifications are stripped from the 30866fb12b70Safresh1template itself. The C<TMPDIR> option is ignored if C<DIR> is set 30876fb12b70Safresh1explicitly. Additionally, C<TMPDIR> is implied if neither a template 30886fb12b70Safresh1nor a directory are supplied. 30896fb12b70Safresh1 30906fb12b70Safresh1 $tempdir = tempdir( $template, CLEANUP => 1); 30916fb12b70Safresh1 30926fb12b70Safresh1Create a temporary directory using the supplied template, but 30936fb12b70Safresh1attempt to remove it (and all files inside it) when the program 30946fb12b70Safresh1exits. Note that an attempt will be made to remove all files from 30956fb12b70Safresh1the directory even if they were not created by this module (otherwise 30966fb12b70Safresh1why ask to clean it up?). The directory removal is made with 30976fb12b70Safresh1the rmtree() function from the L<File::Path|File::Path> module. 30986fb12b70Safresh1Of course, if the template is not specified, the temporary directory 30996fb12b70Safresh1will be created in tmpdir() and will also be removed at program exit. 31006fb12b70Safresh1 31016fb12b70Safresh1Will croak() if there is an error. 31026fb12b70Safresh1 3103f3efcd01Safresh1Current API available since 0.05. 3104f3efcd01Safresh1 31056fb12b70Safresh1=back 31066fb12b70Safresh1 31076fb12b70Safresh1=head1 MKTEMP FUNCTIONS 31086fb12b70Safresh1 31096fb12b70Safresh1The following functions are Perl implementations of the 31106fb12b70Safresh1mktemp() family of temp file generation system calls. 31116fb12b70Safresh1 31126fb12b70Safresh1=over 4 31136fb12b70Safresh1 31146fb12b70Safresh1=item B<mkstemp> 31156fb12b70Safresh1 31166fb12b70Safresh1Given a template, returns a filehandle to the temporary file and the name 31176fb12b70Safresh1of the file. 31186fb12b70Safresh1 31196fb12b70Safresh1 ($fh, $name) = mkstemp( $template ); 31206fb12b70Safresh1 31216fb12b70Safresh1In scalar context, just the filehandle is returned. 31226fb12b70Safresh1 31236fb12b70Safresh1The template may be any filename with some number of X's appended 31246fb12b70Safresh1to it, for example F</tmp/temp.XXXX>. The trailing X's are replaced 31256fb12b70Safresh1with unique alphanumeric combinations. 31266fb12b70Safresh1 31276fb12b70Safresh1Will croak() if there is an error. 31286fb12b70Safresh1 3129f3efcd01Safresh1Current API available since 0.05. 3130f3efcd01Safresh1 31316fb12b70Safresh1=item B<mkstemps> 31326fb12b70Safresh1 31336fb12b70Safresh1Similar to mkstemp(), except that an extra argument can be supplied 31346fb12b70Safresh1with a suffix to be appended to the template. 31356fb12b70Safresh1 31366fb12b70Safresh1 ($fh, $name) = mkstemps( $template, $suffix ); 31376fb12b70Safresh1 31386fb12b70Safresh1For example a template of C<testXXXXXX> and suffix of C<.dat> 31396fb12b70Safresh1would generate a file similar to F<testhGji_w.dat>. 31406fb12b70Safresh1 31416fb12b70Safresh1Returns just the filehandle alone when called in scalar context. 31426fb12b70Safresh1 31436fb12b70Safresh1Will croak() if there is an error. 31446fb12b70Safresh1 3145f3efcd01Safresh1Current API available since 0.05. 3146f3efcd01Safresh1 31476fb12b70Safresh1=item B<mkdtemp> 31486fb12b70Safresh1 31496fb12b70Safresh1Create a directory from a template. The template must end in 31506fb12b70Safresh1X's that are replaced by the routine. 31516fb12b70Safresh1 31526fb12b70Safresh1 $tmpdir_name = mkdtemp($template); 31536fb12b70Safresh1 31546fb12b70Safresh1Returns the name of the temporary directory created. 31556fb12b70Safresh1 31566fb12b70Safresh1Directory must be removed by the caller. 31576fb12b70Safresh1 31586fb12b70Safresh1Will croak() if there is an error. 31596fb12b70Safresh1 3160f3efcd01Safresh1Current API available since 0.05. 3161f3efcd01Safresh1 31626fb12b70Safresh1=item B<mktemp> 31636fb12b70Safresh1 31646fb12b70Safresh1Returns a valid temporary filename but does not guarantee 31656fb12b70Safresh1that the file will not be opened by someone else. 31666fb12b70Safresh1 31676fb12b70Safresh1 $unopened_file = mktemp($template); 31686fb12b70Safresh1 31696fb12b70Safresh1Template is the same as that required by mkstemp(). 31706fb12b70Safresh1 31716fb12b70Safresh1Will croak() if there is an error. 31726fb12b70Safresh1 3173f3efcd01Safresh1Current API available since 0.05. 3174f3efcd01Safresh1 31756fb12b70Safresh1=back 31766fb12b70Safresh1 31776fb12b70Safresh1=head1 POSIX FUNCTIONS 31786fb12b70Safresh1 31796fb12b70Safresh1This section describes the re-implementation of the tmpnam() 31806fb12b70Safresh1and tmpfile() functions described in L<POSIX> 31816fb12b70Safresh1using the mkstemp() from this module. 31826fb12b70Safresh1 31836fb12b70Safresh1Unlike the L<POSIX|POSIX> implementations, the directory used 31846fb12b70Safresh1for the temporary file is not specified in a system include 31856fb12b70Safresh1file (C<P_tmpdir>) but simply depends on the choice of tmpdir() 31866fb12b70Safresh1returned by L<File::Spec|File::Spec>. On some implementations this 31876fb12b70Safresh1location can be set using the C<TMPDIR> environment variable, which 31886fb12b70Safresh1may not be secure. 31896fb12b70Safresh1If this is a problem, simply use mkstemp() and specify a template. 31906fb12b70Safresh1 31916fb12b70Safresh1=over 4 31926fb12b70Safresh1 31936fb12b70Safresh1=item B<tmpnam> 31946fb12b70Safresh1 31956fb12b70Safresh1When called in scalar context, returns the full name (including path) 31966fb12b70Safresh1of a temporary file (uses mktemp()). The only check is that the file does 31976fb12b70Safresh1not already exist, but there is no guarantee that that condition will 31986fb12b70Safresh1continue to apply. 31996fb12b70Safresh1 32006fb12b70Safresh1 $file = tmpnam(); 32016fb12b70Safresh1 32026fb12b70Safresh1When called in list context, a filehandle to the open file and 32036fb12b70Safresh1a filename are returned. This is achieved by calling mkstemp() 32046fb12b70Safresh1after constructing a suitable template. 32056fb12b70Safresh1 32066fb12b70Safresh1 ($fh, $file) = tmpnam(); 32076fb12b70Safresh1 32086fb12b70Safresh1If possible, this form should be used to prevent possible 32096fb12b70Safresh1race conditions. 32106fb12b70Safresh1 32116fb12b70Safresh1See L<File::Spec/tmpdir> for information on the choice of temporary 32126fb12b70Safresh1directory for a particular operating system. 32136fb12b70Safresh1 32146fb12b70Safresh1Will croak() if there is an error. 32156fb12b70Safresh1 3216f3efcd01Safresh1Current API available since 0.05. 3217f3efcd01Safresh1 32186fb12b70Safresh1=item B<tmpfile> 32196fb12b70Safresh1 32206fb12b70Safresh1Returns the filehandle of a temporary file. 32216fb12b70Safresh1 32226fb12b70Safresh1 $fh = tmpfile(); 32236fb12b70Safresh1 32246fb12b70Safresh1The file is removed when the filehandle is closed or when the program 32256fb12b70Safresh1exits. No access to the filename is provided. 32266fb12b70Safresh1 32276fb12b70Safresh1If the temporary file can not be created undef is returned. 32286fb12b70Safresh1Currently this command will probably not work when the temporary 32296fb12b70Safresh1directory is on an NFS file system. 32306fb12b70Safresh1 32316fb12b70Safresh1Will croak() if there is an error. 32326fb12b70Safresh1 3233f3efcd01Safresh1Available since 0.05. 3234f3efcd01Safresh1 3235f3efcd01Safresh1Returning undef if unable to create file added in 0.12. 3236f3efcd01Safresh1 32376fb12b70Safresh1=back 32386fb12b70Safresh1 32396fb12b70Safresh1=head1 ADDITIONAL FUNCTIONS 32406fb12b70Safresh1 32416fb12b70Safresh1These functions are provided for backwards compatibility 32426fb12b70Safresh1with common tempfile generation C library functions. 32436fb12b70Safresh1 32446fb12b70Safresh1They are not exported and must be addressed using the full package 32456fb12b70Safresh1name. 32466fb12b70Safresh1 32476fb12b70Safresh1=over 4 32486fb12b70Safresh1 32496fb12b70Safresh1=item B<tempnam> 32506fb12b70Safresh1 32516fb12b70Safresh1Return the name of a temporary file in the specified directory 32526fb12b70Safresh1using a prefix. The file is guaranteed not to exist at the time 32536fb12b70Safresh1the function was called, but such guarantees are good for one 32546fb12b70Safresh1clock tick only. Always use the proper form of C<sysopen> 32556fb12b70Safresh1with C<O_CREAT | O_EXCL> if you must open such a filename. 32566fb12b70Safresh1 32576fb12b70Safresh1 $filename = File::Temp::tempnam( $dir, $prefix ); 32586fb12b70Safresh1 32596fb12b70Safresh1Equivalent to running mktemp() with $dir/$prefixXXXXXXXX 32606fb12b70Safresh1(using unix file convention as an example) 32616fb12b70Safresh1 32626fb12b70Safresh1Because this function uses mktemp(), it can suffer from race conditions. 32636fb12b70Safresh1 32646fb12b70Safresh1Will croak() if there is an error. 32656fb12b70Safresh1 3266f3efcd01Safresh1Current API available since 0.05. 3267f3efcd01Safresh1 32686fb12b70Safresh1=back 32696fb12b70Safresh1 32706fb12b70Safresh1=head1 UTILITY FUNCTIONS 32716fb12b70Safresh1 32726fb12b70Safresh1Useful functions for dealing with the filehandle and filename. 32736fb12b70Safresh1 32746fb12b70Safresh1=over 4 32756fb12b70Safresh1 32766fb12b70Safresh1=item B<unlink0> 32776fb12b70Safresh1 32786fb12b70Safresh1Given an open filehandle and the associated filename, make a safe 32796fb12b70Safresh1unlink. This is achieved by first checking that the filename and 32806fb12b70Safresh1filehandle initially point to the same file and that the number of 32816fb12b70Safresh1links to the file is 1 (all fields returned by stat() are compared). 32826fb12b70Safresh1Then the filename is unlinked and the filehandle checked once again to 32836fb12b70Safresh1verify that the number of links on that file is now 0. This is the 32846fb12b70Safresh1closest you can come to making sure that the filename unlinked was the 32856fb12b70Safresh1same as the file whose descriptor you hold. 32866fb12b70Safresh1 32876fb12b70Safresh1 unlink0($fh, $path) 32886fb12b70Safresh1 or die "Error unlinking file $path safely"; 32896fb12b70Safresh1 32906fb12b70Safresh1Returns false on error but croaks() if there is a security 32916fb12b70Safresh1anomaly. The filehandle is not closed since on some occasions this is 32926fb12b70Safresh1not required. 32936fb12b70Safresh1 32946fb12b70Safresh1On some platforms, for example Windows NT, it is not possible to 32956fb12b70Safresh1unlink an open file (the file must be closed first). On those 32966fb12b70Safresh1platforms, the actual unlinking is deferred until the program ends and 32976fb12b70Safresh1good status is returned. A check is still performed to make sure that 32986fb12b70Safresh1the filehandle and filename are pointing to the same thing (but not at 32996fb12b70Safresh1the time the end block is executed since the deferred removal may not 33006fb12b70Safresh1have access to the filehandle). 33016fb12b70Safresh1 33026fb12b70Safresh1Additionally, on Windows NT not all the fields returned by stat() can 33036fb12b70Safresh1be compared. For example, the C<dev> and C<rdev> fields seem to be 33046fb12b70Safresh1different. Also, it seems that the size of the file returned by stat() 33056fb12b70Safresh1does not always agree, with C<stat(FH)> being more accurate than 33066fb12b70Safresh1C<stat(filename)>, presumably because of caching issues even when 33076fb12b70Safresh1using autoflush (this is usually overcome by waiting a while after 33086fb12b70Safresh1writing to the tempfile before attempting to C<unlink0> it). 33096fb12b70Safresh1 33106fb12b70Safresh1Finally, on NFS file systems the link count of the file handle does 33116fb12b70Safresh1not always go to zero immediately after unlinking. Currently, this 33126fb12b70Safresh1command is expected to fail on NFS disks. 33136fb12b70Safresh1 33146fb12b70Safresh1This function is disabled if the global variable $KEEP_ALL is true 33156fb12b70Safresh1and an unlink on open file is supported. If the unlink is to be deferred 33166fb12b70Safresh1to the END block, the file is still registered for removal. 33176fb12b70Safresh1 33186fb12b70Safresh1This function should not be called if you are using the object oriented 33196fb12b70Safresh1interface since the it will interfere with the object destructor deleting 33206fb12b70Safresh1the file. 33216fb12b70Safresh1 3322f3efcd01Safresh1Available Since 0.05. 3323f3efcd01Safresh1 3324f3efcd01Safresh1If can not unlink open file, defer removal until later available since 0.06. 3325f3efcd01Safresh1 33266fb12b70Safresh1=item B<cmpstat> 33276fb12b70Safresh1 33286fb12b70Safresh1Compare C<stat> of filehandle with C<stat> of provided filename. This 33296fb12b70Safresh1can be used to check that the filename and filehandle initially point 33306fb12b70Safresh1to the same file and that the number of links to the file is 1 (all 33316fb12b70Safresh1fields returned by stat() are compared). 33326fb12b70Safresh1 33336fb12b70Safresh1 cmpstat($fh, $path) 33346fb12b70Safresh1 or die "Error comparing handle with file"; 33356fb12b70Safresh1 33366fb12b70Safresh1Returns false if the stat information differs or if the link count is 33376fb12b70Safresh1greater than 1. Calls croak if there is a security anomaly. 33386fb12b70Safresh1 33396fb12b70Safresh1On certain platforms, for example Windows, not all the fields returned by stat() 33406fb12b70Safresh1can be compared. For example, the C<dev> and C<rdev> fields seem to be 33416fb12b70Safresh1different in Windows. Also, it seems that the size of the file 33426fb12b70Safresh1returned by stat() does not always agree, with C<stat(FH)> being more 33436fb12b70Safresh1accurate than C<stat(filename)>, presumably because of caching issues 33446fb12b70Safresh1even when using autoflush (this is usually overcome by waiting a while 33456fb12b70Safresh1after writing to the tempfile before attempting to C<unlink0> it). 33466fb12b70Safresh1 33476fb12b70Safresh1Not exported by default. 33486fb12b70Safresh1 3349f3efcd01Safresh1Current API available since 0.14. 3350f3efcd01Safresh1 33516fb12b70Safresh1=item B<unlink1> 33526fb12b70Safresh1 33536fb12b70Safresh1Similar to C<unlink0> except after file comparison using cmpstat, the 33546fb12b70Safresh1filehandle is closed prior to attempting to unlink the file. This 33556fb12b70Safresh1allows the file to be removed without using an END block, but does 33566fb12b70Safresh1mean that the post-unlink comparison of the filehandle state provided 33576fb12b70Safresh1by C<unlink0> is not available. 33586fb12b70Safresh1 33596fb12b70Safresh1 unlink1($fh, $path) 33606fb12b70Safresh1 or die "Error closing and unlinking file"; 33616fb12b70Safresh1 33626fb12b70Safresh1Usually called from the object destructor when using the OO interface. 33636fb12b70Safresh1 33646fb12b70Safresh1Not exported by default. 33656fb12b70Safresh1 33666fb12b70Safresh1This function is disabled if the global variable $KEEP_ALL is true. 33676fb12b70Safresh1 33686fb12b70Safresh1Can call croak() if there is a security anomaly during the stat() 33696fb12b70Safresh1comparison. 33706fb12b70Safresh1 3371f3efcd01Safresh1Current API available since 0.14. 3372f3efcd01Safresh1 337391f110e0Safresh1=item B<cleanup> 337491f110e0Safresh1 337591f110e0Safresh1Calling this function will cause any temp files or temp directories 337691f110e0Safresh1that are registered for removal to be removed. This happens automatically 337791f110e0Safresh1when the process exits but can be triggered manually if the caller is sure 337891f110e0Safresh1that none of the temp files are required. This method can be registered as 337991f110e0Safresh1an Apache callback. 338091f110e0Safresh1 338191f110e0Safresh1Note that if a temp directory is your current directory, it cannot be 338291f110e0Safresh1removed. C<chdir()> out of the directory first before calling 338391f110e0Safresh1C<cleanup()>. (For the cleanup at program exit when the CLEANUP flag 338491f110e0Safresh1is set, this happens automatically.) 338591f110e0Safresh1 338691f110e0Safresh1On OSes where temp files are automatically removed when the temp file 338791f110e0Safresh1is closed, calling this function will have no effect other than to remove 338891f110e0Safresh1temporary directories (which may include temporary files). 338991f110e0Safresh1 339091f110e0Safresh1 File::Temp::cleanup(); 339191f110e0Safresh1 339291f110e0Safresh1Not exported by default. 339391f110e0Safresh1 3394f3efcd01Safresh1Current API available since 0.15. 3395f3efcd01Safresh1 339691f110e0Safresh1=back 339791f110e0Safresh1 339891f110e0Safresh1=head1 PACKAGE VARIABLES 339991f110e0Safresh1 340091f110e0Safresh1These functions control the global state of the package. 340191f110e0Safresh1 340291f110e0Safresh1=over 4 340391f110e0Safresh1 340491f110e0Safresh1=item B<safe_level> 340591f110e0Safresh1 340691f110e0Safresh1Controls the lengths to which the module will go to check the safety of the 340791f110e0Safresh1temporary file or directory before proceeding. 340891f110e0Safresh1Options are: 340991f110e0Safresh1 341091f110e0Safresh1=over 8 341191f110e0Safresh1 341291f110e0Safresh1=item STANDARD 341391f110e0Safresh1 341491f110e0Safresh1Do the basic security measures to ensure the directory exists and is 341591f110e0Safresh1writable, that temporary files are opened only if they do not already 341691f110e0Safresh1exist, and that possible race conditions are avoided. Finally the 341791f110e0Safresh1L<unlink0|"unlink0"> function is used to remove files safely. 341891f110e0Safresh1 341991f110e0Safresh1=item MEDIUM 342091f110e0Safresh1 342191f110e0Safresh1In addition to the STANDARD security, the output directory is checked 342291f110e0Safresh1to make sure that it is owned either by root or the user running the 342391f110e0Safresh1program. If the directory is writable by group or by other, it is then 342491f110e0Safresh1checked to make sure that the sticky bit is set. 342591f110e0Safresh1 342691f110e0Safresh1Will not work on platforms that do not support the C<-k> test 342791f110e0Safresh1for sticky bit. 342891f110e0Safresh1 342991f110e0Safresh1=item HIGH 343091f110e0Safresh1 343191f110e0Safresh1In addition to the MEDIUM security checks, also check for the 343291f110e0Safresh1possibility of ``chown() giveaway'' using the L<POSIX|POSIX> 343391f110e0Safresh1sysconf() function. If this is a possibility, each directory in the 343491f110e0Safresh1path is checked in turn for safeness, recursively walking back to the 343591f110e0Safresh1root directory. 343691f110e0Safresh1 343791f110e0Safresh1For platforms that do not support the L<POSIX|POSIX> 343891f110e0Safresh1C<_PC_CHOWN_RESTRICTED> symbol (for example, Windows NT) it is 343991f110e0Safresh1assumed that ``chown() giveaway'' is possible and the recursive test 344091f110e0Safresh1is performed. 344191f110e0Safresh1 344291f110e0Safresh1=back 344391f110e0Safresh1 344491f110e0Safresh1The level can be changed as follows: 344591f110e0Safresh1 344691f110e0Safresh1 File::Temp->safe_level( File::Temp::HIGH ); 344791f110e0Safresh1 344891f110e0Safresh1The level constants are not exported by the module. 344991f110e0Safresh1 345091f110e0Safresh1Currently, you must be running at least perl v5.6.0 in order to 345191f110e0Safresh1run with MEDIUM or HIGH security. This is simply because the 345291f110e0Safresh1safety tests use functions from L<Fcntl|Fcntl> that are not 345391f110e0Safresh1available in older versions of perl. The problem is that the version 345491f110e0Safresh1number for Fcntl is the same in perl 5.6.0 and in 5.005_03 even though 345591f110e0Safresh1they are different versions. 345691f110e0Safresh1 345791f110e0Safresh1On systems that do not support the HIGH or MEDIUM safety levels 345891f110e0Safresh1(for example Win NT or OS/2) any attempt to change the level will 345991f110e0Safresh1be ignored. The decision to ignore rather than raise an exception 346091f110e0Safresh1allows portable programs to be written with high security in mind 346191f110e0Safresh1for the systems that can support this without those programs failing 346291f110e0Safresh1on systems where the extra tests are irrelevant. 346391f110e0Safresh1 346491f110e0Safresh1If you really need to see whether the change has been accepted 346591f110e0Safresh1simply examine the return value of C<safe_level>. 346691f110e0Safresh1 346791f110e0Safresh1 $newlevel = File::Temp->safe_level( File::Temp::HIGH ); 346891f110e0Safresh1 die "Could not change to high security" 346991f110e0Safresh1 if $newlevel != File::Temp::HIGH; 347091f110e0Safresh1 3471f3efcd01Safresh1Available since 0.05. 3472f3efcd01Safresh1 347391f110e0Safresh1=item TopSystemUID 347491f110e0Safresh1 347591f110e0Safresh1This is the highest UID on the current system that refers to a root 347691f110e0Safresh1UID. This is used to make sure that the temporary directory is 347791f110e0Safresh1owned by a system UID (C<root>, C<bin>, C<sys> etc) rather than 347891f110e0Safresh1simply by root. 347991f110e0Safresh1 348091f110e0Safresh1This is required since on many unix systems C</tmp> is not owned 348191f110e0Safresh1by root. 348291f110e0Safresh1 348391f110e0Safresh1Default is to assume that any UID less than or equal to 10 is a root 348491f110e0Safresh1UID. 348591f110e0Safresh1 348691f110e0Safresh1 File::Temp->top_system_uid(10); 348791f110e0Safresh1 my $topid = File::Temp->top_system_uid; 348891f110e0Safresh1 348991f110e0Safresh1This value can be adjusted to reduce security checking if required. 349091f110e0Safresh1The value is only relevant when C<safe_level> is set to MEDIUM or higher. 349191f110e0Safresh1 3492f3efcd01Safresh1Available since 0.05. 3493f3efcd01Safresh1 349491f110e0Safresh1=item B<$KEEP_ALL> 349591f110e0Safresh1 349691f110e0Safresh1Controls whether temporary files and directories should be retained 349791f110e0Safresh1regardless of any instructions in the program to remove them 349891f110e0Safresh1automatically. This is useful for debugging but should not be used in 349991f110e0Safresh1production code. 350091f110e0Safresh1 350191f110e0Safresh1 $File::Temp::KEEP_ALL = 1; 350291f110e0Safresh1 350391f110e0Safresh1Default is for files to be removed as requested by the caller. 350491f110e0Safresh1 350591f110e0Safresh1In some cases, files will only be retained if this variable is true 350691f110e0Safresh1when the file is created. This means that you can not create a temporary 350791f110e0Safresh1file, set this variable and expect the temp file to still be around 350891f110e0Safresh1when the program exits. 350991f110e0Safresh1 351091f110e0Safresh1=item B<$DEBUG> 351191f110e0Safresh1 351291f110e0Safresh1Controls whether debugging messages should be enabled. 351391f110e0Safresh1 351491f110e0Safresh1 $File::Temp::DEBUG = 1; 351591f110e0Safresh1 351691f110e0Safresh1Default is for debugging mode to be disabled. 351791f110e0Safresh1 3518f3efcd01Safresh1Available since 0.15. 3519f3efcd01Safresh1 352091f110e0Safresh1=back 352191f110e0Safresh1 352291f110e0Safresh1=head1 WARNING 352391f110e0Safresh1 352491f110e0Safresh1For maximum security, endeavour always to avoid ever looking at, 352591f110e0Safresh1touching, or even imputing the existence of the filename. You do not 352691f110e0Safresh1know that that filename is connected to the same file as the handle 352791f110e0Safresh1you have, and attempts to check this can only trigger more race 352891f110e0Safresh1conditions. It's far more secure to use the filehandle alone and 352991f110e0Safresh1dispense with the filename altogether. 353091f110e0Safresh1 353191f110e0Safresh1If you need to pass the handle to something that expects a filename 353291f110e0Safresh1then on a unix system you can use C<"/dev/fd/" . fileno($fh)> for 353391f110e0Safresh1arbitrary programs. Perl code that uses the 2-argument version of 353491f110e0Safresh1C<< open >> can be passed C<< "+<=&" . fileno($fh) >>. Otherwise you 353591f110e0Safresh1will need to pass the filename. You will have to clear the 353691f110e0Safresh1close-on-exec bit on that file descriptor before passing it to another 353791f110e0Safresh1process. 353891f110e0Safresh1 353991f110e0Safresh1 use Fcntl qw/F_SETFD F_GETFD/; 354091f110e0Safresh1 fcntl($tmpfh, F_SETFD, 0) 354191f110e0Safresh1 or die "Can't clear close-on-exec flag on temp fh: $!\n"; 354291f110e0Safresh1 354391f110e0Safresh1=head2 Temporary files and NFS 354491f110e0Safresh1 354591f110e0Safresh1Some problems are associated with using temporary files that reside 354691f110e0Safresh1on NFS file systems and it is recommended that a local filesystem 354791f110e0Safresh1is used whenever possible. Some of the security tests will most probably 354891f110e0Safresh1fail when the temp file is not local. Additionally, be aware that 354991f110e0Safresh1the performance of I/O operations over NFS will not be as good as for 355091f110e0Safresh1a local disk. 355191f110e0Safresh1 355291f110e0Safresh1=head2 Forking 355391f110e0Safresh1 355491f110e0Safresh1In some cases files created by File::Temp are removed from within an 355591f110e0Safresh1END block. Since END blocks are triggered when a child process exits 355691f110e0Safresh1(unless C<POSIX::_exit()> is used by the child) File::Temp takes care 355791f110e0Safresh1to only remove those temp files created by a particular process ID. This 355891f110e0Safresh1means that a child will not attempt to remove temp files created by the 355991f110e0Safresh1parent process. 356091f110e0Safresh1 356191f110e0Safresh1If you are forking many processes in parallel that are all creating 356291f110e0Safresh1temporary files, you may need to reset the random number seed using 356391f110e0Safresh1srand(EXPR) in each child else all the children will attempt to walk 356491f110e0Safresh1through the same set of random file names and may well cause 356591f110e0Safresh1themselves to give up if they exceed the number of retry attempts. 356691f110e0Safresh1 356791f110e0Safresh1=head2 Directory removal 356891f110e0Safresh1 356991f110e0Safresh1Note that if you have chdir'ed into the temporary directory and it is 357091f110e0Safresh1subsequently cleaned up (either in the END block or as part of object 357191f110e0Safresh1destruction), then you will get a warning from File::Path::rmtree(). 357291f110e0Safresh1 357391f110e0Safresh1=head2 Taint mode 357491f110e0Safresh1 357591f110e0Safresh1If you need to run code under taint mode, updating to the latest 3576f3efcd01Safresh1L<File::Spec> is highly recommended. On Windows, if the directory 3577f3efcd01Safresh1given by L<File::Spec::tmpdir> isn't writable, File::Temp will attempt 3578f3efcd01Safresh1to fallback to the user's local application data directory or croak 3579f3efcd01Safresh1with an error. 358091f110e0Safresh1 358191f110e0Safresh1=head2 BINMODE 358291f110e0Safresh1 358391f110e0Safresh1The file returned by File::Temp will have been opened in binary mode 358491f110e0Safresh1if such a mode is available. If that is not correct, use the C<binmode()> 358591f110e0Safresh1function to change the mode of the filehandle. 358691f110e0Safresh1 358791f110e0Safresh1Note that you can modify the encoding of a file opened by File::Temp 358891f110e0Safresh1also by using C<binmode()>. 358991f110e0Safresh1 359091f110e0Safresh1=head1 HISTORY 359191f110e0Safresh1 359291f110e0Safresh1Originally began life in May 1999 as an XS interface to the system 359391f110e0Safresh1mkstemp() function. In March 2000, the OpenBSD mkstemp() code was 359491f110e0Safresh1translated to Perl for total control of the code's 359591f110e0Safresh1security checking, to ensure the presence of the function regardless of 359691f110e0Safresh1operating system and to help with portability. The module was shipped 359791f110e0Safresh1as a standard part of perl from v5.6.1. 359891f110e0Safresh1 35996fb12b70Safresh1Thanks to Tom Christiansen for suggesting that this module 36006fb12b70Safresh1should be written and providing ideas for code improvements and 36016fb12b70Safresh1security enhancements. 36026fb12b70Safresh1 360391f110e0Safresh1=head1 SEE ALSO 360491f110e0Safresh1 360591f110e0Safresh1L<POSIX/tmpnam>, L<POSIX/tmpfile>, L<File::Spec>, L<File::Path> 360691f110e0Safresh1 360791f110e0Safresh1See L<IO::File> and L<File::MkTemp>, L<Apache::TempFile> for 360891f110e0Safresh1different implementations of temporary file handling. 360991f110e0Safresh1 361091f110e0Safresh1See L<File::Tempdir> for an alternative object-oriented wrapper for 361191f110e0Safresh1the C<tempdir> function. 361291f110e0Safresh1 36136fb12b70Safresh1=for Pod::Coverage STRINGIFY NUMIFY top_system_uid 361491f110e0Safresh1 36156fb12b70Safresh1=head1 SUPPORT 36166fb12b70Safresh1 3617f3efcd01Safresh1Bugs may be submitted through L<the RT bug tracker|https://rt.cpan.org/Public/Dist/Display.html?Name=File-Temp> 3618f3efcd01Safresh1(or L<bug-File-Temp@rt.cpan.org|mailto:bug-File-Temp@rt.cpan.org>). 36196fb12b70Safresh1 3620f3efcd01Safresh1There is also a mailing list available for users of this distribution, at 3621f3efcd01Safresh1L<http://lists.perl.org/list/cpan-workers.html>. 36226fb12b70Safresh1 3623f3efcd01Safresh1There is also an irc channel available for users of this distribution, at 3624f3efcd01Safresh1L<C<#toolchain> on C<irc.perl.org>|irc://irc.perl.org/#toolchain>. 36256fb12b70Safresh1 36266fb12b70Safresh1=head1 AUTHOR 36276fb12b70Safresh1 36286fb12b70Safresh1Tim Jenness <tjenness@cpan.org> 36296fb12b70Safresh1 36306fb12b70Safresh1=head1 CONTRIBUTORS 36316fb12b70Safresh1 3632*256a93a4Safresh1=for stopwords Tim Jenness Karen Etheridge David Golden Slaven Rezic mohawk2 Roy Ivy III Peter Rabbitson Olivier Mengué John Acklam Gim Yee Nicolas R Brian Mowrey Dagfinn Ilmari Mannsåker Steinbrunner Ed Avis Guillem Jover James E. Keenan Kevin Ryde Ben Tilly 3633f3efcd01Safresh1 36346fb12b70Safresh1=over 4 36356fb12b70Safresh1 36366fb12b70Safresh1=item * 36376fb12b70Safresh1 3638*256a93a4Safresh1Tim Jenness <t.jenness@jach.hawaii.edu> 36396fb12b70Safresh1 36406fb12b70Safresh1=item * 36416fb12b70Safresh1 3642f3efcd01Safresh1Karen Etheridge <ether@cpan.org> 3643f3efcd01Safresh1 3644f3efcd01Safresh1=item * 3645f3efcd01Safresh1 3646*256a93a4Safresh1David Golden <dagolden@cpan.org> 3647*256a93a4Safresh1 3648*256a93a4Safresh1=item * 3649*256a93a4Safresh1 3650*256a93a4Safresh1Slaven Rezic <srezic@cpan.org> 3651*256a93a4Safresh1 3652*256a93a4Safresh1=item * 3653*256a93a4Safresh1 3654*256a93a4Safresh1mohawk2 <mohawk2@users.noreply.github.com> 3655*256a93a4Safresh1 3656*256a93a4Safresh1=item * 3657*256a93a4Safresh1 3658*256a93a4Safresh1Roy Ivy III <rivy.dev@gmail.com> 3659f3efcd01Safresh1 3660f3efcd01Safresh1=item * 3661f3efcd01Safresh1 3662f3efcd01Safresh1Peter Rabbitson <ribasushi@cpan.org> 3663f3efcd01Safresh1 3664f3efcd01Safresh1=item * 3665f3efcd01Safresh1 3666*256a93a4Safresh1Olivier Mengué <dolmen@cpan.org> 3667f3efcd01Safresh1 3668f3efcd01Safresh1=item * 3669f3efcd01Safresh1 3670f3efcd01Safresh1Peter John Acklam <pjacklam@online.no> 3671f3efcd01Safresh1 3672f3efcd01Safresh1=item * 3673f3efcd01Safresh1 3674*256a93a4Safresh1Tim Gim Yee <tim.gim.yee@gmail.com> 3675f3efcd01Safresh1 3676f3efcd01Safresh1=item * 3677f3efcd01Safresh1 3678*256a93a4Safresh1Nicolas R <atoomic@cpan.org> 3679f3efcd01Safresh1 3680f3efcd01Safresh1=item * 3681f3efcd01Safresh1 3682f3efcd01Safresh1Brian Mowrey <brian@drlabs.org> 3683f3efcd01Safresh1 3684f3efcd01Safresh1=item * 3685f3efcd01Safresh1 3686f3efcd01Safresh1Dagfinn Ilmari Mannsåker <ilmari@ilmari.org> 36876fb12b70Safresh1 36886fb12b70Safresh1=item * 36896fb12b70Safresh1 36906fb12b70Safresh1David Steinbrunner <dsteinbrunner@pobox.com> 36916fb12b70Safresh1 36926fb12b70Safresh1=item * 36936fb12b70Safresh1 36946fb12b70Safresh1Ed Avis <eda@linux01.wcl.local> 36956fb12b70Safresh1 36966fb12b70Safresh1=item * 36976fb12b70Safresh1 3698f3efcd01Safresh1Guillem Jover <guillem@hadrons.org> 36996fb12b70Safresh1 37006fb12b70Safresh1=item * 37016fb12b70Safresh1 3702*256a93a4Safresh1James E. Keenan <jkeen@verizon.net> 3703*256a93a4Safresh1 3704*256a93a4Safresh1=item * 3705*256a93a4Safresh1 3706*256a93a4Safresh1Kevin Ryde <user42@zip.com.au> 3707*256a93a4Safresh1 3708*256a93a4Safresh1=item * 3709*256a93a4Safresh1 3710f3efcd01Safresh1Ben Tilly <btilly@gmail.com> 37116fb12b70Safresh1 37126fb12b70Safresh1=back 37136fb12b70Safresh1 37146fb12b70Safresh1=head1 COPYRIGHT AND LICENSE 37156fb12b70Safresh1 3716*256a93a4Safresh1This software is copyright (c) 2020 by Tim Jenness and the UK Particle Physics and Astronomy Research Council. 37176fb12b70Safresh1 37186fb12b70Safresh1This is free software; you can redistribute it and/or modify it under 37196fb12b70Safresh1the same terms as the Perl 5 programming language system itself. 37206fb12b70Safresh1 37216fb12b70Safresh1=cut 3722