Array context keeps slithering in.
[p5sagit/p5-mst-13.2.git] / lib / File / Temp.pm
CommitLineData
262eb13a 1package File::Temp;
2
3=head1 NAME
4
5File::Temp - return name and handle of a temporary file safely
6
7=head1 SYNOPSIS
8
9 use File::Temp qw/ tempfile tempdir /;
10
11 $dir = tempdir( CLEANUP => 1 );
12 ($fh, $filename) = tempfile( DIR => $dir );
13
14 ($fh, $filename) = tempfile( $template, DIR => $dir);
15 ($fh, $filename) = tempfile( $template, SUFFIX => '.dat');
16
17 $fh = tempfile();
18
19MkTemp family:
20
21 use File::Temp qw/ :mktemp /;
22
23 ($fh, $file) = mkstemp( "tmpfileXXXXX" );
24 ($fh, $file) = mkstemps( "tmpfileXXXXXX", $suffix);
25
26 $tmpdir = mkdtemp( $template );
27
28 $unopened_file = mktemp( $template );
29
30POSIX functions:
31
32 use File::Temp qw/ :POSIX /;
33
34 $file = tmpnam();
35 $fh = tmpfile();
36
37 ($fh, $file) = tmpnam();
38 ($fh, $file) = tmpfile();
39
40
41Compatibility functions:
42
43 $unopened_file = File::Temp::tempnam( $dir, $pfx );
44
45=begin later
46
47Objects (NOT YET IMPLEMENTED):
48
49 require File::Temp;
50
51 $fh = new File::Temp($template);
52 $fname = $fh->filename;
53
54=end later
55
56=head1 DESCRIPTION
57
58C<File::Temp> can be used to create and open temporary files in a safe way.
59The tempfile() function can be used to return the name and the open
60filehandle of a temporary file. The tempdir() function can
61be used to create a temporary directory.
62
63The security aspect of temporary file creation is emphasized such that
64a filehandle and filename are returned together. This helps guarantee that
65a race condition can not occur where the temporary file is created by another process
66between checking for the existence of the file and its
67opening. Additional security levels are provided to check, for
68example, that the sticky bit is set on world writable directories.
69See L<"safe_level"> for more information.
70
71For compatibility with popular C library functions, Perl implementations of
72the mkstemp() family of functions are provided. These are, mkstemp(),
73mkstemps(), mkdtemp() and mktemp().
74
75Additionally, implementations of the standard L<POSIX|POSIX>
76tmpnam() and tmpfile() functions are provided if required.
77
78Implementations of mktemp(), tmpnam(), and tempnam() are provided,
79but should be used with caution since they return only a filename
80that was valid when function was called, so cannot guarantee
81that the file will not exist by the time the caller opens the filename.
82
83=cut
84
85# 5.6.0 gives us S_IWOTH, S_IWGRP, our and auto-vivifying filehandls
86# People would like a version on 5.005 so give them what they want :-)
87use 5.005;
88use strict;
89use Carp;
90use File::Spec 0.8;
91use File::Path qw/ rmtree /;
92use Fcntl 1.03;
93use Errno qw( EEXIST ENOENT ENOTDIR EINVAL );
51fc852f 94require VMS::Stdio if $^O eq 'VMS';
262eb13a 95
51fc852f 96# Need the Symbol package if we are running older perl
1c19c868 97require Symbol if $] < 5.006;
98
99
262eb13a 100# use 'our' on v5.6.0
101use vars qw($VERSION @EXPORT_OK %EXPORT_TAGS $DEBUG);
102
103$DEBUG = 0;
104
105# We are exporting functions
106
262eb13a 107use base qw/Exporter/;
108
109# Export list - to allow fine tuning of export table
110
111@EXPORT_OK = qw{
112 tempfile
113 tempdir
114 tmpnam
115 tmpfile
116 mktemp
669b450a 117 mkstemp
262eb13a 118 mkstemps
119 mkdtemp
120 unlink0
121 };
122
123# Groups of functions for export
124
125%EXPORT_TAGS = (
126 'POSIX' => [qw/ tmpnam tmpfile /],
127 'mktemp' => [qw/ mktemp mkstemp mkstemps mkdtemp/],
128 );
129
130# add contents of these tags to @EXPORT
131Exporter::export_tags('POSIX','mktemp');
132
133# Version number
134
51fc852f 135$VERSION = '0.10';
262eb13a 136
137# This is a list of characters that can be used in random filenames
138
139my @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
140 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
669b450a 141 0 1 2 3 4 5 6 7 8 9 _
262eb13a 142 /);
143
144# Maximum number of tries to make a temp file before failing
145
146use constant MAX_TRIES => 10;
147
148# Minimum number of X characters that should be in a template
149use constant MINX => 4;
150
151# Default template when no template supplied
152
153use constant TEMPXXX => 'X' x 10;
154
155# Constants for the security level
156
157use constant STANDARD => 0;
158use constant MEDIUM => 1;
159use constant HIGH => 2;
160
1c19c868 161# OPENFLAGS. If we defined the flag to use with Sysopen here this gives
162# us an optimisation when many temporary files are requested
163
164my $OPENFLAGS = O_CREAT | O_EXCL | O_RDWR;
165
51fc852f 166for my $oflag (qw/ FOLLOW BINARY LARGEFILE EXLOCK NOINHERIT /) {
1c19c868 167 my ($bit, $func) = (0, "Fcntl::O_" . $oflag);
168 no strict 'refs';
169 $OPENFLAGS |= $bit if eval { $bit = &$func(); 1 };
170}
171
51fc852f 172# On some systems the O_TEMPORARY flag can be used to tell the OS
173# to automatically remove the file when it is closed. This is fine
174# in most cases but not if tempfile is called with UNLINK=>0 and
175# the filename is requested -- in the case where the filename is to
176# be passed to another routine. This happens on windows. We overcome
177# this by using a second open flags variable
178
179my $OPENTEMPFLAGS = $OPENFLAGS;
180for my $oflag (qw/ TEMPORARY /) {
181 my ($bit, $func) = (0, "Fcntl::O_" . $oflag);
182 no strict 'refs';
183 $OPENTEMPFLAGS |= $bit if eval { $bit = &$func(); 1 };
184}
1c19c868 185
186
262eb13a 187# INTERNAL ROUTINES - not to be used outside of package
188
189# Generic routine for getting a temporary filename
190# modelled on OpenBSD _gettemp() in mktemp.c
191
669b450a 192# The template must contain X's that are to be replaced
262eb13a 193# with the random values
194
195# Arguments:
196
197# TEMPLATE - string containing the XXXXX's that is converted
198# to a random filename and opened if required
199
200# Optionally, a hash can also be supplied containing specific options
201# "open" => if true open the temp file, else just return the name
202# default is 0
203# "mkdir"=> if true, we are creating a temp directory rather than tempfile
204# default is 0
205# "suffixlen" => number of characters at end of PATH to be ignored.
206# default is 0.
51fc852f 207# "unlink_on_close" => indicates that, if possible, the OS should remove
208# the file as soon as it is closed. Usually indicates
209# use of the O_TEMPORARY flag to sysopen.
210# Usually irrelevant on unix
211
262eb13a 212# "open" and "mkdir" can not both be true
51fc852f 213# "unlink_on_close" is not used when "mkdir" is true.
262eb13a 214
215# The default options are equivalent to mktemp().
216
217# Returns:
218# filehandle - open file handle (if called with doopen=1, else undef)
219# temp name - name of the temp file or directory
220
221# For example:
222# ($fh, $name) = _gettemp($template, "open" => 1);
223
224# for the current version, failures are associated with
225# a carp to give the reason whilst debugging
226
227sub _gettemp {
228
229 croak 'Usage: ($fh, $name) = _gettemp($template, OPTIONS);'
230 unless scalar(@_) >= 1;
231
232 # Default options
233 my %options = (
234 "open" => 0,
235 "mkdir" => 0,
236 "suffixlen" => 0,
51fc852f 237 "unlink_on_close" => 0,
262eb13a 238 );
239
240 # Read the template
241 my $template = shift;
242 if (ref($template)) {
243 carp "File::Temp::_gettemp: template must not be a reference";
244 return ();
245 }
246
247 # Check that the number of entries on stack are even
248 if (scalar(@_) % 2 != 0) {
249 carp "File::Temp::_gettemp: Must have even number of options";
250 return ();
251 }
252
253 # Read the options and merge with defaults
254 %options = (%options, @_) if @_;
669b450a 255
262eb13a 256 # Can not open the file and make a directory in a single call
257 if ($options{"open"} && $options{"mkdir"}) {
258 carp "File::Temp::_gettemp: doopen and domkdir can not both be true\n";
259 return ();
260 }
261
262 # Find the start of the end of the Xs (position of last X)
263 # Substr starts from 0
264 my $start = length($template) - 1 - $options{"suffixlen"};
265
266 # Check that we have at least MINX x X (eg 'XXXX") at the end of the string
267 # (taking suffixlen into account). Any fewer is insecure.
268
269 # Do it using substr - no reason to use a pattern match since
270 # we know where we are looking and what we are looking for
271
272 if (substr($template, $start - MINX + 1, MINX) ne 'X' x MINX) {
273 carp "File::Temp::_gettemp: The template must contain at least ". MINX ." 'X' characters\n";
274 return ();
275 }
276
277 # Replace all the X at the end of the substring with a
278 # random character or just all the XX at the end of a full string.
279 # Do it as an if, since the suffix adjusts which section to replace
280 # and suffixlen=0 returns nothing if used in the substr directly
281 # and generate a full path from the template
282
283 my $path = _replace_XX($template, $options{"suffixlen"});
284
285
286 # Split the path into constituent parts - eventually we need to check
287 # whether the directory exists
288 # We need to know whether we are making a temp directory
289 # or a tempfile
290
291 my ($volume, $directories, $file);
292 my $parent; # parent directory
293 if ($options{"mkdir"}) {
294 # There is no filename at the end
295 ($volume, $directories, $file) = File::Spec->splitpath( $path, 1);
296
297 # The parent is then $directories without the last directory
298 # Split the directory and put it back together again
299 my @dirs = File::Spec->splitdir($directories);
300
301 # If @dirs only has one entry that means we are in the current
302 # directory
303 if ($#dirs == 0) {
304 $parent = File::Spec->curdir;
305 } else {
306
669b450a 307 if ($^O eq 'VMS') { # need volume to avoid relative dir spec
308 $parent = File::Spec->catdir($volume, @dirs[0..$#dirs-1]);
309 } else {
310
311 # Put it back together without the last one
312 $parent = File::Spec->catdir(@dirs[0..$#dirs-1]);
262eb13a 313
669b450a 314 # ...and attach the volume (no filename)
315 $parent = File::Spec->catpath($volume, $parent, '');
316 }
262eb13a 317
318 }
319
320 } else {
321
322 # Get rid of the last filename (use File::Basename for this?)
323 ($volume, $directories, $file) = File::Spec->splitpath( $path );
324
325 # Join up without the file part
326 $parent = File::Spec->catpath($volume,$directories,'');
327
328 # If $parent is empty replace with curdir
329 $parent = File::Spec->curdir
330 unless $directories ne '';
331
332 }
333
334 # Check that the parent directories exist
335 # Do this even for the case where we are simply returning a name
336 # not a file -- no point returning a name that includes a directory
337 # that does not exist or is not writable
338
339 unless (-d $parent && -w _) {
669b450a 340 carp "File::Temp::_gettemp: Parent directory ($parent) is not a directory"
262eb13a 341 . " or is not writable\n";
342 return ();
343 }
344
345 # Check the stickiness of the directory and chown giveaway if required
346 # If the directory is world writable the sticky bit
347 # must be set
348
349 if (File::Temp->safe_level == MEDIUM) {
350 unless (_is_safe($parent)) {
351 carp "File::Temp::_gettemp: Parent directory ($parent) is not safe (sticky bit not set when world writable?)";
352 return ();
353 }
354 } elsif (File::Temp->safe_level == HIGH) {
355 unless (_is_verysafe($parent)) {
356 carp "File::Temp::_gettemp: Parent directory ($parent) is not safe (sticky bit not set when world writable?)";
357 return ();
358 }
359 }
360
361
262eb13a 362 # Now try MAX_TRIES time to open the file
363 for (my $i = 0; $i < MAX_TRIES; $i++) {
364
365 # Try to open the file if requested
366 if ($options{"open"}) {
367 my $fh;
368
369 # If we are running before perl5.6.0 we can not auto-vivify
370 if ($] < 5.006) {
262eb13a 371 $fh = &Symbol::gensym;
372 }
373
374 # Try to make sure this will be marked close-on-exec
375 # XXX: Win32 doesn't respect this, nor the proper fcntl,
376 # but may have O_NOINHERIT. This may or may not be in Fcntl.
377 local $^F = 2;
378
379 # Store callers umask
380 my $umask = umask();
381
382 # Set a known umask
383 umask(066);
384
385 # Attempt to open the file
51fc852f 386 my $open_success = undef;
f826e675 387 if ( $^O eq 'VMS' and $options{"unlink_on_close"} ) {
388 # make it auto delete on close by setting FAB$V_DLT bit
51fc852f 389 $fh = VMS::Stdio::vmssysopen($path, $OPENFLAGS, 0600, 'fop=dlt');
390 $open_success = $fh;
391 } else {
392 my $flags = ( $options{"unlink_on_close"} ?
393 $OPENTEMPFLAGS :
394 $OPENFLAGS );
395 $open_success = sysopen($fh, $path, $flags, 0600);
396 }
397 if ( $open_success ) {
262eb13a 398
399 # Reset umask
400 umask($umask);
401
402 # Opened successfully - return file handle and name
403 return ($fh, $path);
404
405 } else {
406 # Reset umask
407 umask($umask);
408
409 # Error opening file - abort with error
410 # if the reason was anything but EEXIST
411 unless ($! == EEXIST) {
412 carp "File::Temp: Could not create temp file $path: $!";
413 return ();
414 }
415
416 # Loop round for another try
417
418 }
419 } elsif ($options{"mkdir"}) {
420
421 # Store callers umask
422 my $umask = umask();
423
424 # Set a known umask
425 umask(066);
426
427 # Open the temp directory
428 if (mkdir( $path, 0700)) {
429 # created okay
430 # Reset umask
431 umask($umask);
432
433 return undef, $path;
434 } else {
435
436 # Reset umask
437 umask($umask);
438
439 # Abort with error if the reason for failure was anything
440 # except EEXIST
441 unless ($! == EEXIST) {
442 carp "File::Temp: Could not create directory $path: $!";
443 return ();
444 }
445
446 # Loop round for another try
447
448 }
449
450 } else {
451
452 # Return true if the file can not be found
453 # Directory has been checked previously
454
455 return (undef, $path) unless -e $path;
456
669b450a 457 # Try again until MAX_TRIES
262eb13a 458
459 }
669b450a 460
262eb13a 461 # Did not successfully open the tempfile/dir
462 # so try again with a different set of random letters
463 # No point in trying to increment unless we have only
464 # 1 X say and the randomness could come up with the same
465 # file MAX_TRIES in a row.
466
467 # Store current attempt - in principal this implies that the
468 # 3rd time around the open attempt that the first temp file
469 # name could be generated again. Probably should store each
470 # attempt and make sure that none are repeated
471
472 my $original = $path;
473 my $counter = 0; # Stop infinite loop
474 my $MAX_GUESS = 50;
475
476 do {
477
478 # Generate new name from original template
479 $path = _replace_XX($template, $options{"suffixlen"});
480
481 $counter++;
482
483 } until ($path ne $original || $counter > $MAX_GUESS);
484
485 # Check for out of control looping
486 if ($counter > $MAX_GUESS) {
1c19c868 487 carp "Tried to get a new temp name different to the previous value $MAX_GUESS times.\nSomething wrong with template?? ($template)";
262eb13a 488 return ();
489 }
490
491 }
492
493 # If we get here, we have run out of tries
494 carp "Have exceeded the maximum number of attempts (".MAX_TRIES .
495 ") to open temp file/dir";
496
497 return ();
498
499}
500
501# Internal routine to return a random character from the
502# character list. Does not do an srand() since rand()
503# will do one automatically
504
505# No arguments. Return value is the random character
506
1c19c868 507# No longer called since _replace_XX runs a few percent faster if
508# I inline the code. This is important if we are creating thousands of
509# temporary files.
510
262eb13a 511sub _randchar {
512
513 $CHARS[ int( rand( $#CHARS ) ) ];
514
515}
516
517# Internal routine to replace the XXXX... with random characters
518# This has to be done by _gettemp() every time it fails to
519# open a temp file/dir
520
521# Arguments: $template (the template with XXX),
522# $ignore (number of characters at end to ignore)
523
524# Returns: modified template
525
526sub _replace_XX {
527
528 croak 'Usage: _replace_XX($template, $ignore)'
529 unless scalar(@_) == 2;
530
531 my ($path, $ignore) = @_;
532
533 # Do it as an if, since the suffix adjusts which section to replace
534 # and suffixlen=0 returns nothing if used in the substr directly
535 # Alternatively, could simply set $ignore to length($path)-1
536 # Don't want to always use substr when not required though.
537
538 if ($ignore) {
1c19c868 539 substr($path, 0, - $ignore) =~ s/X(?=X*\z)/$CHARS[ int( rand( $#CHARS ) ) ]/ge;
262eb13a 540 } else {
1c19c868 541 $path =~ s/X(?=X*\z)/$CHARS[ int( rand( $#CHARS ) ) ]/ge;
262eb13a 542 }
543
544 return $path;
545}
546
547# internal routine to check to see if the directory is safe
669b450a 548# First checks to see if the directory is not owned by the
262eb13a 549# current user or root. Then checks to see if anyone else
669b450a 550# can write to the directory and if so, checks to see if
262eb13a 551# it has the sticky bit set
552
553# Will not work on systems that do not support sticky bit
554
555#Args: directory path to check
556# Returns true if the path is safe and false otherwise.
557# Returns undef if can not even run stat() on the path
558
559# This routine based on version written by Tom Christiansen
560
561# Presumably, by the time we actually attempt to create the
562# file or directory in this directory, it may not be safe
563# anymore... Have to run _is_safe directly after the open.
564
565sub _is_safe {
566
567 my $path = shift;
568
569 # Stat path
570 my @info = stat($path);
571 return 0 unless scalar(@info);
669b450a 572 return 1 if $^O eq 'VMS'; # owner delete control at file level
262eb13a 573
574 # Check to see whether owner is neither superuser (or a system uid) nor me
575 # Use the real uid from the $< variable
576 # UID is in [4]
577 if ( $info[4] > File::Temp->top_system_uid() && $info[4] != $<) {
578 carp "Directory owned neither by root nor the current user";
579 return 0;
580 }
581
582 # check whether group or other can write file
583 # use 066 to detect either reading or writing
584 # use 022 to check writability
585 # Do it with S_IWOTH and S_IWGRP for portability (maybe)
586 # mode is in info[2]
587 if (($info[2] & &Fcntl::S_IWGRP) || # Is group writable?
588 ($info[2] & &Fcntl::S_IWOTH) ) { # Is world writable?
589 return 0 unless -d _; # Must be a directory
590 return 0 unless -k _; # Must be sticky
591 }
592
593 return 1;
594}
595
596# Internal routine to check whether a directory is safe
597# for temp files. Safer than _is_safe since it checks for
598# the possibility of chown giveaway and if that is a possibility
599# checks each directory in the path to see if it is safe (with _is_safe)
600
601# If _PC_CHOWN_RESTRICTED is not set, does the full test of each
602# directory anyway.
603
604sub _is_verysafe {
605
606 # Need POSIX - but only want to bother if really necessary due to overhead
607 require POSIX;
608
609 my $path = shift;
669b450a 610 return 1 if $^O eq 'VMS'; # owner delete control at file level
262eb13a 611
612 # Should Get the value of _PC_CHOWN_RESTRICTED if it is defined
613 # and If it is not there do the extensive test
614 my $chown_restricted;
615 $chown_restricted = &POSIX::_PC_CHOWN_RESTRICTED()
616 if eval { &POSIX::_PC_CHOWN_RESTRICTED(); 1};
617
618 # If chown_resticted is set to some value we should test it
619 if (defined $chown_restricted) {
620
621 # Return if the current directory is safe
622 return _is_safe($path) if POSIX::sysconf( $chown_restricted );
623
624 }
625
626 # To reach this point either, the _PC_CHOWN_RESTRICTED symbol
627 # was not avialable or the symbol was there but chown giveaway
628 # is allowed. Either way, we now have to test the entire tree for
629 # safety.
630
631 # Convert path to an absolute directory if required
632 unless (File::Spec->file_name_is_absolute($path)) {
633 $path = File::Spec->rel2abs($path);
634 }
635
636 # Split directory into components - assume no file
637 my ($volume, $directories, undef) = File::Spec->splitpath( $path, 1);
638
639 # Slightly less efficient than having a a function in File::Spec
640 # to chop off the end of a directory or even a function that
641 # can handle ../ in a directory tree
642 # Sometimes splitdir() returns a blank at the end
643 # so we will probably check the bottom directory twice in some cases
644 my @dirs = File::Spec->splitdir($directories);
645
646 # Concatenate one less directory each time around
647 foreach my $pos (0.. $#dirs) {
648 # Get a directory name
649 my $dir = File::Spec->catpath($volume,
650 File::Spec->catdir(@dirs[0.. $#dirs - $pos]),
651 ''
652 );
653
654 print "TESTING DIR $dir\n" if $DEBUG;
655
656 # Check the directory
657 return 0 unless _is_safe($dir);
658
659 }
660
661 return 1;
662}
663
664
665
666# internal routine to determine whether unlink works on this
667# platform for files that are currently open.
668# Returns true if we can, false otherwise.
669
669b450a 670# Currently WinNT, OS/2 and VMS can not unlink an opened file
671# On VMS this is because the O_EXCL flag is used to open the
672# temporary file. Currently I do not know enough about the issues
673# on VMS to decide whether O_EXCL is a requirement.
262eb13a 674
675sub _can_unlink_opened_file {
676
669b450a 677 if ($^O eq 'MSWin32' || $^O eq 'os2' || $^O eq 'VMS') {
1c19c868 678 return 0;
679 } else {
680 return 1;
681 }
262eb13a 682
683}
684
1c19c868 685# internal routine to decide which security levels are allowed
686# see safe_level() for more information on this
687
688# Controls whether the supplied security level is allowed
689
690# $cando = _can_do_level( $level )
691
692sub _can_do_level {
693
694 # Get security level
695 my $level = shift;
696
697 # Always have to be able to do STANDARD
698 return 1 if $level == STANDARD;
699
700 # Currently, the systems that can do HIGH or MEDIUM are identical
08d8cd79 701 if ( $^O eq 'MSWin32' || $^O eq 'os2' || $^O eq 'cygwin') {
1c19c868 702 return 0;
703 } else {
704 return 1;
705 }
706
707}
262eb13a 708
709# This routine sets up a deferred unlinking of a specified
710# filename and filehandle. It is used in the following cases:
669b450a 711# - Called by unlink0 if an opened file can not be unlinked
262eb13a 712# - Called by tempfile() if files are to be removed on shutdown
713# - Called by tempdir() if directories are to be removed on shutdown
714
715# Arguments:
716# _deferred_unlink( $fh, $fname, $isdir );
717#
718# - filehandle (so that it can be expclicitly closed if open
719# - filename (the thing we want to remove)
720# - isdir (flag to indicate that we are being given a directory)
721# [and hence no filehandle]
722
51fc852f 723# Status is not referred to since all the magic is done with an END block
262eb13a 724
1c19c868 725{
726 # Will set up two lexical variables to contain all the files to be
727 # removed. One array for files, another for directories
728 # They will only exist in this block
729 # This means we only have to set up a single END block to remove all files
730 # @files_to_unlink contains an array ref with the filehandle and filename
731 my (@files_to_unlink, @dirs_to_unlink);
732
733 # Set up an end block to use these arrays
734 END {
735 # Files
736 foreach my $file (@files_to_unlink) {
737 # close the filehandle without checking its state
738 # in order to make real sure that this is closed
739 # if its already closed then I dont care about the answer
740 # probably a better way to do this
741 close($file->[0]); # file handle is [0]
742
743 if (-f $file->[1]) { # file name is [1]
744 unlink $file->[1] or warn "Error removing ".$file->[1];
745 }
746 }
747 # Dirs
748 foreach my $dir (@dirs_to_unlink) {
749 if (-d $dir) {
750 rmtree($dir, $DEBUG, 1);
751 }
752 }
262eb13a 753
262eb13a 754
1c19c868 755 }
262eb13a 756
1c19c868 757 # This is the sub called to register a file for deferred unlinking
758 # This could simply store the input parameters and defer everything
759 # until the END block. For now we do a bit of checking at this
760 # point in order to make sure that (1) we have a file/dir to delete
761 # and (2) we have been called with the correct arguments.
762 sub _deferred_unlink {
763
764 croak 'Usage: _deferred_unlink($fh, $fname, $isdir)'
765 unless scalar(@_) == 3;
669b450a 766
1c19c868 767 my ($fh, $fname, $isdir) = @_;
262eb13a 768
1c19c868 769 warn "Setting up deferred removal of $fname\n"
770 if $DEBUG;
669b450a 771
1c19c868 772 # If we have a directory, check that it is a directory
773 if ($isdir) {
262eb13a 774
1c19c868 775 if (-d $fname) {
262eb13a 776
1c19c868 777 # Directory exists so store it
51fc852f 778 # first on VMS turn []foo into [.foo] for rmtree
779 $fname = VMS::Filespec::vmspath($fname) if $^O eq 'VMS';
1c19c868 780 push (@dirs_to_unlink, $fname);
262eb13a 781
1c19c868 782 } else {
51fc852f 783 carp "Request to remove directory $fname could not be completed since it does not exist!\n";
1c19c868 784 }
785
262eb13a 786 } else {
262eb13a 787
1c19c868 788 if (-f $fname) {
262eb13a 789
1c19c868 790 # file exists so store handle and name for later removal
791 push(@files_to_unlink, [$fh, $fname]);
262eb13a 792
1c19c868 793 } else {
794 carp "Request to remove file $fname could not be completed since it is not there!\n";
795 }
262eb13a 796
262eb13a 797 }
798
262eb13a 799 }
800
262eb13a 801
1c19c868 802}
262eb13a 803
804=head1 FUNCTIONS
805
806This section describes the recommended interface for generating
807temporary files and directories.
808
809=over 4
810
811=item B<tempfile>
812
813This is the basic function to generate temporary files.
814The behaviour of the file can be changed using various options:
815
816 ($fh, $filename) = tempfile();
817
818Create a temporary file in the directory specified for temporary
819files, as specified by the tmpdir() function in L<File::Spec>.
820
821 ($fh, $filename) = tempfile($template);
822
823Create a temporary file in the current directory using the supplied
824template. Trailing `X' characters are replaced with random letters to
825generate the filename. At least four `X' characters must be present
826in the template.
827
828 ($fh, $filename) = tempfile($template, SUFFIX => $suffix)
829
830Same as previously, except that a suffix is added to the template
831after the `X' translation. Useful for ensuring that a temporary
832filename has a particular extension when needed by other applications.
833But see the WARNING at the end.
834
835 ($fh, $filename) = tempfile($template, DIR => $dir);
836
837Translates the template as before except that a directory name
838is specified.
839
51fc852f 840 ($fh, $filename) = tempfile($template, UNLINK => 1);
841
842Return the filename and filehandle as before except that the file is
843automatically removed when the program exits. Default is for the file
844to be removed if a file handle is requested and to be kept if the
845filename is requested.
846
262eb13a 847If the template is not specified, a template is always
848automatically generated. This temporary file is placed in tmpdir()
849(L<File::Spec>) unless a directory is specified explicitly with the
850DIR option.
851
852 $fh = tempfile( $template, DIR => $dir );
853
854If called in scalar context, only the filehandle is returned
855and the file will automatically be deleted when closed (see
856the description of tmpfile() elsewhere in this document).
857This is the preferred mode of operation, as if you only
858have a filehandle, you can never create a race condition
859by fumbling with the filename. On systems that can not unlink
860an open file (for example, Windows NT) the file is marked for
861deletion when the program ends (equivalent to setting UNLINK to 1).
862
863 (undef, $filename) = tempfile($template, OPEN => 0);
864
865This will return the filename based on the template but
866will not open this file. Cannot be used in conjunction with
867UNLINK set to true. Default is to always open the file
868to protect from possible race conditions. A warning is issued
869if warnings are turned on. Consider using the tmpnam()
870and mktemp() functions described elsewhere in this document
871if opening the file is not required.
872
51fc852f 873Options can be combined as required.
874
262eb13a 875=cut
876
877sub tempfile {
878
879 # Can not check for argument count since we can have any
880 # number of args
881
882 # Default options
883 my %options = (
884 "DIR" => undef, # Directory prefix
f826e675 885 "SUFFIX" => '', # Template suffix
886 "UNLINK" => 0, # Do not unlink file on exit
887 "OPEN" => 1, # Open file
262eb13a 888 );
889
890 # Check to see whether we have an odd or even number of arguments
891 my $template = (scalar(@_) % 2 == 1 ? shift(@_) : undef);
892
893 # Read the options and merge with defaults
894 %options = (%options, @_) if @_;
895
896 # First decision is whether or not to open the file
897 if (! $options{"OPEN"}) {
898
899 warn "tempfile(): temporary filename requested but not opened.\nPossibly unsafe, consider using tempfile() with OPEN set to true\n"
900 if $^W;
901
902 }
903
f826e675 904 if ($options{"DIR"} and $^O eq 'VMS') {
905
906 # on VMS turn []foo into [.foo] for concatenation
907 $options{"DIR"} = VMS::Filespec::vmspath($options{"DIR"});
908 }
909
669b450a 910 # Construct the template
262eb13a 911
912 # Have a choice of trying to work around the mkstemp/mktemp/tmpnam etc
913 # functions or simply constructing a template and using _gettemp()
914 # explicitly. Go for the latter
915
916 # First generate a template if not defined and prefix the directory
917 # If no template must prefix the temp directory
918 if (defined $template) {
919 if ($options{"DIR"}) {
920
921 $template = File::Spec->catfile($options{"DIR"}, $template);
922
923 }
924
925 } else {
926
927 if ($options{"DIR"}) {
928
929 $template = File::Spec->catfile($options{"DIR"}, TEMPXXX);
930
931 } else {
669b450a 932
262eb13a 933 $template = File::Spec->catfile(File::Spec->tmpdir, TEMPXXX);
934
935 }
669b450a 936
262eb13a 937 }
938
939 # Now add a suffix
940 $template .= $options{"SUFFIX"};
941
942 # Create the file
943 my ($fh, $path);
944 croak "Error in tempfile() using $template"
945 unless (($fh, $path) = _gettemp($template,
51fc852f 946 "open" => $options{'OPEN'},
262eb13a 947 "mkdir"=> 0 ,
f826e675 948 "unlink_on_close" => $options{'UNLINK'},
262eb13a 949 "suffixlen" => length($options{'SUFFIX'}),
669b450a 950 ) );
262eb13a 951
952 # Set up an exit handler that can do whatever is right for the
953 # system. Do not check return status since this is all done with
954 # END blocks
955 _deferred_unlink($fh, $path, 0) if $options{"UNLINK"};
669b450a 956
262eb13a 957 # Return
958 if (wantarray()) {
959
960 if ($options{'OPEN'}) {
961 return ($fh, $path);
962 } else {
963 return (undef, $path);
964 }
965
966 } else {
967
968 # Unlink the file. It is up to unlink0 to decide what to do with
969 # this (whether to unlink now or to defer until later)
970 unlink0($fh, $path) or croak "Error unlinking file $path using unlink0";
669b450a 971
262eb13a 972 # Return just the filehandle.
973 return $fh;
974 }
975
976
977}
978
979=item B<tempdir>
980
981This is the recommended interface for creation of temporary directories.
982The behaviour of the function depends on the arguments:
983
984 $tempdir = tempdir();
985
986Create a directory in tmpdir() (see L<File::Spec|File::Spec>).
987
988 $tempdir = tempdir( $template );
989
990Create a directory from the supplied template. This template is
991similar to that described for tempfile(). `X' characters at the end
992of the template are replaced with random letters to construct the
993directory name. At least four `X' characters must be in the template.
994
995 $tempdir = tempdir ( DIR => $dir );
996
997Specifies the directory to use for the temporary directory.
998The temporary directory name is derived from an internal template.
999
1000 $tempdir = tempdir ( $template, DIR => $dir );
1001
1002Prepend the supplied directory name to the template. The template
1003should not include parent directory specifications itself. Any parent
1004directory specifications are removed from the template before
1005prepending the supplied directory.
1006
1007 $tempdir = tempdir ( $template, TMPDIR => 1 );
1008
1009Using the supplied template, creat the temporary directory in
1010a standard location for temporary files. Equivalent to doing
1011
1012 $tempdir = tempdir ( $template, DIR => File::Spec->tmpdir);
1013
1014but shorter. Parent directory specifications are stripped from the
1015template itself. The C<TMPDIR> option is ignored if C<DIR> is set
1016explicitly. Additionally, C<TMPDIR> is implied if neither a template
1017nor a directory are supplied.
1018
1019 $tempdir = tempdir( $template, CLEANUP => 1);
1020
1021Create a temporary directory using the supplied template, but
1022attempt to remove it (and all files inside it) when the program
1023exits. Note that an attempt will be made to remove all files from
1024the directory even if they were not created by this module (otherwise
1025why ask to clean it up?). The directory removal is made with
1026the rmtree() function from the L<File::Path|File::Path> module.
1027Of course, if the template is not specified, the temporary directory
1028will be created in tmpdir() and will also be removed at program exit.
1029
1030=cut
1031
1032# '
1033
1034sub tempdir {
1035
1036 # Can not check for argument count since we can have any
1037 # number of args
1038
1039 # Default options
1040 my %options = (
1041 "CLEANUP" => 0, # Remove directory on exit
1042 "DIR" => '', # Root directory
1043 "TMPDIR" => 0, # Use tempdir with template
1044 );
1045
1046 # Check to see whether we have an odd or even number of arguments
1047 my $template = (scalar(@_) % 2 == 1 ? shift(@_) : undef );
1048
1049 # Read the options and merge with defaults
1050 %options = (%options, @_) if @_;
1051
1052 # Modify or generate the template
1053
1054 # Deal with the DIR and TMPDIR options
1055 if (defined $template) {
1056
1057 # Need to strip directory path if using DIR or TMPDIR
1058 if ($options{'TMPDIR'} || $options{'DIR'}) {
1059
1060 # Strip parent directory from the filename
51fc852f 1061 #
262eb13a 1062 # There is no filename at the end
51fc852f 1063 $template = VMS::Filespec::vmspath($template) if $^O eq 'VMS';
262eb13a 1064 my ($volume, $directories, undef) = File::Spec->splitpath( $template, 1);
1065
1066 # Last directory is then our template
1067 $template = (File::Spec->splitdir($directories))[-1];
1068
1069 # Prepend the supplied directory or temp dir
1070 if ($options{"DIR"}) {
1071
1072 $template = File::Spec->catfile($options{"DIR"}, $template);
1073
1074 } elsif ($options{TMPDIR}) {
1075
1076 # Prepend tmpdir
1077 $template = File::Spec->catdir(File::Spec->tmpdir, $template);
1078
1079 }
1080
1081 }
1082
1083 } else {
1084
1085 if ($options{"DIR"}) {
1086
1087 $template = File::Spec->catdir($options{"DIR"}, TEMPXXX);
1088
1089 } else {
669b450a 1090
262eb13a 1091 $template = File::Spec->catdir(File::Spec->tmpdir, TEMPXXX);
1092
1093 }
669b450a 1094
262eb13a 1095 }
1096
1097 # Create the directory
1098 my $tempdir;
669b450a 1099 my $suffixlen = 0;
1100 if ($^O eq 'VMS') { # dir names can end in delimiters
1101 $template =~ m/([\.\]:>]+)$/;
1102 $suffixlen = length($1);
1103 }
262eb13a 1104 croak "Error in tempdir() using $template"
1105 unless ((undef, $tempdir) = _gettemp($template,
669b450a 1106 "open" => 0,
262eb13a 1107 "mkdir"=> 1 ,
669b450a 1108 "suffixlen" => $suffixlen,
1109 ) );
1110
262eb13a 1111 # Install exit handler; must be dynamic to get lexical
669b450a 1112 if ( $options{'CLEANUP'} && -d $tempdir) {
262eb13a 1113 _deferred_unlink(undef, $tempdir, 1);
669b450a 1114 }
262eb13a 1115
1116 # Return the dir name
1117 return $tempdir;
1118
1119}
1120
1121=back
1122
1123=head1 MKTEMP FUNCTIONS
1124
1125The following functions are Perl implementations of the
1126mktemp() family of temp file generation system calls.
1127
1128=over 4
1129
1130=item B<mkstemp>
1131
1132Given a template, returns a filehandle to the temporary file and the name
1133of the file.
1134
1135 ($fh, $name) = mkstemp( $template );
1136
1137In scalar context, just the filehandle is returned.
1138
1139The template may be any filename with some number of X's appended
1140to it, for example F</tmp/temp.XXXX>. The trailing X's are replaced
1141with unique alphanumeric combinations.
1142
1143=cut
1144
1145
1146
1147sub mkstemp {
1148
1149 croak "Usage: mkstemp(template)"
1150 if scalar(@_) != 1;
1151
1152 my $template = shift;
1153
1154 my ($fh, $path);
1155 croak "Error in mkstemp using $template"
669b450a 1156 unless (($fh, $path) = _gettemp($template,
1157 "open" => 1,
262eb13a 1158 "mkdir"=> 0 ,
1159 "suffixlen" => 0,
1160 ) );
1161
1162 if (wantarray()) {
1163 return ($fh, $path);
1164 } else {
1165 return $fh;
1166 }
1167
1168}
1169
1170
1171=item B<mkstemps>
1172
1173Similar to mkstemp(), except that an extra argument can be supplied
1174with a suffix to be appended to the template.
1175
1176 ($fh, $name) = mkstemps( $template, $suffix );
1177
1178For example a template of C<testXXXXXX> and suffix of C<.dat>
1179would generate a file similar to F<testhGji_w.dat>.
1180
1181Returns just the filehandle alone when called in scalar context.
1182
1183=cut
1184
1185sub mkstemps {
1186
1187 croak "Usage: mkstemps(template, suffix)"
1188 if scalar(@_) != 2;
1189
1190
1191 my $template = shift;
1192 my $suffix = shift;
1193
1194 $template .= $suffix;
669b450a 1195
262eb13a 1196 my ($fh, $path);
1197 croak "Error in mkstemps using $template"
1198 unless (($fh, $path) = _gettemp($template,
1199 "open" => 1,
1200 "mkdir"=> 0 ,
1201 "suffixlen" => length($suffix),
1202 ) );
1203
1204 if (wantarray()) {
1205 return ($fh, $path);
1206 } else {
1207 return $fh;
1208 }
1209
1210}
1211
1212=item B<mkdtemp>
1213
1214Create a directory from a template. The template must end in
1215X's that are replaced by the routine.
1216
1217 $tmpdir_name = mkdtemp($template);
1218
1219Returns the name of the temporary directory created.
1220Returns undef on failure.
1221
1222Directory must be removed by the caller.
1223
1224=cut
1225
1226#' # for emacs
1227
1228sub mkdtemp {
1229
1230 croak "Usage: mkdtemp(template)"
1231 if scalar(@_) != 1;
262eb13a 1232
669b450a 1233 my $template = shift;
1234 my $suffixlen = 0;
1235 if ($^O eq 'VMS') { # dir names can end in delimiters
1236 $template =~ m/([\.\]:>]+)$/;
1237 $suffixlen = length($1);
1238 }
262eb13a 1239 my ($junk, $tmpdir);
1240 croak "Error creating temp directory from template $template\n"
1241 unless (($junk, $tmpdir) = _gettemp($template,
669b450a 1242 "open" => 0,
262eb13a 1243 "mkdir"=> 1 ,
669b450a 1244 "suffixlen" => $suffixlen,
262eb13a 1245 ) );
1246
1247 return $tmpdir;
1248
1249}
1250
1251=item B<mktemp>
1252
1253Returns a valid temporary filename but does not guarantee
1254that the file will not be opened by someone else.
1255
1256 $unopened_file = mktemp($template);
1257
1258Template is the same as that required by mkstemp().
1259
1260=cut
1261
1262sub mktemp {
1263
1264 croak "Usage: mktemp(template)"
1265 if scalar(@_) != 1;
1266
1267 my $template = shift;
1268
1269 my ($tmpname, $junk);
1270 croak "Error getting name to temp file from template $template\n"
1271 unless (($junk, $tmpname) = _gettemp($template,
669b450a 1272 "open" => 0,
262eb13a 1273 "mkdir"=> 0 ,
1274 "suffixlen" => 0,
1275 ) );
1276
1277 return $tmpname;
1278}
1279
1280=back
1281
1282=head1 POSIX FUNCTIONS
1283
1284This section describes the re-implementation of the tmpnam()
1285and tmpfile() functions described in L<POSIX>
1286using the mkstemp() from this module.
1287
1288Unlike the L<POSIX|POSIX> implementations, the directory used
1289for the temporary file is not specified in a system include
1290file (C<P_tmpdir>) but simply depends on the choice of tmpdir()
1291returned by L<File::Spec|File::Spec>. On some implementations this
1292location can be set using the C<TMPDIR> environment variable, which
1293may not be secure.
1294If this is a problem, simply use mkstemp() and specify a template.
1295
1296=over 4
1297
1298=item B<tmpnam>
1299
1300When called in scalar context, returns the full name (including path)
1301of a temporary file (uses mktemp()). The only check is that the file does
1302not already exist, but there is no guarantee that that condition will
1303continue to apply.
1304
1305 $file = tmpnam();
1306
1307When called in list context, a filehandle to the open file and
1308a filename are returned. This is achieved by calling mkstemp()
1309after constructing a suitable template.
1310
1311 ($fh, $file) = tmpnam();
1312
1313If possible, this form should be used to prevent possible
1314race conditions.
1315
1316See L<File::Spec/tmpdir> for information on the choice of temporary
1317directory for a particular operating system.
1318
1319=cut
1320
1321sub tmpnam {
1322
1323 # Retrieve the temporary directory name
1324 my $tmpdir = File::Spec->tmpdir;
1325
1326 croak "Error temporary directory is not writable"
1327 if $tmpdir eq '';
1328
1329 # Use a ten character template and append to tmpdir
1330 my $template = File::Spec->catfile($tmpdir, TEMPXXX);
669b450a 1331
262eb13a 1332 if (wantarray() ) {
1333 return mkstemp($template);
1334 } else {
1335 return mktemp($template);
1336 }
1337
1338}
1339
1340=item B<tmpfile>
1341
1342In scalar context, returns the filehandle of a temporary file.
1343
1344 $fh = tmpfile();
1345
1346The file is removed when the filehandle is closed or when the program
1347exits. No access to the filename is provided.
1348
1349=cut
1350
1351sub tmpfile {
1352
91e74348 1353 # Simply call tmpnam() in a list context
262eb13a 1354 my ($fh, $file) = tmpnam();
1355
1356 # Make sure file is removed when filehandle is closed
1357 unlink0($fh, $file) or croak "Unable to unlink temporary file: $!";
1358
1359 return $fh;
1360
1361}
1362
1363=back
1364
1365=head1 ADDITIONAL FUNCTIONS
1366
1367These functions are provided for backwards compatibility
1368with common tempfile generation C library functions.
1369
1370They are not exported and must be addressed using the full package
1371name.
1372
1373=over 4
1374
1375=item B<tempnam>
1376
1377Return the name of a temporary file in the specified directory
1378using a prefix. The file is guaranteed not to exist at the time
1379the function was called, but such guarantees are good for one
1380clock tick only. Always use the proper form of C<sysopen>
1381with C<O_CREAT | O_EXCL> if you must open such a filename.
1382
1383 $filename = File::Temp::tempnam( $dir, $prefix );
1384
1385Equivalent to running mktemp() with $dir/$prefixXXXXXXXX
1386(using unix file convention as an example)
1387
1388Because this function uses mktemp(), it can suffer from race conditions.
1389
1390=cut
1391
1392sub tempnam {
1393
1394 croak 'Usage tempnam($dir, $prefix)' unless scalar(@_) == 2;
1395
1396 my ($dir, $prefix) = @_;
1397
1398 # Add a string to the prefix
1399 $prefix .= 'XXXXXXXX';
1400
1401 # Concatenate the directory to the file
1402 my $template = File::Spec->catfile($dir, $prefix);
1403
1404 return mktemp($template);
1405
1406}
1407
1408=back
1409
1410=head1 UTILITY FUNCTIONS
1411
1412Useful functions for dealing with the filehandle and filename.
1413
1414=over 4
1415
1416=item B<unlink0>
1417
1418Given an open filehandle and the associated filename, make a safe
1419unlink. This is achieved by first checking that the filename and
1420filehandle initially point to the same file and that the number of
1421links to the file is 1 (all fields returned by stat() are compared).
1422Then the filename is unlinked and the filehandle checked once again to
1423verify that the number of links on that file is now 0. This is the
1424closest you can come to making sure that the filename unlinked was the
1425same as the file whose descriptor you hold.
1426
1427 unlink0($fh, $path) or die "Error unlinking file $path safely";
1428
1429Returns false on error. The filehandle is not closed since on some
1430occasions this is not required.
1431
1432On some platforms, for example Windows NT, it is not possible to
1433unlink an open file (the file must be closed first). On those
1c19c868 1434platforms, the actual unlinking is deferred until the program ends and
1435good status is returned. A check is still performed to make sure that
1436the filehandle and filename are pointing to the same thing (but not at
1437the time the end block is executed since the deferred removal may not
1438have access to the filehandle).
262eb13a 1439
1440Additionally, on Windows NT not all the fields returned by stat() can
51fc852f 1441be compared. For example, the C<dev> and C<rdev> fields seem to be
1442different. Also, it seems that the size of the file returned by stat()
262eb13a 1443does not always agree, with C<stat(FH)> being more accurate than
1444C<stat(filename)>, presumably because of caching issues even when
1445using autoflush (this is usually overcome by waiting a while after
1446writing to the tempfile before attempting to C<unlink0> it).
1447
1c19c868 1448Finally, on NFS file systems the link count of the file handle does
1449not always go to zero immediately after unlinking. Currently, this
1450command is expected to fail on NFS disks.
1451
262eb13a 1452=cut
1453
1454sub unlink0 {
1455
1456 croak 'Usage: unlink0(filehandle, filename)'
1457 unless scalar(@_) == 2;
1458
1459 # Read args
1460 my ($fh, $path) = @_;
1461
1462 warn "Unlinking $path using unlink0\n"
1463 if $DEBUG;
1464
1465 # Stat the filehandle
1466 my @fh = stat $fh;
1467
1468 if ($fh[3] > 1 && $^W) {
1469 carp "unlink0: fstat found too many links; SB=@fh";
669b450a 1470 }
262eb13a 1471
1472 # Stat the path
1473 my @path = stat $path;
1474
1475 unless (@path) {
1476 carp "unlink0: $path is gone already" if $^W;
1477 return;
669b450a 1478 }
262eb13a 1479
1480 # this is no longer a file, but may be a directory, or worse
1481 unless (-f _) {
1482 confess "panic: $path is no longer a file: SB=@fh";
669b450a 1483 }
262eb13a 1484
1485 # Do comparison of each member of the array
1486 # On WinNT dev and rdev seem to be different
1487 # depending on whether it is a file or a handle.
1488 # Cannot simply compare all members of the stat return
1489 # Select the ones we can use
1490 my @okstat = (0..$#fh); # Use all by default
1491 if ($^O eq 'MSWin32') {
1492 @okstat = (1,2,3,4,5,7,8,9,10);
669b450a 1493 } elsif ($^O eq 'os2') {
d62e1b7f 1494 @okstat = (0, 2..$#fh);
51fc852f 1495 } elsif ($^O eq 'VMS') { # device and file ID are sufficient
1496 @okstat = (0, 1);
262eb13a 1497 }
1498
1499 # Now compare each entry explicitly by number
1500 for (@okstat) {
1501 print "Comparing: $_ : $fh[$_] and $path[$_]\n" if $DEBUG;
d62e1b7f 1502 # Use eq rather than == since rdev, blksize, and blocks (6, 11,
1503 # and 12) will be '' on platforms that do not support them. This
1504 # is fine since we are only comparing integers.
669b450a 1505 unless ($fh[$_] eq $path[$_]) {
262eb13a 1506 warn "Did not match $_ element of stat\n" if $DEBUG;
1507 return 0;
1508 }
1509 }
669b450a 1510
262eb13a 1511 # attempt remove the file (does not work on some platforms)
1512 if (_can_unlink_opened_file()) {
1513 # XXX: do *not* call this on a directory; possible race
1514 # resulting in recursive removal
1515 croak "unlink0: $path has become a directory!" if -d $path;
1516 unlink($path) or return 0;
1517
1518 # Stat the filehandle
1519 @fh = stat $fh;
1520
1521 print "Link count = $fh[3] \n" if $DEBUG;
1522
1523 # Make sure that the link count is zero
ceb977da 1524 # - Cygwin provides deferred unlinking, however,
1525 # on Win9x the link count remains 1
1526 return ( $fh[3] == 0 or $^O eq 'cygwin' ? 1 : 0);
262eb13a 1527
1528 } else {
1529 _deferred_unlink($fh, $path, 0);
1530 return 1;
1531 }
1532
1533}
1534
1535=back
1536
1537=head1 PACKAGE VARIABLES
1538
1539These functions control the global state of the package.
1540
1541=over 4
1542
1543=item B<safe_level>
1544
1545Controls the lengths to which the module will go to check the safety of the
1546temporary file or directory before proceeding.
1547Options are:
1548
1549=over 8
1550
1551=item STANDARD
1552
1553Do the basic security measures to ensure the directory exists and
1554is writable, that the umask() is fixed before opening of the file,
1555that temporary files are opened only if they do not already exist, and
1556that possible race conditions are avoided. Finally the L<unlink0|"unlink0">
1557function is used to remove files safely.
1558
1559=item MEDIUM
1560
1561In addition to the STANDARD security, the output directory is checked
1562to make sure that it is owned either by root or the user running the
1563program. If the directory is writable by group or by other, it is then
1564checked to make sure that the sticky bit is set.
1565
1566Will not work on platforms that do not support the C<-k> test
1567for sticky bit.
1568
1569=item HIGH
1570
1571In addition to the MEDIUM security checks, also check for the
1572possibility of ``chown() giveaway'' using the L<POSIX|POSIX>
1573sysconf() function. If this is a possibility, each directory in the
1574path is checked in turn for safeness, recursively walking back to the
1575root directory.
1576
1577For platforms that do not support the L<POSIX|POSIX>
1578C<_PC_CHOWN_RESTRICTED> symbol (for example, Windows NT) it is
1579assumed that ``chown() giveaway'' is possible and the recursive test
1580is performed.
1581
1582=back
1583
1584The level can be changed as follows:
1585
1586 File::Temp->safe_level( File::Temp::HIGH );
1587
1588The level constants are not exported by the module.
1589
1590Currently, you must be running at least perl v5.6.0 in order to
1591run with MEDIUM or HIGH security. This is simply because the
1592safety tests use functions from L<Fcntl|Fcntl> that are not
1593available in older versions of perl. The problem is that the version
1594number for Fcntl is the same in perl 5.6.0 and in 5.005_03 even though
1c19c868 1595they are different versions.
1596
1597On systems that do not support the HIGH or MEDIUM safety levels
1598(for example Win NT or OS/2) any attempt to change the level will
1599be ignored. The decision to ignore rather than raise an exception
1600allows portable programs to be written with high security in mind
1601for the systems that can support this without those programs failing
1602on systems where the extra tests are irrelevant.
1603
1604If you really need to see whether the change has been accepted
1605simply examine the return value of C<safe_level>.
1606
1607 $newlevel = File::Temp->safe_level( File::Temp::HIGH );
1608 die "Could not change to high security"
1609 if $newlevel != File::Temp::HIGH;
262eb13a 1610
1611=cut
1612
1613{
1614 # protect from using the variable itself
1615 my $LEVEL = STANDARD;
1616 sub safe_level {
1617 my $self = shift;
1618 if (@_) {
1619 my $level = shift;
1620 if (($level != STANDARD) && ($level != MEDIUM) && ($level != HIGH)) {
1621 carp "safe_level: Specified level ($level) not STANDARD, MEDIUM or HIGH - ignoring\n";
1622 } else {
1c19c868 1623 # Dont allow this on perl 5.005 or earlier
262eb13a 1624 if ($] < 5.006 && $level != STANDARD) {
1625 # Cant do MEDIUM or HIGH checks
1626 croak "Currently requires perl 5.006 or newer to do the safe checks";
1627 }
1c19c868 1628 # Check that we are allowed to change level
1629 # Silently ignore if we can not.
1630 $LEVEL = $level if _can_do_level($level);
262eb13a 1631 }
1632 }
1633 return $LEVEL;
1634 }
1635}
1636
1637=item TopSystemUID
1638
1639This is the highest UID on the current system that refers to a root
1640UID. This is used to make sure that the temporary directory is
1641owned by a system UID (C<root>, C<bin>, C<sys> etc) rather than
1642simply by root.
1643
1644This is required since on many unix systems C</tmp> is not owned
1645by root.
1646
1647Default is to assume that any UID less than or equal to 10 is a root
1648UID.
1649
1650 File::Temp->top_system_uid(10);
1651 my $topid = File::Temp->top_system_uid;
1652
1653This value can be adjusted to reduce security checking if required.
1654The value is only relevant when C<safe_level> is set to MEDIUM or higher.
1655
1656=back
1657
1658=cut
1659
1660{
1661 my $TopSystemUID = 10;
1662 sub top_system_uid {
1663 my $self = shift;
1664 if (@_) {
1665 my $newuid = shift;
1666 croak "top_system_uid: UIDs should be numeric"
1667 unless $newuid =~ /^\d+$/s;
1668 $TopSystemUID = $newuid;
1669 }
1670 return $TopSystemUID;
1671 }
1672}
1673
1674=head1 WARNING
1675
1676For maximum security, endeavour always to avoid ever looking at,
1677touching, or even imputing the existence of the filename. You do not
1678know that that filename is connected to the same file as the handle
1679you have, and attempts to check this can only trigger more race
1680conditions. It's far more secure to use the filehandle alone and
1681dispense with the filename altogether.
1682
1683If you need to pass the handle to something that expects a filename
1684then, on a unix system, use C<"/dev/fd/" . fileno($fh)> for arbitrary
1685programs, or more generally C<< "+<=&" . fileno($fh) >> for Perl
1686programs. You will have to clear the close-on-exec bit on that file
1687descriptor before passing it to another process.
1688
1689 use Fcntl qw/F_SETFD F_GETFD/;
1690 fcntl($tmpfh, F_SETFD, 0)
1691 or die "Can't clear close-on-exec flag on temp fh: $!\n";
1692
1693=head1 HISTORY
1694
1695Originally began life in May 1999 as an XS interface to the system
1696mkstemp() function. In March 2000, the mkstemp() code was
1697translated to Perl for total control of the code's
1698security checking, to ensure the presence of the function regardless of
1699operating system and to help with portability.
1700
1701=head1 SEE ALSO
1702
1703L<POSIX/tmpnam>, L<POSIX/tmpfile>, L<File::Spec>, L<File::Path>
1704
1705See L<File::MkTemp> for a different implementation of temporary
1706file handling.
1707
1708=head1 AUTHOR
1709
1710Tim Jenness E<lt>t.jenness@jach.hawaii.eduE<gt>
1711
1712Copyright (C) 1999, 2000 Tim Jenness and the UK Particle Physics and
1713Astronomy Research Council. All Rights Reserved. This program is free
1714software; you can redistribute it and/or modify it under the same
1715terms as Perl itself.
1716
1717Original Perl implementation loosely based on the OpenBSD C code for
1718mkstemp(). Thanks to Tom Christiansen for suggesting that this module
1719should be written and providing ideas for code improvements and
1720security enhancements.
1721
1722=cut
1723
1724
17251;