📄 file::temp.3
字号:
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 \f(CW\*(C`sysopen\*(C'\fRwith \f(CW\*(C`O_CREAT | O_EXCL\*(C'\fR if you must open such a filename..Sp.Vb 1\& $filename = File::Temp::tempnam( $dir, $prefix );.Ve.SpEquivalent to running \fImktemp()\fR with \f(CW$dir\fR/$prefixXXXXXXXX(using unix file convention as an example).SpBecause this function uses \fImktemp()\fR, it can suffer from race conditions..SpWill \fIcroak()\fR if there is an error..SH "UTILITY FUNCTIONS".IX Header "UTILITY FUNCTIONS"Useful functions for dealing with the filehandle and filename..IP "\fBunlink0\fR" 4.IX Item "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 \fIstat()\fR 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..Sp.Vb 2\& unlink0($fh, $path)\& or die "Error unlinking file $path safely";.Ve.SpReturns false on error but \fIcroaks()\fR if there is a securityanomaly. The filehandle is not closed since on some occasions this isnot required..SpOn some platforms, for example Windows \s-1NT\s0, 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)..SpAdditionally, on Windows \s-1NT\s0 not all the fields returned by \fIstat()\fR canbe compared. For example, the \f(CW\*(C`dev\*(C'\fR and \f(CW\*(C`rdev\*(C'\fR fields seem to bedifferent. Also, it seems that the size of the file returned by \fIstat()\fRdoes not always agree, with \f(CW\*(C`stat(FH)\*(C'\fR being more accurate than\&\f(CW\*(C`stat(filename)\*(C'\fR, presumably because of caching issues even whenusing autoflush (this is usually overcome by waiting a while afterwriting to the tempfile before attempting to \f(CW\*(C`unlink0\*(C'\fR it)..SpFinally, on \s-1NFS\s0 file systems the link count of the file handle doesnot always go to zero immediately after unlinking. Currently, thiscommand is expected to fail on \s-1NFS\s0 disks..SpThis function is disabled if the global variable \f(CW$KEEP_ALL\fR is trueand an unlink on open file is supported. If the unlink is to be deferredto the \s-1END\s0 block, the file is still registered for removal..SpThis function should not be called if you are using the object orientedinterface since the it will interfere with the object destructor deletingthe file..IP "\fBcmpstat\fR" 4.IX Item "cmpstat"Compare \f(CW\*(C`stat\*(C'\fR of filehandle with \f(CW\*(C`stat\*(C'\fR 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 \fIstat()\fR are compared)..Sp.Vb 2\& cmpstat($fh, $path)\& or die "Error comparing handle with file";.Ve.SpReturns false if the stat information differs or if the link count isgreater than 1. Calls croak if there is a security anomaly..SpOn certain platforms, for example Windows, not all the fields returned by \fIstat()\fRcan be compared. For example, the \f(CW\*(C`dev\*(C'\fR and \f(CW\*(C`rdev\*(C'\fR fields seem to bedifferent in Windows. Also, it seems that the size of the filereturned by \fIstat()\fR does not always agree, with \f(CW\*(C`stat(FH)\*(C'\fR being moreaccurate than \f(CW\*(C`stat(filename)\*(C'\fR, presumably because of caching issueseven when using autoflush (this is usually overcome by waiting a whileafter writing to the tempfile before attempting to \f(CW\*(C`unlink0\*(C'\fR it)..SpNot exported by default..IP "\fBunlink1\fR" 4.IX Item "unlink1"Similar to \f(CW\*(C`unlink0\*(C'\fR 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 \s-1END\s0 block, but doesmean that the post-unlink comparison of the filehandle state providedby \f(CW\*(C`unlink0\*(C'\fR is not available..Sp.Vb 2\& unlink1($fh, $path)\& or die "Error closing and unlinking file";.Ve.SpUsually called from the object destructor when using the \s-1OO\s0 interface..SpNot exported by default..SpThis function is disabled if the global variable \f(CW$KEEP_ALL\fR is true..SpCan call \fIcroak()\fR if there is a security anomaly during the \fIstat()\fRcomparison..IP "\fBcleanup\fR" 4.IX Item "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..SpOn 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)..Sp.Vb 1\& File::Temp::cleanup();.Ve.SpNot exported by default..SH "PACKAGE VARIABLES".IX Header "PACKAGE VARIABLES"These functions control the global state of the package..IP "\fBsafe_level\fR" 4.IX Item "safe_level"Controls the lengths to which the module will go to check the safety of thetemporary file or directory before proceeding.Options are:.RS 4.IP "\s-1STANDARD\s0" 8.IX Item "STANDARD"Do the basic security measures to ensure the directory exists and iswritable, that temporary files are opened only if they do not alreadyexist, and that possible race conditions are avoided. Finally theunlink0 function is used to remove files safely..IP "\s-1MEDIUM\s0" 8.IX Item "MEDIUM"In addition to the \s-1STANDARD\s0 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..SpWill not work on platforms that do not support the \f(CW\*(C`\-k\*(C'\fR testfor sticky bit..IP "\s-1HIGH\s0" 8.IX Item "HIGH"In addition to the \s-1MEDIUM\s0 security checks, also check for thepossibility of ``\fIchown()\fR giveaway'' using the \s-1POSIX\s0\&\fIsysconf()\fR function. If this is a possibility, each directory in thepath is checked in turn for safeness, recursively walking back to theroot directory..SpFor platforms that do not support the \s-1POSIX\s0\&\f(CW\*(C`_PC_CHOWN_RESTRICTED\*(C'\fR symbol (for example, Windows \s-1NT\s0) it isassumed that ``\fIchown()\fR giveaway'' is possible and the recursive testis performed..RE.RS 4.SpThe level can be changed as follows:.Sp.Vb 1\& File::Temp\->safe_level( File::Temp::HIGH );.Ve.SpThe level constants are not exported by the module..SpCurrently, you must be running at least perl v5.6.0 in order torun with \s-1MEDIUM\s0 or \s-1HIGH\s0 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..SpOn systems that do not support the \s-1HIGH\s0 or \s-1MEDIUM\s0 safety levels(for example Win \s-1NT\s0 or \s-1OS/2\s0) 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..SpIf you really need to see whether the change has been acceptedsimply examine the return value of \f(CW\*(C`safe_level\*(C'\fR..Sp.Vb 3\& $newlevel = File::Temp\->safe_level( File::Temp::HIGH );\& die "Could not change to high security"\& if $newlevel != File::Temp::HIGH;.Ve.RE.IP "TopSystemUID" 4.IX Item "TopSystemUID"This is the highest \s-1UID\s0 on the current system that refers to a root\&\s-1UID\s0. This is used to make sure that the temporary directory isowned by a system \s-1UID\s0 (\f(CW\*(C`root\*(C'\fR, \f(CW\*(C`bin\*(C'\fR, \f(CW\*(C`sys\*(C'\fR etc) rather thansimply by root..SpThis is required since on many unix systems \f(CW\*(C`/tmp\*(C'\fR is not ownedby root..SpDefault is to assume that any \s-1UID\s0 less than or equal to 10 is a root\&\s-1UID\s0..Sp.Vb 2\& File::Temp\->top_system_uid(10);\& my $topid = File::Temp\->top_system_uid;.Ve.SpThis value can be adjusted to reduce security checking if required.The value is only relevant when \f(CW\*(C`safe_level\*(C'\fR is set to \s-1MEDIUM\s0 or higher..ie n .IP "\fB\fB$KEEP_ALL\fB\fR" 4.el .IP "\fB\f(CB$KEEP_ALL\fB\fR" 4.IX Item "$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..Sp.Vb 1\& $File::Temp::KEEP_ALL = 1;.Ve.SpDefault is for files to be removed as requested by the caller..SpIn 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..ie n .IP "\fB\fB$DEBUG\fB\fR" 4.el .IP "\fB\f(CB$DEBUG\fB\fR" 4.IX Item "$DEBUG"Controls whether debugging messages should be enabled..Sp.Vb 1\& $File::Temp::DEBUG = 1;.Ve.SpDefault is for debugging mode to be disabled..SH "WARNING".IX Header "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..PPIf you need to pass the handle to something that expects a filenamethen, on a unix system, use \f(CW\*(C`"/dev/fd/" . fileno($fh)\*(C'\fR for arbitraryprograms, or more generally \f(CW\*(C`"+<=&" . fileno($fh)\*(C'\fR for Perlprograms. You will have to clear the close-on-exec bit on that filedescriptor before passing it to another process..PP.Vb 3\& use Fcntl qw/F_SETFD F_GETFD/;\& fcntl($tmpfh, F_SETFD, 0)\& or die "Can\*(Aqt clear close\-on\-exec flag on temp fh: $!\en";.Ve.Sh "Temporary files and \s-1NFS\s0".IX Subsection "Temporary files and NFS"Some problems are associated with using temporary files that resideon \s-1NFS\s0 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 \s-1NFS\s0 will not be as good as fora local disk..Sh "Forking".IX Subsection "Forking"In some cases files created by File::Temp are removed from within an\&\s-1END\s0 block. Since \s-1END\s0 blocks are triggered when a child process exits(unless \f(CW\*(C`POSIX::_exit()\*(C'\fR is used by the child) File::Temp takes careto only remove those temp files created by a particular process \s-1ID\s0. Thismeans that a child will not attempt to remove temp files created by theparent process..PPIf you are forking many processes in parallel that are all creatingtemporary files, you may need to reset the random number seed usingsrand(\s-1EXPR\s0) in each child else all the children will attempt to walkthrough the same set of random file names and may well causethemselves to give up if they exceed the number of retry attempts..Sh "\s-1BINMODE\s0".IX Subsection "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 \f(CW\*(C`binmode()\*(C'\fRfunction to change the mode of the filehandle..PPNote that you can modify the encoding of a file opened by File::Tempalso by using \f(CW\*(C`binmode()\*(C'\fR..SH "HISTORY".IX Header "HISTORY"Originally began life in May 1999 as an \s-1XS\s0 interface to the system\&\fImkstemp()\fR function. In March 2000, the OpenBSD \fImkstemp()\fR 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..SH "SEE ALSO".IX Header "SEE ALSO"\&\*(L"tmpnam\*(R" in \s-1POSIX\s0, \*(L"tmpfile\*(R" in \s-1POSIX\s0, File::Spec, File::Path.PPSee IO::File and File::MkTemp, Apache::TempFile fordifferent implementations of temporary file handling..PPSee File::Tempdir for an alternative object-oriented wrapper forthe \f(CW\*(C`tempdir\*(C'\fR function..SH "AUTHOR".IX Header "AUTHOR"Tim Jenness <tjenness@cpan.org>.PPCopyright (C) 2007 Tim Jenness.Copyright (C) 1999\-2007 Tim Jenness and the \s-1UK\s0 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..PPOriginal Perl implementation loosely based on the OpenBSD C code for\&\fImkstemp()\fR. Thanks to Tom Christiansen for suggesting that this moduleshould be written and providing ideas for code improvements andsecurity enhancements.
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -