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