Fixed handling of filenames with an embedded $, @, or %.
[rsync/rsync.git] / support / file-attr-restore
1 #!/usr/bin/perl
2 # This script will parse the output of "find ARG [ARG...] -ls" and
3 # apply (at your discretion) the permissions, owner, and group info
4 # it reads onto any existing files and dirs (it doesn't try to affect
5 # symlinks).  Run this with --help (-h) for a usage summary.
6
7 use strict;
8 use Getopt::Long;
9
10 our($p_opt, $o_opt, $g_opt, $map_file, $dry_run, $verbosity, $help_opt);
11
12 &Getopt::Long::Configure('bundling');
13 &usage if !&GetOptions(
14     'all|a' => sub { $p_opt = $o_opt = $g_opt = 1 },
15     'perms|p' => \$p_opt,
16     'owner|o' => \$o_opt,
17     'groups|g' => \$g_opt,
18     'map|m=s' => \$map_file,
19     'dry-run|n' => \$dry_run,
20     'help|h' => \$help_opt,
21     'verbose|v+' => \$verbosity,
22 ) || $help_opt;
23
24 our(%uid_hash, %gid_hash);
25
26 $" = ', '; # How to join arrays referenced in double-quotes.
27
28 &parse_map_file($map_file) if defined $map_file;
29
30 my $detail_line = qr{
31     ^ \s* \d+ \s+             # ignore inode
32     \d+ \s+                   # ignore size
33     ([-bcdlps])               # 1. File type
34     ( [-r][-w][-xsS]          # 2. user-permissions
35       [-r][-w][-xsS]          # 3. group-permissions
36       [-r][-w][-xtT] ) \s+    # 4. other-permissions
37     \d+ \s+                   # ignore number of links
38     (\S+) \s+                 # 5. owner
39     (\S+) \s+                 # 6. group
40     (?: \d+ \s+ )?            # ignore size (when present)
41     \w+ \s+ \d+ \s+           # ignore month and date
42     \d+ (?: : \d+ )? \s+      # ignore time or year
43     ([^\r\n]+) $              # 7. name
44 }x;
45
46 while (<>) {
47     my($type, $perms, $owner, $group, $name) = /$detail_line/;
48     die "Invalid input line $.:\n$_" unless defined $name;
49     die "A filename is not properly escaped:\n$_" unless $name =~ /^[^"\\]*(\\(\d\d\d|\D)[^"\\]*)*$/;
50     my $fn = $name;
51     $fn =~ s/([\$\@\%])/\\$1/g;
52     $fn = eval "\"$fn\"";
53     if ($type eq '-') {
54         undef $type unless -f $fn;
55     } elsif ($type eq 'd') {
56         undef $type unless -d $fn;
57     } elsif ($type eq 'b') {
58         undef $type unless -b $fn;
59     } elsif ($type eq 'c') {
60         undef $type unless -c $fn;
61     } elsif ($type eq 'p') {
62         undef $type unless -p $fn;
63     } elsif ($type eq 's') {
64         undef $type unless -S $fn;
65     } else {
66         if ($verbosity) {
67             if ($type eq 'l') {
68                 $name =~ s/ -> .*//;
69                 $type = 'symlink';
70             } else {
71                 $type = "type '$type'";
72             }
73             print "Skipping $name ($type ignored)\n";
74         }
75         next;
76     }
77     if (!defined $type) {
78         my $reason = -e _ ? "types don't match" : 'missing';
79         print "Skipping $name ($reason)\n";
80         next;
81     }
82     my($cur_mode, $cur_uid, $cur_gid) = (stat(_))[2,4,5];
83     $cur_mode &= 07777;
84     my $highs = join('', $perms =~ /..(.)..(.)..(.)/);
85     $highs =~ tr/-rwxSTst/00001111/;
86     $perms =~ tr/-STrwxst/00011111/;
87     my $mode = $p_opt ? oct('0b' . $highs . $perms) : $cur_mode;
88     my $uid = $o_opt ? $uid_hash{$owner} : $cur_uid;
89     if (!defined $uid) {
90         if ($owner =~ /^\d+$/) {
91             $uid = $owner;
92         } else {
93             $uid = getpwnam($owner);
94         }
95         $uid_hash{$owner} = $uid;
96     }
97     my $gid = $g_opt ? $gid_hash{$group} : $cur_gid;
98     if (!defined $gid) {
99         if ($group =~ /^\d+$/) {
100             $gid = $group;
101         } else {
102             $gid = getgrnam($group);
103         }
104         $gid_hash{$group} = $gid;
105     }
106
107     my @changes;
108     if ($mode != $cur_mode) {
109         push(@changes, 'permissions');
110         if (!$dry_run && !chmod($mode, $fn)) {
111             warn "chmod($mode, \"$name\") failed: $!\n";
112         }
113     }
114     if ($uid != $cur_uid || $gid != $cur_gid) {
115         push(@changes, 'owner') if $uid != $cur_uid;
116         push(@changes, 'group') if $gid != $cur_gid;
117         if (!$dry_run) {
118             if (!chown($uid, $gid, $fn)) {
119                 warn "chown($uid, $gid, \"$name\") failed: $!\n";
120             }
121             if (($mode & 06000) && !chmod($mode, $fn)) {
122                 warn "post-chown chmod($mode, \"$name\") failed: $!\n";
123             }
124         }
125     }
126     if (@changes) {
127         print "$name: changed @changes\n";
128     } elsif ($verbosity) {
129         print "$name: OK\n";
130     }
131 }
132 exit;
133
134 sub parse_map_file
135 {
136     my($fn) = @_;
137     open(IN, $fn) or die "Unable to open $fn: $!\n";
138     while (<IN>) {
139         if (/^user\s+(\S+)\s+(\S+)/) {
140             $uid_hash{$1} = $2;
141         } elsif (/^group\s+(\S+)\s+(\S+)/) {
142             $gid_hash{$1} = $2;
143         } else {
144             die "Invalid line #$. in mapfile `$fn':\n$_";
145         }
146     }
147     close IN;
148 }
149
150 sub usage
151 {
152     die <<EOT;
153 Usage: file-attr-restore [OPTIONS] FILE [FILE...]
154  -a, --all       Restore all the attributes (-pog)
155  -p, --perms     Restore the permissions
156  -o, --owner     Restore the ownership
157  -g, --groups    Restore the group
158  -m, --map=FILE  Read user/group mappings from FILE
159  -n, --dry-run   Don't actually make the changes
160  -v, --verbose   Increase verbosity
161  -h, --help      Show this help text
162
163 The FILE arg(s) should have been created by running the "find"
164 program with "-ls" as the output specifier.
165
166 The input file for the --map option must be in this format:
167
168     user FROM TO
169     group FROM TO
170
171 The "FROM" should be an user/group mentioned in the input, and the TO
172 should be either a uid/gid number, or a local user/group name.
173 EOT
174 }