13 # can't say 'opendir my $dh, $dirname'
14 # need to initialise $dh
20 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK);
22 $VERSION = eval $VERSION;
24 @EXPORT = qw(mkpath rmtree);
25 @EXPORT_OK = qw(make_path remove_tree);
28 for (qw(VMS MacOS MSWin32 os2)) {
30 *{"_IS_\U$_"} = $^O eq $_ ? sub () { 1 } : sub () { 0 };
33 # These OSes complain if you want to remove a file that you have no
34 # write permission to:
36 grep { $^O eq $_ } qw(amigaos dos epoc MSWin32 MacOS os2)
37 ) ? sub () { 1 } : sub () { 0 };
39 # Unix-like systems need to stat each directory in order to detect
40 # race condition. MS-Windows is immune to this particular attack.
41 *_NEED_STAT_CHECK = !(_IS_MSWIN32()) ? sub () { 1 } : sub () { 0 };
59 if ( $arg->{error} ) {
60 $object = '' unless defined $object;
61 $message .= ": $!" if $!;
62 push @{ ${ $arg->{error} } }, { $object => $message };
65 _carp( defined($object) ? "$message for $object: $!" : "$message: $!" );
72 # If client code blessed an array ref to HASH, this will not work
73 # properly. We could have done $arg->isa() wrapped in eval, but
74 # that would be expensive. This implementation should suffice.
75 # We could have also used Scalar::Util:blessed, but we choose not
76 # to add this dependency
77 return ( ref $arg eq 'HASH' );
81 push @_, {} unless @_ and __is_arg( $_[-1] );
86 my $old_style = !( @_ and __is_arg( $_[-1] ) );
92 my ( $verbose, $mode );
93 ( $paths, $verbose, $mode ) = @_;
94 $paths = [$paths] unless UNIVERSAL::isa( $paths, 'ARRAY' );
95 $data->{verbose} = $verbose;
96 $data->{mode} = defined $mode ? $mode : oct '777';
99 my %args_permitted = map { $_ => 1 } ( qw|
110 my %not_on_win32_args = map { $_ => 1 } ( qw|
117 my @win32_implausible_args = ();
119 for my $k (sort keys %{$arg}) {
120 if (! $args_permitted{$k}) {
123 elsif ($not_on_win32_args{$k} and _IS_MSWIN32) {
124 push @win32_implausible_args, $k;
127 $data->{$k} = $arg->{$k};
130 _carp("Unrecognized option(s) passed to mkpath() or make_path(): @bad_args")
132 _carp("Option(s) implausible on Win32 passed to mkpath() or make_path(): @win32_implausible_args")
133 if @win32_implausible_args;
134 $data->{mode} = delete $data->{mask} if exists $data->{mask};
135 $data->{mode} = oct '777' unless exists $data->{mode};
136 ${ $data->{error} } = [] if exists $data->{error};
137 unless (@win32_implausible_args) {
138 $data->{owner} = delete $data->{user} if exists $data->{user};
139 $data->{owner} = delete $data->{uid} if exists $data->{uid};
140 if ( exists $data->{owner} and $data->{owner} =~ /\D/ ) {
141 my $uid = ( getpwnam $data->{owner} )[2];
142 if ( defined $uid ) {
143 $data->{owner} = $uid;
147 "unable to map $data->{owner} to a uid, ownership not changed"
149 delete $data->{owner};
152 if ( exists $data->{group} and $data->{group} =~ /\D/ ) {
153 my $gid = ( getgrnam $data->{group} )[2];
154 if ( defined $gid ) {
155 $data->{group} = $gid;
159 "unable to map $data->{group} to a gid, group ownership not changed"
161 delete $data->{group};
164 if ( exists $data->{owner} and not exists $data->{group} ) {
165 $data->{group} = -1; # chown will leave group unchanged
167 if ( exists $data->{group} and not exists $data->{owner} ) {
168 $data->{owner} = -1; # chown will leave owner unchanged
173 return _mkpath( $data, $paths );
181 foreach my $path ( @{$paths} ) {
182 next unless defined($path) and length($path);
183 $path .= '/' if _IS_OS2 and $path =~ /^\w:\z/s; # feature of CRT
185 # Logic wants Unix paths, so go with the flow.
187 next if $path eq '/';
188 $path = VMS::Filespec::unixify($path);
191 my $parent = File::Basename::dirname($path);
192 # Coverage note: It's not clear how we would test the condition:
193 # '-d $parent or $path eq $parent'
194 unless ( -d $parent or $path eq $parent ) {
195 push( @created, _mkpath( $data, [$parent] ) );
197 print "mkdir $path\n" if $data->{verbose};
198 if ( mkdir( $path, $data->{mode} ) ) {
199 push( @created, $path );
200 if ( exists $data->{owner} ) {
202 # NB: $data->{group} guaranteed to be set during initialisation
203 if ( !chown $data->{owner}, $data->{group}, $path ) {
205 "Cannot change ownership of $path to $data->{owner}:$data->{group}"
209 if ( exists $data->{chmod} ) {
210 # Coverage note: It's not clear how we would trigger the next
211 # 'if' block. Failure of 'chmod' might first result in a
212 # system error: "Permission denied".
213 if ( !chmod $data->{chmod}, $path ) {
215 "Cannot change permissions of $path to $data->{chmod}" );
222 # From 'perldoc perlvar': $EXTENDED_OS_ERROR ($^E) is documented
224 # Error information specific to the current operating system. At the
225 # moment, this differs from "$!" under only VMS, OS/2, and Win32
226 # (and for MacPerl). On all other platforms, $^E is always just the
229 my ( $e, $e1 ) = ( $save_bang, $^E );
230 $e .= "; $e1" if $e ne $e1;
232 # allow for another process to have created it meanwhile
235 if ( $data->{error} ) {
236 push @{ ${ $data->{error} } }, { $path => $e };
239 _croak("mkdir $path: $e");
248 push @_, {} unless @_ and __is_arg( $_[-1] );
253 my ( $dir, $test ) = @_;
255 my ( $dv, $dd ) = File::Spec->splitpath( $dir, 1 );
256 my ( $tv, $td ) = File::Spec->splitpath( $test, 1 );
259 return 0 if $dv ne $tv;
261 my @d = File::Spec->splitdir($dd);
262 my @t = File::Spec->splitdir($td);
264 # @t can't be a subdir if it's shorter than @d
267 return join( '/', @d ) eq join( '/', splice @t, 0, +@d );
271 my $old_style = !( @_ and __is_arg( $_[-1] ) );
273 my ($arg, $data, $paths);
276 my ( $verbose, $safe );
277 ( $paths, $verbose, $safe ) = @_;
278 $data->{verbose} = $verbose;
279 $data->{safe} = defined $safe ? $safe : 0;
281 if ( defined($paths) and length($paths) ) {
282 $paths = [$paths] unless UNIVERSAL::isa( $paths, 'ARRAY' );
285 _carp("No root path(s) specified\n");
290 my %args_permitted = map { $_ => 1 } ( qw|
299 for my $k (sort keys %{$arg}) {
300 if (! $args_permitted{$k}) {
304 $data->{$k} = $arg->{$k};
307 _carp("Unrecognized option(s) passed to remove_tree(): @bad_args")
309 ${ $data->{error} } = [] if exists $data->{error};
310 ${ $data->{result} } = [] if exists $data->{result};
312 # Wouldn't it make sense to do some validation on @_ before assigning
314 # In the $old_style case we guarantee that each path is both defined
315 # and non-empty. We don't check that here, which means we have to
316 # check it later in the first condition in this line:
317 # if ( $ortho_root_length && _is_subdir( $ortho_root, $ortho_cwd ) ) {
318 # Granted, that would be a change in behavior for the two
319 # non-old-style interfaces.
324 $data->{prefix} = '';
328 $data->{cwd} = getcwd() or do {
329 _error( $data, "cannot fetch initial working directory" );
332 for ( $data->{cwd} ) { /\A(.*)\Z/s; $_ = $1 } # untaint
334 for my $p (@$paths) {
336 # need to fixup case and map \ to / on Windows
337 my $ortho_root = _IS_MSWIN32 ? _slash_lc($p) : $p;
339 _IS_MSWIN32 ? _slash_lc( $data->{cwd} ) : $data->{cwd};
340 my $ortho_root_length = length($ortho_root);
341 $ortho_root_length-- if _IS_VMS; # don't compare '.' with ']'
342 if ( $ortho_root_length && _is_subdir( $ortho_root, $ortho_cwd ) ) {
344 _error( $data, "cannot remove path when cwd is $data->{cwd}", $p );
349 $p = ":$p" unless $p =~ /:/;
350 $p .= ":" unless $p =~ /:\z/;
352 elsif ( _IS_MSWIN32 ) {
358 push @clean_path, $p;
361 @{$data}{qw(device inode)} = ( lstat $data->{cwd} )[ 0, 1 ] or do {
362 _error( $data, "cannot stat initial working directory", $data->{cwd} );
366 return _rmtree( $data, \@clean_path );
374 my $curdir = File::Spec->curdir();
375 my $updir = File::Spec->updir();
377 my ( @files, $root );
379 foreach my $root (@$paths) {
381 # since we chdir into each directory, it may not be obvious
382 # to figure out where we are if we generate a message about
383 # a file name. We therefore construct a semi-canonical
384 # filename, anchored from the directory being unlinked (as
385 # opposed to being truly canonical, anchored from the root (/).
389 ? File::Spec->catfile( $data->{prefix}, $root )
392 my ( $ldev, $lino, $perm ) = ( lstat $root )[ 0, 1, 2 ]
396 $root = VMS::Filespec::vmspath( VMS::Filespec::pathify($root) )
399 if ( !chdir($root) ) {
401 # see if we can escalate privileges to get in
402 # (e.g. funny protection mask such as -w- instead of rwx)
403 # This uses fchmod to avoid traversing outside of the proper
404 # location (CVE-2017-6512)
406 if (open($root_fh, '<', $root)) {
407 my ($fh_dev, $fh_inode) = (stat $root_fh )[0,1];
409 my $nperm = $perm | oct '700';
417 or $fh_inode ne $lino
418 or eval { chmod( $nperm, $root_fh ) }
423 "cannot make child directory read-write-exec", $canon );
428 if ( !chdir($root) ) {
429 _error( $data, "cannot chdir to child", $canon );
434 my ( $cur_dev, $cur_inode, $perm ) = ( stat $curdir )[ 0, 1, 2 ]
436 _error( $data, "cannot stat current working directory", $canon );
440 if (_NEED_STAT_CHECK) {
441 ( $ldev eq $cur_dev and $lino eq $cur_inode )
443 "directory $canon changed before chdir, expected dev=$ldev ino=$lino, actual dev=$cur_dev ino=$cur_inode, aborting."
447 $perm &= oct '7777'; # don't forget setuid, setgid, sticky bits
448 my $nperm = $perm | oct '700';
450 # notabene: 0700 is for making readable in the first place,
451 # it's also intended to change it to writable in case we have
452 # to recurse in which case we are better than rm -rf for
453 # subtrees with strange permissions
459 or chmod( $nperm, $curdir )
463 _error( $data, "cannot make directory read+writeable", $canon );
468 $d = gensym() if $] < 5.006;
469 if ( !opendir $d, $curdir ) {
470 _error( $data, "cannot opendir", $canon );
474 if ( !defined ${^TAINT} or ${^TAINT} ) {
475 # Blindly untaint dir names if taint mode is active
476 @files = map { /\A(.*)\z/s; $1 } readdir $d;
486 # Deleting large numbers of files from VMS Files-11
487 # filesystems is faster if done in reverse ASCIIbetical order.
488 # include '.' to '.;' from blead patch #31775
489 @files = map { $_ eq '.' ? '.;' : $_ } reverse @files;
492 @files = grep { $_ ne $updir and $_ ne $curdir } @files;
496 # remove the contained files before the directory itself
498 @{$narg}{qw(device inode cwd prefix depth)} =
499 ( $cur_dev, $cur_inode, $updir, $canon, $data->{depth} + 1 );
500 $count += _rmtree( $narg, \@files );
503 # restore directory permissions of required now (in case the rmdir
504 # below fails), while we are still in the directory and may do so
505 # without a race via '.'
506 if ( $nperm != $perm and not chmod( $perm, $curdir ) ) {
507 _error( $data, "cannot reset chmod", $canon );
510 # don't leave the client code in an unexpected directory
511 chdir( $data->{cwd} )
513 _croak("cannot chdir to $data->{cwd} from $canon: $!, aborting.");
515 # ensure that a chdir upwards didn't take us somewhere other
516 # than we expected (see CVE-2002-0435)
517 ( $cur_dev, $cur_inode ) = ( stat $curdir )[ 0, 1 ]
519 "cannot stat prior working directory $data->{cwd}: $!, aborting."
522 if (_NEED_STAT_CHECK) {
523 ( $data->{device} eq $cur_dev and $data->{inode} eq $cur_inode )
524 or _croak( "previous directory $data->{cwd} "
525 . "changed before entering $canon, "
526 . "expected dev=$ldev ino=$lino, "
527 . "actual dev=$cur_dev ino=$cur_inode, aborting."
531 if ( $data->{depth} or !$data->{keep_root} ) {
534 ? !&VMS::Filespec::candelete($root)
537 print "skipped $root\n" if $data->{verbose};
540 if ( _FORCE_WRITABLE and !chmod $perm | oct '700', $root ) {
541 _error( $data, "cannot make directory writeable", $canon );
543 print "rmdir $root\n" if $data->{verbose};
545 push @{ ${ $data->{result} } }, $root if $data->{result};
549 _error( $data, "cannot remove directory", $canon );
553 ( _IS_VMS ? VMS::Filespec::fileify($root) : $root )
559 sprintf( "cannot restore permissions to 0%o",
569 $root = VMS::Filespec::vmsify("./$root")
571 && !File::Spec->file_name_is_absolute($root)
572 && ( $root !~ m/(?<!\^)[\]>]+/ ); # not already in VMS syntax
578 ? !&VMS::Filespec::candelete($root)
579 : !( -l $root || -w $root )
583 print "skipped $root\n" if $data->{verbose};
587 my $nperm = $perm & oct '7777' | oct '600';
590 and not chmod $nperm, $root )
592 _error( $data, "cannot make file writeable", $canon );
594 print "unlink $canon\n" if $data->{verbose};
596 # delete all versions under VMS
598 if ( unlink $root ) {
599 push @{ ${ $data->{result} } }, $root if $data->{result};
602 _error( $data, "cannot unlink file", $canon );
603 _FORCE_WRITABLE and chmod( $perm, $root )
605 sprintf( "cannot restore permissions to 0%o", $perm ),
610 last unless _IS_VMS && lstat $root;
619 # fix up slashes and case on MSWin32 so that we can determine that
620 # c:\path\to\dir is underneath C:/Path/To
632 File::Path - Create or remove directory trees
636 2.16 - released August 31 2018.
640 use File::Path qw(make_path remove_tree);
642 @created = make_path('foo/bar/baz', '/zug/zwang');
643 @created = make_path('foo/bar/baz', '/zug/zwang', {
647 make_path('foo/bar/baz', '/zug/zwang', {
651 $removed_count = remove_tree('foo/bar/baz', '/zug/zwang', {
653 error => \my $err_list,
657 # legacy (interface promoted before v2.00)
658 @created = mkpath('/foo/bar/baz');
659 @created = mkpath('/foo/bar/baz', 1, 0711);
660 @created = mkpath(['/foo/bar/baz', 'blurfl/quux'], 1, 0711);
661 $removed_count = rmtree('foo/bar/baz', 1, 1);
662 $removed_count = rmtree(['foo/bar/baz', 'blurfl/quux'], 1, 1);
664 # legacy (interface promoted before v2.06)
665 @created = mkpath('foo/bar/baz', '/zug/zwang', { verbose => 1, mode => 0711 });
666 $removed_count = rmtree('foo/bar/baz', '/zug/zwang', { verbose => 1, mode => 0711 });
670 This module provides a convenient way to create directories of
671 arbitrary depth and to delete an entire directory subtree from the
674 The following functions are provided:
678 =item make_path( $dir1, $dir2, .... )
680 =item make_path( $dir1, $dir2, ...., \%opts )
682 The C<make_path> function creates the given directories if they don't
683 exist before, much like the Unix command C<mkdir -p>.
685 The function accepts a list of directories to be created. Its
686 behaviour may be tuned by an optional hashref appearing as the last
687 parameter on the call.
689 The function returns the list of directories actually created during
690 the call; in scalar context the number of directories created.
692 The following keys are recognised in the option hash:
698 The numeric permissions mode to apply to each created directory
699 (defaults to C<0777>), to be modified by the current C<umask>. If the
700 directory already exists (and thus does not need to be created),
701 the permissions will not be modified.
703 C<mask> is recognised as an alias for this parameter.
707 Takes a numeric mode to apply to each created directory (not
708 modified by the current C<umask>). If the directory already exists
709 (and thus does not need to be created), the permissions will
712 =item verbose => $bool
714 If present, will cause C<make_path> to print the name of each directory
715 as it is created. By default nothing is printed.
719 If present, it should be a reference to a scalar.
720 This scalar will be made to reference an array, which will
721 be used to store any errors that are encountered. See the L</"ERROR
722 HANDLING"> section for more information.
724 If this parameter is not used, certain error conditions may raise
725 a fatal error that will cause the program to halt, unless trapped
728 =item owner => $owner
734 If present, will cause any created directory to be owned by C<$owner>.
735 If the value is numeric, it will be interpreted as a uid; otherwise a
736 username is assumed. An error will be issued if the username cannot be
737 mapped to a uid, the uid does not exist or the process lacks the
738 privileges to change ownership.
740 Ownership of directories that already exist will not be changed.
742 C<user> and C<uid> are aliases of C<owner>.
744 =item group => $group
746 If present, will cause any created directory to be owned by the group
747 C<$group>. If the value is numeric, it will be interpreted as a gid;
748 otherwise a group name is assumed. An error will be issued if the
749 group name cannot be mapped to a gid, the gid does not exist or the
750 process lacks the privileges to change group ownership.
752 Group ownership of directories that already exist will not be changed.
754 make_path '/var/tmp/webcache', {owner=>'nobody', group=>'nogroup'};
760 =item mkpath( $dir, $verbose, $mode )
762 =item mkpath( [$dir1, $dir2,...], $verbose, $mode )
764 =item mkpath( $dir1, $dir2,..., \%opt )
766 The C<mkpath()> function provide the legacy interface of
767 C<make_path()> with a different interpretation of the arguments
768 passed. The behaviour and return value of the function is otherwise
769 identical to C<make_path()>.
771 =item remove_tree( $dir1, $dir2, .... )
773 =item remove_tree( $dir1, $dir2, ...., \%opts )
775 The C<remove_tree> function deletes the given directories and any
776 files and subdirectories they might contain, much like the Unix
777 command C<rm -rf> or the Windows commands C<rmdir /s> and C<rd /s>.
779 The function accepts a list of directories to be removed. (In point of fact,
780 it will also accept filesystem entries which are not directories, such as
781 regular files and symlinks. But, as its name suggests, its intent is to
782 remove trees rather than individual files.)
784 C<remove_tree()>'s behaviour may be tuned by an optional hashref
785 appearing as the last parameter on the call. If an empty string is
786 passed to C<remove_tree>, an error will occur.
788 B<NOTE:> For security reasons, we strongly advise use of the
789 hashref-as-final-argument syntax -- specifically, with a setting of the C<safe>
790 element to a true value.
792 remove_tree( $dir1, $dir2, ....,
795 ... # other key-value pairs
799 The function returns the number of files successfully deleted.
801 The following keys are recognised in the option hash:
805 =item verbose => $bool
807 If present, will cause C<remove_tree> to print the name of each file as
808 it is unlinked. By default nothing is printed.
812 When set to a true value, will cause C<remove_tree> to skip the files
813 for which the process lacks the required privileges needed to delete
814 files, such as delete privileges on VMS. In other words, the code
815 will make no attempt to alter file permissions. Thus, if the process
816 is interrupted, no filesystem object will be left in a more
819 =item keep_root => $bool
821 When set to a true value, will cause all files and subdirectories
822 to be removed, except the initially specified directories. This comes
823 in handy when cleaning out an application's scratch directory.
825 remove_tree( '/tmp', {keep_root => 1} );
827 =item result => \$res
829 If present, it should be a reference to a scalar.
830 This scalar will be made to reference an array, which will
831 be used to store all files and directories unlinked
832 during the call. If nothing is unlinked, the array will be empty.
834 remove_tree( '/tmp', {result => \my $list} );
835 print "unlinked $_\n" for @$list;
837 This is a useful alternative to the C<verbose> key.
841 If present, it should be a reference to a scalar.
842 This scalar will be made to reference an array, which will
843 be used to store any errors that are encountered. See the L</"ERROR
844 HANDLING"> section for more information.
846 Removing things is a much more dangerous proposition than
847 creating things. As such, there are certain conditions that
848 C<remove_tree> may encounter that are so dangerous that the only
849 sane action left is to kill the program.
851 Use C<error> to trap all that is reasonable (problems with
852 permissions and the like), and let it die if things get out
853 of hand. This is the safest course of action.
859 =item rmtree( $dir, $verbose, $safe )
861 =item rmtree( [$dir1, $dir2,...], $verbose, $safe )
863 =item rmtree( $dir1, $dir2,..., \%opt )
865 The C<rmtree()> function provide the legacy interface of
866 C<remove_tree()> with a different interpretation of the arguments
867 passed. The behaviour and return value of the function is otherwise
868 identical to C<remove_tree()>.
870 B<NOTE:> For security reasons, we strongly advise use of the
871 hashref-as-final-argument syntax, specifically with a setting of the C<safe>
872 element to a true value.
874 rmtree( $dir1, $dir2, ....,
877 ... # other key-value pairs
883 =head2 ERROR HANDLING
889 The following error handling mechanism is consistent throughout all
890 code paths EXCEPT in cases where the ROOT node is nonexistent. In
891 version 2.11 the maintainers attempted to rectify this inconsistency
892 but too many downstream modules encountered problems. In such case,
893 if you require root node evaluation or error checking prior to calling
894 C<make_path> or C<remove_tree>, you should take additional precautions.
898 If C<make_path> or C<remove_tree> encounters an error, a diagnostic
899 message will be printed to C<STDERR> via C<carp> (for non-fatal
900 errors) or via C<croak> (for fatal errors).
902 If this behaviour is not desirable, the C<error> attribute may be
903 used to hold a reference to a variable, which will be used to store
904 the diagnostics. The variable is made a reference to an array of hash
905 references. Each hash contain a single key/value pair where the key
906 is the name of the file, and the value is the error message (including
907 the contents of C<$!> when appropriate). If a general error is
908 encountered the diagnostic key will be empty.
910 An example usage looks like:
912 remove_tree( 'foo/bar', 'bar/rat', {error => \my $err} );
914 for my $diag (@$err) {
915 my ($file, $message) = %$diag;
917 print "general error: $message\n";
920 print "problem unlinking $file: $message\n";
925 print "No error encountered\n";
928 Note that if no errors are encountered, C<$err> will reference an
929 empty array. This means that C<$err> will always end up TRUE; so you
930 need to test C<@$err> to determine if errors occurred.
934 C<File::Path> blindly exports C<mkpath> and C<rmtree> into the
935 current namespace. These days, this is considered bad style, but
936 to change it now would break too much code. Nonetheless, you are
937 invited to specify what it is you are expecting to use:
939 use File::Path 'rmtree';
941 The routines C<make_path> and C<remove_tree> are B<not> exported
942 by default. You must specify which ones you want to use.
944 use File::Path 'remove_tree';
946 Note that a side-effect of the above is that C<mkpath> and C<rmtree>
947 are no longer exported at all. This is due to the way the C<Exporter>
948 module works. If you are migrating a codebase to use the new
949 interface, you will have to list everything explicitly. But that's
950 just good practice anyway.
952 use File::Path qw(remove_tree rmtree);
956 The API was changed in the 2.0 branch. For a time, C<mkpath> and
957 C<rmtree> tried, unsuccessfully, to deal with the two different
958 calling mechanisms. This approach was considered a failure.
960 The new semantics are now only available with C<make_path> and
961 C<remove_tree>. The old semantics are only available through
962 C<mkpath> and C<rmtree>. Users are strongly encouraged to upgrade
963 to at least 2.08 in order to avoid surprises.
965 =head3 SECURITY CONSIDERATIONS
967 There were race conditions in the 1.x implementations of File::Path's
968 C<rmtree> function (although sometimes patched depending on the OS
969 distribution or platform). The 2.0 version contains code to avoid the
970 problem mentioned in CVE-2002-0435.
972 See the following pages for more information:
974 http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=286905
975 http://www.nntp.perl.org/group/perl.perl5.porters/2005/01/msg97623.html
976 http://www.debian.org/security/2005/dsa-696
978 Additionally, unless the C<safe> parameter is set (or the
979 third parameter in the traditional interface is TRUE), should a
980 C<remove_tree> be interrupted, files that were originally in read-only
981 mode may now have their permissions set to a read-write (or "delete
984 The following CVE reports were previously filed against File-Path and are
985 believed to have been addressed:
989 =item * L<http://cve.circl.lu/cve/CVE-2004-0452>
991 =item * L<http://cve.circl.lu/cve/CVE-2005-0448>
995 In February 2017 the cPanel Security Team reported an additional vulnerability
996 in File-Path. The C<chmod()> logic to make directories traversable can be
997 abused to set the mode on an attacker-chosen file to an attacker-chosen value.
998 This is due to the time-of-check-to-time-of-use (TOCTTOU) race condition
999 (L<https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use>) between the
1000 C<stat()> that decides the inode is a directory and the C<chmod()> that tries
1001 to make it user-rwx. CPAN versions 2.13 and later incorporate a patch
1002 provided by John Lightsey to address this problem. This vulnerability has
1003 been reported as CVE-2017-6512.
1007 FATAL errors will cause the program to halt (C<croak>), since the
1008 problem is so severe that it would be dangerous to continue. (This
1009 can always be trapped with C<eval>, but it's not a good idea. Under
1010 the circumstances, dying is the best thing to do).
1012 SEVERE errors may be trapped using the modern interface. If the
1013 they are not trapped, or if the old interface is used, such an error
1014 will cause the program will halt.
1016 All other errors may be trapped using the modern interface, otherwise
1017 they will be C<carp>ed about. Program execution will not be halted.
1021 =item mkdir [path]: [errmsg] (SEVERE)
1023 C<make_path> was unable to create the path. Probably some sort of
1024 permissions error at the point of departure or insufficient resources
1025 (such as free inodes on Unix).
1027 =item No root path(s) specified
1029 C<make_path> was not given any paths to create. This message is only
1030 emitted if the routine is called with the traditional interface.
1031 The modern interface will remain silent if given nothing to do.
1033 =item No such file or directory
1035 On Windows, if C<make_path> gives you this warning, it may mean that
1036 you have exceeded your filesystem's maximum path length.
1038 =item cannot fetch initial working directory: [errmsg]
1040 C<remove_tree> attempted to determine the initial directory by calling
1041 C<Cwd::getcwd>, but the call failed for some reason. No attempt
1042 will be made to delete anything.
1044 =item cannot stat initial working directory: [errmsg]
1046 C<remove_tree> attempted to stat the initial directory (after having
1047 successfully obtained its name via C<getcwd>), however, the call
1048 failed for some reason. No attempt will be made to delete anything.
1050 =item cannot chdir to [dir]: [errmsg]
1052 C<remove_tree> attempted to set the working directory in order to
1053 begin deleting the objects therein, but was unsuccessful. This is
1054 usually a permissions issue. The routine will continue to delete
1055 other things, but this directory will be left intact.
1057 =item directory [dir] changed before chdir, expected dev=[n] ino=[n], actual dev=[n] ino=[n], aborting. (FATAL)
1059 C<remove_tree> recorded the device and inode of a directory, and then
1060 moved into it. It then performed a C<stat> on the current directory
1061 and detected that the device and inode were no longer the same. As
1062 this is at the heart of the race condition problem, the program
1063 will die at this point.
1065 =item cannot make directory [dir] read+writeable: [errmsg]
1067 C<remove_tree> attempted to change the permissions on the current directory
1068 to ensure that subsequent unlinkings would not run into problems,
1069 but was unable to do so. The permissions remain as they were, and
1070 the program will carry on, doing the best it can.
1072 =item cannot read [dir]: [errmsg]
1074 C<remove_tree> tried to read the contents of the directory in order
1075 to acquire the names of the directory entries to be unlinked, but
1076 was unsuccessful. This is usually a permissions issue. The
1077 program will continue, but the files in this directory will remain
1080 =item cannot reset chmod [dir]: [errmsg]
1082 C<remove_tree>, after having deleted everything in a directory, attempted
1083 to restore its permissions to the original state but failed. The
1084 directory may wind up being left behind.
1086 =item cannot remove [dir] when cwd is [dir]
1088 The current working directory of the program is F</some/path/to/here>
1089 and you are attempting to remove an ancestor, such as F</some/path>.
1090 The directory tree is left untouched.
1092 The solution is to C<chdir> out of the child directory to a place
1093 outside the directory tree to be removed.
1095 =item cannot chdir to [parent-dir] from [child-dir]: [errmsg], aborting. (FATAL)
1097 C<remove_tree>, after having deleted everything and restored the permissions
1098 of a directory, was unable to chdir back to the parent. The program
1099 halts to avoid a race condition from occurring.
1101 =item cannot stat prior working directory [dir]: [errmsg], aborting. (FATAL)
1103 C<remove_tree> was unable to stat the parent directory after having returned
1104 from the child. Since there is no way of knowing if we returned to
1105 where we think we should be (by comparing device and inode) the only
1106 way out is to C<croak>.
1108 =item previous directory [parent-dir] changed before entering [child-dir], expected dev=[n] ino=[n], actual dev=[n] ino=[n], aborting. (FATAL)
1110 When C<remove_tree> returned from deleting files in a child directory, a
1111 check revealed that the parent directory it returned to wasn't the one
1112 it started out from. This is considered a sign of malicious activity.
1114 =item cannot make directory [dir] writeable: [errmsg]
1116 Just before removing a directory (after having successfully removed
1117 everything it contained), C<remove_tree> attempted to set the permissions
1118 on the directory to ensure it could be removed and failed. Program
1119 execution continues, but the directory may possibly not be deleted.
1121 =item cannot remove directory [dir]: [errmsg]
1123 C<remove_tree> attempted to remove a directory, but failed. This may be because
1124 some objects that were unable to be removed remain in the directory, or
1125 it could be a permissions issue. The directory will be left behind.
1127 =item cannot restore permissions of [dir] to [0nnn]: [errmsg]
1129 After having failed to remove a directory, C<remove_tree> was unable to
1130 restore its permissions from a permissive state back to a possibly
1131 more restrictive setting. (Permissions given in octal).
1133 =item cannot make file [file] writeable: [errmsg]
1135 C<remove_tree> attempted to force the permissions of a file to ensure it
1136 could be deleted, but failed to do so. It will, however, still attempt
1139 =item cannot unlink file [file]: [errmsg]
1141 C<remove_tree> failed to remove a file. Probably a permissions issue.
1143 =item cannot restore permissions of [file] to [0nnn]: [errmsg]
1145 After having failed to remove a file, C<remove_tree> was also unable
1146 to restore the permissions on the file to a possibly less permissive
1147 setting. (Permissions given in octal).
1149 =item unable to map [owner] to a uid, ownership not changed");
1151 C<make_path> was instructed to give the ownership of created
1152 directories to the symbolic name [owner], but C<getpwnam> did
1153 not return the corresponding numeric uid. The directory will
1154 be created, but ownership will not be changed.
1156 =item unable to map [group] to a gid, group ownership not changed
1158 C<make_path> was instructed to give the group ownership of created
1159 directories to the symbolic name [group], but C<getgrnam> did
1160 not return the corresponding numeric gid. The directory will
1161 be created, but group ownership will not be changed.
1173 Allows files and directories to be moved to the Trashcan/Recycle
1174 Bin (where they may later be restored if necessary) if the operating
1175 system supports such functionality. This feature may one day be
1176 made available directly in C<File::Path>.
1182 When removing directory trees, if you want to examine each file to
1183 decide whether to delete it (and possibly leaving large swathes
1184 alone), F<File::Find::Rule> offers a convenient and flexible approach
1185 to examining directory trees.
1189 =head1 BUGS AND LIMITATIONS
1191 The following describes F<File::Path> limitations and how to report bugs.
1193 =head2 MULTITHREADED APPLICATIONS
1195 F<File::Path> C<rmtree> and C<remove_tree> will not work with
1196 multithreaded applications due to its use of C<chdir>. At this time,
1197 no warning or error is generated in this situation. You will
1198 certainly encounter unexpected results.
1200 The implementation that surfaces this limitation will not be changed. See the
1201 F<File::Path::Tiny> module for functionality similar to F<File::Path> but which does
1204 =head2 NFS Mount Points
1206 F<File::Path> is not responsible for triggering the automounts, mirror mounts,
1207 and the contents of network mounted filesystems. If your NFS implementation
1208 requires an action to be performed on the filesystem in order for
1209 F<File::Path> to perform operations, it is strongly suggested you assure
1210 filesystem availability by reading the root of the mounted filesystem.
1212 =head2 REPORTING BUGS
1214 Please report all bugs on the RT queue, either via the web interface:
1216 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=File-Path>
1220 bug-File-Path@rt.cpan.org
1222 In either case, please B<attach> patches to the bug report rather than
1223 including them inline in the web post or the body of the email.
1225 You can also send pull requests to the Github repository:
1227 L<https://github.com/rpcme/File-Path>
1229 =head1 ACKNOWLEDGEMENTS
1231 Paul Szabo identified the race condition originally, and Brendan
1232 O'Dea wrote an implementation for Debian that addressed the problem.
1233 That code was used as a basis for the current code. Their efforts
1234 are greatly appreciated.
1236 Gisle Aas made a number of improvements to the documentation for
1237 2.07 and his advice and assistance is also greatly appreciated.
1241 Prior authors and maintainers: Tim Bunce, Charles Bailey, and
1242 David Landgren <F<david@landgren.net>>.
1244 Current maintainers are Richard Elberger <F<riche@cpan.org>> and
1245 James (Jim) Keenan <F<jkeenan@cpan.org>>.
1249 Contributors to File::Path, in alphabetical order by first name.
1253 =item <F<bulkdd@cpan.org>>
1255 =item Charlie Gonzalez <F<itcharlie@cpan.org>>
1257 =item Craig A. Berry <F<craigberry@mac.com>>
1259 =item James E Keenan <F<jkeenan@cpan.org>>
1261 =item John Lightsey <F<john@perlsec.org>>
1263 =item Nigel Horne <F<njh@bandsman.co.uk>>
1265 =item Richard Elberger <F<riche@cpan.org>>
1267 =item Ryan Yee <F<ryee@cpan.org>>
1269 =item Skye Shaw <F<shaw@cpan.org>>
1271 =item Tom Lutz <F<tommylutz@gmail.com>>
1273 =item Will Sheppard <F<willsheppard@github>>
1279 This module is copyright (C) Charles Bailey, Tim Bunce, David Landgren,
1280 James Keenan and Richard Elberger 1995-2018. All rights reserved.
1284 This library is free software; you can redistribute it and/or modify
1285 it under the same terms as Perl itself.