xref: /openbsd-src/gnu/usr.bin/perl/cpan/File-Path/lib/File/Path.pm (revision c0dd97bfcad3dab6c31ec12b9de1274fd2d2f993)
1package File::Path;
2
3use 5.005_04;
4use strict;
5
6use Cwd 'getcwd';
7use File::Basename ();
8use File::Spec     ();
9
10BEGIN {
11    if ( $] < 5.006 ) {
12
13        # can't say 'opendir my $dh, $dirname'
14        # need to initialise $dh
15        eval 'use Symbol';
16    }
17}
18
19use Exporter ();
20use vars qw($VERSION @ISA @EXPORT @EXPORT_OK);
21$VERSION   = '2.12_01';
22$VERSION   = eval $VERSION;
23@ISA       = qw(Exporter);
24@EXPORT    = qw(mkpath rmtree);
25@EXPORT_OK = qw(make_path remove_tree);
26
27BEGIN {
28  for (qw(VMS MacOS MSWin32 os2)) {
29    no strict 'refs';
30    *{"_IS_\U$_"} = $^O eq $_ ? sub () { 1 } : sub () { 0 };
31  }
32
33  # These OSes complain if you want to remove a file that you have no
34  # write permission to:
35  *_FORCE_WRITABLE = (
36    grep { $^O eq $_ } qw(amigaos dos epoc MSWin32 MacOS os2)
37  ) ? sub () { 1 } : sub () { 0 };
38
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 };
42}
43
44sub _carp {
45    require Carp;
46    goto &Carp::carp;
47}
48
49sub _croak {
50    require Carp;
51    goto &Carp::croak;
52}
53
54sub _error {
55    my $arg     = shift;
56    my $message = shift;
57    my $object  = shift;
58
59    if ( $arg->{error} ) {
60        $object = '' unless defined $object;
61        $message .= ": $!" if $!;
62        push @{ ${ $arg->{error} } }, { $object => $message };
63    }
64    else {
65        _carp( defined($object) ? "$message for $object: $!" : "$message: $!" );
66    }
67}
68
69sub __is_arg {
70    my ($arg) = @_;
71
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' );
78}
79
80sub make_path {
81    push @_, {} unless @_ and __is_arg( $_[-1] );
82    goto &mkpath;
83}
84
85sub mkpath {
86    my $old_style = !( @_ and __is_arg( $_[-1] ) );
87
88    my $arg;
89    my $paths;
90
91    if ($old_style) {
92        my ( $verbose, $mode );
93        ( $paths, $verbose, $mode ) = @_;
94        $paths = [$paths] unless UNIVERSAL::isa( $paths, 'ARRAY' );
95        $arg->{verbose} = $verbose;
96        $arg->{mode} = defined $mode ? $mode : oct '777';
97    }
98    else {
99        my %args_permitted = map { $_ => 1 } ( qw|
100            chmod
101            error
102            group
103            mask
104            mode
105            owner
106            uid
107            user
108            verbose
109        | );
110        my @bad_args = ();
111        $arg = pop @_;
112        for my $k (sort keys %{$arg}) {
113            push @bad_args, $k unless $args_permitted{$k};
114        }
115        _carp("Unrecognized option(s) passed to make_path(): @bad_args")
116            if @bad_args;
117        $arg->{mode} = delete $arg->{mask} if exists $arg->{mask};
118        $arg->{mode} = oct '777' unless exists $arg->{mode};
119        ${ $arg->{error} } = [] if exists $arg->{error};
120        $arg->{owner} = delete $arg->{user} if exists $arg->{user};
121        $arg->{owner} = delete $arg->{uid}  if exists $arg->{uid};
122        if ( exists $arg->{owner} and $arg->{owner} =~ /\D/ ) {
123            my $uid = ( getpwnam $arg->{owner} )[2];
124            if ( defined $uid ) {
125                $arg->{owner} = $uid;
126            }
127            else {
128                _error( $arg,
129"unable to map $arg->{owner} to a uid, ownership not changed"
130                );
131                delete $arg->{owner};
132            }
133        }
134        if ( exists $arg->{group} and $arg->{group} =~ /\D/ ) {
135            my $gid = ( getgrnam $arg->{group} )[2];
136            if ( defined $gid ) {
137                $arg->{group} = $gid;
138            }
139            else {
140                _error( $arg,
141"unable to map $arg->{group} to a gid, group ownership not changed"
142                );
143                delete $arg->{group};
144            }
145        }
146        if ( exists $arg->{owner} and not exists $arg->{group} ) {
147            $arg->{group} = -1;    # chown will leave group unchanged
148        }
149        if ( exists $arg->{group} and not exists $arg->{owner} ) {
150            $arg->{owner} = -1;    # chown will leave owner unchanged
151        }
152        $paths = [@_];
153    }
154    return _mkpath( $arg, $paths );
155}
156
157sub _mkpath {
158    my $arg   = shift;
159    my $paths = shift;
160
161    my ( @created );
162    foreach my $path ( @{$paths} ) {
163        next unless defined($path) and length($path);
164        $path .= '/' if _IS_OS2 and $path =~ /^\w:\z/s; # feature of CRT
165
166        # Logic wants Unix paths, so go with the flow.
167        if (_IS_VMS) {
168            next if $path eq '/';
169            $path = VMS::Filespec::unixify($path);
170        }
171        next if -d $path;
172        my $parent = File::Basename::dirname($path);
173        unless ( -d $parent or $path eq $parent ) {
174            push( @created, _mkpath( $arg, [$parent] ) );
175        }
176        print "mkdir $path\n" if $arg->{verbose};
177        if ( mkdir( $path, $arg->{mode} ) ) {
178            push( @created, $path );
179            if ( exists $arg->{owner} ) {
180
181                # NB: $arg->{group} guaranteed to be set during initialisation
182                if ( !chown $arg->{owner}, $arg->{group}, $path ) {
183                    _error( $arg,
184"Cannot change ownership of $path to $arg->{owner}:$arg->{group}"
185                    );
186                }
187            }
188            if ( exists $arg->{chmod} ) {
189                if ( !chmod $arg->{chmod}, $path ) {
190                    _error( $arg,
191                        "Cannot change permissions of $path to $arg->{chmod}" );
192                }
193            }
194        }
195        else {
196            my $save_bang = $!;
197            my ( $e, $e1 ) = ( $save_bang, $^E );
198            $e .= "; $e1" if $e ne $e1;
199
200            # allow for another process to have created it meanwhile
201            if ( ! -d $path ) {
202                $! = $save_bang;
203                if ( $arg->{error} ) {
204                    push @{ ${ $arg->{error} } }, { $path => $e };
205                }
206                else {
207                    _croak("mkdir $path: $e");
208                }
209            }
210        }
211    }
212    return @created;
213}
214
215sub remove_tree {
216    push @_, {} unless @_ and __is_arg( $_[-1] );
217    goto &rmtree;
218}
219
220sub _is_subdir {
221    my ( $dir, $test ) = @_;
222
223    my ( $dv, $dd ) = File::Spec->splitpath( $dir,  1 );
224    my ( $tv, $td ) = File::Spec->splitpath( $test, 1 );
225
226    # not on same volume
227    return 0 if $dv ne $tv;
228
229    my @d = File::Spec->splitdir($dd);
230    my @t = File::Spec->splitdir($td);
231
232    # @t can't be a subdir if it's shorter than @d
233    return 0 if @t < @d;
234
235    return join( '/', @d ) eq join( '/', splice @t, 0, +@d );
236}
237
238sub rmtree {
239    my $old_style = !( @_ and __is_arg( $_[-1] ) );
240
241    my $arg;
242    my $paths;
243
244    if ($old_style) {
245        my ( $verbose, $safe );
246        ( $paths, $verbose, $safe ) = @_;
247        $arg->{verbose} = $verbose;
248        $arg->{safe} = defined $safe ? $safe : 0;
249
250        if ( defined($paths) and length($paths) ) {
251            $paths = [$paths] unless UNIVERSAL::isa( $paths, 'ARRAY' );
252        }
253        else {
254            _carp("No root path(s) specified\n");
255            return 0;
256        }
257    }
258    else {
259        my %args_permitted = map { $_ => 1 } ( qw|
260            error
261            keep_root
262            result
263            safe
264            verbose
265        | );
266        my @bad_args = ();
267        $arg = pop @_;
268        for my $k (sort keys %{$arg}) {
269            push @bad_args, $k unless $args_permitted{$k};
270        }
271        _carp("Unrecognized option(s) passed to remove_tree(): @bad_args")
272            if @bad_args;
273        ${ $arg->{error} }  = [] if exists $arg->{error};
274        ${ $arg->{result} } = [] if exists $arg->{result};
275        $paths = [@_];
276    }
277
278    $arg->{prefix} = '';
279    $arg->{depth}  = 0;
280
281    my @clean_path;
282    $arg->{cwd} = getcwd() or do {
283        _error( $arg, "cannot fetch initial working directory" );
284        return 0;
285    };
286    for ( $arg->{cwd} ) { /\A(.*)\Z/s; $_ = $1 }    # untaint
287
288    for my $p (@$paths) {
289
290        # need to fixup case and map \ to / on Windows
291        my $ortho_root = _IS_MSWIN32 ? _slash_lc($p) : $p;
292        my $ortho_cwd =
293          _IS_MSWIN32 ? _slash_lc( $arg->{cwd} ) : $arg->{cwd};
294        my $ortho_root_length = length($ortho_root);
295        $ortho_root_length-- if _IS_VMS;   # don't compare '.' with ']'
296        if ( $ortho_root_length && _is_subdir( $ortho_root, $ortho_cwd ) ) {
297            local $! = 0;
298            _error( $arg, "cannot remove path when cwd is $arg->{cwd}", $p );
299            next;
300        }
301
302        if (_IS_MACOS) {
303            $p = ":$p" unless $p =~ /:/;
304            $p .= ":" unless $p =~ /:\z/;
305        }
306        elsif ( _IS_MSWIN32 ) {
307            $p =~ s{[/\\]\z}{};
308        }
309        else {
310            $p =~ s{/\z}{};
311        }
312        push @clean_path, $p;
313    }
314
315    @{$arg}{qw(device inode perm)} = ( lstat $arg->{cwd} )[ 0, 1 ] or do {
316        _error( $arg, "cannot stat initial working directory", $arg->{cwd} );
317        return 0;
318    };
319
320    return _rmtree( $arg, \@clean_path );
321}
322
323sub _rmtree {
324    my $arg   = shift;
325    my $paths = shift;
326
327    my $count  = 0;
328    my $curdir = File::Spec->curdir();
329    my $updir  = File::Spec->updir();
330
331    my ( @files, $root );
332  ROOT_DIR:
333    foreach my $root (@$paths) {
334
335        # since we chdir into each directory, it may not be obvious
336        # to figure out where we are if we generate a message about
337        # a file name. We therefore construct a semi-canonical
338        # filename, anchored from the directory being unlinked (as
339        # opposed to being truly canonical, anchored from the root (/).
340
341        my $canon =
342          $arg->{prefix}
343          ? File::Spec->catfile( $arg->{prefix}, $root )
344          : $root;
345
346        my ( $ldev, $lino, $perm ) = ( lstat $root )[ 0, 1, 2 ]
347          or next ROOT_DIR;
348
349        if ( -d _ ) {
350            $root = VMS::Filespec::vmspath( VMS::Filespec::pathify($root) )
351              if _IS_VMS;
352
353            if ( !chdir($root) ) {
354
355                # see if we can escalate privileges to get in
356                # (e.g. funny protection mask such as -w- instead of rwx)
357                $perm &= oct '7777';
358                my $nperm = $perm | oct '700';
359                if (
360                    !(
361                           $arg->{safe}
362                        or $nperm == $perm
363                        or chmod( $nperm, $root )
364                    )
365                  )
366                {
367                    _error( $arg,
368                        "cannot make child directory read-write-exec", $canon );
369                    next ROOT_DIR;
370                }
371                elsif ( !chdir($root) ) {
372                    _error( $arg, "cannot chdir to child", $canon );
373                    next ROOT_DIR;
374                }
375            }
376
377            my ( $cur_dev, $cur_inode, $perm ) = ( stat $curdir )[ 0, 1, 2 ]
378              or do {
379                _error( $arg, "cannot stat current working directory", $canon );
380                next ROOT_DIR;
381              };
382
383            if (_NEED_STAT_CHECK) {
384                ( $ldev eq $cur_dev and $lino eq $cur_inode )
385                  or _croak(
386"directory $canon changed before chdir, expected dev=$ldev ino=$lino, actual dev=$cur_dev ino=$cur_inode, aborting."
387                  );
388            }
389
390            $perm &= oct '7777';    # don't forget setuid, setgid, sticky bits
391            my $nperm = $perm | oct '700';
392
393            # notabene: 0700 is for making readable in the first place,
394            # it's also intended to change it to writable in case we have
395            # to recurse in which case we are better than rm -rf for
396            # subtrees with strange permissions
397
398            if (
399                !(
400                       $arg->{safe}
401                    or $nperm == $perm
402                    or chmod( $nperm, $curdir )
403                )
404              )
405            {
406                _error( $arg, "cannot make directory read+writeable", $canon );
407                $nperm = $perm;
408            }
409
410            my $d;
411            $d = gensym() if $] < 5.006;
412            if ( !opendir $d, $curdir ) {
413                _error( $arg, "cannot opendir", $canon );
414                @files = ();
415            }
416            else {
417                if ( !defined ${^TAINT} or ${^TAINT} ) {
418                    # Blindly untaint dir names if taint mode is active
419                    @files = map { /\A(.*)\z/s; $1 } readdir $d;
420                }
421                else {
422                    @files = readdir $d;
423                }
424                closedir $d;
425            }
426
427            if (_IS_VMS) {
428
429                # Deleting large numbers of files from VMS Files-11
430                # filesystems is faster if done in reverse ASCIIbetical order.
431                # include '.' to '.;' from blead patch #31775
432                @files = map { $_ eq '.' ? '.;' : $_ } reverse @files;
433            }
434
435            @files = grep { $_ ne $updir and $_ ne $curdir } @files;
436
437            if (@files) {
438
439                # remove the contained files before the directory itself
440                my $narg = {%$arg};
441                @{$narg}{qw(device inode cwd prefix depth)} =
442                  ( $cur_dev, $cur_inode, $updir, $canon, $arg->{depth} + 1 );
443                $count += _rmtree( $narg, \@files );
444            }
445
446            # restore directory permissions of required now (in case the rmdir
447            # below fails), while we are still in the directory and may do so
448            # without a race via '.'
449            if ( $nperm != $perm and not chmod( $perm, $curdir ) ) {
450                _error( $arg, "cannot reset chmod", $canon );
451            }
452
453            # don't leave the client code in an unexpected directory
454            chdir( $arg->{cwd} )
455              or
456              _croak("cannot chdir to $arg->{cwd} from $canon: $!, aborting.");
457
458            # ensure that a chdir upwards didn't take us somewhere other
459            # than we expected (see CVE-2002-0435)
460            ( $cur_dev, $cur_inode ) = ( stat $curdir )[ 0, 1 ]
461              or _croak(
462                "cannot stat prior working directory $arg->{cwd}: $!, aborting."
463              );
464
465            if (_NEED_STAT_CHECK) {
466                ( $arg->{device} eq $cur_dev and $arg->{inode} eq $cur_inode )
467                  or _croak(  "previous directory $arg->{cwd} "
468                            . "changed before entering $canon, "
469                            . "expected dev=$ldev ino=$lino, "
470                            . "actual dev=$cur_dev ino=$cur_inode, aborting."
471                  );
472            }
473
474            if ( $arg->{depth} or !$arg->{keep_root} ) {
475                if ( $arg->{safe}
476                    && ( _IS_VMS
477                        ? !&VMS::Filespec::candelete($root)
478                        : !-w $root ) )
479                {
480                    print "skipped $root\n" if $arg->{verbose};
481                    next ROOT_DIR;
482                }
483                if ( _FORCE_WRITABLE and !chmod $perm | oct '700', $root ) {
484                    _error( $arg, "cannot make directory writeable", $canon );
485                }
486                print "rmdir $root\n" if $arg->{verbose};
487                if ( rmdir $root ) {
488                    push @{ ${ $arg->{result} } }, $root if $arg->{result};
489                    ++$count;
490                }
491                else {
492                    _error( $arg, "cannot remove directory", $canon );
493                    if (
494                        _FORCE_WRITABLE
495                        && !chmod( $perm,
496                            ( _IS_VMS ? VMS::Filespec::fileify($root) : $root )
497                        )
498                      )
499                    {
500                        _error(
501                            $arg,
502                            sprintf( "cannot restore permissions to 0%o",
503                                $perm ),
504                            $canon
505                        );
506                    }
507                }
508            }
509        }
510        else {
511            # not a directory
512            $root = VMS::Filespec::vmsify("./$root")
513              if _IS_VMS
514              && !File::Spec->file_name_is_absolute($root)
515              && ( $root !~ m/(?<!\^)[\]>]+/ );    # not already in VMS syntax
516
517            if (
518                $arg->{safe}
519                && (
520                    _IS_VMS
521                    ? !&VMS::Filespec::candelete($root)
522                    : !( -l $root || -w $root )
523                )
524              )
525            {
526                print "skipped $root\n" if $arg->{verbose};
527                next ROOT_DIR;
528            }
529
530            my $nperm = $perm & oct '7777' | oct '600';
531            if (    _FORCE_WRITABLE
532                and $nperm != $perm
533                and not chmod $nperm, $root )
534            {
535                _error( $arg, "cannot make file writeable", $canon );
536            }
537            print "unlink $canon\n" if $arg->{verbose};
538
539            # delete all versions under VMS
540            for ( ; ; ) {
541                if ( unlink $root ) {
542                    push @{ ${ $arg->{result} } }, $root if $arg->{result};
543                }
544                else {
545                    _error( $arg, "cannot unlink file", $canon );
546                    _FORCE_WRITABLE and chmod( $perm, $root )
547                      or _error( $arg,
548                        sprintf( "cannot restore permissions to 0%o", $perm ),
549                        $canon );
550                    last;
551                }
552                ++$count;
553                last unless _IS_VMS && lstat $root;
554            }
555        }
556    }
557    return $count;
558}
559
560sub _slash_lc {
561
562    # fix up slashes and case on MSWin32 so that we can determine that
563    # c:\path\to\dir is underneath C:/Path/To
564    my $path = shift;
565    $path =~ tr{\\}{/};
566    return lc($path);
567}
568
5691;
570
571__END__
572
573=head1 NAME
574
575File::Path - Create or remove directory trees
576
577=head1 VERSION
578
579This document describes version 2.12 of File::Path.
580
581=head1 SYNOPSIS
582
583  use File::Path qw(make_path remove_tree);
584
585  @created = make_path('foo/bar/baz', '/zug/zwang');
586  @created = make_path('foo/bar/baz', '/zug/zwang', {
587      verbose => 1,
588      mode => 0711,
589  });
590  make_path('foo/bar/baz', '/zug/zwang', {
591      chmod => 0777,
592  });
593
594  $removed_count = remove_tree('foo/bar/baz', '/zug/zwang');
595  $removed_count = remove_tree('foo/bar/baz', '/zug/zwang', {
596      verbose => 1,
597      error  => \my $err_list,
598  });
599
600  # legacy (interface promoted before v2.00)
601  @created = mkpath('/foo/bar/baz');
602  @created = mkpath('/foo/bar/baz', 1, 0711);
603  @created = mkpath(['/foo/bar/baz', 'blurfl/quux'], 1, 0711);
604  $removed_count = rmtree('foo/bar/baz', 1, 1);
605  $removed_count = rmtree(['foo/bar/baz', 'blurfl/quux'], 1, 1);
606
607  # legacy (interface promoted before v2.06)
608  @created = mkpath('foo/bar/baz', '/zug/zwang', { verbose => 1, mode => 0711 });
609  $removed_count = rmtree('foo/bar/baz', '/zug/zwang', { verbose => 1, mode => 0711 });
610
611=head1 DESCRIPTION
612
613This module provide a convenient way to create directories of
614arbitrary depth and to delete an entire directory subtree from the
615filesystem.
616
617The following functions are provided:
618
619=over
620
621=item make_path( $dir1, $dir2, .... )
622
623=item make_path( $dir1, $dir2, ...., \%opts )
624
625The C<make_path> function creates the given directories if they don't
626exists before, much like the Unix command C<mkdir -p>.
627
628The function accepts a list of directories to be created. Its
629behaviour may be tuned by an optional hashref appearing as the last
630parameter on the call.
631
632The function returns the list of directories actually created during
633the call; in scalar context the number of directories created.
634
635The following keys are recognised in the option hash:
636
637=over
638
639=item mode => $num
640
641The numeric permissions mode to apply to each created directory
642(defaults to 0777), to be modified by the current C<umask>. If the
643directory already exists (and thus does not need to be created),
644the permissions will not be modified.
645
646C<mask> is recognised as an alias for this parameter.
647
648=item chmod => $num
649
650Takes a numeric mode to apply to each created directory (not
651modified by the current C<umask>). If the directory already exists
652(and thus does not need to be created), the permissions will
653not be modified.
654
655=item verbose => $bool
656
657If present, will cause C<make_path> to print the name of each directory
658as it is created. By default nothing is printed.
659
660=item error => \$err
661
662If present, it should be a reference to a scalar.
663This scalar will be made to reference an array, which will
664be used to store any errors that are encountered.  See the L</"ERROR
665HANDLING"> section for more information.
666
667If this parameter is not used, certain error conditions may raise
668a fatal error that will cause the program to halt, unless trapped
669in an C<eval> block.
670
671=item owner => $owner
672
673=item user => $owner
674
675=item uid => $owner
676
677If present, will cause any created directory to be owned by C<$owner>.
678If the value is numeric, it will be interpreted as a uid, otherwise
679as username is assumed. An error will be issued if the username cannot be
680mapped to a uid, or the uid does not exist, or the process lacks the
681privileges to change ownership.
682
683Ownership of directories that already exist will not be changed.
684
685C<user> and C<uid> are aliases of C<owner>.
686
687=item group => $group
688
689If present, will cause any created directory to be owned by the group C<$group>.
690If the value is numeric, it will be interpreted as a gid, otherwise
691as group name is assumed. An error will be issued if the group name cannot be
692mapped to a gid, or the gid does not exist, or the process lacks the
693privileges to change group ownership.
694
695Group ownership of directories that already exist will not be changed.
696
697    make_path '/var/tmp/webcache', {owner=>'nobody', group=>'nogroup'};
698
699=back
700
701=item mkpath( $dir )
702
703=item mkpath( $dir, $verbose, $mode )
704
705=item mkpath( [$dir1, $dir2,...], $verbose, $mode )
706
707=item mkpath( $dir1, $dir2,..., \%opt )
708
709The mkpath() function provide the legacy interface of make_path() with
710a different interpretation of the arguments passed.  The behaviour and
711return value of the function is otherwise identical to make_path().
712
713=item remove_tree( $dir1, $dir2, .... )
714
715=item remove_tree( $dir1, $dir2, ...., \%opts )
716
717The C<remove_tree> function deletes the given directories and any
718files and subdirectories they might contain, much like the Unix
719command C<rm -r> or the Windows commands C<rmdir /s> and C<rd /s>. The
720only exception to the function similarity is C<remove_tree> accepts
721only directories whereas C<rm -r> also accepts files.
722
723The function accepts a list of directories to be
724removed. Its behaviour may be tuned by an optional hashref
725appearing as the last parameter on the call.  If an empty string is
726passed to C<remove_tree>, an error will occur.
727
728The functions returns the number of files successfully deleted.
729
730The following keys are recognised in the option hash:
731
732=over
733
734=item verbose => $bool
735
736If present, will cause C<remove_tree> to print the name of each file as
737it is unlinked. By default nothing is printed.
738
739=item safe => $bool
740
741When set to a true value, will cause C<remove_tree> to skip the files
742for which the process lacks the required privileges needed to delete
743files, such as delete privileges on VMS. In other words, the code
744will make no attempt to alter file permissions. Thus, if the process
745is interrupted, no filesystem object will be left in a more
746permissive mode.
747
748=item keep_root => $bool
749
750When set to a true value, will cause all files and subdirectories
751to be removed, except the initially specified directories. This comes
752in handy when cleaning out an application's scratch directory.
753
754  remove_tree( '/tmp', {keep_root => 1} );
755
756=item result => \$res
757
758If present, it should be a reference to a scalar.
759This scalar will be made to reference an array, which will
760be used to store all files and directories unlinked
761during the call. If nothing is unlinked, the array will be empty.
762
763  remove_tree( '/tmp', {result => \my $list} );
764  print "unlinked $_\n" for @$list;
765
766This is a useful alternative to the C<verbose> key.
767
768=item error => \$err
769
770If present, it should be a reference to a scalar.
771This scalar will be made to reference an array, which will
772be used to store any errors that are encountered.  See the L</"ERROR
773HANDLING"> section for more information.
774
775Removing things is a much more dangerous proposition than
776creating things. As such, there are certain conditions that
777C<remove_tree> may encounter that are so dangerous that the only
778sane action left is to kill the program.
779
780Use C<error> to trap all that is reasonable (problems with
781permissions and the like), and let it die if things get out
782of hand. This is the safest course of action.
783
784=back
785
786=item rmtree( $dir )
787
788=item rmtree( $dir, $verbose, $safe )
789
790=item rmtree( [$dir1, $dir2,...], $verbose, $safe )
791
792=item rmtree( $dir1, $dir2,..., \%opt )
793
794The rmtree() function provide the legacy interface of remove_tree()
795with a different interpretation of the arguments passed. The behaviour
796and return value of the function is otherwise identical to
797remove_tree().
798
799=back
800
801=head2 ERROR HANDLING
802
803=over 4
804
805=item B<NOTE:>
806
807The following error handling mechanism is consistent throughout all
808code paths EXCEPT in cases where the ROOT node is nonexistent.  In
809version 2.11 the maintainers attempted to rectify this inconsistency
810but too many downstream modules encountered problems.  In such case,
811if you require root node evaluation or error checking prior to calling
812C<make_path> or C<remove_tree>, you should take additional precautions.
813
814=back
815
816If C<make_path> or C<remove_tree> encounter an error, a diagnostic
817message will be printed to C<STDERR> via C<carp> (for non-fatal
818errors), or via C<croak> (for fatal errors).
819
820If this behaviour is not desirable, the C<error> attribute may be
821used to hold a reference to a variable, which will be used to store
822the diagnostics. The variable is made a reference to an array of hash
823references.  Each hash contain a single key/value pair where the key
824is the name of the file, and the value is the error message (including
825the contents of C<$!> when appropriate).  If a general error is
826encountered the diagnostic key will be empty.
827
828An example usage looks like:
829
830  remove_tree( 'foo/bar', 'bar/rat', {error => \my $err} );
831  if (@$err) {
832      for my $diag (@$err) {
833          my ($file, $message) = %$diag;
834          if ($file eq '') {
835              print "general error: $message\n";
836          }
837          else {
838              print "problem unlinking $file: $message\n";
839          }
840      }
841  }
842  else {
843      print "No error encountered\n";
844  }
845
846Note that if no errors are encountered, C<$err> will reference an
847empty array.  This means that C<$err> will always end up TRUE; so you
848need to test C<@$err> to determine if errors occurred.
849
850=head2 NOTES
851
852C<File::Path> blindly exports C<mkpath> and C<rmtree> into the
853current namespace. These days, this is considered bad style, but
854to change it now would break too much code. Nonetheless, you are
855invited to specify what it is you are expecting to use:
856
857  use File::Path 'rmtree';
858
859The routines C<make_path> and C<remove_tree> are B<not> exported
860by default. You must specify which ones you want to use.
861
862  use File::Path 'remove_tree';
863
864Note that a side-effect of the above is that C<mkpath> and C<rmtree>
865are no longer exported at all. This is due to the way the C<Exporter>
866module works. If you are migrating a codebase to use the new
867interface, you will have to list everything explicitly. But that's
868just good practice anyway.
869
870  use File::Path qw(remove_tree rmtree);
871
872=head3 API CHANGES
873
874The API was changed in the 2.0 branch. For a time, C<mkpath> and
875C<rmtree> tried, unsuccessfully, to deal with the two different
876calling mechanisms. This approach was considered a failure.
877
878The new semantics are now only available with C<make_path> and
879C<remove_tree>. The old semantics are only available through
880C<mkpath> and C<rmtree>. Users are strongly encouraged to upgrade
881to at least 2.08 in order to avoid surprises.
882
883=head3 SECURITY CONSIDERATIONS
884
885There were race conditions 1.x implementations of File::Path's
886C<rmtree> function (although sometimes patched depending on the OS
887distribution or platform). The 2.0 version contains code to avoid the
888problem mentioned in CVE-2002-0435.
889
890See the following pages for more information:
891
892  http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=286905
893  http://www.nntp.perl.org/group/perl.perl5.porters/2005/01/msg97623.html
894  http://www.debian.org/security/2005/dsa-696
895
896Additionally, unless the C<safe> parameter is set (or the
897third parameter in the traditional interface is TRUE), should a
898C<remove_tree> be interrupted, files that were originally in read-only
899mode may now have their permissions set to a read-write (or "delete
900OK") mode.
901
902=head1 DIAGNOSTICS
903
904FATAL errors will cause the program to halt (C<croak>), since the
905problem is so severe that it would be dangerous to continue. (This
906can always be trapped with C<eval>, but it's not a good idea. Under
907the circumstances, dying is the best thing to do).
908
909SEVERE errors may be trapped using the modern interface. If the
910they are not trapped, or the old interface is used, such an error
911will cause the program will halt.
912
913All other errors may be trapped using the modern interface, otherwise
914they will be C<carp>ed about. Program execution will not be halted.
915
916=over 4
917
918=item mkdir [path]: [errmsg] (SEVERE)
919
920C<make_path> was unable to create the path. Probably some sort of
921permissions error at the point of departure, or insufficient resources
922(such as free inodes on Unix).
923
924=item No root path(s) specified
925
926C<make_path> was not given any paths to create. This message is only
927emitted if the routine is called with the traditional interface.
928The modern interface will remain silent if given nothing to do.
929
930=item No such file or directory
931
932On Windows, if C<make_path> gives you this warning, it may mean that
933you have exceeded your filesystem's maximum path length.
934
935=item cannot fetch initial working directory: [errmsg]
936
937C<remove_tree> attempted to determine the initial directory by calling
938C<Cwd::getcwd>, but the call failed for some reason. No attempt
939will be made to delete anything.
940
941=item cannot stat initial working directory: [errmsg]
942
943C<remove_tree> attempted to stat the initial directory (after having
944successfully obtained its name via C<getcwd>), however, the call
945failed for some reason. No attempt will be made to delete anything.
946
947=item cannot chdir to [dir]: [errmsg]
948
949C<remove_tree> attempted to set the working directory in order to
950begin deleting the objects therein, but was unsuccessful. This is
951usually a permissions issue. The routine will continue to delete
952other things, but this directory will be left intact.
953
954=item directory [dir] changed before chdir, expected dev=[n] ino=[n], actual dev=[n] ino=[n], aborting. (FATAL)
955
956C<remove_tree> recorded the device and inode of a directory, and then
957moved into it. It then performed a C<stat> on the current directory
958and detected that the device and inode were no longer the same. As
959this is at the heart of the race condition problem, the program
960will die at this point.
961
962=item cannot make directory [dir] read+writeable: [errmsg]
963
964C<remove_tree> attempted to change the permissions on the current directory
965to ensure that subsequent unlinkings would not run into problems,
966but was unable to do so. The permissions remain as they were, and
967the program will carry on, doing the best it can.
968
969=item cannot read [dir]: [errmsg]
970
971C<remove_tree> tried to read the contents of the directory in order
972to acquire the names of the directory entries to be unlinked, but
973was unsuccessful. This is usually a permissions issue. The
974program will continue, but the files in this directory will remain
975after the call.
976
977=item cannot reset chmod [dir]: [errmsg]
978
979C<remove_tree>, after having deleted everything in a directory, attempted
980to restore its permissions to the original state but failed. The
981directory may wind up being left behind.
982
983=item cannot remove [dir] when cwd is [dir]
984
985The current working directory of the program is F</some/path/to/here>
986and you are attempting to remove an ancestor, such as F</some/path>.
987The directory tree is left untouched.
988
989The solution is to C<chdir> out of the child directory to a place
990outside the directory tree to be removed.
991
992=item cannot chdir to [parent-dir] from [child-dir]: [errmsg], aborting. (FATAL)
993
994C<remove_tree>, after having deleted everything and restored the permissions
995of a directory, was unable to chdir back to the parent. The program
996halts to avoid a race condition from occurring.
997
998=item cannot stat prior working directory [dir]: [errmsg], aborting. (FATAL)
999
1000C<remove_tree> was unable to stat the parent directory after have returned
1001from the child. Since there is no way of knowing if we returned to
1002where we think we should be (by comparing device and inode) the only
1003way out is to C<croak>.
1004
1005=item previous directory [parent-dir] changed before entering [child-dir], expected dev=[n] ino=[n], actual dev=[n] ino=[n], aborting. (FATAL)
1006
1007When C<remove_tree> returned from deleting files in a child directory, a
1008check revealed that the parent directory it returned to wasn't the one
1009it started out from. This is considered a sign of malicious activity.
1010
1011=item cannot make directory [dir] writeable: [errmsg]
1012
1013Just before removing a directory (after having successfully removed
1014everything it contained), C<remove_tree> attempted to set the permissions
1015on the directory to ensure it could be removed and failed. Program
1016execution continues, but the directory may possibly not be deleted.
1017
1018=item cannot remove directory [dir]: [errmsg]
1019
1020C<remove_tree> attempted to remove a directory, but failed. This may because
1021some objects that were unable to be removed remain in the directory, or
1022a permissions issue. The directory will be left behind.
1023
1024=item cannot restore permissions of [dir] to [0nnn]: [errmsg]
1025
1026After having failed to remove a directory, C<remove_tree> was unable to
1027restore its permissions from a permissive state back to a possibly
1028more restrictive setting. (Permissions given in octal).
1029
1030=item cannot make file [file] writeable: [errmsg]
1031
1032C<remove_tree> attempted to force the permissions of a file to ensure it
1033could be deleted, but failed to do so. It will, however, still attempt
1034to unlink the file.
1035
1036=item cannot unlink file [file]: [errmsg]
1037
1038C<remove_tree> failed to remove a file. Probably a permissions issue.
1039
1040=item cannot restore permissions of [file] to [0nnn]: [errmsg]
1041
1042After having failed to remove a file, C<remove_tree> was also unable
1043to restore the permissions on the file to a possibly less permissive
1044setting. (Permissions given in octal).
1045
1046=item unable to map [owner] to a uid, ownership not changed");
1047
1048C<make_path> was instructed to give the ownership of created
1049directories to the symbolic name [owner], but C<getpwnam> did
1050not return the corresponding numeric uid. The directory will
1051be created, but ownership will not be changed.
1052
1053=item unable to map [group] to a gid, group ownership not changed
1054
1055C<make_path> was instructed to give the group ownership of created
1056directories to the symbolic name [group], but C<getgrnam> did
1057not return the corresponding numeric gid. The directory will
1058be created, but group ownership will not be changed.
1059
1060=back
1061
1062=head1 SEE ALSO
1063
1064=over 4
1065
1066=item *
1067
1068L<File::Remove>
1069
1070Allows files and directories to be moved to the Trashcan/Recycle
1071Bin (where they may later be restored if necessary) if the operating
1072system supports such functionality. This feature may one day be
1073made available directly in C<File::Path>.
1074
1075=item *
1076
1077L<File::Find::Rule>
1078
1079When removing directory trees, if you want to examine each file to
1080decide whether to delete it (and possibly leaving large swathes
1081alone), F<File::Find::Rule> offers a convenient and flexible approach
1082to examining directory trees.
1083
1084=back
1085
1086=head1 BUGS AND LIMITATIONS
1087
1088The following describes F<File::Path> limitations and how to report bugs.
1089
1090=head2 MULTITHREAD APPLICATIONS
1091
1092F<File::Path> B<rmtree> and B<remove_tree> will not work with multithreaded
1093applications due to its use of B<chdir>.  At this time, no warning or error
1094results and you will certainly encounter unexpected results.
1095
1096The implementation that surfaces this limitation may change in a future
1097release.
1098
1099=head2 NFS Mount Points
1100
1101F<File::Path> is not responsible for triggering the automounts, mirror mounts,
1102and the contents of network mounted filesystems.  If your NFS implementation
1103requires an action to be performed on the filesystem in order for
1104F<File::Path> to perform operations, it is strongly suggested you assure
1105filesystem availability by reading the root of the mounted filesystem.
1106
1107=head2 REPORTING BUGS
1108
1109Please report all bugs on the RT queue, either via the web interface:
1110
1111L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=File-Path>
1112
1113or by email:
1114
1115    bug-File-Path@rt.cpan.org
1116
1117In either case, please B<attach> patches to the bug report rather than
1118including them inline in the web post or the body of the email.
1119
1120You can also send pull requests to the Github repository:
1121
1122L<https://github.com/rpcme/File-Path>
1123
1124=head1 ACKNOWLEDGEMENTS
1125
1126Paul Szabo identified the race condition originally, and Brendan
1127O'Dea wrote an implementation for Debian that addressed the problem.
1128That code was used as a basis for the current code. Their efforts
1129are greatly appreciated.
1130
1131Gisle Aas made a number of improvements to the documentation for
11322.07 and his advice and assistance is also greatly appreciated.
1133
1134=head1 AUTHORS
1135
1136Prior authors and maintainers: Tim Bunce, Charles Bailey, and
1137David Landgren <F<david@landgren.net>>.
1138
1139Current maintainers are Richard Elberger <F<riche@cpan.org>> and
1140James (Jim) Keenan <F<jkeenan@cpan.org>>.
1141
1142=head1 CONTRIBUTORS
1143
1144Contributors to File::Path, in alphabetical order.
1145
1146=over 1
1147
1148=item <F<bulkdd@cpan.org>>
1149
1150=item Craig A. Berry <F<craigberry@mac.com>>
1151
1152=item Richard Elberger <F<riche@cpan.org>>
1153
1154=item Ryan Yee <F<ryee@cpan.org>>
1155
1156=item Skye Shaw <F<shaw@cpan.org>>
1157
1158=item Tom Lutz <F<tommylutz@gmail.com>>
1159
1160=back
1161
1162=head1 COPYRIGHT
1163
1164This module is copyright (C) Charles Bailey, Tim Bunce, David Landgren,
1165James Keenan, and Richard Elberger 1995-2015. All rights reserved.
1166
1167=head1 LICENSE
1168
1169This library is free software; you can redistribute it and/or modify
1170it under the same terms as Perl itself.
1171
1172=cut
1173