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