File Coverage

inc/File/Temp.pm
Criterion Covered Total %
statement 176 544 32.3
branch 50 364 13.7
condition 6 102 5.8
subroutine 33 61 54.1
pod 18 21 85.7
total 283 1092 25.9


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