Debian Codegraph @

tests/CuTmpdir.pm

raw
1 package CuTmpdir;
2 # This file (CuTmpDir.pm) was copied from GNU Coretils.
3 # It has the following copyright notice and license:
4 #
5 # create, then chdir into a temporary sub-directory
6
7 # Copyright (C) 2007-2013 Free Software Foundation, Inc.
8
9 # This program is free software: you can redistribute it and/or modify
10 # it under the terms of the GNU General Public License as published by
11 # the Free Software Foundation, either version 3 of the License, or
12 # (at your option) any later version.
13
14 # This program is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
18
19 # You should have received a copy of the GNU General Public License
20 # along with this program. If not, see <http://www.gnu.org/licenses/>.
21
22 use strict;
23 use warnings;
24
25 use File::Temp;
26 use File::Find;
27
28 our $ME = $0 || "<???>";
29
30 my $dir;
31
32 sub skip_test($)
33 {
34 warn "$ME: skipping test: unsafe working directory name: '$_[0]'\n";
35 exit 77;
36 }
37
38 sub chmod_1
39 {
40 my $name = $_;
41
42 # Skip symlinks and non-directories.
43 -l $name || !-d _
44 and return;
45
46 chmod 0700, $name;
47 }
48
49 sub chmod_tree
50 {
51 # When tempdir fails, it croaks, which leaves $dir undefined.
52 defined $dir
53 or return;
54
55 # Perform the equivalent of find "$dir" -type d -print0|xargs -0 chmod -R 700.
56 my $options = {untaint => 1, wanted => \&chmod_1};
57 find ($options, $dir);
58 }
59
60 sub import {
61 my $prefix = $_[1];
62
63 $ME eq '-' && defined $prefix
64 and $ME = $prefix;
65
66 if ($prefix !~ /^\//)
67 {
68 eval 'use Cwd';
69 my $cwd = $@ ? '.' : Cwd::getcwd();
70 $prefix = "$cwd/$prefix";
71 }
72
73 # Untaint for the upcoming mkdir.
74 $prefix =~ m!^([-+\@\w./]+)$!
75 or skip_test $prefix;
76 $prefix = $1;
77
78 my $original_pid = $$;
79
80 my $on_sig_remove_tmpdir = sub {
81 my ($sig) = @_;
82 if ($$ == $original_pid and defined $dir)
83 {
84 chmod_tree;
85 # Older versions of File::Temp lack this method.
86 exists &File::Temp::cleanup
87 and &File::Temp::cleanup;
88 }
89 $SIG{$sig} = 'DEFAULT';
90 kill $sig, $$;
91 };
92
93 foreach my $sig (qw (INT TERM HUP))
94 {
95 $SIG{$sig} = $on_sig_remove_tmpdir;
96 }
97
98 $dir = File::Temp::tempdir("$prefix.tmp-XXXX", CLEANUP => 1 );
99 chdir $dir
100 or warn "$ME: failed to chdir to $dir: $!\n";
101 }
102
103 END {
104 # Move cwd out of the directory we're about to remove.
105 # This is required on some systems, and by some versions of File::Temp.
106 chdir '..'
107 or warn "$ME: failed to chdir to .. from $dir: $!\n";
108
109 my $saved_errno = $?;
110 chmod_tree;
111 $? = $saved_errno;
112 }
113
114 1;