forked from timj/perl-File-Temp
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Temp.pm
2484 lines (1809 loc) · 74.1 KB
/
Temp.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package File::Temp;
=head1 NAME
File::Temp - return name and handle of a temporary file safely
=begin __INTERNALS
=head1 PORTABILITY
This section is at the top in order to provide easier access to
porters. It is not expected to be rendered by a standard pod
formatting tool. Please skip straight to the SYNOPSIS section if you
are not trying to port this module to a new platform.
This module is designed to be portable across operating systems and it
currently supports Unix, VMS, DOS, OS/2, Windows and Mac OS
(Classic). When porting to a new OS there are generally three main
issues that have to be solved:
=over 4
=item *
Can the OS unlink an open file? If it can not then the
C<_can_unlink_opened_file> method should be modified.
=item *
Are the return values from C<stat> reliable? By default all the
return values from C<stat> are compared when unlinking a temporary
file using the filename and the handle. Operating systems other than
unix do not always have valid entries in all fields. If C<unlink0> fails
then the C<stat> comparison should be modified accordingly.
=item *
Security. Systems that can not support a test for the sticky bit
on a directory can not use the MEDIUM and HIGH security tests.
The C<_can_do_level> method should be modified accordingly.
=back
=end __INTERNALS
=head1 SYNOPSIS
use File::Temp qw/ tempfile tempdir /;
$fh = tempfile();
($fh, $filename) = tempfile();
($fh, $filename) = tempfile( $template, DIR => $dir);
($fh, $filename) = tempfile( $template, SUFFIX => '.dat');
($fh, $filename) = tempfile( $template, TMPDIR => 1 );
binmode( $fh, ":utf8" );
$dir = tempdir( CLEANUP => 1 );
($fh, $filename) = tempfile( DIR => $dir );
Object interface:
require File::Temp;
use File::Temp ();
use File::Temp qw/ :seekable /;
$fh = File::Temp->new();
$fname = $fh->filename;
$fh = File::Temp->new(TEMPLATE => $template);
$fname = $fh->filename;
$tmp = File::Temp->new( UNLINK => 0, SUFFIX => '.dat' );
print $tmp "Some data\n";
print "Filename is $tmp\n";
$tmp->seek( 0, SEEK_END );
The following interfaces are provided for compatibility with
existing APIs. They should not be used in new code.
MkTemp family:
use File::Temp qw/ :mktemp /;
($fh, $file) = mkstemp( "tmpfileXXXXX" );
($fh, $file) = mkstemps( "tmpfileXXXXXX", $suffix);
$tmpdir = mkdtemp( $template );
$unopened_file = mktemp( $template );
POSIX functions:
use File::Temp qw/ :POSIX /;
$file = tmpnam();
$fh = tmpfile();
($fh, $file) = tmpnam();
Compatibility functions:
$unopened_file = File::Temp::tempnam( $dir, $pfx );
=head1 DESCRIPTION
C<File::Temp> can be used to create and open temporary files in a safe
way. There is both a function interface and an object-oriented
interface. The File::Temp constructor or the tempfile() function can
be used to return the name and the open filehandle of a temporary
file. The tempdir() function can be used to create a temporary
directory.
The security aspect of temporary file creation is emphasized such that
a filehandle and filename are returned together. This helps guarantee
that a race condition can not occur where the temporary file is
created by another process between checking for the existence of the
file and its opening. Additional security levels are provided to
check, for example, that the sticky bit is set on world writable
directories. See L<"safe_level"> for more information.
For compatibility with popular C library functions, Perl implementations of
the mkstemp() family of functions are provided. These are, mkstemp(),
mkstemps(), mkdtemp() and mktemp().
Additionally, implementations of the standard L<POSIX|POSIX>
tmpnam() and tmpfile() functions are provided if required.
Implementations of mktemp(), tmpnam(), and tempnam() are provided,
but should be used with caution since they return only a filename
that was valid when function was called, so cannot guarantee
that the file will not exist by the time the caller opens the filename.
Filehandles returned by these functions support the seekable methods.
=cut
# 5.6.0 gives us S_IWOTH, S_IWGRP, our and auto-vivifying filehandls
# People would like a version on 5.004 so give them what they want :-)
use 5.004;
use strict;
use Carp;
use File::Spec 0.8;
use File::Path qw/ rmtree /;
use Fcntl 1.03;
use IO::Seekable; # For SEEK_*
use Errno;
require VMS::Stdio if $^O eq 'VMS';
# pre-emptively load Carp::Heavy. If we don't when we run out of file
# handles and attempt to call croak() we get an error message telling
# us that Carp::Heavy won't load rather than an error telling us we
# have run out of file handles. We either preload croak() or we
# switch the calls to croak from _gettemp() to use die.
eval { require Carp::Heavy; };
# Need the Symbol package if we are running older perl
require Symbol if $] < 5.006;
### For the OO interface
use base qw/ IO::Handle IO::Seekable /;
use overload '""' => "STRINGIFY", fallback => 1;
# use 'our' on v5.6.0
use vars qw($VERSION @EXPORT_OK %EXPORT_TAGS $DEBUG $KEEP_ALL);
$DEBUG = 0;
$KEEP_ALL = 0;
# We are exporting functions
use base qw/Exporter/;
# Export list - to allow fine tuning of export table
@EXPORT_OK = qw{
tempfile
tempdir
tmpnam
tmpfile
mktemp
mkstemp
mkstemps
mkdtemp
unlink0
cleanup
SEEK_SET
SEEK_CUR
SEEK_END
};
# Groups of functions for export
%EXPORT_TAGS = (
'POSIX' => [qw/ tmpnam tmpfile /],
'mktemp' => [qw/ mktemp mkstemp mkstemps mkdtemp/],
'seekable' => [qw/ SEEK_SET SEEK_CUR SEEK_END /],
);
# add contents of these tags to @EXPORT
Exporter::export_tags('POSIX','mktemp','seekable');
# Version number
$VERSION = '0.22';
# This is a list of characters that can be used in random filenames
my @CHARS = (qw/ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
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
0 1 2 3 4 5 6 7 8 9 _
/);
# Maximum number of tries to make a temp file before failing
use constant MAX_TRIES => 1000;
# Minimum number of X characters that should be in a template
use constant MINX => 4;
# Default template when no template supplied
use constant TEMPXXX => 'X' x 10;
# Constants for the security level
use constant STANDARD => 0;
use constant MEDIUM => 1;
use constant HIGH => 2;
# OPENFLAGS. If we defined the flag to use with Sysopen here this gives
# us an optimisation when many temporary files are requested
my $OPENFLAGS = O_CREAT | O_EXCL | O_RDWR;
my $LOCKFLAG;
unless ($^O eq 'MacOS') {
for my $oflag (qw/ NOFOLLOW BINARY LARGEFILE NOINHERIT /) {
my ($bit, $func) = (0, "Fcntl::O_" . $oflag);
no strict 'refs';
$OPENFLAGS |= $bit if eval {
# Make sure that redefined die handlers do not cause problems
# e.g. CGI::Carp
local $SIG{__DIE__} = sub {};
local $SIG{__WARN__} = sub {};
$bit = &$func();
1;
};
}
# Special case O_EXLOCK
$LOCKFLAG = eval {
local $SIG{__DIE__} = sub {};
local $SIG{__WARN__} = sub {};
&Fcntl::O_EXLOCK();
};
}
# On some systems the O_TEMPORARY flag can be used to tell the OS
# to automatically remove the file when it is closed. This is fine
# in most cases but not if tempfile is called with UNLINK=>0 and
# the filename is requested -- in the case where the filename is to
# be passed to another routine. This happens on windows. We overcome
# this by using a second open flags variable
my $OPENTEMPFLAGS = $OPENFLAGS;
unless ($^O eq 'MacOS') {
for my $oflag (qw/ TEMPORARY /) {
my ($bit, $func) = (0, "Fcntl::O_" . $oflag);
local($@);
no strict 'refs';
$OPENTEMPFLAGS |= $bit if eval {
# Make sure that redefined die handlers do not cause problems
# e.g. CGI::Carp
local $SIG{__DIE__} = sub {};
local $SIG{__WARN__} = sub {};
$bit = &$func();
1;
};
}
}
# Private hash tracking which files have been created by each process id via the OO interface
my %FILES_CREATED_BY_OBJECT;
# INTERNAL ROUTINES - not to be used outside of package
# Generic routine for getting a temporary filename
# modelled on OpenBSD _gettemp() in mktemp.c
# The template must contain X's that are to be replaced
# with the random values
# Arguments:
# TEMPLATE - string containing the XXXXX's that is converted
# to a random filename and opened if required
# Optionally, a hash can also be supplied containing specific options
# "open" => if true open the temp file, else just return the name
# default is 0
# "mkdir"=> if true, we are creating a temp directory rather than tempfile
# default is 0
# "suffixlen" => number of characters at end of PATH to be ignored.
# default is 0.
# "unlink_on_close" => indicates that, if possible, the OS should remove
# the file as soon as it is closed. Usually indicates
# use of the O_TEMPORARY flag to sysopen.
# Usually irrelevant on unix
# "use_exlock" => Indicates that O_EXLOCK should be used. Default is true.
# Optionally a reference to a scalar can be passed into the function
# On error this will be used to store the reason for the error
# "ErrStr" => \$errstr
# "open" and "mkdir" can not both be true
# "unlink_on_close" is not used when "mkdir" is true.
# The default options are equivalent to mktemp().
# Returns:
# filehandle - open file handle (if called with doopen=1, else undef)
# temp name - name of the temp file or directory
# For example:
# ($fh, $name) = _gettemp($template, "open" => 1);
# for the current version, failures are associated with
# stored in an error string and returned to give the reason whilst debugging
# This routine is not called by any external function
sub _gettemp {
croak 'Usage: ($fh, $name) = _gettemp($template, OPTIONS);'
unless scalar(@_) >= 1;
# the internal error string - expect it to be overridden
# Need this in case the caller decides not to supply us a value
# need an anonymous scalar
my $tempErrStr;
# Default options
my %options = (
"open" => 0,
"mkdir" => 0,
"suffixlen" => 0,
"unlink_on_close" => 0,
"use_exlock" => 1,
"ErrStr" => \$tempErrStr,
);
# Read the template
my $template = shift;
if (ref($template)) {
# Use a warning here since we have not yet merged ErrStr
carp "File::Temp::_gettemp: template must not be a reference";
return ();
}
# Check that the number of entries on stack are even
if (scalar(@_) % 2 != 0) {
# Use a warning here since we have not yet merged ErrStr
carp "File::Temp::_gettemp: Must have even number of options";
return ();
}
# Read the options and merge with defaults
%options = (%options, @_) if @_;
# Make sure the error string is set to undef
${$options{ErrStr}} = undef;
# Can not open the file and make a directory in a single call
if ($options{"open"} && $options{"mkdir"}) {
${$options{ErrStr}} = "doopen and domkdir can not both be true\n";
return ();
}
# Find the start of the end of the Xs (position of last X)
# Substr starts from 0
my $start = length($template) - 1 - $options{"suffixlen"};
# Check that we have at least MINX x X (e.g. 'XXXX") at the end of the string
# (taking suffixlen into account). Any fewer is insecure.
# Do it using substr - no reason to use a pattern match since
# we know where we are looking and what we are looking for
if (substr($template, $start - MINX + 1, MINX) ne 'X' x MINX) {
${$options{ErrStr}} = "The template must end with at least ".
MINX . " 'X' characters\n";
return ();
}
# Replace all the X at the end of the substring with a
# random character or just all the XX at the end of a full string.
# Do it as an if, since the suffix adjusts which section to replace
# and suffixlen=0 returns nothing if used in the substr directly
# and generate a full path from the template
my $path = _replace_XX($template, $options{"suffixlen"});
# Split the path into constituent parts - eventually we need to check
# whether the directory exists
# We need to know whether we are making a temp directory
# or a tempfile
my ($volume, $directories, $file);
my $parent; # parent directory
if ($options{"mkdir"}) {
# There is no filename at the end
($volume, $directories, $file) = File::Spec->splitpath( $path, 1);
# The parent is then $directories without the last directory
# Split the directory and put it back together again
my @dirs = File::Spec->splitdir($directories);
# If @dirs only has one entry (i.e. the directory template) that means
# we are in the current directory
if ($#dirs == 0) {
$parent = File::Spec->curdir;
} else {
if ($^O eq 'VMS') { # need volume to avoid relative dir spec
$parent = File::Spec->catdir($volume, @dirs[0..$#dirs-1]);
$parent = 'sys$disk:[]' if $parent eq '';
} else {
# Put it back together without the last one
$parent = File::Spec->catdir(@dirs[0..$#dirs-1]);
# ...and attach the volume (no filename)
$parent = File::Spec->catpath($volume, $parent, '');
}
}
} else {
# Get rid of the last filename (use File::Basename for this?)
($volume, $directories, $file) = File::Spec->splitpath( $path );
# Join up without the file part
$parent = File::Spec->catpath($volume,$directories,'');
# If $parent is empty replace with curdir
$parent = File::Spec->curdir
unless $directories ne '';
}
# Check that the parent directories exist
# Do this even for the case where we are simply returning a name
# not a file -- no point returning a name that includes a directory
# that does not exist or is not writable
unless (-e $parent) {
${$options{ErrStr}} = "Parent directory ($parent) does not exist";
return ();
}
unless (-d $parent) {
${$options{ErrStr}} = "Parent directory ($parent) is not a directory";
return ();
}
# Check the stickiness of the directory and chown giveaway if required
# If the directory is world writable the sticky bit
# must be set
if (File::Temp->safe_level == MEDIUM) {
my $safeerr;
unless (_is_safe($parent,\$safeerr)) {
${$options{ErrStr}} = "Parent directory ($parent) is not safe ($safeerr)";
return ();
}
} elsif (File::Temp->safe_level == HIGH) {
my $safeerr;
unless (_is_verysafe($parent, \$safeerr)) {
${$options{ErrStr}} = "Parent directory ($parent) is not safe ($safeerr)";
return ();
}
}
# Now try MAX_TRIES time to open the file
for (my $i = 0; $i < MAX_TRIES; $i++) {
# Try to open the file if requested
if ($options{"open"}) {
my $fh;
# If we are running before perl5.6.0 we can not auto-vivify
if ($] < 5.006) {
$fh = &Symbol::gensym;
}
# Try to make sure this will be marked close-on-exec
# XXX: Win32 doesn't respect this, nor the proper fcntl,
# but may have O_NOINHERIT. This may or may not be in Fcntl.
local $^F = 2;
# Attempt to open the file
my $open_success = undef;
if ( $^O eq 'VMS' and $options{"unlink_on_close"} && !$KEEP_ALL) {
# make it auto delete on close by setting FAB$V_DLT bit
$fh = VMS::Stdio::vmssysopen($path, $OPENFLAGS, 0600, 'fop=dlt');
$open_success = $fh;
} else {
my $flags = ( ($options{"unlink_on_close"} && !$KEEP_ALL) ?
$OPENTEMPFLAGS :
$OPENFLAGS );
$flags |= $LOCKFLAG if (defined $LOCKFLAG && $options{use_exlock});
$open_success = sysopen($fh, $path, $flags, 0600);
}
if ( $open_success ) {
# in case of odd umask force rw
chmod(0600, $path);
# Opened successfully - return file handle and name
return ($fh, $path);
} else {
# Error opening file - abort with error
# if the reason was anything but EEXIST
unless ($!{EEXIST}) {
${$options{ErrStr}} = "Could not create temp file $path: $!";
return ();
}
# Loop round for another try
}
} elsif ($options{"mkdir"}) {
# Open the temp directory
if (mkdir( $path, 0700)) {
# in case of odd umask
chmod(0700, $path);
return undef, $path;
} else {
# Abort with error if the reason for failure was anything
# except EEXIST
unless ($!{EEXIST}) {
${$options{ErrStr}} = "Could not create directory $path: $!";
return ();
}
# Loop round for another try
}
} else {
# Return true if the file can not be found
# Directory has been checked previously
return (undef, $path) unless -e $path;
# Try again until MAX_TRIES
}
# Did not successfully open the tempfile/dir
# so try again with a different set of random letters
# No point in trying to increment unless we have only
# 1 X say and the randomness could come up with the same
# file MAX_TRIES in a row.
# Store current attempt - in principal this implies that the
# 3rd time around the open attempt that the first temp file
# name could be generated again. Probably should store each
# attempt and make sure that none are repeated
my $original = $path;
my $counter = 0; # Stop infinite loop
my $MAX_GUESS = 50;
do {
# Generate new name from original template
$path = _replace_XX($template, $options{"suffixlen"});
$counter++;
} until ($path ne $original || $counter > $MAX_GUESS);
# Check for out of control looping
if ($counter > $MAX_GUESS) {
${$options{ErrStr}} = "Tried to get a new temp name different to the previous value $MAX_GUESS times.\nSomething wrong with template?? ($template)";
return ();
}
}
# If we get here, we have run out of tries
${ $options{ErrStr} } = "Have exceeded the maximum number of attempts ("
. MAX_TRIES . ") to open temp file/dir";
return ();
}
# Internal routine to replace the XXXX... with random characters
# This has to be done by _gettemp() every time it fails to
# open a temp file/dir
# Arguments: $template (the template with XXX),
# $ignore (number of characters at end to ignore)
# Returns: modified template
sub _replace_XX {
croak 'Usage: _replace_XX($template, $ignore)'
unless scalar(@_) == 2;
my ($path, $ignore) = @_;
# Do it as an if, since the suffix adjusts which section to replace
# and suffixlen=0 returns nothing if used in the substr directly
# Alternatively, could simply set $ignore to length($path)-1
# Don't want to always use substr when not required though.
my $end = ( $] >= 5.006 ? "\\z" : "\\Z" );
if ($ignore) {
substr($path, 0, - $ignore) =~ s/X(?=X*$end)/$CHARS[ int( rand( @CHARS ) ) ]/ge;
} else {
$path =~ s/X(?=X*$end)/$CHARS[ int( rand( @CHARS ) ) ]/ge;
}
return $path;
}
# Internal routine to force a temp file to be writable after
# it is created so that we can unlink it. Windows seems to occassionally
# force a file to be readonly when written to certain temp locations
sub _force_writable {
my $file = shift;
chmod 0600, $file;
}
# internal routine to check to see if the directory is safe
# First checks to see if the directory is not owned by the
# current user or root. Then checks to see if anyone else
# can write to the directory and if so, checks to see if
# it has the sticky bit set
# Will not work on systems that do not support sticky bit
#Args: directory path to check
# Optionally: reference to scalar to contain error message
# Returns true if the path is safe and false otherwise.
# Returns undef if can not even run stat() on the path
# This routine based on version written by Tom Christiansen
# Presumably, by the time we actually attempt to create the
# file or directory in this directory, it may not be safe
# anymore... Have to run _is_safe directly after the open.
sub _is_safe {
my $path = shift;
my $err_ref = shift;
# Stat path
my @info = stat($path);
unless (scalar(@info)) {
$$err_ref = "stat(path) returned no values";
return 0;
}
;
return 1 if $^O eq 'VMS'; # owner delete control at file level
# Check to see whether owner is neither superuser (or a system uid) nor me
# Use the effective uid from the $> variable
# UID is in [4]
if ($info[4] > File::Temp->top_system_uid() && $info[4] != $>) {
Carp::cluck(sprintf "uid=$info[4] topuid=%s euid=$> path='$path'",
File::Temp->top_system_uid());
$$err_ref = "Directory owned neither by root nor the current user"
if ref($err_ref);
return 0;
}
# check whether group or other can write file
# use 066 to detect either reading or writing
# use 022 to check writability
# Do it with S_IWOTH and S_IWGRP for portability (maybe)
# mode is in info[2]
if (($info[2] & &Fcntl::S_IWGRP) || # Is group writable?
($info[2] & &Fcntl::S_IWOTH) ) { # Is world writable?
# Must be a directory
unless (-d $path) {
$$err_ref = "Path ($path) is not a directory"
if ref($err_ref);
return 0;
}
# Must have sticky bit set
unless (-k $path) {
$$err_ref = "Sticky bit not set on $path when dir is group|world writable"
if ref($err_ref);
return 0;
}
}
return 1;
}
# Internal routine to check whether a directory is safe
# for temp files. Safer than _is_safe since it checks for
# the possibility of chown giveaway and if that is a possibility
# checks each directory in the path to see if it is safe (with _is_safe)
# If _PC_CHOWN_RESTRICTED is not set, does the full test of each
# directory anyway.
# Takes optional second arg as scalar ref to error reason
sub _is_verysafe {
# Need POSIX - but only want to bother if really necessary due to overhead
require POSIX;
my $path = shift;
print "_is_verysafe testing $path\n" if $DEBUG;
return 1 if $^O eq 'VMS'; # owner delete control at file level
my $err_ref = shift;
# Should Get the value of _PC_CHOWN_RESTRICTED if it is defined
# and If it is not there do the extensive test
local($@);
my $chown_restricted;
$chown_restricted = &POSIX::_PC_CHOWN_RESTRICTED()
if eval { &POSIX::_PC_CHOWN_RESTRICTED(); 1};
# If chown_resticted is set to some value we should test it
if (defined $chown_restricted) {
# Return if the current directory is safe
return _is_safe($path,$err_ref) if POSIX::sysconf( $chown_restricted );
}
# To reach this point either, the _PC_CHOWN_RESTRICTED symbol
# was not avialable or the symbol was there but chown giveaway
# is allowed. Either way, we now have to test the entire tree for
# safety.
# Convert path to an absolute directory if required
unless (File::Spec->file_name_is_absolute($path)) {
$path = File::Spec->rel2abs($path);
}
# Split directory into components - assume no file
my ($volume, $directories, undef) = File::Spec->splitpath( $path, 1);
# Slightly less efficient than having a function in File::Spec
# to chop off the end of a directory or even a function that
# can handle ../ in a directory tree
# Sometimes splitdir() returns a blank at the end
# so we will probably check the bottom directory twice in some cases
my @dirs = File::Spec->splitdir($directories);
# Concatenate one less directory each time around
foreach my $pos (0.. $#dirs) {
# Get a directory name
my $dir = File::Spec->catpath($volume,
File::Spec->catdir(@dirs[0.. $#dirs - $pos]),
''
);
print "TESTING DIR $dir\n" if $DEBUG;
# Check the directory
return 0 unless _is_safe($dir,$err_ref);
}
return 1;
}
# internal routine to determine whether unlink works on this
# platform for files that are currently open.
# Returns true if we can, false otherwise.
# Currently WinNT, OS/2 and VMS can not unlink an opened file
# On VMS this is because the O_EXCL flag is used to open the
# temporary file. Currently I do not know enough about the issues
# on VMS to decide whether O_EXCL is a requirement.
sub _can_unlink_opened_file {
if ($^O eq 'MSWin32' || $^O eq 'os2' || $^O eq 'VMS' || $^O eq 'dos' || $^O eq 'MacOS') {
return 0;
} else {
return 1;
}
}
# internal routine to decide which security levels are allowed
# see safe_level() for more information on this
# Controls whether the supplied security level is allowed
# $cando = _can_do_level( $level )
sub _can_do_level {
# Get security level
my $level = shift;
# Always have to be able to do STANDARD
return 1 if $level == STANDARD;
# Currently, the systems that can do HIGH or MEDIUM are identical
if ( $^O eq 'MSWin32' || $^O eq 'os2' || $^O eq 'cygwin' || $^O eq 'dos' || $^O eq 'MacOS' || $^O eq 'mpeix') {
return 0;
} else {
return 1;
}
}
# This routine sets up a deferred unlinking of a specified
# filename and filehandle. It is used in the following cases:
# - Called by unlink0 if an opened file can not be unlinked
# - Called by tempfile() if files are to be removed on shutdown
# - Called by tempdir() if directories are to be removed on shutdown
# Arguments:
# _deferred_unlink( $fh, $fname, $isdir );
#
# - filehandle (so that it can be expclicitly closed if open
# - filename (the thing we want to remove)
# - isdir (flag to indicate that we are being given a directory)
# [and hence no filehandle]
# Status is not referred to since all the magic is done with an END block
{
# Will set up two lexical variables to contain all the files to be
# removed. One array for files, another for directories They will
# only exist in this block.
# This means we only have to set up a single END block to remove
# all files.
# in order to prevent child processes inadvertently deleting the parent
# temp files we use a hash to store the temp files and directories
# created by a particular process id.
# %files_to_unlink contains values that are references to an array of
# array references containing the filehandle and filename associated with
# the temp file.
my (%files_to_unlink, %dirs_to_unlink);
# Set up an end block to use these arrays
END {
local($., $@, $!, $^E, $?);
cleanup(at_exit => 1);
}
# Cleanup function. Always triggered on END (with at_exit => 1) but
# can be invoked manually.
sub cleanup {
my %h = @_;
my $at_exit = delete $h{at_exit};
$at_exit = 0 if not defined $at_exit;
{ my @k = sort keys %h; die "unrecognized parameters: @k" if @k }
if (!$KEEP_ALL) {
# Files
my @files = (exists $files_to_unlink{$$} ?
@{ $files_to_unlink{$$} } : () );
foreach my $file (@files) {
# close the filehandle without checking its state
# in order to make real sure that this is closed
# if its already closed then I dont care about the answer
# probably a better way to do this
close($file->[0]); # file handle is [0]
if (-f $file->[1]) { # file name is [1]
_force_writable( $file->[1] ); # for windows
unlink $file->[1] or warn "Error removing ".$file->[1];
}
}
# Dirs
my @dirs = (exists $dirs_to_unlink{$$} ?
@{ $dirs_to_unlink{$$} } : () );
my ($cwd, $cwd_to_remove);
foreach my $dir (@dirs) {
if (-d $dir) {
# Some versions of rmtree will abort if you attempt to remove
# the directory you are sitting in. For automatic cleanup
# at program exit, we avoid this by chdir()ing out of the way
# first. If not at program exit, it's best not to mess with the
# current directory, so just let it fail with a warning.
if ($at_exit) {
$cwd = File::Spec->rel2abs(File::Spec->curdir) if not defined $cwd;
my $abs = File::Spec->rel2abs($dir);
if ($abs eq $cwd) {
$cwd_to_remove = $dir;
next;
}
}
eval { rmtree($dir, $DEBUG, 0); };
warn $@ if ($@ && $^W);
}
}
if (defined $cwd_to_remove) {
# We do need to clean up the current directory, and everything
# else is done, so get out of there and remove it.
my $root = File::Spec->rootdir;
chdir $root or die "cannot chdir to $root: $!";
eval { rmtree($cwd_to_remove, $DEBUG, 0); };
warn $@ if ($@ && $^W);
}
# clear the arrays
@{ $files_to_unlink{$$} } = ()
if exists $files_to_unlink{$$};
@{ $dirs_to_unlink{$$} } = ()
if exists $dirs_to_unlink{$$};
}
}
# This is the sub called to register a file for deferred unlinking
# This could simply store the input parameters and defer everything
# until the END block. For now we do a bit of checking at this
# point in order to make sure that (1) we have a file/dir to delete
# and (2) we have been called with the correct arguments.
sub _deferred_unlink {
croak 'Usage: _deferred_unlink($fh, $fname, $isdir)'
unless scalar(@_) == 3;
my ($fh, $fname, $isdir) = @_;
warn "Setting up deferred removal of $fname\n"
if $DEBUG;
# If we have a directory, check that it is a directory
if ($isdir) {
if (-d $fname) {
# Directory exists so store it
# first on VMS turn []foo into [.foo] for rmtree
$fname = VMS::Filespec::vmspath($fname) if $^O eq 'VMS';
$dirs_to_unlink{$$} = []
unless exists $dirs_to_unlink{$$};
push (@{ $dirs_to_unlink{$$} }, $fname);
} else {
carp "Request to remove directory $fname could not be completed since it does not exist!\n" if $^W;
}
} else {
if (-f $fname) {
# file exists so store handle and name for later removal
$files_to_unlink{$$} = []
unless exists $files_to_unlink{$$};
push(@{ $files_to_unlink{$$} }, [$fh, $fname]);
} else {
carp "Request to remove file $fname could not be completed since it is not there!\n" if $^W;
}
}
}
}
=head1 OBJECT-ORIENTED INTERFACE
This is the primary interface for interacting with
C<File::Temp>. Using the OO interface a temporary file can be created
when the object is constructed and the file can be removed when the
object is no longer required.
Note that there is no method to obtain the filehandle from the
C<File::Temp> object. The object itself acts as a filehandle. Also,
the object is configured such that it stringifies to the name of the