5 File::Temp - return name and handle of a temporary file safely
9 use File::Temp qw/ tempfile tempdir /;
11 $dir = tempdir( CLEANUP => 1 );
12 ($fh, $filename) = tempfile( DIR => $dir );
14 ($fh, $filename) = tempfile( $template, DIR => $dir);
15 ($fh, $filename) = tempfile( $template, SUFFIX => '.dat');
21 use File::Temp qw/ :mktemp /;
23 ($fh, $file) = mkstemp( "tmpfileXXXXX" );
24 ($fh, $file) = mkstemps( "tmpfileXXXXXX", $suffix);
26 $tmpdir = mkdtemp( $template );
28 $unopened_file = mktemp( $template );
32 use File::Temp qw/ :POSIX /;
37 ($fh, $file) = tmpnam();
38 ($fh, $file) = tmpfile();
41 Compatibility functions:
43 $unopened_file = File::Temp::tempnam( $dir, $pfx );
47 Objects (NOT YET IMPLEMENTED):
51 $fh = new File::Temp($template);
52 $fname = $fh->filename;
58 C<File::Temp> can be used to create and open temporary files in a safe way.
59 The tempfile() function can be used to return the name and the open
60 filehandle of a temporary file. The tempdir() function can
61 be used to create a temporary directory.
63 The security aspect of temporary file creation is emphasized such that
64 a filehandle and filename are returned together. This helps guarantee that
65 a race condition can not occur where the temporary file is created by another process
66 between checking for the existence of the file and its
67 opening. Additional security levels are provided to check, for
68 example, that the sticky bit is set on world writable directories.
69 See L<"safe_level"> for more information.
71 For compatibility with popular C library functions, Perl implementations of
72 the mkstemp() family of functions are provided. These are, mkstemp(),
73 mkstemps(), mkdtemp() and mktemp().
75 Additionally, implementations of the standard L<POSIX|POSIX>
76 tmpnam() and tmpfile() functions are provided if required.
78 Implementations of mktemp(), tmpnam(), and tempnam() are provided,
79 but should be used with caution since they return only a filename
80 that was valid when function was called, so cannot guarantee
81 that the file will not exist by the time the caller opens the filename.
85 # 5.6.0 gives us S_IWOTH, S_IWGRP, our and auto-vivifying filehandls
86 # People would like a version on 5.005 so give them what they want :-)
91 use File::Path qw/ rmtree /;
93 use Errno qw( EEXIST ENOENT ENOTDIR EINVAL );
96 use vars qw($VERSION @EXPORT_OK %EXPORT_TAGS $DEBUG);
100 # We are exporting functions
103 #@ISA = qw/Exporter/;
104 use base qw/Exporter/;
106 # Export list - to allow fine tuning of export table
120 # Groups of functions for export
123 'POSIX' => [qw/ tmpnam tmpfile /],
124 'mktemp' => [qw/ mktemp mkstemp mkstemps mkdtemp/],
127 # add contents of these tags to @EXPORT
128 Exporter::export_tags('POSIX','mktemp');
134 # This is a list of characters that can be used in random filenames
136 my @CHARS = (qw/ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
137 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
138 0 1 2 3 4 5 6 7 8 9 _
141 # Maximum number of tries to make a temp file before failing
143 use constant MAX_TRIES => 10;
145 # Minimum number of X characters that should be in a template
146 use constant MINX => 4;
148 # Default template when no template supplied
150 use constant TEMPXXX => 'X' x 10;
152 # Constants for the security level
154 use constant STANDARD => 0;
155 use constant MEDIUM => 1;
156 use constant HIGH => 2;
158 # INTERNAL ROUTINES - not to be used outside of package
160 # Generic routine for getting a temporary filename
161 # modelled on OpenBSD _gettemp() in mktemp.c
163 # The template must contain X's that are to be replaced
164 # with the random values
168 # TEMPLATE - string containing the XXXXX's that is converted
169 # to a random filename and opened if required
171 # Optionally, a hash can also be supplied containing specific options
172 # "open" => if true open the temp file, else just return the name
174 # "mkdir"=> if true, we are creating a temp directory rather than tempfile
176 # "suffixlen" => number of characters at end of PATH to be ignored.
178 # "open" and "mkdir" can not both be true
180 # The default options are equivalent to mktemp().
183 # filehandle - open file handle (if called with doopen=1, else undef)
184 # temp name - name of the temp file or directory
187 # ($fh, $name) = _gettemp($template, "open" => 1);
189 # for the current version, failures are associated with
190 # a carp to give the reason whilst debugging
194 croak 'Usage: ($fh, $name) = _gettemp($template, OPTIONS);'
195 unless scalar(@_) >= 1;
205 my $template = shift;
206 if (ref($template)) {
207 carp "File::Temp::_gettemp: template must not be a reference";
211 # Check that the number of entries on stack are even
212 if (scalar(@_) % 2 != 0) {
213 carp "File::Temp::_gettemp: Must have even number of options";
217 # Read the options and merge with defaults
218 %options = (%options, @_) if @_;
220 # Can not open the file and make a directory in a single call
221 if ($options{"open"} && $options{"mkdir"}) {
222 carp "File::Temp::_gettemp: doopen and domkdir can not both be true\n";
226 # Find the start of the end of the Xs (position of last X)
227 # Substr starts from 0
228 my $start = length($template) - 1 - $options{"suffixlen"};
230 # Check that we have at least MINX x X (eg 'XXXX") at the end of the string
231 # (taking suffixlen into account). Any fewer is insecure.
233 # Do it using substr - no reason to use a pattern match since
234 # we know where we are looking and what we are looking for
236 if (substr($template, $start - MINX + 1, MINX) ne 'X' x MINX) {
237 carp "File::Temp::_gettemp: The template must contain at least ". MINX ." 'X' characters\n";
241 # Replace all the X at the end of the substring with a
242 # random character or just all the XX at the end of a full string.
243 # Do it as an if, since the suffix adjusts which section to replace
244 # and suffixlen=0 returns nothing if used in the substr directly
245 # and generate a full path from the template
247 my $path = _replace_XX($template, $options{"suffixlen"});
250 # Split the path into constituent parts - eventually we need to check
251 # whether the directory exists
252 # We need to know whether we are making a temp directory
255 my ($volume, $directories, $file);
256 my $parent; # parent directory
257 if ($options{"mkdir"}) {
258 # There is no filename at the end
259 ($volume, $directories, $file) = File::Spec->splitpath( $path, 1);
261 # The parent is then $directories without the last directory
262 # Split the directory and put it back together again
263 my @dirs = File::Spec->splitdir($directories);
265 # If @dirs only has one entry that means we are in the current
268 $parent = File::Spec->curdir;
271 # Put it back together without the last one
272 $parent = File::Spec->catdir(@dirs[0..$#dirs-1]);
274 # ...and attach the volume (no filename)
275 $parent = File::Spec->catpath($volume, $parent, '');
281 # Get rid of the last filename (use File::Basename for this?)
282 ($volume, $directories, $file) = File::Spec->splitpath( $path );
284 # Join up without the file part
285 $parent = File::Spec->catpath($volume,$directories,'');
287 # If $parent is empty replace with curdir
288 $parent = File::Spec->curdir
289 unless $directories ne '';
293 # Check that the parent directories exist
294 # Do this even for the case where we are simply returning a name
295 # not a file -- no point returning a name that includes a directory
296 # that does not exist or is not writable
298 unless (-d $parent && -w _) {
299 carp "File::Temp::_gettemp: Parent directory ($parent) is not a directory"
300 . " or is not writable\n";
304 # Check the stickiness of the directory and chown giveaway if required
305 # If the directory is world writable the sticky bit
308 if (File::Temp->safe_level == MEDIUM) {
309 unless (_is_safe($parent)) {
310 carp "File::Temp::_gettemp: Parent directory ($parent) is not safe (sticky bit not set when world writable?)";
313 } elsif (File::Temp->safe_level == HIGH) {
314 unless (_is_verysafe($parent)) {
315 carp "File::Temp::_gettemp: Parent directory ($parent) is not safe (sticky bit not set when world writable?)";
321 # Calculate the flags that we wish to use for the sysopen
322 # Some of these are not always available
324 if ($options{"open"}) {
326 $openflags = O_CREAT | O_EXCL | O_RDWR;
328 for my $oflag (qw/FOLLOW BINARY LARGEFILE EXLOCK NOINHERIT TEMPORARY/) {
329 my ($bit, $func) = (0, "Fcntl::O_" . $oflag);
331 $openflags |= $bit if eval { $bit = &$func(); 1 };
337 # Now try MAX_TRIES time to open the file
338 for (my $i = 0; $i < MAX_TRIES; $i++) {
340 # Try to open the file if requested
341 if ($options{"open"}) {
344 # If we are running before perl5.6.0 we can not auto-vivify
347 $fh = &Symbol::gensym;
350 # Try to make sure this will be marked close-on-exec
351 # XXX: Win32 doesn't respect this, nor the proper fcntl,
352 # but may have O_NOINHERIT. This may or may not be in Fcntl.
355 # Store callers umask
361 # Attempt to open the file
362 if ( sysopen($fh, $path, $openflags, 0600) ) {
367 # Opened successfully - return file handle and name
374 # Error opening file - abort with error
375 # if the reason was anything but EEXIST
376 unless ($! == EEXIST) {
377 carp "File::Temp: Could not create temp file $path: $!";
381 # Loop round for another try
384 } elsif ($options{"mkdir"}) {
386 # Store callers umask
392 # Open the temp directory
393 if (mkdir( $path, 0700)) {
404 # Abort with error if the reason for failure was anything
406 unless ($! == EEXIST) {
407 carp "File::Temp: Could not create directory $path: $!";
411 # Loop round for another try
417 # Return true if the file can not be found
418 # Directory has been checked previously
420 return (undef, $path) unless -e $path;
422 # Try again until MAX_TRIES
426 # Did not successfully open the tempfile/dir
427 # so try again with a different set of random letters
428 # No point in trying to increment unless we have only
429 # 1 X say and the randomness could come up with the same
430 # file MAX_TRIES in a row.
432 # Store current attempt - in principal this implies that the
433 # 3rd time around the open attempt that the first temp file
434 # name could be generated again. Probably should store each
435 # attempt and make sure that none are repeated
437 my $original = $path;
438 my $counter = 0; # Stop infinite loop
443 # Generate new name from original template
444 $path = _replace_XX($template, $options{"suffixlen"});
448 } until ($path ne $original || $counter > $MAX_GUESS);
450 # Check for out of control looping
451 if ($counter > $MAX_GUESS) {
452 carp "Tried to get a new temp name different to the previous value$MAX_GUESS times.\nSomething wrong with template?? ($template)";
458 # If we get here, we have run out of tries
459 carp "Have exceeded the maximum number of attempts (".MAX_TRIES .
460 ") to open temp file/dir";
466 # Internal routine to return a random character from the
467 # character list. Does not do an srand() since rand()
468 # will do one automatically
470 # No arguments. Return value is the random character
474 $CHARS[ int( rand( $#CHARS ) ) ];
478 # Internal routine to replace the XXXX... with random characters
479 # This has to be done by _gettemp() every time it fails to
480 # open a temp file/dir
482 # Arguments: $template (the template with XXX),
483 # $ignore (number of characters at end to ignore)
485 # Returns: modified template
489 croak 'Usage: _replace_XX($template, $ignore)'
490 unless scalar(@_) == 2;
492 my ($path, $ignore) = @_;
494 # Do it as an if, since the suffix adjusts which section to replace
495 # and suffixlen=0 returns nothing if used in the substr directly
496 # Alternatively, could simply set $ignore to length($path)-1
497 # Don't want to always use substr when not required though.
500 substr($path, 0, - $ignore) =~ s/X(?=X*\z)/_randchar()/ge;
502 $path =~ s/X(?=X*\z)/_randchar()/ge;
508 # internal routine to check to see if the directory is safe
509 # First checks to see if the directory is not owned by the
510 # current user or root. Then checks to see if anyone else
511 # can write to the directory and if so, checks to see if
512 # it has the sticky bit set
514 # Will not work on systems that do not support sticky bit
516 #Args: directory path to check
517 # Returns true if the path is safe and false otherwise.
518 # Returns undef if can not even run stat() on the path
520 # This routine based on version written by Tom Christiansen
522 # Presumably, by the time we actually attempt to create the
523 # file or directory in this directory, it may not be safe
524 # anymore... Have to run _is_safe directly after the open.
531 my @info = stat($path);
532 return 0 unless scalar(@info);
534 # Check to see whether owner is neither superuser (or a system uid) nor me
535 # Use the real uid from the $< variable
537 if ( $info[4] > File::Temp->top_system_uid() && $info[4] != $<) {
538 carp "Directory owned neither by root nor the current user";
542 # check whether group or other can write file
543 # use 066 to detect either reading or writing
544 # use 022 to check writability
545 # Do it with S_IWOTH and S_IWGRP for portability (maybe)
547 if (($info[2] & &Fcntl::S_IWGRP) || # Is group writable?
548 ($info[2] & &Fcntl::S_IWOTH) ) { # Is world writable?
549 return 0 unless -d _; # Must be a directory
550 return 0 unless -k _; # Must be sticky
556 # Internal routine to check whether a directory is safe
557 # for temp files. Safer than _is_safe since it checks for
558 # the possibility of chown giveaway and if that is a possibility
559 # checks each directory in the path to see if it is safe (with _is_safe)
561 # If _PC_CHOWN_RESTRICTED is not set, does the full test of each
566 # Need POSIX - but only want to bother if really necessary due to overhead
571 # Should Get the value of _PC_CHOWN_RESTRICTED if it is defined
572 # and If it is not there do the extensive test
573 my $chown_restricted;
574 $chown_restricted = &POSIX::_PC_CHOWN_RESTRICTED()
575 if eval { &POSIX::_PC_CHOWN_RESTRICTED(); 1};
577 # If chown_resticted is set to some value we should test it
578 if (defined $chown_restricted) {
580 # Return if the current directory is safe
581 return _is_safe($path) if POSIX::sysconf( $chown_restricted );
585 # To reach this point either, the _PC_CHOWN_RESTRICTED symbol
586 # was not avialable or the symbol was there but chown giveaway
587 # is allowed. Either way, we now have to test the entire tree for
590 # Convert path to an absolute directory if required
591 unless (File::Spec->file_name_is_absolute($path)) {
592 $path = File::Spec->rel2abs($path);
595 # Split directory into components - assume no file
596 my ($volume, $directories, undef) = File::Spec->splitpath( $path, 1);
598 # Slightly less efficient than having a a function in File::Spec
599 # to chop off the end of a directory or even a function that
600 # can handle ../ in a directory tree
601 # Sometimes splitdir() returns a blank at the end
602 # so we will probably check the bottom directory twice in some cases
603 my @dirs = File::Spec->splitdir($directories);
605 # Concatenate one less directory each time around
606 foreach my $pos (0.. $#dirs) {
607 # Get a directory name
608 my $dir = File::Spec->catpath($volume,
609 File::Spec->catdir(@dirs[0.. $#dirs - $pos]),
613 print "TESTING DIR $dir\n" if $DEBUG;
615 # Check the directory
616 return 0 unless _is_safe($dir);
625 # internal routine to determine whether unlink works on this
626 # platform for files that are currently open.
627 # Returns true if we can, false otherwise.
629 # Currently WinNT can not unlink an opened file
631 sub _can_unlink_opened_file {
634 $^O ne 'MSWin32' ? 1 : 0;
639 # This routine sets up a deferred unlinking of a specified
640 # filename and filehandle. It is used in the following cases:
641 # - Called by unlink0 if an opend file can not be unlinked
642 # - Called by tempfile() if files are to be removed on shutdown
643 # - Called by tempdir() if directories are to be removed on shutdown
646 # _deferred_unlink( $fh, $fname, $isdir );
648 # - filehandle (so that it can be expclicitly closed if open
649 # - filename (the thing we want to remove)
650 # - isdir (flag to indicate that we are being given a directory)
651 # [and hence no filehandle]
653 # Status is not referred since all the magic is done with END blocks
655 sub _deferred_unlink {
657 croak 'Usage: _deferred_unlink($fh, $fname, $isdir)'
658 unless scalar(@_) == 3;
660 my ($fh, $fname, $isdir) = @_;
662 warn "Setting up deferred removal of $fname\n"
665 # If we have a directory, check that it is a directory
670 # Directory exists so set up END block
671 # (quoted to preserve lexical variables)
675 rmtree($fname, $DEBUG, 1);
682 carp "Request to remove directory $fname could not be completed since it does not exists!\n";
690 # dile exists so set up END block
691 # (quoted to preserve lexical variables)
694 # close the filehandle without checking its state
695 # in order to make real sure that this is closed
696 # if its already closed then I dont care about the answer
697 # probably a better way to do this
702 || warn "Error removing $fname";
709 carp "Request to remove file $fname could not be completed since it is not there!\n";
721 This section describes the recommended interface for generating
722 temporary files and directories.
728 This is the basic function to generate temporary files.
729 The behaviour of the file can be changed using various options:
731 ($fh, $filename) = tempfile();
733 Create a temporary file in the directory specified for temporary
734 files, as specified by the tmpdir() function in L<File::Spec>.
736 ($fh, $filename) = tempfile($template);
738 Create a temporary file in the current directory using the supplied
739 template. Trailing `X' characters are replaced with random letters to
740 generate the filename. At least four `X' characters must be present
743 ($fh, $filename) = tempfile($template, SUFFIX => $suffix)
745 Same as previously, except that a suffix is added to the template
746 after the `X' translation. Useful for ensuring that a temporary
747 filename has a particular extension when needed by other applications.
748 But see the WARNING at the end.
750 ($fh, $filename) = tempfile($template, DIR => $dir);
752 Translates the template as before except that a directory name
755 If the template is not specified, a template is always
756 automatically generated. This temporary file is placed in tmpdir()
757 (L<File::Spec>) unless a directory is specified explicitly with the
760 $fh = tempfile( $template, DIR => $dir );
762 If called in scalar context, only the filehandle is returned
763 and the file will automatically be deleted when closed (see
764 the description of tmpfile() elsewhere in this document).
765 This is the preferred mode of operation, as if you only
766 have a filehandle, you can never create a race condition
767 by fumbling with the filename. On systems that can not unlink
768 an open file (for example, Windows NT) the file is marked for
769 deletion when the program ends (equivalent to setting UNLINK to 1).
771 (undef, $filename) = tempfile($template, OPEN => 0);
773 This will return the filename based on the template but
774 will not open this file. Cannot be used in conjunction with
775 UNLINK set to true. Default is to always open the file
776 to protect from possible race conditions. A warning is issued
777 if warnings are turned on. Consider using the tmpnam()
778 and mktemp() functions described elsewhere in this document
779 if opening the file is not required.
785 # Can not check for argument count since we can have any
790 "DIR" => undef, # Directory prefix
791 "SUFFIX" => '', # Template suffix
792 "UNLINK" => 0, # Unlink file on exit
793 "OPEN" => 1, # Do not open file
796 # Check to see whether we have an odd or even number of arguments
797 my $template = (scalar(@_) % 2 == 1 ? shift(@_) : undef);
799 # Read the options and merge with defaults
800 %options = (%options, @_) if @_;
802 # First decision is whether or not to open the file
803 if (! $options{"OPEN"}) {
805 warn "tempfile(): temporary filename requested but not opened.\nPossibly unsafe, consider using tempfile() with OPEN set to true\n"
810 # Construct the template
812 # Have a choice of trying to work around the mkstemp/mktemp/tmpnam etc
813 # functions or simply constructing a template and using _gettemp()
814 # explicitly. Go for the latter
816 # First generate a template if not defined and prefix the directory
817 # If no template must prefix the temp directory
818 if (defined $template) {
819 if ($options{"DIR"}) {
821 $template = File::Spec->catfile($options{"DIR"}, $template);
827 if ($options{"DIR"}) {
829 $template = File::Spec->catfile($options{"DIR"}, TEMPXXX);
833 $template = File::Spec->catfile(File::Spec->tmpdir, TEMPXXX);
840 $template .= $options{"SUFFIX"};
844 croak "Error in tempfile() using $template"
845 unless (($fh, $path) = _gettemp($template,
846 "open" => $options{'OPEN'},
848 "suffixlen" => length($options{'SUFFIX'}),
851 # Set up an exit handler that can do whatever is right for the
852 # system. Do not check return status since this is all done with
854 _deferred_unlink($fh, $path, 0) if $options{"UNLINK"};
859 if ($options{'OPEN'}) {
862 return (undef, $path);
867 # Unlink the file. It is up to unlink0 to decide what to do with
868 # this (whether to unlink now or to defer until later)
869 unlink0($fh, $path) or croak "Error unlinking file $path using unlink0";
871 # Return just the filehandle.
880 This is the recommended interface for creation of temporary directories.
881 The behaviour of the function depends on the arguments:
883 $tempdir = tempdir();
885 Create a directory in tmpdir() (see L<File::Spec|File::Spec>).
887 $tempdir = tempdir( $template );
889 Create a directory from the supplied template. This template is
890 similar to that described for tempfile(). `X' characters at the end
891 of the template are replaced with random letters to construct the
892 directory name. At least four `X' characters must be in the template.
894 $tempdir = tempdir ( DIR => $dir );
896 Specifies the directory to use for the temporary directory.
897 The temporary directory name is derived from an internal template.
899 $tempdir = tempdir ( $template, DIR => $dir );
901 Prepend the supplied directory name to the template. The template
902 should not include parent directory specifications itself. Any parent
903 directory specifications are removed from the template before
904 prepending the supplied directory.
906 $tempdir = tempdir ( $template, TMPDIR => 1 );
908 Using the supplied template, creat the temporary directory in
909 a standard location for temporary files. Equivalent to doing
911 $tempdir = tempdir ( $template, DIR => File::Spec->tmpdir);
913 but shorter. Parent directory specifications are stripped from the
914 template itself. The C<TMPDIR> option is ignored if C<DIR> is set
915 explicitly. Additionally, C<TMPDIR> is implied if neither a template
916 nor a directory are supplied.
918 $tempdir = tempdir( $template, CLEANUP => 1);
920 Create a temporary directory using the supplied template, but
921 attempt to remove it (and all files inside it) when the program
922 exits. Note that an attempt will be made to remove all files from
923 the directory even if they were not created by this module (otherwise
924 why ask to clean it up?). The directory removal is made with
925 the rmtree() function from the L<File::Path|File::Path> module.
926 Of course, if the template is not specified, the temporary directory
927 will be created in tmpdir() and will also be removed at program exit.
935 # Can not check for argument count since we can have any
940 "CLEANUP" => 0, # Remove directory on exit
941 "DIR" => '', # Root directory
942 "TMPDIR" => 0, # Use tempdir with template
945 # Check to see whether we have an odd or even number of arguments
946 my $template = (scalar(@_) % 2 == 1 ? shift(@_) : undef );
948 # Read the options and merge with defaults
949 %options = (%options, @_) if @_;
951 # Modify or generate the template
953 # Deal with the DIR and TMPDIR options
954 if (defined $template) {
956 # Need to strip directory path if using DIR or TMPDIR
957 if ($options{'TMPDIR'} || $options{'DIR'}) {
959 # Strip parent directory from the filename
961 # There is no filename at the end
962 my ($volume, $directories, undef) = File::Spec->splitpath( $template, 1);
964 # Last directory is then our template
965 $template = (File::Spec->splitdir($directories))[-1];
967 # Prepend the supplied directory or temp dir
968 if ($options{"DIR"}) {
970 $template = File::Spec->catfile($options{"DIR"}, $template);
972 } elsif ($options{TMPDIR}) {
975 $template = File::Spec->catdir(File::Spec->tmpdir, $template);
983 if ($options{"DIR"}) {
985 $template = File::Spec->catdir($options{"DIR"}, TEMPXXX);
989 $template = File::Spec->catdir(File::Spec->tmpdir, TEMPXXX);
995 # Create the directory
997 croak "Error in tempdir() using $template"
998 unless ((undef, $tempdir) = _gettemp($template,
1004 # Install exit handler; must be dynamic to get lexical
1005 if ( $options{'CLEANUP'} && -d $tempdir) {
1006 _deferred_unlink(undef, $tempdir, 1);
1009 # Return the dir name
1016 =head1 MKTEMP FUNCTIONS
1018 The following functions are Perl implementations of the
1019 mktemp() family of temp file generation system calls.
1025 Given a template, returns a filehandle to the temporary file and the name
1028 ($fh, $name) = mkstemp( $template );
1030 In scalar context, just the filehandle is returned.
1032 The template may be any filename with some number of X's appended
1033 to it, for example F</tmp/temp.XXXX>. The trailing X's are replaced
1034 with unique alphanumeric combinations.
1042 croak "Usage: mkstemp(template)"
1045 my $template = shift;
1048 croak "Error in mkstemp using $template"
1049 unless (($fh, $path) = _gettemp($template,
1056 return ($fh, $path);
1066 Similar to mkstemp(), except that an extra argument can be supplied
1067 with a suffix to be appended to the template.
1069 ($fh, $name) = mkstemps( $template, $suffix );
1071 For example a template of C<testXXXXXX> and suffix of C<.dat>
1072 would generate a file similar to F<testhGji_w.dat>.
1074 Returns just the filehandle alone when called in scalar context.
1080 croak "Usage: mkstemps(template, suffix)"
1084 my $template = shift;
1087 $template .= $suffix;
1090 croak "Error in mkstemps using $template"
1091 unless (($fh, $path) = _gettemp($template,
1094 "suffixlen" => length($suffix),
1098 return ($fh, $path);
1107 Create a directory from a template. The template must end in
1108 X's that are replaced by the routine.
1110 $tmpdir_name = mkdtemp($template);
1112 Returns the name of the temporary directory created.
1113 Returns undef on failure.
1115 Directory must be removed by the caller.
1123 croak "Usage: mkdtemp(template)"
1126 my $template = shift;
1128 my ($junk, $tmpdir);
1129 croak "Error creating temp directory from template $template\n"
1130 unless (($junk, $tmpdir) = _gettemp($template,
1142 Returns a valid temporary filename but does not guarantee
1143 that the file will not be opened by someone else.
1145 $unopened_file = mktemp($template);
1147 Template is the same as that required by mkstemp().
1153 croak "Usage: mktemp(template)"
1156 my $template = shift;
1158 my ($tmpname, $junk);
1159 croak "Error getting name to temp file from template $template\n"
1160 unless (($junk, $tmpname) = _gettemp($template,
1171 =head1 POSIX FUNCTIONS
1173 This section describes the re-implementation of the tmpnam()
1174 and tmpfile() functions described in L<POSIX>
1175 using the mkstemp() from this module.
1177 Unlike the L<POSIX|POSIX> implementations, the directory used
1178 for the temporary file is not specified in a system include
1179 file (C<P_tmpdir>) but simply depends on the choice of tmpdir()
1180 returned by L<File::Spec|File::Spec>. On some implementations this
1181 location can be set using the C<TMPDIR> environment variable, which
1183 If this is a problem, simply use mkstemp() and specify a template.
1189 When called in scalar context, returns the full name (including path)
1190 of a temporary file (uses mktemp()). The only check is that the file does
1191 not already exist, but there is no guarantee that that condition will
1196 When called in list context, a filehandle to the open file and
1197 a filename are returned. This is achieved by calling mkstemp()
1198 after constructing a suitable template.
1200 ($fh, $file) = tmpnam();
1202 If possible, this form should be used to prevent possible
1205 See L<File::Spec/tmpdir> for information on the choice of temporary
1206 directory for a particular operating system.
1212 # Retrieve the temporary directory name
1213 my $tmpdir = File::Spec->tmpdir;
1215 croak "Error temporary directory is not writable"
1218 # Use a ten character template and append to tmpdir
1219 my $template = File::Spec->catfile($tmpdir, TEMPXXX);
1222 return mkstemp($template);
1224 return mktemp($template);
1231 In scalar context, returns the filehandle of a temporary file.
1235 The file is removed when the filehandle is closed or when the program
1236 exits. No access to the filename is provided.
1242 # Simply call tmpnam() in an array context
1243 my ($fh, $file) = tmpnam();
1245 # Make sure file is removed when filehandle is closed
1246 unlink0($fh, $file) or croak "Unable to unlink temporary file: $!";
1254 =head1 ADDITIONAL FUNCTIONS
1256 These functions are provided for backwards compatibility
1257 with common tempfile generation C library functions.
1259 They are not exported and must be addressed using the full package
1266 Return the name of a temporary file in the specified directory
1267 using a prefix. The file is guaranteed not to exist at the time
1268 the function was called, but such guarantees are good for one
1269 clock tick only. Always use the proper form of C<sysopen>
1270 with C<O_CREAT | O_EXCL> if you must open such a filename.
1272 $filename = File::Temp::tempnam( $dir, $prefix );
1274 Equivalent to running mktemp() with $dir/$prefixXXXXXXXX
1275 (using unix file convention as an example)
1277 Because this function uses mktemp(), it can suffer from race conditions.
1283 croak 'Usage tempnam($dir, $prefix)' unless scalar(@_) == 2;
1285 my ($dir, $prefix) = @_;
1287 # Add a string to the prefix
1288 $prefix .= 'XXXXXXXX';
1290 # Concatenate the directory to the file
1291 my $template = File::Spec->catfile($dir, $prefix);
1293 return mktemp($template);
1299 =head1 UTILITY FUNCTIONS
1301 Useful functions for dealing with the filehandle and filename.
1307 Given an open filehandle and the associated filename, make a safe
1308 unlink. This is achieved by first checking that the filename and
1309 filehandle initially point to the same file and that the number of
1310 links to the file is 1 (all fields returned by stat() are compared).
1311 Then the filename is unlinked and the filehandle checked once again to
1312 verify that the number of links on that file is now 0. This is the
1313 closest you can come to making sure that the filename unlinked was the
1314 same as the file whose descriptor you hold.
1316 unlink0($fh, $path) or die "Error unlinking file $path safely";
1318 Returns false on error. The filehandle is not closed since on some
1319 occasions this is not required.
1321 On some platforms, for example Windows NT, it is not possible to
1322 unlink an open file (the file must be closed first). On those
1323 platforms, the actual unlinking is deferred until the program ends
1324 and good status is returned. A check is still performed to make sure that
1325 the filehandle and filename are pointing to the same thing (but not at the time
1326 the end block is executed since the deferred removal may not have access to
1329 Additionally, on Windows NT not all the fields returned by stat() can
1330 be compared. For example, the C<dev> and C<rdev> fields seem to be different
1331 and also. Also, it seems that the size of the file returned by stat()
1332 does not always agree, with C<stat(FH)> being more accurate than
1333 C<stat(filename)>, presumably because of caching issues even when
1334 using autoflush (this is usually overcome by waiting a while after
1335 writing to the tempfile before attempting to C<unlink0> it).
1341 croak 'Usage: unlink0(filehandle, filename)'
1342 unless scalar(@_) == 2;
1345 my ($fh, $path) = @_;
1347 warn "Unlinking $path using unlink0\n"
1350 # Stat the filehandle
1353 if ($fh[3] > 1 && $^W) {
1354 carp "unlink0: fstat found too many links; SB=@fh";
1358 my @path = stat $path;
1361 carp "unlink0: $path is gone already" if $^W;
1365 # this is no longer a file, but may be a directory, or worse
1367 confess "panic: $path is no longer a file: SB=@fh";
1370 # Do comparison of each member of the array
1371 # On WinNT dev and rdev seem to be different
1372 # depending on whether it is a file or a handle.
1373 # Cannot simply compare all members of the stat return
1374 # Select the ones we can use
1375 my @okstat = (0..$#fh); # Use all by default
1376 if ($^O eq 'MSWin32') {
1377 @okstat = (1,2,3,4,5,7,8,9,10);
1380 # Now compare each entry explicitly by number
1382 print "Comparing: $_ : $fh[$_] and $path[$_]\n" if $DEBUG;
1383 unless ($fh[$_] == $path[$_]) {
1384 warn "Did not match $_ element of stat\n" if $DEBUG;
1389 # attempt remove the file (does not work on some platforms)
1390 if (_can_unlink_opened_file()) {
1391 # XXX: do *not* call this on a directory; possible race
1392 # resulting in recursive removal
1393 croak "unlink0: $path has become a directory!" if -d $path;
1394 unlink($path) or return 0;
1396 # Stat the filehandle
1399 print "Link count = $fh[3] \n" if $DEBUG;
1401 # Make sure that the link count is zero
1402 return ( $fh[3] == 0 ? 1 : 0);
1405 _deferred_unlink($fh, $path, 0);
1413 =head1 PACKAGE VARIABLES
1415 These functions control the global state of the package.
1421 Controls the lengths to which the module will go to check the safety of the
1422 temporary file or directory before proceeding.
1429 Do the basic security measures to ensure the directory exists and
1430 is writable, that the umask() is fixed before opening of the file,
1431 that temporary files are opened only if they do not already exist, and
1432 that possible race conditions are avoided. Finally the L<unlink0|"unlink0">
1433 function is used to remove files safely.
1437 In addition to the STANDARD security, the output directory is checked
1438 to make sure that it is owned either by root or the user running the
1439 program. If the directory is writable by group or by other, it is then
1440 checked to make sure that the sticky bit is set.
1442 Will not work on platforms that do not support the C<-k> test
1447 In addition to the MEDIUM security checks, also check for the
1448 possibility of ``chown() giveaway'' using the L<POSIX|POSIX>
1449 sysconf() function. If this is a possibility, each directory in the
1450 path is checked in turn for safeness, recursively walking back to the
1453 For platforms that do not support the L<POSIX|POSIX>
1454 C<_PC_CHOWN_RESTRICTED> symbol (for example, Windows NT) it is
1455 assumed that ``chown() giveaway'' is possible and the recursive test
1460 The level can be changed as follows:
1462 File::Temp->safe_level( File::Temp::HIGH );
1464 The level constants are not exported by the module.
1466 Currently, you must be running at least perl v5.6.0 in order to
1467 run with MEDIUM or HIGH security. This is simply because the
1468 safety tests use functions from L<Fcntl|Fcntl> that are not
1469 available in older versions of perl. The problem is that the version
1470 number for Fcntl is the same in perl 5.6.0 and in 5.005_03 even though
1471 they are different versions.....
1476 # protect from using the variable itself
1477 my $LEVEL = STANDARD;
1482 if (($level != STANDARD) && ($level != MEDIUM) && ($level != HIGH)) {
1483 carp "safe_level: Specified level ($level) not STANDARD, MEDIUM or HIGH - ignoring\n";
1485 if ($] < 5.006 && $level != STANDARD) {
1486 # Cant do MEDIUM or HIGH checks
1487 croak "Currently requires perl 5.006 or newer to do the safe checks";
1498 This is the highest UID on the current system that refers to a root
1499 UID. This is used to make sure that the temporary directory is
1500 owned by a system UID (C<root>, C<bin>, C<sys> etc) rather than
1503 This is required since on many unix systems C</tmp> is not owned
1506 Default is to assume that any UID less than or equal to 10 is a root
1509 File::Temp->top_system_uid(10);
1510 my $topid = File::Temp->top_system_uid;
1512 This value can be adjusted to reduce security checking if required.
1513 The value is only relevant when C<safe_level> is set to MEDIUM or higher.
1520 my $TopSystemUID = 10;
1521 sub top_system_uid {
1525 croak "top_system_uid: UIDs should be numeric"
1526 unless $newuid =~ /^\d+$/s;
1527 $TopSystemUID = $newuid;
1529 return $TopSystemUID;
1535 For maximum security, endeavour always to avoid ever looking at,
1536 touching, or even imputing the existence of the filename. You do not
1537 know that that filename is connected to the same file as the handle
1538 you have, and attempts to check this can only trigger more race
1539 conditions. It's far more secure to use the filehandle alone and
1540 dispense with the filename altogether.
1542 If you need to pass the handle to something that expects a filename
1543 then, on a unix system, use C<"/dev/fd/" . fileno($fh)> for arbitrary
1544 programs, or more generally C<< "+<=&" . fileno($fh) >> for Perl
1545 programs. You will have to clear the close-on-exec bit on that file
1546 descriptor before passing it to another process.
1548 use Fcntl qw/F_SETFD F_GETFD/;
1549 fcntl($tmpfh, F_SETFD, 0)
1550 or die "Can't clear close-on-exec flag on temp fh: $!\n";
1554 Originally began life in May 1999 as an XS interface to the system
1555 mkstemp() function. In March 2000, the mkstemp() code was
1556 translated to Perl for total control of the code's
1557 security checking, to ensure the presence of the function regardless of
1558 operating system and to help with portability.
1562 L<POSIX/tmpnam>, L<POSIX/tmpfile>, L<File::Spec>, L<File::Path>
1564 See L<File::MkTemp> for a different implementation of temporary
1569 Tim Jenness E<lt>t.jenness@jach.hawaii.eduE<gt>
1571 Copyright (C) 1999, 2000 Tim Jenness and the UK Particle Physics and
1572 Astronomy Research Council. All Rights Reserved. This program is free
1573 software; you can redistribute it and/or modify it under the same
1574 terms as Perl itself.
1576 Original Perl implementation loosely based on the OpenBSD C code for
1577 mkstemp(). Thanks to Tom Christiansen for suggesting that this module
1578 should be written and providing ideas for code improvements and
1579 security enhancements.