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