blib/lib/File/Temp.pm

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