File Coverage

blib/lib/File/Temp.pm
Criterion Covered Total %
statement 427 543 78.6
branch 205 364 56.3
condition 47 105 44.7
subroutine 60 61 98.3
pod 18 21 85.7
total 757 1094 69.2


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