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