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