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