Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1863 lines
54 KiB

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