Path.pm 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985
  1. package File::Path;
  2. use 5.005_04;
  3. use strict;
  4. use Cwd 'getcwd';
  5. use File::Basename ();
  6. use File::Spec ();
  7. BEGIN {
  8. if ($] < 5.006) {
  9. # can't say 'opendir my $dh, $dirname'
  10. # need to initialise $dh
  11. eval "use Symbol";
  12. }
  13. }
  14. use Exporter ();
  15. use vars qw($VERSION @ISA @EXPORT @EXPORT_OK);
  16. $VERSION = '2.09';
  17. @ISA = qw(Exporter);
  18. @EXPORT = qw(mkpath rmtree);
  19. @EXPORT_OK = qw(make_path remove_tree);
  20. my $Is_VMS = $^O eq 'VMS';
  21. my $Is_MacOS = $^O eq 'MacOS';
  22. # These OSes complain if you want to remove a file that you have no
  23. # write permission to:
  24. my $Force_Writeable = grep {$^O eq $_} qw(amigaos dos epoc MSWin32 MacOS os2);
  25. # Unix-like systems need to stat each directory in order to detect
  26. # race condition. MS-Windows is immune to this particular attack.
  27. my $Need_Stat_Check = !($^O eq 'MSWin32');
  28. sub _carp {
  29. require Carp;
  30. goto &Carp::carp;
  31. }
  32. sub _croak {
  33. require Carp;
  34. goto &Carp::croak;
  35. }
  36. sub _error {
  37. my $arg = shift;
  38. my $message = shift;
  39. my $object = shift;
  40. if ($arg->{error}) {
  41. $object = '' unless defined $object;
  42. $message .= ": $!" if $!;
  43. push @{${$arg->{error}}}, {$object => $message};
  44. }
  45. else {
  46. _carp(defined($object) ? "$message for $object: $!" : "$message: $!");
  47. }
  48. }
  49. sub make_path {
  50. push @_, {} unless @_ and UNIVERSAL::isa($_[-1],'HASH');
  51. goto &mkpath;
  52. }
  53. sub mkpath {
  54. my $old_style = !(@_ and UNIVERSAL::isa($_[-1],'HASH'));
  55. my $arg;
  56. my $paths;
  57. if ($old_style) {
  58. my ($verbose, $mode);
  59. ($paths, $verbose, $mode) = @_;
  60. $paths = [$paths] unless UNIVERSAL::isa($paths,'ARRAY');
  61. $arg->{verbose} = $verbose;
  62. $arg->{mode} = defined $mode ? $mode : 0777;
  63. }
  64. else {
  65. $arg = pop @_;
  66. $arg->{mode} = delete $arg->{mask} if exists $arg->{mask};
  67. $arg->{mode} = 0777 unless exists $arg->{mode};
  68. ${$arg->{error}} = [] if exists $arg->{error};
  69. $arg->{owner} = delete $arg->{user} if exists $arg->{user};
  70. $arg->{owner} = delete $arg->{uid} if exists $arg->{uid};
  71. if (exists $arg->{owner} and $arg->{owner} =~ /\D/) {
  72. my $uid = (getpwnam $arg->{owner})[2];
  73. if (defined $uid) {
  74. $arg->{owner} = $uid;
  75. }
  76. else {
  77. _error($arg, "unable to map $arg->{owner} to a uid, ownership not changed");
  78. delete $arg->{owner};
  79. }
  80. }
  81. if (exists $arg->{group} and $arg->{group} =~ /\D/) {
  82. my $gid = (getgrnam $arg->{group})[2];
  83. if (defined $gid) {
  84. $arg->{group} = $gid;
  85. }
  86. else {
  87. _error($arg, "unable to map $arg->{group} to a gid, group ownership not changed");
  88. delete $arg->{group};
  89. }
  90. }
  91. if (exists $arg->{owner} and not exists $arg->{group}) {
  92. $arg->{group} = -1; # chown will leave group unchanged
  93. }
  94. if (exists $arg->{group} and not exists $arg->{owner}) {
  95. $arg->{owner} = -1; # chown will leave owner unchanged
  96. }
  97. $paths = [@_];
  98. }
  99. return _mkpath($arg, $paths);
  100. }
  101. sub _mkpath {
  102. my $arg = shift;
  103. my $paths = shift;
  104. my(@created,$path);
  105. foreach $path (@$paths) {
  106. next unless defined($path) and length($path);
  107. $path .= '/' if $^O eq 'os2' and $path =~ /^\w:\z/s; # feature of CRT
  108. # Logic wants Unix paths, so go with the flow.
  109. if ($Is_VMS) {
  110. next if $path eq '/';
  111. $path = VMS::Filespec::unixify($path);
  112. }
  113. next if -d $path;
  114. my $parent = File::Basename::dirname($path);
  115. unless (-d $parent or $path eq $parent) {
  116. push(@created,_mkpath($arg, [$parent]));
  117. }
  118. print "mkdir $path\n" if $arg->{verbose};
  119. if (mkdir($path,$arg->{mode})) {
  120. push(@created, $path);
  121. if (exists $arg->{owner}) {
  122. # NB: $arg->{group} guaranteed to be set during initialisation
  123. if (!chown $arg->{owner}, $arg->{group}, $path) {
  124. _error($arg, "Cannot change ownership of $path to $arg->{owner}:$arg->{group}");
  125. }
  126. }
  127. }
  128. else {
  129. my $save_bang = $!;
  130. my ($e, $e1) = ($save_bang, $^E);
  131. $e .= "; $e1" if $e ne $e1;
  132. # allow for another process to have created it meanwhile
  133. if (!-d $path) {
  134. $! = $save_bang;
  135. if ($arg->{error}) {
  136. push @{${$arg->{error}}}, {$path => $e};
  137. }
  138. else {
  139. _croak("mkdir $path: $e");
  140. }
  141. }
  142. }
  143. }
  144. return @created;
  145. }
  146. sub remove_tree {
  147. push @_, {} unless @_ and UNIVERSAL::isa($_[-1],'HASH');
  148. goto &rmtree;
  149. }
  150. sub _is_subdir {
  151. my($dir, $test) = @_;
  152. my($dv, $dd) = File::Spec->splitpath($dir, 1);
  153. my($tv, $td) = File::Spec->splitpath($test, 1);
  154. # not on same volume
  155. return 0 if $dv ne $tv;
  156. my @d = File::Spec->splitdir($dd);
  157. my @t = File::Spec->splitdir($td);
  158. # @t can't be a subdir if it's shorter than @d
  159. return 0 if @t < @d;
  160. return join('/', @d) eq join('/', splice @t, 0, +@d);
  161. }
  162. sub rmtree {
  163. my $old_style = !(@_ and UNIVERSAL::isa($_[-1],'HASH'));
  164. my $arg;
  165. my $paths;
  166. if ($old_style) {
  167. my ($verbose, $safe);
  168. ($paths, $verbose, $safe) = @_;
  169. $arg->{verbose} = $verbose;
  170. $arg->{safe} = defined $safe ? $safe : 0;
  171. if (defined($paths) and length($paths)) {
  172. $paths = [$paths] unless UNIVERSAL::isa($paths,'ARRAY');
  173. }
  174. else {
  175. _carp ("No root path(s) specified\n");
  176. return 0;
  177. }
  178. }
  179. else {
  180. $arg = pop @_;
  181. ${$arg->{error}} = [] if exists $arg->{error};
  182. ${$arg->{result}} = [] if exists $arg->{result};
  183. $paths = [@_];
  184. }
  185. $arg->{prefix} = '';
  186. $arg->{depth} = 0;
  187. my @clean_path;
  188. $arg->{cwd} = getcwd() or do {
  189. _error($arg, "cannot fetch initial working directory");
  190. return 0;
  191. };
  192. for ($arg->{cwd}) { /\A(.*)\Z/; $_ = $1 } # untaint
  193. for my $p (@$paths) {
  194. # need to fixup case and map \ to / on Windows
  195. my $ortho_root = $^O eq 'MSWin32' ? _slash_lc($p) : $p;
  196. my $ortho_cwd = $^O eq 'MSWin32' ? _slash_lc($arg->{cwd}) : $arg->{cwd};
  197. my $ortho_root_length = length($ortho_root);
  198. $ortho_root_length-- if $^O eq 'VMS'; # don't compare '.' with ']'
  199. if ($ortho_root_length && _is_subdir($ortho_root, $ortho_cwd)) {
  200. local $! = 0;
  201. _error($arg, "cannot remove path when cwd is $arg->{cwd}", $p);
  202. next;
  203. }
  204. if ($Is_MacOS) {
  205. $p = ":$p" unless $p =~ /:/;
  206. $p .= ":" unless $p =~ /:\z/;
  207. }
  208. elsif ($^O eq 'MSWin32') {
  209. $p =~ s{[/\\]\z}{};
  210. }
  211. else {
  212. $p =~ s{/\z}{};
  213. }
  214. push @clean_path, $p;
  215. }
  216. @{$arg}{qw(device inode perm)} = (lstat $arg->{cwd})[0,1] or do {
  217. _error($arg, "cannot stat initial working directory", $arg->{cwd});
  218. return 0;
  219. };
  220. return _rmtree($arg, \@clean_path);
  221. }
  222. sub _rmtree {
  223. my $arg = shift;
  224. my $paths = shift;
  225. my $count = 0;
  226. my $curdir = File::Spec->curdir();
  227. my $updir = File::Spec->updir();
  228. my (@files, $root);
  229. ROOT_DIR:
  230. foreach $root (@$paths) {
  231. # since we chdir into each directory, it may not be obvious
  232. # to figure out where we are if we generate a message about
  233. # a file name. We therefore construct a semi-canonical
  234. # filename, anchored from the directory being unlinked (as
  235. # opposed to being truly canonical, anchored from the root (/).
  236. my $canon = $arg->{prefix}
  237. ? File::Spec->catfile($arg->{prefix}, $root)
  238. : $root
  239. ;
  240. my ($ldev, $lino, $perm) = (lstat $root)[0,1,2] or next ROOT_DIR;
  241. if ( -d _ ) {
  242. $root = VMS::Filespec::vmspath(VMS::Filespec::pathify($root)) if $Is_VMS;
  243. if (!chdir($root)) {
  244. # see if we can escalate privileges to get in
  245. # (e.g. funny protection mask such as -w- instead of rwx)
  246. $perm &= 07777;
  247. my $nperm = $perm | 0700;
  248. if (!($arg->{safe} or $nperm == $perm or chmod($nperm, $root))) {
  249. _error($arg, "cannot make child directory read-write-exec", $canon);
  250. next ROOT_DIR;
  251. }
  252. elsif (!chdir($root)) {
  253. _error($arg, "cannot chdir to child", $canon);
  254. next ROOT_DIR;
  255. }
  256. }
  257. my ($cur_dev, $cur_inode, $perm) = (stat $curdir)[0,1,2] or do {
  258. _error($arg, "cannot stat current working directory", $canon);
  259. next ROOT_DIR;
  260. };
  261. if ($Need_Stat_Check) {
  262. ($ldev eq $cur_dev and $lino eq $cur_inode)
  263. or _croak("directory $canon changed before chdir, expected dev=$ldev ino=$lino, actual dev=$cur_dev ino=$cur_inode, aborting.");
  264. }
  265. $perm &= 07777; # don't forget setuid, setgid, sticky bits
  266. my $nperm = $perm | 0700;
  267. # notabene: 0700 is for making readable in the first place,
  268. # it's also intended to change it to writable in case we have
  269. # to recurse in which case we are better than rm -rf for
  270. # subtrees with strange permissions
  271. if (!($arg->{safe} or $nperm == $perm or chmod($nperm, $curdir))) {
  272. _error($arg, "cannot make directory read+writeable", $canon);
  273. $nperm = $perm;
  274. }
  275. my $d;
  276. $d = gensym() if $] < 5.006;
  277. if (!opendir $d, $curdir) {
  278. _error($arg, "cannot opendir", $canon);
  279. @files = ();
  280. }
  281. else {
  282. no strict 'refs';
  283. if (!defined ${"\cTAINT"} or ${"\cTAINT"}) {
  284. # Blindly untaint dir names if taint mode is
  285. # active, or any perl < 5.006
  286. @files = map { /\A(.*)\z/s; $1 } readdir $d;
  287. }
  288. else {
  289. @files = readdir $d;
  290. }
  291. closedir $d;
  292. }
  293. if ($Is_VMS) {
  294. # Deleting large numbers of files from VMS Files-11
  295. # filesystems is faster if done in reverse ASCIIbetical order.
  296. # include '.' to '.;' from blead patch #31775
  297. @files = map {$_ eq '.' ? '.;' : $_} reverse @files;
  298. }
  299. @files = grep {$_ ne $updir and $_ ne $curdir} @files;
  300. if (@files) {
  301. # remove the contained files before the directory itself
  302. my $narg = {%$arg};
  303. @{$narg}{qw(device inode cwd prefix depth)}
  304. = ($cur_dev, $cur_inode, $updir, $canon, $arg->{depth}+1);
  305. $count += _rmtree($narg, \@files);
  306. }
  307. # restore directory permissions of required now (in case the rmdir
  308. # below fails), while we are still in the directory and may do so
  309. # without a race via '.'
  310. if ($nperm != $perm and not chmod($perm, $curdir)) {
  311. _error($arg, "cannot reset chmod", $canon);
  312. }
  313. # don't leave the client code in an unexpected directory
  314. chdir($arg->{cwd})
  315. or _croak("cannot chdir to $arg->{cwd} from $canon: $!, aborting.");
  316. # ensure that a chdir upwards didn't take us somewhere other
  317. # than we expected (see CVE-2002-0435)
  318. ($cur_dev, $cur_inode) = (stat $curdir)[0,1]
  319. or _croak("cannot stat prior working directory $arg->{cwd}: $!, aborting.");
  320. if ($Need_Stat_Check) {
  321. ($arg->{device} eq $cur_dev and $arg->{inode} eq $cur_inode)
  322. or _croak("previous directory $arg->{cwd} changed before entering $canon, expected dev=$ldev ino=$lino, actual dev=$cur_dev ino=$cur_inode, aborting.");
  323. }
  324. if ($arg->{depth} or !$arg->{keep_root}) {
  325. if ($arg->{safe} &&
  326. ($Is_VMS ? !&VMS::Filespec::candelete($root) : !-w $root)) {
  327. print "skipped $root\n" if $arg->{verbose};
  328. next ROOT_DIR;
  329. }
  330. if ($Force_Writeable and !chmod $perm | 0700, $root) {
  331. _error($arg, "cannot make directory writeable", $canon);
  332. }
  333. print "rmdir $root\n" if $arg->{verbose};
  334. if (rmdir $root) {
  335. push @{${$arg->{result}}}, $root if $arg->{result};
  336. ++$count;
  337. }
  338. else {
  339. _error($arg, "cannot remove directory", $canon);
  340. if ($Force_Writeable && !chmod($perm, ($Is_VMS ? VMS::Filespec::fileify($root) : $root))
  341. ) {
  342. _error($arg, sprintf("cannot restore permissions to 0%o",$perm), $canon);
  343. }
  344. }
  345. }
  346. }
  347. else {
  348. # not a directory
  349. $root = VMS::Filespec::vmsify("./$root")
  350. if $Is_VMS
  351. && !File::Spec->file_name_is_absolute($root)
  352. && ($root !~ m/(?<!\^)[\]>]+/); # not already in VMS syntax
  353. if ($arg->{safe} &&
  354. ($Is_VMS ? !&VMS::Filespec::candelete($root)
  355. : !(-l $root || -w $root)))
  356. {
  357. print "skipped $root\n" if $arg->{verbose};
  358. next ROOT_DIR;
  359. }
  360. my $nperm = $perm & 07777 | 0600;
  361. if ($Force_Writeable and $nperm != $perm and not chmod $nperm, $root) {
  362. _error($arg, "cannot make file writeable", $canon);
  363. }
  364. print "unlink $canon\n" if $arg->{verbose};
  365. # delete all versions under VMS
  366. for (;;) {
  367. if (unlink $root) {
  368. push @{${$arg->{result}}}, $root if $arg->{result};
  369. }
  370. else {
  371. _error($arg, "cannot unlink file", $canon);
  372. $Force_Writeable and chmod($perm, $root) or
  373. _error($arg, sprintf("cannot restore permissions to 0%o",$perm), $canon);
  374. last;
  375. }
  376. ++$count;
  377. last unless $Is_VMS && lstat $root;
  378. }
  379. }
  380. }
  381. return $count;
  382. }
  383. sub _slash_lc {
  384. # fix up slashes and case on MSWin32 so that we can determine that
  385. # c:\path\to\dir is underneath C:/Path/To
  386. my $path = shift;
  387. $path =~ tr{\\}{/};
  388. return lc($path);
  389. }
  390. 1;
  391. __END__
  392. =head1 NAME
  393. File::Path - Create or remove directory trees
  394. =head1 VERSION
  395. This document describes version 2.09 of File::Path, released
  396. 2013-01-17.
  397. =head1 SYNOPSIS
  398. use File::Path qw(make_path remove_tree);
  399. make_path('foo/bar/baz', '/zug/zwang');
  400. make_path('foo/bar/baz', '/zug/zwang', {
  401. verbose => 1,
  402. mode => 0711,
  403. });
  404. remove_tree('foo/bar/baz', '/zug/zwang');
  405. remove_tree('foo/bar/baz', '/zug/zwang', {
  406. verbose => 1,
  407. error => \my $err_list,
  408. });
  409. # legacy (interface promoted before v2.00)
  410. mkpath('/foo/bar/baz');
  411. mkpath('/foo/bar/baz', 1, 0711);
  412. mkpath(['/foo/bar/baz', 'blurfl/quux'], 1, 0711);
  413. rmtree('foo/bar/baz', 1, 1);
  414. rmtree(['foo/bar/baz', 'blurfl/quux'], 1, 1);
  415. # legacy (interface promoted before v2.06)
  416. mkpath('foo/bar/baz', '/zug/zwang', { verbose => 1, mode => 0711 });
  417. rmtree('foo/bar/baz', '/zug/zwang', { verbose => 1, mode => 0711 });
  418. =head1 DESCRIPTION
  419. This module provide a convenient way to create directories of
  420. arbitrary depth and to delete an entire directory subtree from the
  421. filesystem.
  422. The following functions are provided:
  423. =over
  424. =item make_path( $dir1, $dir2, .... )
  425. =item make_path( $dir1, $dir2, ...., \%opts )
  426. The C<make_path> function creates the given directories if they don't
  427. exists before, much like the Unix command C<mkdir -p>.
  428. The function accepts a list of directories to be created. Its
  429. behaviour may be tuned by an optional hashref appearing as the last
  430. parameter on the call.
  431. The function returns the list of directories actually created during
  432. the call; in scalar context the number of directories created.
  433. The following keys are recognised in the option hash:
  434. =over
  435. =item mode => $num
  436. The numeric permissions mode to apply to each created directory
  437. (defaults to 0777), to be modified by the current C<umask>. If the
  438. directory already exists (and thus does not need to be created),
  439. the permissions will not be modified.
  440. C<mask> is recognised as an alias for this parameter.
  441. =item verbose => $bool
  442. If present, will cause C<make_path> to print the name of each directory
  443. as it is created. By default nothing is printed.
  444. =item error => \$err
  445. If present, it should be a reference to a scalar.
  446. This scalar will be made to reference an array, which will
  447. be used to store any errors that are encountered. See the L</"ERROR
  448. HANDLING"> section for more information.
  449. If this parameter is not used, certain error conditions may raise
  450. a fatal error that will cause the program will halt, unless trapped
  451. in an C<eval> block.
  452. =item owner => $owner
  453. =item user => $owner
  454. =item uid => $owner
  455. If present, will cause any created directory to be owned by C<$owner>.
  456. If the value is numeric, it will be interpreted as a uid, otherwise
  457. as username is assumed. An error will be issued if the username cannot be
  458. mapped to a uid, or the uid does not exist, or the process lacks the
  459. privileges to change ownership.
  460. Ownwership of directories that already exist will not be changed.
  461. C<user> and C<uid> are aliases of C<owner>.
  462. =item group => $group
  463. If present, will cause any created directory to be owned by the group C<$group>.
  464. If the value is numeric, it will be interpreted as a gid, otherwise
  465. as group name is assumed. An error will be issued if the group name cannot be
  466. mapped to a gid, or the gid does not exist, or the process lacks the
  467. privileges to change group ownership.
  468. Group ownwership of directories that already exist will not be changed.
  469. make_path '/var/tmp/webcache', {owner=>'nobody', group=>'nogroup'};
  470. =back
  471. =item mkpath( $dir )
  472. =item mkpath( $dir, $verbose, $mode )
  473. =item mkpath( [$dir1, $dir2,...], $verbose, $mode )
  474. =item mkpath( $dir1, $dir2,..., \%opt )
  475. The mkpath() function provide the legacy interface of make_path() with
  476. a different interpretation of the arguments passed. The behaviour and
  477. return value of the function is otherwise identical to make_path().
  478. =item remove_tree( $dir1, $dir2, .... )
  479. =item remove_tree( $dir1, $dir2, ...., \%opts )
  480. The C<remove_tree> function deletes the given directories and any
  481. files and subdirectories they might contain, much like the Unix
  482. command C<rm -r> or C<del /s> on Windows.
  483. The function accepts a list of directories to be
  484. removed. Its behaviour may be tuned by an optional hashref
  485. appearing as the last parameter on the call.
  486. The functions returns the number of files successfully deleted.
  487. The following keys are recognised in the option hash:
  488. =over
  489. =item verbose => $bool
  490. If present, will cause C<remove_tree> to print the name of each file as
  491. it is unlinked. By default nothing is printed.
  492. =item safe => $bool
  493. When set to a true value, will cause C<remove_tree> to skip the files
  494. for which the process lacks the required privileges needed to delete
  495. files, such as delete privileges on VMS. In other words, the code
  496. will make no attempt to alter file permissions. Thus, if the process
  497. is interrupted, no filesystem object will be left in a more
  498. permissive mode.
  499. =item keep_root => $bool
  500. When set to a true value, will cause all files and subdirectories
  501. to be removed, except the initially specified directories. This comes
  502. in handy when cleaning out an application's scratch directory.
  503. remove_tree( '/tmp', {keep_root => 1} );
  504. =item result => \$res
  505. If present, it should be a reference to a scalar.
  506. This scalar will be made to reference an array, which will
  507. be used to store all files and directories unlinked
  508. during the call. If nothing is unlinked, the array will be empty.
  509. remove_tree( '/tmp', {result => \my $list} );
  510. print "unlinked $_\n" for @$list;
  511. This is a useful alternative to the C<verbose> key.
  512. =item error => \$err
  513. If present, it should be a reference to a scalar.
  514. This scalar will be made to reference an array, which will
  515. be used to store any errors that are encountered. See the L</"ERROR
  516. HANDLING"> section for more information.
  517. Removing things is a much more dangerous proposition than
  518. creating things. As such, there are certain conditions that
  519. C<remove_tree> may encounter that are so dangerous that the only
  520. sane action left is to kill the program.
  521. Use C<error> to trap all that is reasonable (problems with
  522. permissions and the like), and let it die if things get out
  523. of hand. This is the safest course of action.
  524. =back
  525. =item rmtree( $dir )
  526. =item rmtree( $dir, $verbose, $safe )
  527. =item rmtree( [$dir1, $dir2,...], $verbose, $safe )
  528. =item rmtree( $dir1, $dir2,..., \%opt )
  529. The rmtree() function provide the legacy interface of remove_tree()
  530. with a different interpretation of the arguments passed. The behaviour
  531. and return value of the function is otherwise identical to
  532. remove_tree().
  533. =back
  534. =head2 ERROR HANDLING
  535. =over 4
  536. =item B<NOTE:>
  537. The following error handling mechanism is considered
  538. experimental and is subject to change pending feedback from
  539. users.
  540. =back
  541. If C<make_path> or C<remove_tree> encounter an error, a diagnostic
  542. message will be printed to C<STDERR> via C<carp> (for non-fatal
  543. errors), or via C<croak> (for fatal errors).
  544. If this behaviour is not desirable, the C<error> attribute may be
  545. used to hold a reference to a variable, which will be used to store
  546. the diagnostics. The variable is made a reference to an array of hash
  547. references. Each hash contain a single key/value pair where the key
  548. is the name of the file, and the value is the error message (including
  549. the contents of C<$!> when appropriate). If a general error is
  550. encountered the diagnostic key will be empty.
  551. An example usage looks like:
  552. remove_tree( 'foo/bar', 'bar/rat', {error => \my $err} );
  553. if (@$err) {
  554. for my $diag (@$err) {
  555. my ($file, $message) = %$diag;
  556. if ($file eq '') {
  557. print "general error: $message\n";
  558. }
  559. else {
  560. print "problem unlinking $file: $message\n";
  561. }
  562. }
  563. }
  564. else {
  565. print "No error encountered\n";
  566. }
  567. Note that if no errors are encountered, C<$err> will reference an
  568. empty array. This means that C<$err> will always end up TRUE; so you
  569. need to test C<@$err> to determine if errors occured.
  570. =head2 NOTES
  571. C<File::Path> blindly exports C<mkpath> and C<rmtree> into the
  572. current namespace. These days, this is considered bad style, but
  573. to change it now would break too much code. Nonetheless, you are
  574. invited to specify what it is you are expecting to use:
  575. use File::Path 'rmtree';
  576. The routines C<make_path> and C<remove_tree> are B<not> exported
  577. by default. You must specify which ones you want to use.
  578. use File::Path 'remove_tree';
  579. Note that a side-effect of the above is that C<mkpath> and C<rmtree>
  580. are no longer exported at all. This is due to the way the C<Exporter>
  581. module works. If you are migrating a codebase to use the new
  582. interface, you will have to list everything explicitly. But that's
  583. just good practice anyway.
  584. use File::Path qw(remove_tree rmtree);
  585. =head3 API CHANGES
  586. The API was changed in the 2.0 branch. For a time, C<mkpath> and
  587. C<rmtree> tried, unsuccessfully, to deal with the two different
  588. calling mechanisms. This approach was considered a failure.
  589. The new semantics are now only available with C<make_path> and
  590. C<remove_tree>. The old semantics are only available through
  591. C<mkpath> and C<rmtree>. Users are strongly encouraged to upgrade
  592. to at least 2.08 in order to avoid surprises.
  593. =head3 SECURITY CONSIDERATIONS
  594. There were race conditions 1.x implementations of File::Path's
  595. C<rmtree> function (although sometimes patched depending on the OS
  596. distribution or platform). The 2.0 version contains code to avoid the
  597. problem mentioned in CVE-2002-0435.
  598. See the following pages for more information:
  599. http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=286905
  600. http://www.nntp.perl.org/group/perl.perl5.porters/2005/01/msg97623.html
  601. http://www.debian.org/security/2005/dsa-696
  602. Additionally, unless the C<safe> parameter is set (or the
  603. third parameter in the traditional interface is TRUE), should a
  604. C<remove_tree> be interrupted, files that were originally in read-only
  605. mode may now have their permissions set to a read-write (or "delete
  606. OK") mode.
  607. =head1 DIAGNOSTICS
  608. FATAL errors will cause the program to halt (C<croak>), since the
  609. problem is so severe that it would be dangerous to continue. (This
  610. can always be trapped with C<eval>, but it's not a good idea. Under
  611. the circumstances, dying is the best thing to do).
  612. SEVERE errors may be trapped using the modern interface. If the
  613. they are not trapped, or the old interface is used, such an error
  614. will cause the program will halt.
  615. All other errors may be trapped using the modern interface, otherwise
  616. they will be C<carp>ed about. Program execution will not be halted.
  617. =over 4
  618. =item mkdir [path]: [errmsg] (SEVERE)
  619. C<make_path> was unable to create the path. Probably some sort of
  620. permissions error at the point of departure, or insufficient resources
  621. (such as free inodes on Unix).
  622. =item No root path(s) specified
  623. C<make_path> was not given any paths to create. This message is only
  624. emitted if the routine is called with the traditional interface.
  625. The modern interface will remain silent if given nothing to do.
  626. =item No such file or directory
  627. On Windows, if C<make_path> gives you this warning, it may mean that
  628. you have exceeded your filesystem's maximum path length.
  629. =item cannot fetch initial working directory: [errmsg]
  630. C<remove_tree> attempted to determine the initial directory by calling
  631. C<Cwd::getcwd>, but the call failed for some reason. No attempt
  632. will be made to delete anything.
  633. =item cannot stat initial working directory: [errmsg]
  634. C<remove_tree> attempted to stat the initial directory (after having
  635. successfully obtained its name via C<getcwd>), however, the call
  636. failed for some reason. No attempt will be made to delete anything.
  637. =item cannot chdir to [dir]: [errmsg]
  638. C<remove_tree> attempted to set the working directory in order to
  639. begin deleting the objects therein, but was unsuccessful. This is
  640. usually a permissions issue. The routine will continue to delete
  641. other things, but this directory will be left intact.
  642. =item directory [dir] changed before chdir, expected dev=[n] ino=[n], actual dev=[n] ino=[n], aborting. (FATAL)
  643. C<remove_tree> recorded the device and inode of a directory, and then
  644. moved into it. It then performed a C<stat> on the current directory
  645. and detected that the device and inode were no longer the same. As
  646. this is at the heart of the race condition problem, the program
  647. will die at this point.
  648. =item cannot make directory [dir] read+writeable: [errmsg]
  649. C<remove_tree> attempted to change the permissions on the current directory
  650. to ensure that subsequent unlinkings would not run into problems,
  651. but was unable to do so. The permissions remain as they were, and
  652. the program will carry on, doing the best it can.
  653. =item cannot read [dir]: [errmsg]
  654. C<remove_tree> tried to read the contents of the directory in order
  655. to acquire the names of the directory entries to be unlinked, but
  656. was unsuccessful. This is usually a permissions issue. The
  657. program will continue, but the files in this directory will remain
  658. after the call.
  659. =item cannot reset chmod [dir]: [errmsg]
  660. C<remove_tree>, after having deleted everything in a directory, attempted
  661. to restore its permissions to the original state but failed. The
  662. directory may wind up being left behind.
  663. =item cannot remove [dir] when cwd is [dir]
  664. The current working directory of the program is F</some/path/to/here>
  665. and you are attempting to remove an ancestor, such as F</some/path>.
  666. The directory tree is left untouched.
  667. The solution is to C<chdir> out of the child directory to a place
  668. outside the directory tree to be removed.
  669. =item cannot chdir to [parent-dir] from [child-dir]: [errmsg], aborting. (FATAL)
  670. C<remove_tree>, after having deleted everything and restored the permissions
  671. of a directory, was unable to chdir back to the parent. The program
  672. halts to avoid a race condition from occurring.
  673. =item cannot stat prior working directory [dir]: [errmsg], aborting. (FATAL)
  674. C<remove_tree> was unable to stat the parent directory after have returned
  675. from the child. Since there is no way of knowing if we returned to
  676. where we think we should be (by comparing device and inode) the only
  677. way out is to C<croak>.
  678. =item previous directory [parent-dir] changed before entering [child-dir], expected dev=[n] ino=[n], actual dev=[n] ino=[n], aborting. (FATAL)
  679. When C<remove_tree> returned from deleting files in a child directory, a
  680. check revealed that the parent directory it returned to wasn't the one
  681. it started out from. This is considered a sign of malicious activity.
  682. =item cannot make directory [dir] writeable: [errmsg]
  683. Just before removing a directory (after having successfully removed
  684. everything it contained), C<remove_tree> attempted to set the permissions
  685. on the directory to ensure it could be removed and failed. Program
  686. execution continues, but the directory may possibly not be deleted.
  687. =item cannot remove directory [dir]: [errmsg]
  688. C<remove_tree> attempted to remove a directory, but failed. This may because
  689. some objects that were unable to be removed remain in the directory, or
  690. a permissions issue. The directory will be left behind.
  691. =item cannot restore permissions of [dir] to [0nnn]: [errmsg]
  692. After having failed to remove a directory, C<remove_tree> was unable to
  693. restore its permissions from a permissive state back to a possibly
  694. more restrictive setting. (Permissions given in octal).
  695. =item cannot make file [file] writeable: [errmsg]
  696. C<remove_tree> attempted to force the permissions of a file to ensure it
  697. could be deleted, but failed to do so. It will, however, still attempt
  698. to unlink the file.
  699. =item cannot unlink file [file]: [errmsg]
  700. C<remove_tree> failed to remove a file. Probably a permissions issue.
  701. =item cannot restore permissions of [file] to [0nnn]: [errmsg]
  702. After having failed to remove a file, C<remove_tree> was also unable
  703. to restore the permissions on the file to a possibly less permissive
  704. setting. (Permissions given in octal).
  705. =item unable to map [owner] to a uid, ownership not changed");
  706. C<make_path> was instructed to give the ownership of created
  707. directories to the symbolic name [owner], but C<getpwnam> did
  708. not return the corresponding numeric uid. The directory will
  709. be created, but ownership will not be changed.
  710. =item unable to map [group] to a gid, group ownership not changed
  711. C<make_path> was instructed to give the group ownership of created
  712. directories to the symbolic name [group], but C<getgrnam> did
  713. not return the corresponding numeric gid. The directory will
  714. be created, but group ownership will not be changed.
  715. =back
  716. =head1 SEE ALSO
  717. =over 4
  718. =item *
  719. L<File::Remove>
  720. Allows files and directories to be moved to the Trashcan/Recycle
  721. Bin (where they may later be restored if necessary) if the operating
  722. system supports such functionality. This feature may one day be
  723. made available directly in C<File::Path>.
  724. =item *
  725. L<File::Find::Rule>
  726. When removing directory trees, if you want to examine each file to
  727. decide whether to delete it (and possibly leaving large swathes
  728. alone), F<File::Find::Rule> offers a convenient and flexible approach
  729. to examining directory trees.
  730. =back
  731. =head1 BUGS
  732. Please report all bugs on the RT queue:
  733. L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=File-Path>
  734. You can also send pull requests to the Github repository:
  735. L<https://github.com/dland/File-Path>
  736. =head1 ACKNOWLEDGEMENTS
  737. Paul Szabo identified the race condition originally, and Brendan
  738. O'Dea wrote an implementation for Debian that addressed the problem.
  739. That code was used as a basis for the current code. Their efforts
  740. are greatly appreciated.
  741. Gisle Aas made a number of improvements to the documentation for
  742. 2.07 and his advice and assistance is also greatly appreciated.
  743. =head1 AUTHORS
  744. Tim Bunce and Charles Bailey. Currently maintained by David Landgren
  745. <F<david@landgren.net>>.
  746. =head1 COPYRIGHT
  747. This module is copyright (C) Charles Bailey, Tim Bunce and
  748. David Landgren 1995-2013. All rights reserved.
  749. =head1 LICENSE
  750. This library is free software; you can redistribute it and/or modify
  751. it under the same terms as Perl itself.
  752. =cut