old
[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                 die "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         warn "<<< $line\n";
184         my ($user,$hostname,$pwd,$command,$rel_path,$message) = split(/\s+/,$line,6);
185         $hostname =~ s/\..+$//;
186
187         my $on_host = '';
188         if ( $rel_path =~ s/^([^:]+):(.+)$/$2/ ) {
189                 if ( -e $1 ) {
190                         $on_host = $1;
191                 } else {
192                         print $client "host $1 doesn't exist in backup\n";
193                         next;
194                 }
195         }
196         my $path = $rel_path =~ m{^/} ? $rel_path : "$pwd/$rel_path";
197
198         foreach my $command ( split /,/, $command ) { # XXX command loop
199
200         warn "$hostname [$command] $on_host:$path | $message\n";
201
202         my $args_message = $message;
203
204         $message ||= "$path [$command]";
205         $message = "$hostname: $message";
206
207         my $dir = $path;
208         $dir =~ s{/[^/]+$}{};
209
210         my $backup_path = -e "$hostname/$path" ? "$hostname/$path" : $hostname;
211
212         sub git {
213                 my $args = join(' ',@_);
214                 warn "# git $args\n";
215                 my $out = `git $args`;
216                 warn "$out\n# [", length($out), " bytes]\n" if defined $out;
217                 return $out;
218         }
219
220         if ( ! $command ) {
221                 pull_changes $hostname;
222         } elsif ( $command eq 'add' ) {
223                 mkpath "$hostname/$dir" unless -e "$hostname/$dir";
224                 while ( $path ) {
225                         rsync( '-avv', "root\@$hostname:$path", "$hostname/$path" );
226                         print $client git 'add', "$hostname/$path";
227
228                         $args_message =~ s/^(.+)\b// || last;
229                         $path = $1;
230                         warn "? $path";
231                 }
232         } elsif ( $command eq 'commit' ) {
233                 pull_changes $hostname;
234                 $message =~ s/'/\\'/g;
235                 $user =~ s/\/$//;
236                 print $client git( "commit -m '$message' --author '$user <$hostname>' $backup_path" );
237         } elsif ( $command =~ m{(diff|status|log|ch)} ) {
238                 $command .= ' --stat' if $command eq 'log';
239                 $command = 'log --patch-with-stat' if $command =~ m/^ch/;
240                 pull_changes( $hostname ) if $command eq 'diff';
241                 if ( $on_host ) {
242                         mkpath $_ foreach grep { ! -e $_ } ( "$hostname/$dir", "$on_host/$dir" );
243                         rsync( '-avv', "root\@$hostname:$path", "$hostname/$path" );
244                         rsync( '-avv', "root\@$on_host:$path", "$on_host/$path" );
245                         open(my $diff, '-|', "diff -Nuw $hostname$path $on_host$path");
246                         while(<$diff>) {
247                                 print $client $_;
248                         }
249                 } else {
250                         # commands without path will show host-wide status/changes
251                         my $backup_path = $path ? "$hostname/$path" : "$hostname/";
252                         # hostname must end with / to prevent error from git:
253                         # ambiguous argument 'arh-hw': both revision and filename
254                         # to support branches named as hosts
255                         print $client git($command, $backup_path);
256                 }
257         } elsif ( $command eq 'revert' ) {
258                 if ( $on_host ) {
259                         rsync( '-avv', "$on_host/$path", "root\@$hostname:$path" );
260                 } else {
261                         print $client git "checkout -- $hostname/$path";
262                         rsync( '-avv', "$hostname/$path", "root\@$hostname:$path" );
263                 }
264         } elsif ( $command eq 'cat' ) {
265                 my $file_path = ( $on_host ? $on_host : $hostname ) . "/$path";
266                 if ( -r $file_path ) {
267                         open(my $file, '<', $file_path) || warn "ERROR $file_path: $!";
268                         while(<$file>) {
269                                 print $client $_;
270                         }
271                         close($file);
272                 } else {
273                         print $client "ERROR: $file_path: $!\n";
274                 }
275         } elsif ( $command eq 'ls' ) {
276                 my $file_path = ( $on_host ? $on_host : $hostname ) . "/$path";
277                 print $client `ls $file_path 2>&1`;
278         } elsif ( $command eq 'show' ) {
279                 print $client `git show $rel_path`;
280         } elsif ( $command eq 'grep' ) {
281                 print $client `git log -g --grep=$rel_path`;
282         } elsif ( $command eq 'find' ) {
283                 print $client `find . -iname '*$rel_path*' | sed -e 's,^./,,' -e 's,/,:/,'`
284         } elsif ( $command eq 'link' ) {
285                 if ( $on_host ) {
286                         mkbasedir "$on_host/$path";
287                         rsync( '-avv', "root\@$on_host:$path", "$on_host/$path" );
288                         mkbasedir "$hostname/$path";
289                         link "$on_host/$path", "$hostname/$path";
290                         rsync( '-avv', "$hostname/$path", "root\@$hostname:$path" );
291                 } else {
292                         print $client "ERROR: link requires host:/path\n";
293                 }
294         } else {
295                 print $client "ERROR: unknown command: $command\n";
296         }
297
298         } # XXX command, loop
299
300         close($client);
301 }
302