⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 temp.pm

📁 1. 记录每个帖子的访问人情况
💻 PM
📖 第 1 页 / 共 4 页
字号:
=back=head1 POSIX FUNCTIONSThis section describes the re-implementation of the tmpnam()and tmpfile() functions described in L<POSIX> using the mkstemp() from this module.Unlike the L<POSIX|POSIX> implementations, the directory usedfor the temporary file is not specified in a system includefile (C<P_tmpdir>) but simply depends on the choice of tmpdir()returned by L<File::Spec|File::Spec>. On some implementations thislocation can be set using the C<TMPDIR> environment variable, whichmay not be secure.If this is a problem, simply use mkstemp() and specify a template.=over 4=item B<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 L<File::Spec/tmpdir> for information on the choice of temporarydirectory for a particular operating system.=cutsub tmpnam {   # Retrieve the temporary directory name   my $tmpdir = File::Spec->tmpdir;   croak "Error temporary directory is not writable"     if $tmpdir eq '';   # Use a ten character template and append to tmpdir   my $template = File::Spec->catfile($tmpdir, TEMPXXX);   if (wantarray() ) {       return mkstemp($template);   } else {       return mktemp($template);   }}=item B<tmpfile>In scalar context, 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.=cutsub tmpfile {  # Simply call tmpnam() in a list context  my ($fh, $file) = tmpnam();  # Make sure file is removed when filehandle is closed  # This will fail on NFS  unlink0($fh, $file)    or return undef;  return $fh;}=back=head1 ADDITIONAL FUNCTIONSThese functions are provided for backwards compatibilitywith common tempfile generation C library functions.They are not exported and must be addressed using the full packagename. =over 4=item B<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 one clock tick only.  Always use the proper form of C<sysopen>with C<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.=cutsub tempnam {  croak 'Usage tempnam($dir, $prefix)' unless scalar(@_) == 2;  my ($dir, $prefix) = @_;  # Add a string to the prefix  $prefix .= 'XXXXXXXX';  # Concatenate the directory to the file  my $template = File::Spec->catfile($dir, $prefix);  return mktemp($template);}=back=head1 UTILITY FUNCTIONSUseful functions for dealing with the filehandle and filename.=over 4=item B<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 C<dev> and C<rdev> fields seem to bedifferent.  Also, it seems that the size of the file returned by stat()does not always agree, with C<stat(FH)> being more accurate thanC<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 C<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.=cutsub unlink0 {  croak 'Usage: unlink0(filehandle, filename)'    unless scalar(@_) == 2;  # Read args  my ($fh, $path) = @_;  warn "Unlinking $path using unlink0\n"    if $DEBUG;  # Stat the filehandle  my @fh = stat $fh;  if ($fh[3] > 1 && $^W) {    carp "unlink0: fstat found too many links; SB=@fh" if $^W;  }  # Stat the path  my @path = stat $path;  unless (@path) {    carp "unlink0: $path is gone already" if $^W;    return;  }  # this is no longer a file, but may be a directory, or worse  unless (-f _) {    confess "panic: $path is no longer a file: SB=@fh";  }  # Do comparison of each member of the array  # On WinNT dev and rdev seem to be different  # depending on whether it is a file or a handle.  # Cannot simply compare all members of the stat return  # Select the ones we can use  my @okstat = (0..$#fh);  # Use all by default  if ($^O eq 'MSWin32') {    @okstat = (1,2,3,4,5,7,8,9,10);  } elsif ($^O eq 'os2') {    @okstat = (0, 2..$#fh);  } elsif ($^O eq 'VMS') { # device and file ID are sufficient    @okstat = (0, 1);  } elsif ($^O eq 'dos') {     @okstat = (0,2..7,11..$#fh);  }  # Now compare each entry explicitly by number  for (@okstat) {    print "Comparing: $_ : $fh[$_] and $path[$_]\n" if $DEBUG;    # Use eq rather than == since rdev, blksize, and blocks (6, 11,    # and 12) will be '' on platforms that do not support them.  This    # is fine since we are only comparing integers.    unless ($fh[$_] eq $path[$_]) {      warn "Did not match $_ element of stat\n" if $DEBUG;      return 0;    }  }  # attempt remove the file (does not work on some platforms)  if (_can_unlink_opened_file()) {    # XXX: do *not* call this on a directory; possible race    #      resulting in recursive removal    croak "unlink0: $path has become a directory!" if -d $path;    unlink($path) or return 0;    # Stat the filehandle    @fh = stat $fh;    print "Link count = $fh[3] \n" if $DEBUG;    # Make sure that the link count is zero    # - Cygwin provides deferred unlinking, however,    #   on Win9x the link count remains 1    # On NFS the link count may still be 1 but we cant know that    # we are on NFS    return ( $fh[3] == 0 or $^O eq 'cygwin' ? 1 : 0);  } else {    _deferred_unlink($fh, $path, 0);    return 1;  }}=back=head1 PACKAGE VARIABLESThese functions control the global state of the package.=over 4=item B<safe_level>Controls the lengths to which the module will go to check the safety of thetemporary file or directory before proceeding.Options are:=over 8=item STANDARDDo 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 L<unlink0|"unlink0">function is used to remove files safely.=item MEDIUMIn 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 C<-k> testfor sticky bit.=item HIGHIn addition to the MEDIUM security checks, also check for thepossibility of ``chown() giveaway'' using the L<POSIX|POSIX>sysconf() function. If this is a possibility, each directory in thepath is checked in turn for safeness, recursively walking back to the root directory.For platforms that do not support the L<POSIX|POSIX>C<_PC_CHOWN_RESTRICTED> symbol (for example, Windows NT) it is assumed that ``chown() giveaway'' is possible and the recursive testis performed.=backThe 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 the safety tests use functions from L<Fcntl|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 C<safe_level>.  $newlevel = File::Temp->safe_level( File::Temp::HIGH );  die "Could not change to high security"       if $newlevel != File::Temp::HIGH;=cut{  # protect from using the variable itself  my $LEVEL = STANDARD;  sub safe_level {    my $self = shift;    if (@_) {       my $level = shift;      if (($level != STANDARD) && ($level != MEDIUM) && ($level != HIGH)) {	carp "safe_level: Specified level ($level) not STANDARD, MEDIUM or HIGH - ignoring\n" if $^W;      } else {	# Dont allow this on perl 5.005 or earlier	if ($] < 5.006 && $level != STANDARD) {	  # Cant do MEDIUM or HIGH checks	  croak "Currently requires perl 5.006 or newer to do the safe checks";	}	# Check that we are allowed to change level	# Silently ignore if we can not.        $LEVEL = $level if _can_do_level($level);      }    }    return $LEVEL;  }}=item TopSystemUIDThis is the highest UID on the current system that refers to a rootUID. This is used to make sure that the temporary directory is owned by a system UID (C<root>, C<bin>, C<sys> etc) rather than simply by root.This is required since on many unix systems C</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 C<safe_level> is set to MEDIUM or higher.=back=cut{  my $TopSystemUID = 10;  sub top_system_uid {    my $self = shift;    if (@_) {      my $newuid = shift;      croak "top_system_uid: UIDs should be numeric"        unless $newuid =~ /^\d+$/s;      $TopSystemUID = $newuid;    }    return $TopSystemUID;  }}=head1 WARNINGFor 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 C<"/dev/fd/" . fileno($fh)> for arbitraryprograms, or more generally C<< "+<=&" . 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";=head2 Temporary files and NFSSome 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.=head1 HISTORYOriginally 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.=head1 SEE ALSOL<POSIX/tmpnam>, L<POSIX/tmpfile>, L<File::Spec>, L<File::Path>See L<IO::File> and L<File::MkTemp> for different implementations of temporary file handling.=head1 AUTHORTim Jenness E<lt>t.jenness@jach.hawaii.eduE<gt>Copyright (C) 1999-2001 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 for mkstemp(). Thanks to Tom Christiansen for suggesting that this moduleshould be written and providing ideas for code improvements andsecurity enhancements.=cut1;

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -