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