SEARCH
NEW RPMS
DIRECTORIES
ABOUT
FAQ
VARIOUS
BLOG

BotDetect - Real-Time Bot Detection API
 
 

MAN page from Mandriva  2007 perl-5.8.8-7.1mdv2007.0.x86_64.rpm

File::Temp

Section: Perl Programmers Reference Guide (3pm)
Updated: 2001-09-21
Index 

NAME

File::Temp - return name and handle of a temporary file safely 

SYNOPSIS

  use File::Temp qw/ tempfile tempdir /;

  $fh = tempfile();  ($fh, $filename) = tempfile();

  ($fh, $filename) = tempfile( $template, DIR => $dir);  ($fh, $filename) = tempfile( $template, SUFFIX => '.dat');

  $dir = tempdir( CLEANUP => 1 );  ($fh, $filename) = tempfile( DIR => $dir );

Object interface:

  require File::Temp;  use File::Temp ();

  $fh = new File::Temp($template);  $fname = $fh->filename;

  $tmp = new File::Temp( UNLINK => 0, SUFFIX => '.dat' );  print $tmp "Some data\n";  print "Filename is $tmp\n";

The following interfaces are provided for compatibility withexisting 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 );
 

DESCRIPTION

"File::Temp" can be used to create and open temporary files in a safeway. There is both a function interface and an object-orientedinterface. The File::Temp constructor or the tempfile() function canbe used to return the name and the open filehandle of a temporaryfile. The tempdir() function can be used to create a temporarydirectory.

The security aspect of temporary file creation is emphasized such thata filehandle and filename are returned together. This helps guaranteethat a race condition can not occur where the temporary file iscreated by another process between checking for the existence of thefile and its opening. Additional security levels are provided tocheck, for example, that the sticky bit is set on world writabledirectories. See ``safe_level'' for more information.

For compatibility with popular C library functions, Perl implementations ofthe mkstemp() family of functions are provided. These are, mkstemp(),mkstemps(), mkdtemp() and mktemp().

Additionally, implementations of the standard POSIXtmpnam() 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 filenamethat was valid when function was called, so cannot guaranteethat the file will not exist by the time the caller opens the filename. 

OBJECT-ORIENTED INTERFACE

This is the primary interface for interacting with"File::Temp". Using the OO interface a temporary file can be createdwhen the object is constructed and the file can be removed when theobject is no longer required.

Note that there is no method to obtain the filehandle from the"File::Temp" object. The object itself acts as a filehandle. Also,the object is configured such that it stringifies to the name of thetemporary file.

new
Create a temporary file object.

  my $tmp = new File::Temp();

by default the object is constructed as if "tempfile"was called without options, but with the additional behaviourthat the temporary file is removed by the object destructorif UNLINK is set to true (the default).

Supported arguments are the same as for "tempfile": UNLINK(defaulting to true), DIR and SUFFIX. Additionally, the filenametemplate is specified using the TEMPLATE option. The OPEN optionis not supported (the file is always opened).

 $tmp = new File::Temp( TEMPLATE => 'tempXXXXX',                        DIR => 'mydir',                        SUFFIX => '.dat');

Arguments are case insensitive.

filename
Return the name of the temporary file associated with this object.

  $filename = $tmp->filename;

This method is called automatically when the object is used asa string.

unlink_on_destroy
Control whether the file is unlinked when the object goes out of scope.The file is removed if this value is true and $KEEP_ALL is not.

 $fh->unlink_on_destroy( 1 );

Default is for the file to be removed.

DESTROY
When the object goes out of scope, the destructor is called. Thisdestructor will attempt to unlink the file (using "unlink1")if the constructor was called with UNLINK set to 1 (the default stateif UNLINK is not specified).

No error is given if the unlink fails.

If the global variable $KEEP_ALL is true, the file will not be removed.

 

FUNCTIONS

This section describes the recommended interface for generatingtemporary files and directories.
tempfile
This is the basic function to generate temporary files.The behaviour of the file can be changed using various options:

  $fh = tempfile();  ($fh, $filename) = tempfile();

Create a temporary file in the directory specified for temporaryfiles, as specified by the tmpdir() function in File::Spec.

  ($fh, $filename) = tempfile($template);

Create a temporary file in the current directory using the suppliedtemplate. Trailing `X' characters are replaced with random letters togenerate the filename. At least four `X' characters must be presentat the end of the template.

  ($fh, $filename) = tempfile($template, SUFFIX => $suffix)

Same as previously, except that a suffix is added to the templateafter the `X' translation. Useful for ensuring that a temporaryfilename has a particular extension when needed by other applications.But see the WARNING at the end.

  ($fh, $filename) = tempfile($template, DIR => $dir);

Translates the template as before except that a directory nameis specified.

  ($fh, $filename) = tempfile($template, UNLINK => 1);

Return the filename and filehandle as before except that the file isautomatically removed when the program exits (dependent on$KEEP_ALL). Default is for the file to be removed if a file handle isrequested and to be kept if the filename is requested. In a scalarcontext (where no filename is returned) the file is always deletedeither (depending on the operating system) on exit or when it isclosed (unless $KEEP_ALL is true when the temp file is created).

Use the object-oriented interface if fine-grained control of whena file is removed is required.

If the template is not specified, a template is alwaysautomatically generated. This temporary file is placed in tmpdir()(File::Spec) unless a directory is specified explicitly with theDIR option.

  $fh = tempfile( $template, DIR => $dir );

If called in scalar context, only the filehandle is returned and thefile will automatically be deleted when closed on operating systemsthat support this (see the description of tmpfile() elsewhere in thisdocument). This is the preferred mode of operation, as if you onlyhave a filehandle, you can never create a race condition by fumblingwith the filename. On systems that can not unlink an open file or cannot mark a file as temporary when it is opened (for example, WindowsNT uses the "O_TEMPORARY" flag) the file is marked for deletion whenthe program ends (equivalent to setting UNLINK to 1). The "UNLINK"flag is ignored if present.

  (undef, $filename) = tempfile($template, OPEN => 0);

This will return the filename based on the template butwill not open this file. Cannot be used in conjunction withUNLINK set to true. Default is to always open the fileto protect from possible race conditions. A warning is issuedif warnings are turned on. Consider using the tmpnam()and mktemp() functions described elsewhere in this documentif opening the file is not required.

Options can be combined as required.

tempdir
This is the recommended interface for creation of temporary directories.The behaviour of the function depends on the arguments:

  $tempdir = tempdir();

Create a directory in tmpdir() (see File::Spec).

  $tempdir = tempdir( $template );

Create a directory from the supplied template. This template issimilar to that described for tempfile(). `X' characters at the endof the template are replaced with random letters to construct thedirectory name. At least four `X' characters must be in the template.

  $tempdir = tempdir ( DIR => $dir );

Specifies the directory to use for the temporary directory.The temporary directory name is derived from an internal template.

  $tempdir = tempdir ( $template, DIR => $dir );

Prepend the supplied directory name to the template. The templateshould not include parent directory specifications itself. Any parentdirectory specifications are removed from the template beforeprepending the supplied directory.

  $tempdir = tempdir ( $template, TMPDIR => 1 );

Using the supplied template, create the temporary directory ina standard location for temporary files. Equivalent to doing

  $tempdir = tempdir ( $template, DIR => File::Spec->tmpdir);

but shorter. Parent directory specifications are stripped from thetemplate itself. The "TMPDIR" option is ignored if "DIR" is setexplicitly. Additionally, "TMPDIR" is implied if neither a templatenor a directory are supplied.

  $tempdir = tempdir( $template, CLEANUP => 1);

Create a temporary directory using the supplied template, butattempt to remove it (and all files inside it) when the programexits. Note that an attempt will be made to remove all files fromthe directory even if they were not created by this module (otherwisewhy ask to clean it up?). The directory removal is made withthe rmtree() function from the File::Path module.Of course, if the template is not specified, the temporary directorywill be created in tmpdir() and will also be removed at program exit.

 

MKTEMP FUNCTIONS

The following functions are Perl implementations of themktemp() family of temp file generation system calls.
mkstemp
Given a template, returns a filehandle to the temporary file and the nameof the file.

  ($fh, $name) = mkstemp( $template );

In scalar context, just the filehandle is returned.

The template may be any filename with some number of X's appendedto it, for example /tmp/temp.XXXX. The trailing X's are replacedwith unique alphanumeric combinations.

mkstemps
Similar to mkstemp(), except that an extra argument can be suppliedwith a suffix to be appended to the template.

  ($fh, $name) = mkstemps( $template, $suffix );

For example a template of "testXXXXXX" and suffix of ".dat"would generate a file similar to testhGji_w.dat.

Returns just the filehandle alone when called in scalar context.

mkdtemp
Create a directory from a template. The template must end inX's that are replaced by the routine.

  $tmpdir_name = mkdtemp($template);

Returns the name of the temporary directory created.Returns undef on failure.

Directory must be removed by the caller.

mktemp
Returns a valid temporary filename but does not guaranteethat the file will not be opened by someone else.

  $unopened_file = mktemp($template);

Template is the same as that required by mkstemp().

 

POSIX FUNCTIONS

This section describes the re-implementation of the tmpnam()and tmpfile() functions described in POSIXusing the mkstemp() from this module.

Unlike the POSIX implementations, the directory usedfor the temporary file is not specified in a system includefile ("P_tmpdir") but simply depends on the choice of tmpdir()returned by File::Spec. On some implementations thislocation can be set using the "TMPDIR" environment variable, whichmay not be secure.If this is a problem, simply use mkstemp() and specify a template.

tmpnam
When called in scalar context, returns the full name (including path)of a temporary file (uses mktemp()). The only check is that the file doesnot already exist, but there is no guarantee that that condition willcontinue to apply.

  $file = tmpnam();

When called in list context, a filehandle to the open file anda filename are returned. This is achieved by calling mkstemp()after constructing a suitable template.

  ($fh, $file) = tmpnam();

If possible, this form should be used to prevent possiblerace conditions.

See ``tmpdir'' in File::Spec for information on the choice of temporarydirectory for a particular operating system.

tmpfile
Returns the filehandle of a temporary file.

  $fh = tmpfile();

The file is removed when the filehandle is closed or when the programexits. No access to the filename is provided.

If the temporary file can not be created undef is returned.Currently this command will probably not work when the temporarydirectory is on an NFS file system.

 

ADDITIONAL FUNCTIONS

These functions are provided for backwards compatibilitywith common tempfile generation C library functions.

They are not exported and must be addressed using the full packagename.

tempnam
Return the name of a temporary file in the specified directoryusing a prefix. The file is guaranteed not to exist at the timethe function was called, but such guarantees are good for oneclock tick only. Always use the proper form of "sysopen"with "O_CREAT | O_EXCL" if you must open such a filename.

  $filename = File::Temp::tempnam( $dir, $prefix );

Equivalent to running mktemp() with $dir/$prefixXXXXXXXX(using unix file convention as an example)

Because this function uses mktemp(), it can suffer from race conditions.

 

UTILITY FUNCTIONS

Useful functions for dealing with the filehandle and filename.
unlink0
Given an open filehandle and the associated filename, make a safeunlink. This is achieved by first checking that the filename andfilehandle initially point to the same file and that the number oflinks to the file is 1 (all fields returned by stat() are compared).Then the filename is unlinked and the filehandle checked once again toverify that the number of links on that file is now 0. This is theclosest you can come to making sure that the filename unlinked was thesame as the file whose descriptor you hold.

  unlink0($fh, $path)     or die "Error unlinking file $path safely";

Returns false on error. The filehandle is not closed since on someoccasions this is not required.

On some platforms, for example Windows NT, it is not possible tounlink an open file (the file must be closed first). On thoseplatforms, the actual unlinking is deferred until the program ends andgood status is returned. A check is still performed to make sure thatthe filehandle and filename are pointing to the same thing (but not atthe time the end block is executed since the deferred removal may nothave access to the filehandle).

Additionally, on Windows NT not all the fields returned by stat() canbe compared. For example, the "dev" and "rdev" fields seem to bedifferent. Also, it seems that the size of the file returned by stat()does not always agree, with "stat(FH)" being more accurate than"stat(filename)", presumably because of caching issues even whenusing autoflush (this is usually overcome by waiting a while afterwriting to the tempfile before attempting to "unlink0" it).

Finally, on NFS file systems the link count of the file handle doesnot always go to zero immediately after unlinking. Currently, thiscommand is expected to fail on NFS disks.

This function is disabled if the global variable $KEEP_ALL is trueand an unlink on open file is supported. If the unlink is to be deferredto the END block, the file is still registered for removal.

cmpstat
Compare "stat" of filehandle with "stat" of provided filename. Thiscan be used to check that the filename and filehandle initially pointto the same file and that the number of links to the file is 1 (allfields returned by stat() are compared).

  cmpstat($fh, $path)     or die "Error comparing handle with file";

Returns false if the stat information differs or if the link count isgreater than 1.

On certain platofms, eg Windows, not all the fields returned by stat()can be compared. For example, the "dev" and "rdev" fields seem to bedifferent in Windows. Also, it seems that the size of the filereturned by stat() does not always agree, with "stat(FH)" being moreaccurate than "stat(filename)", presumably because of caching issueseven when using autoflush (this is usually overcome by waiting a whileafter writing to the tempfile before attempting to "unlink0" it).

Not exported by default.

unlink1
Similar to "unlink0" except after file comparison using cmpstat, thefilehandle is closed prior to attempting to unlink the file. Thisallows the file to be removed without using an END block, but doesmean that the post-unlink comparison of the filehandle state providedby "unlink0" is not available.

  unlink1($fh, $path)     or die "Error closing and unlinking file";

Usually called from the object destructor when using the OO interface.

Not exported by default.

This function is disabled if the global variable $KEEP_ALL is true.

cleanup
Calling this function will cause any temp files or temp directoriesthat are registered for removal to be removed. This happens automaticallywhen the process exits but can be triggered manually if the caller is surethat none of the temp files are required. This method can be registered asan Apache callback.

On OSes where temp files are automatically removed when the temp fileis closed, calling this function will have no effect other than to removetemporary directories (which may include temporary files).

  File::Temp::cleanup();

Not exported by default.

 

PACKAGE VARIABLES

These functions control the global state of the package.
safe_level
Controls the lengths to which the module will go to check the safety of thetemporary file or directory before proceeding.Options are:
STANDARD
Do the basic security measures to ensure the directory exists andis writable, that the umask() is fixed before opening of the file,that temporary files are opened only if they do not already exist, andthat possible race conditions are avoided. Finally the unlink0function is used to remove files safely.
MEDIUM
In addition to the STANDARD security, the output directory is checkedto make sure that it is owned either by root or the user running theprogram. If the directory is writable by group or by other, it is thenchecked to make sure that the sticky bit is set.

Will not work on platforms that do not support the "-k" testfor sticky bit.

HIGH
In addition to the MEDIUM security checks, also check for thepossibility of ``chown() giveaway'' using the POSIXsysconf() function. If this is a possibility, each directory in thepath is checked in turn for safeness, recursively walking back to theroot directory.

For platforms that do not support the POSIX"_PC_CHOWN_RESTRICTED" symbol (for example, Windows NT) it isassumed that ``chown() giveaway'' is possible and the recursive testis performed.

The level can be changed as follows:

  File::Temp->safe_level( File::Temp::HIGH );

The level constants are not exported by the module.

Currently, you must be running at least perl v5.6.0 in order torun with MEDIUM or HIGH security. This is simply because thesafety tests use functions from Fcntl that are notavailable in older versions of perl. The problem is that the versionnumber for Fcntl is the same in perl 5.6.0 and in 5.005_03 even thoughthey are different versions.

On systems that do not support the HIGH or MEDIUM safety levels(for example Win NT or OS/2) any attempt to change the level willbe ignored. The decision to ignore rather than raise an exceptionallows portable programs to be written with high security in mindfor the systems that can support this without those programs failingon systems where the extra tests are irrelevant.

If you really need to see whether the change has been acceptedsimply examine the return value of "safe_level".

  $newlevel = File::Temp->safe_level( File::Temp::HIGH );  die "Could not change to high security"      if $newlevel != File::Temp::HIGH;
TopSystemUID
This is the highest UID on the current system that refers to a rootUID. This is used to make sure that the temporary directory isowned by a system UID ("root", "bin", "sys" etc) rather thansimply by root.

This is required since on many unix systems "/tmp" is not ownedby root.

Default is to assume that any UID less than or equal to 10 is a rootUID.

  File::Temp->top_system_uid(10);  my $topid = File::Temp->top_system_uid;

This value can be adjusted to reduce security checking if required.The value is only relevant when "safe_level" is set to MEDIUM or higher.

$KEEP_ALL
Controls whether temporary files and directories should be retainedregardless of any instructions in the program to remove themautomatically. This is useful for debugging but should not be used inproduction code.

  $File::Temp::KEEP_ALL = 1;

Default is for files to be removed as requested by the caller.

In some cases, files will only be retained if this variable is truewhen the file is created. This means that you can not create a temporaryfile, set this variable and expect the temp file to still be aroundwhen the program exits.

$DEBUG
Controls whether debugging messages should be enabled.

  $File::Temp::DEBUG = 1;

Default is for debugging mode to be disabled.

 

WARNING

For maximum security, endeavour always to avoid ever looking at,touching, or even imputing the existence of the filename. You do notknow that that filename is connected to the same file as the handleyou have, and attempts to check this can only trigger more raceconditions. It's far more secure to use the filehandle alone anddispense with the filename altogether.

If you need to pass the handle to something that expects a filenamethen, on a unix system, use ""/dev/fd/" . fileno($fh)" for arbitraryprograms, or more generally ""+<=&" . fileno($fh)" for Perlprograms. You will have to clear the close-on-exec bit on that filedescriptor before passing it to another process.

    use Fcntl qw/F_SETFD F_GETFD/;    fcntl($tmpfh, F_SETFD, 0)        or die "Can't clear close-on-exec flag on temp fh: $!\n";

Temporary files and NFS

Some problems are associated with using temporary files that resideon NFS file systems and it is recommended that a local filesystemis used whenever possible. Some of the security tests will most probablyfail when the temp file is not local. Additionally, be aware thatthe performance of I/O operations over NFS will not be as good as fora local disk.

Forking

In some cases files created by File::Temp are removed from within anEND block. Since END blocks are triggered when a child process exits(unless "POSIX::_exit()" is used by the child) File::Temp takes careto only remove those temp files created by a particular process ID. Thismeans that a child will not attempt to remove temp files created by theparent process.

BINMODE

The file returned by File::Temp will have been opened in binary modeif such a mode is available. If that is not correct, use the binmode()function to change the mode of the filehandle. 

HISTORY

Originally began life in May 1999 as an XS interface to the systemmkstemp() function. In March 2000, the OpenBSD mkstemp() code wastranslated to Perl for total control of the code'ssecurity checking, to ensure the presence of the function regardless ofoperating system and to help with portability. The module was shippedas a standard part of perl from v5.6.1. 

SEE ALSO

``tmpnam'' in POSIX, ``tmpfile'' in POSIX, File::Spec, File::Path

See IO::File and File::MkTemp, Apachae::TempFile fordifferent implementations of temporary file handling. 

AUTHOR

Tim Jenness <tjennessAATTcpan.org>

Copyright (C) 1999-2005 Tim Jenness and the UK Particle Physics andAstronomy Research Council. All Rights Reserved. This program is freesoftware; you can redistribute it and/or modify it under the sameterms as Perl itself.

Original Perl implementation loosely based on the OpenBSD C code formkstemp(). Thanks to Tom Christiansen for suggesting that this moduleshould be written and providing ideas for code improvements andsecurity enhancements.


 

Index

NAME
SYNOPSIS
DESCRIPTION
OBJECT-ORIENTED INTERFACE
FUNCTIONS
MKTEMP FUNCTIONS
POSIX FUNCTIONS
ADDITIONAL FUNCTIONS
UTILITY FUNCTIONS
PACKAGE VARIABLES
WARNING
HISTORY
SEE ALSO
AUTHOR

This document was created byman2html,using the manual pages.
 
ICM Bot detect detector