added peer IP address validation
[bak-git.git] / bak-git-server.pl
1 #!/usr/bin/perl
2
3 =head1 bak-git
4
5 Simple tracking of remote files in central git repository
6 with only shell, netcat, rsync and ssh on client
7
8 Start server, install on remote-host or upgrade with:
9
10   ./bak-git-server.pl /path/to/backup 192.168.42.42
11         [--install remote-host]
12         [--upgrade]
13
14 C<rsync> traffic is always transfered over ssh, but C<diff> or C<ch> can
15 still leak sensitive information if C<bak> shell client connects directly
16 to server host.
17
18 Add following line to C<~/.ssh/config> under C<Host> for which you want encrypted
19 controll channel (or to pass through server ssh hops using C<ProxyCommand>)
20
21   RemoteForward 9001 192.168.42.42:9001
22
23 bak command, overview:
24
25   bak add /path
26   bak commit [/path [message]]
27   bak diff [host:][/path]
28   bak status [/path]
29   bak log [/path]
30
31   bak show
32   bak ch[anges]
33   bak revert [host:]/path
34
35   bak cat [host:]/path
36   bak grep pattern
37   bak find filename-pattern
38
39   bak - push all changed files to server
40
41   bak add,commit /path
42
43 See L<http://blog.rot13.org/bak-git> for more information
44
45 =cut
46
47 use warnings;
48 use strict;
49 use autodie;
50 use IO::Socket::INET;
51 use File::Path;
52 use Getopt::Long;
53
54 my $upgrade = 0;
55 my $install;
56
57 GetOptions(
58         'upgrade!'  => \$upgrade,
59         'install=s' => \$install,
60 ) || die "$!\n";
61
62 my ( $dir, $server_ip ) = @ARGV;
63 die "usage: $0 /backup/directory 127.0.0.1\n" unless $dir;
64 $server_ip ||= '127.0.0.1';
65
66 # parse ssh config
67 my $ssh_tunnel;
68 open(my $ssh_fd, '<', "$ENV{HOME}/.ssh/config");
69 my $host;
70 while(<$ssh_fd>) {
71         chomp;
72         next unless length($_) > 0;
73         next if m/^\s*#/;
74
75         if ( /^Host\s+(.+)/i ) {
76                 $host = $1;
77         } elsif ( /^\s+(\S+)\s+(.+)/ ) {
78                 $ssh_tunnel->{$host}++ if lc($1) eq 'remoteforward' && $2 =~ m/9001/;
79         } elsif ( /^\s+$/ ) {
80                 # nop
81         } else {
82                 warn "can't parse [$_]";
83         }
84 }
85
86 sub shell_client {
87         my ( $hostname ) = @_;
88         my $path = '/tmp/bak';
89         my $server = $server_ip;
90         $server = '127.0.0.1' if $ssh_tunnel->{$hostname};
91 warn "# ssh_client $hostname $server";
92         open(my $fh, '>', $path);
93         print $fh "#!/bin/sh\n";
94         print $fh "echo \$USER/\$SUDO_USER $hostname `pwd` \$* | nc $server 9001\n";
95         close($fh);
96         chmod 0755, $path;
97         return $path;
98 }
99
100 sub _kill_ssh {
101         while ( my($host,$pid) = each %$ssh_tunnel ) {
102                 warn "$host kill TERM $pid";
103                 eval { kill 15, $pid; } # TERM
104         }
105 }
106
107 #$SIG{INT};
108 $SIG{TERM} = &_kill_ssh;
109
110 chdir $dir;
111 system 'git init' unless -e '.git';
112
113 if ( $upgrade || $install ) {
114
115         my @hosts = grep { -d $_ } glob '*';
116         @hosts = ( $install ) if $install;
117
118         foreach my $hostname ( @hosts ) {
119                 warn "install on $hostname\n";
120                 system 'ssh-copy-id', "root\@$hostname" if ! -d $hostname;
121                 my $path = shell_client( $hostname );
122                 system "scp $path root\@$hostname:/usr/local/bin/";
123                 system "ssh root\@$hostname apt-get install -y netcat rsync";
124         }
125 } else {
126         my $ssh = $ENV{SSH} || 'ssh';
127         warn "# start $ssh tunnels...";
128         foreach my $host ( keys %$ssh_tunnel ) {
129 last; # FIXME disabled
130                 warn "## $host\n";
131                 my $pid = fork;
132                 if ( ! defined $pid ) {
133                         die "fork: $!";
134                 } elsif ( $pid ) {
135 #                       waitpid $pid, 0;
136                         warn "FIXME: waitpid $pid";
137                 } else {
138                         warn "EXEC $ssh $host";
139                         exec "$ssh -N root\@$host";
140                 }
141
142                 $ssh_tunnel->{$host} = $pid;
143         }
144 }
145
146 warn "dir: $dir listen: $server_ip:9001\n";
147
148 my $server = IO::Socket::INET->new(
149         Proto     => 'tcp',
150 #       LocalAddr => $server_ip,
151         LocalPort => 9001,
152         Listen    => SOMAXCONN,
153         Reuse     => 1
154 ) || die $!;
155
156
157 sub rsync {
158         warn "# rsync ",join(' ', @_), "\n";
159         system 'rsync', @_;
160 }
161
162 sub pull_changes {
163         my $hostname = shift;
164         system "find $hostname -type f | sed 's,$hostname,,' > /tmp/$hostname.list";
165         if ( @_ ) {
166                 open(my $files, '>>', "/tmp/$hostname.list");
167                 print $files "$_\n" foreach @_;
168                 close($files);
169         }
170         rsync split / /, "-avv --files-from /tmp/$hostname.list root\@$hostname:/ $hostname/";
171 }
172
173 sub mkbasedir {
174         my $path = shift;
175         $path =~ s{/[^/]+$}{};
176         warn "# mkpath $path\n";
177         mkpath $path || die $!;
178 }
179
180 while (my $client = $server->accept()) {
181         my $line = <$client>;
182         chomp($line);
183
184         my $peerhost = $client->peerhost;
185         if ( $peerhost !~ m/^(10\.13\.37\.|10\.60\.0\.)/ ) {
186                 print $client "$peerhost not allowed\n";
187                 next;
188         }
189
190         warn "<<< $peerhost $line\n";
191         my ($user,$hostname,$pwd,$command,$rel_path,$message) = split(/\s+/,$line,6);
192         $hostname =~ s/\..+$//;
193
194         my $on_host = '';
195         if ( $rel_path =~ s/^([^:]+):(.+)$/$2/ ) {
196                 if ( -e $1 ) {
197                         $on_host = $1;
198                 } else {
199                         print $client "host $1 doesn't exist in backup\n";
200                         next;
201                 }
202         }
203         my $path = $rel_path =~ m{^/} ? $rel_path : "$pwd/$rel_path";
204
205         foreach my $command ( split /,/, $command ) { # XXX command loop
206
207         warn "$hostname [$command] $on_host:$path | $message\n";
208
209         my $args_message = $message;
210
211         $message ||= "$path [$command]";
212         $message = "$hostname: $message";
213
214         my $dir = $path;
215         $dir =~ s{/[^/]+$}{};
216
217         my $backup_path = -e "$hostname/$path" ? "$hostname/$path" : $hostname;
218
219         sub git {
220                 my $args = join(' ',@_);
221                 warn "# git $args\n";
222                 my $out = `git $args`;
223                 warn "$out\n# [", length($out), " bytes]\n" if defined $out;
224                 return $out;
225         }
226
227         if ( ! $command ) {
228                 pull_changes $hostname;
229         } elsif ( $command eq 'add' ) {
230                 mkpath "$hostname/$dir" unless -e "$hostname/$dir";
231                 while ( $path ) {
232                         rsync( '-avv', "root\@$hostname:$path", "$hostname/$path" );
233                         print $client git 'add', "$hostname/$path";
234
235                         $args_message =~ s/^(.+)\b// || last;
236                         $path = $1;
237                         warn "? $path";
238                 }
239         } elsif ( $command eq 'commit' ) {
240                 pull_changes $hostname;
241                 $message =~ s/'/\\'/g;
242                 $user =~ s/\/$//;
243                 print $client git( "commit -m '$message' --author '$user <$hostname>' $backup_path" );
244         } elsif ( $command =~ m{(diff|status|log|ch)} ) {
245                 $command .= ' --stat' if $command eq 'log';
246                 $command = 'log --patch-with-stat' if $command =~ m/^ch/;
247                 pull_changes( $hostname ) if $command eq 'diff';
248                 if ( $on_host ) {
249                         mkpath $_ foreach grep { ! -e $_ } ( "$hostname/$dir", "$on_host/$dir" );
250                         rsync( '-avv', "root\@$hostname:$path", "$hostname/$path" );
251                         rsync( '-avv', "root\@$on_host:$path", "$on_host/$path" );
252                         open(my $diff, '-|', "diff -Nuw $hostname$path $on_host$path");
253                         while(<$diff>) {
254                                 print $client $_;
255                         }
256                 } else {
257                         # commands without path will show host-wide status/changes
258                         my $backup_path = $path ? "$hostname/$path" : "$hostname/";
259                         # hostname must end with / to prevent error from git:
260                         # ambiguous argument 'arh-hw': both revision and filename
261                         # to support branches named as hosts
262                         print $client git($command, $backup_path);
263                 }
264         } elsif ( $command eq 'revert' ) {
265                 if ( $on_host ) {
266                         rsync( '-avv', "$on_host/$path", "root\@$hostname:$path" );
267                 } else {
268                         print $client git "checkout -- $hostname/$path";
269                         rsync( '-avv', "$hostname/$path", "root\@$hostname:$path" );
270                 }
271         } elsif ( $command eq 'cat' ) {
272                 my $file_path = ( $on_host ? $on_host : $hostname ) . "/$path";
273                 if ( -r $file_path ) {
274                         open(my $file, '<', $file_path) || warn "ERROR $file_path: $!";
275                         while(<$file>) {
276                                 print $client $_;
277                         }
278                         close($file);
279                 } else {
280                         print $client "ERROR: $file_path: $!\n";
281                 }
282         } elsif ( $command eq 'ls' ) {
283                 my $file_path = ( $on_host ? $on_host : $hostname ) . "/$path";
284                 print $client `ls $file_path 2>&1`;
285         } elsif ( $command eq 'show' ) {
286                 print $client `git show $rel_path`;
287         } elsif ( $command eq 'grep' ) {
288                 print $client `git log -g --grep=$rel_path`;
289         } elsif ( $command eq 'find' ) {
290                 print $client `find . -iname '*$rel_path*' | sed -e 's,^./,,' -e 's,/,:/,'`
291         } elsif ( $command eq 'link' ) {
292                 if ( $on_host ) {
293                         mkbasedir "$on_host/$path";
294                         rsync( '-avv', "root\@$on_host:$path", "$on_host/$path" );
295                         mkbasedir "$hostname/$path";
296                         link "$on_host/$path", "$hostname/$path";
297                         rsync( '-avv', "$hostname/$path", "root\@$hostname:$path" );
298                 } else {
299                         print $client "ERROR: link requires host:/path\n";
300                 }
301         } else {
302                 print $client "ERROR: unknown command: $command\n";
303         }
304
305         } # XXX command, loop
306
307         close($client);
308 }
309