]> Git — Sourcephile - git-remote-gpg.git/blob - git-remote-gpg
fix remote rsync://
[git-remote-gpg.git] / git-remote-gpg
1 #!/usr/bin/perl
2 our $VERSION = '2014.01.28';
3 # License
4 # This file is a git-remote-helpers(1) to use a gpg(1)
5 # as a cryptographic layer below git(1)'s objects.
6 # Copyright (C) 2014 Julien Moutinho
7 #
8 # This program is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published
10 # by the Free Software Foundation, either version 3 of the License,
11 # or any later version.
12 #
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty
15 # of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
16 # See the GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20 # Dependencies
21 use strict;
22 use warnings FATAL => qw(all);
23 use Carp;
24 use Cwd;
25 use File::Basename;
26 use File::Copy;
27 use File::Path;
28 use File::Spec::Functions qw(:ALL);
29 use File::Temp;
30 use Getopt::Long;
31 use IPC::Run;
32 # NOTE: to debug: IPCRUNDEBUG=basic|data|details|gory
33 use IO::Handle;
34 use JSON;
35 use POSIX qw(WNOHANG);
36 use URI;
37
38 require Pod::Usage;
39 require Data::Dumper;
40 # Trace utilities
41 sub trace (@) {
42 foreach my $msg (@_) {
43 print STDERR $msg
44 if defined $msg;
45 }
46 }
47 sub debug (@) {
48 my $call = (caller(1))[3];
49 if ($ENV{TRACE}) {
50 trace
51 ( "\e[35mDEBUG\e[m"
52 , "\e[30m\e[1m.", join('.', $call."\e[m")
53 , " ", (map {
54 ref $_ eq 'CODE'
55 ? $_->()
56 : Data::Dumper::Dumper($_)
57 } @_)
58 );
59 }
60 return 1;
61 }
62 sub info (@) {
63 my $call = (caller(1))[3];
64 trace
65 ( "\e[32mINFO\e[m"
66 , "\e[30m\e[1m.", join('.', $call."\e[m")
67 , " ", (ref $_ eq 'CODE'?(join("\n ", $_->()), "\n"):(@_, "\n"))
68 );
69 }
70 sub warning (@) {
71 local $Carp::CarpLevel = 1;
72 carp("\e[33mWARNING\e[m ", @_, "\n\t");
73 }
74 sub error (@) {
75 local $Carp::CarpLevel = 1;
76 croak("\e[31mERROR\e[m ", @_, "\n\t");
77 }
78 # System utilities
79 sub rm (@) {
80 foreach my $file (@_) {
81 debug(sub{"file=$file\n"});
82 if (not -e $file) {
83 unlink($file)
84 or error("rm $file");
85 }
86 }
87 }
88 sub mkdir (@) {
89 foreach my $dir (@_) {
90 debug(sub{"dir=$dir\n"});
91 File::Path::make_path($dir, {verbose=>0, error => \my $error});
92 if (@$error) {
93 for my $diag (@$error) {
94 my ($dir, $message) = %$diag;
95 error("dir=$dir: $message");
96 }
97 }
98 }
99 }
100 # grg crypto
101 sub grg_rand ($$) {
102 my ($ctx, $size) = @_;
103 local $_;
104 IPC::Run::run([@{$ctx->{config}->{gpg}}
105 , '--armor', '--gen-rand', '1', $size]
106 , '>', \$_)
107 or error("failed to get random bits");
108 chomp;
109 return $_;
110 }
111 sub grg_hash ($$;$) {
112 my ($ctx, $algo, $run) = @_;
113 $run = sub {return @_} unless defined $run;
114 my $hash;
115 IPC::Run::run($run->([@{$ctx->{config}->{gpg}}
116 , '--with-colons', '--print-md', $algo]
117 , '>', \$hash))
118 or error("failed to hash data");
119 return ((split(':', $hash))[2]);
120 }
121 sub gpg_fingerprint($$$) {
122 my ($ctx, $id, $caps_needed) = @_;
123 my ($output);
124 my %h = ();
125 if (IPC::Run::run([@{$ctx->{config}->{gpg}}
126 , '--fixed-list-mode', '--with-colons', '--with-fingerprint', '--list-keys', $id]
127 , '>', \$output)) {
128 my @lines = split(/\n/,$output);
129 while (my $line = shift @lines) {
130 if (my ($longkeyid, $caps) = $line =~ m/^pub:[^:]*:[^:]*:[^:]*:([^:]*):[^:]*:[^:]*:[^:]*:[^:]*:[^:]*:[^:]*:([^:]+):.*$/) {
131 my $skip = 0;
132 foreach my $cap (@$caps_needed) {
133 if (not ($caps =~ m/$cap/)) {
134 warning("skipping key 0x$longkeyid which has not usable capability: $cap, but matches: `$id'");
135 $skip = 1;
136 }
137 }
138 if (not $skip) {
139 my $fpr = undef;
140 my $uid = undef;
141 while ((not defined $fpr or not defined $uid)
142 and $line = shift @lines) {
143 (not defined $fpr and (($fpr) = $line =~ m/^fpr:[^:]*:[^:]*:[^:]*:[^:]*:[^:]*:[^:]*:[^:]*:[^:]*:([0-9A-F]+):.*$/)) or
144 (not defined $uid and (($uid) = $line =~ m/^uid:[^:]*:[^:]*:[^:]*:[^:]*:[^:]*:[^:]*:[^:]*:[^:]*:([^:]+):.*$/)) or
145 1;
146 }
147 error("unable to extract fingerprint and user ID")
148 unless defined $fpr
149 and defined $uid;
150 $h{$fpr} = $uid;
151 }
152 }
153 }
154 }
155 error("unable to find any OpenPGP key with usable capability: ".join('', @$caps_needed)." for: `$id'")
156 unless scalar(%h) gt 0;
157 debug(sub{"$id -> "}, \%h);
158 return %h;
159 }
160 sub grg_encrypt_symmetric ($$$;$) {
161 my ($ctx, $clear, $key, $run) = @_;
162 $run = sub {return @_} unless defined $run;
163 IPC::Run::run($run->([@{$ctx->{config}->{gpg}}
164 , '--batch', '--yes'
165 , '--compress-algo', 'none'
166 , '--force-mdc'
167 , '--passphrase-fd', '3'
168 , '--s2k-mode', '1'
169 , '--trust-model', 'always'
170 , '--symmetric']
171 , '<', \$clear, '3<', \$key))
172 or error("failed to encrypt symmetrically data");
173 }
174 sub grg_decrypt_symmetric ($$$;$) {
175 my ($ctx, $key, $run) = @_;
176 debug(sub{'ctx='}, $ctx);
177 debug(sub{'key='}, $key);
178 $run = sub {return @_} unless defined $run;
179 IPC::Run::run($run->([@{$ctx->{config}->{gpg}}
180 , '--batch', '--no-default-keyring', '--keyring', '/dev/null', '--secret-keyring', '/dev/null'
181 , '--passphrase-fd', '3', '--quiet', '--decrypt']
182 , '3<', \$key))
183 or error("failed to decrypt symmetrically data");
184 }
185 sub grg_encrypt_asymmetric ($$;$) {
186 my ($ctx, $clear, $run) = @_;
187 $run = sub {return @_} unless defined $run;
188 my @recipients =
189 ( (map { ('--recipient', '0x'.$_) } (keys %{$ctx->{config}->{keys}}))
190 , (map { ('--hidden-recipient', '0x'.$_) } (keys %{$ctx->{config}->{'hidden-keys'}})) );
191 @recipients = ('--default-recipient-self')
192 if @recipients == 0;
193 IPC::Run::run($run->([@{$ctx->{config}->{gpg}}
194 , '--batch', '--yes'
195 , '--compress-algo', 'none'
196 , '--trust-model', 'always'
197 , '--sign', '--encrypt'
198 , ($ctx->{config}->{signingkey}->{fpr} ? ('--local-user', $ctx->{config}->{signingkey}->{fpr}) : ())
199 , @recipients ]
200 , '<', \$clear))
201 or error("failed to encrypt asymmetrically data");
202 }
203 sub grg_decrypt_asymmetric ($$;$) {
204 my ($ctx, $run) = @_;
205 my ($clear, $status);
206 $run = sub {return @_} unless defined $run;
207 IPC::Run::run($run->([@{$ctx->{config}->{gpg}}
208 , '--batch', '--no-default-keyring',
209 , '--status-fd', '3', '--quiet', '--decrypt']
210 , '>', \$clear, '3>', \$status))
211 or error("failed to decrypt asymmetrically data");
212 debug(sub{"status=\n$status"});
213 my @lines = split(/\n/,$status);
214 my ($enc_to, $goodsig, $validsig, $validpub, $goodmdc);
215 foreach my $line (@lines) {
216 (not defined $enc_to and (($enc_to) = $line =~ m/^\[GNUPG:\] ENC_TO ([0-9A-F]+).*$/)) or
217 (not defined $goodsig and (($goodsig) = $line =~ m/^\[GNUPG:\] GOODSIG ([0-9A-F]+).*$/)) or
218 (not defined $goodmdc and (($goodmdc) = $line =~ m/^\[GNUPG:\] (GOODMDC)$/)) or
219 (not defined $validsig and not defined $validpub and (($validsig, $validpub)
220 = $line =~ m/^\[GNUPG:\] VALIDSIG ([0-9A-F]+) [^ ]+ [^ ]+ [^ ]+ [^ ]+ [^ ]+ [^ ]+ [^ ]+ [^ ]+ ([0-9A-F]+).*$/)) or
221 1;
222 }
223 error("data expected to be encrypted")
224 unless $enc_to;
225 debug(sub{"enc_to=$enc_to\n"});
226 error("data expected to be signed")
227 unless $goodsig;
228 debug(sub{"goodsig=$goodsig\n"});
229 error("modification detection code incorrect")
230 unless $goodmdc;
231 debug(sub{"good_mdc=$goodmdc\n"});
232 error("data signature invalid")
233 unless $validsig and $validpub;
234 debug(sub{"validsig=$validsig\n"});
235 debug(sub{"validpub=$validpub\n"});
236 error("data signature refused")
237 unless exists $ctx->{config}->{keys}->{$validpub}
238 or exists $ctx->{config}->{'hidden-keys'}->{$validpub};
239 debug(sub{"accepted:$validpub\n"});
240 return $clear;
241 }
242 # grg remote I/O
243 sub grg_remote_fetch_file ($) {
244 my ($ctx) = @_;
245 # NOTE: avoid File::Copy::copy().
246 while (my ($file, undef) = each %{$ctx->{remote}->{fetch}}) {
247 my $path = File::Spec->catfile($ctx->{remote}->{uri}->file, $file);
248 if (-r $path) {
249 my $h = $ctx->{remote}->{fetch}->{$file};
250 $h->{path} = $path;
251 $h->{preserve} = 1;
252 }
253 else { return 0; }
254 }
255 return 1;
256 }
257 sub grg_remote_fetch_rsync ($) {
258 my ($ctx) = @_;
259 my $uri = $ctx->{remote}->{uri}->clone;
260 my @src;
261 if ($uri->opaque =~ m{^//}) {
262 $uri->fragment(undef);
263 $uri->query(undef);
264 @src = map { $uri->path($_); $uri->as_string; }
265 (keys %{$ctx->{remote}->{fetch}});
266 }
267 else {
268 my ($authority, $path, $fragment)
269 = $uri->as_string =~ m|^rsync:(?:([^/#:]+):)?([^?#]*)(?:#(.*))?$|;
270 @src = map { "$authority:$path/$_" }
271 (keys %{$ctx->{remote}->{fetch}});
272 }
273 IPC::Run::run([@{$ctx->{config}->{rsync}}
274 , '-i', '--ignore-times', '--inplace', '--progress'
275 , @src
276 , $ctx->{'dir-cache'}.'/']
277 , '>&2')
278 }
279 sub grg_remote_fetch_sftp ($) {
280 my ($ctx) = @_;
281 IPC::Run::run([@{$ctx->{config}->{curl}}
282 , '--show-error'
283 , '--output', File::Spec->catfile($ctx->{'dir-cache'}, '#1')
284 , File::Spec->catfile($ctx->{remote}->{uri}->as_string
285 , '{'.join(',', (keys %{$ctx->{remote}->{fetch}})).'}') ])
286 }
287 sub grg_remote_fetch ($$) {
288 my ($ctx, $files) = @_;
289 debug(sub{'files='}, $files);
290 my $scheme = $ctx->{remote}->{uri}->scheme;
291 $ctx->{remote}->{fetch}
292 = {map { $_ =>
293 { path => File::Spec->catfile($ctx->{'dir-cache'}, $_)
294 , preserve => 0 }
295 } @$files};
296 my $fct =
297 { file => \&grg_remote_fetch_file
298 , rsync => \&grg_remote_fetch_rsync
299 , sftp => \&grg_remote_fetch_sftp
300 }->{$scheme};
301 error("URL scheme not supported: `$scheme'")
302 unless $fct;
303 $fct->($ctx)
304 or $ctx->{remote}->{fetch} = {};
305 return $ctx->{remote}->{fetch};
306 }
307 sub grg_remote_init_file ($) {
308 my ($ctx) = @_;
309 my $dst = $ctx->{remote}->{uri}->file;
310 &mkdir($dst);
311 return 1;
312 }
313 sub grg_remote_init_rsync ($) {
314 my ($ctx) = @_;
315 my $tmp = File::Temp->tempdir('grg_rsync_XXXXXXXX', CLEANUP => 1);
316 my $uri = $ctx->{remote}->{uri}->clone;
317 my ($path, $dst);
318 if ($uri->opaque =~ m{^//}) {
319 $uri->fragment(undef);
320 $uri->query(undef);
321 $path = $uri->path;
322 $dst = $uri->as_string;
323 }
324 else {
325 my ($authority, $fragment);
326 ($authority, $path, $fragment)
327 = $uri->as_string =~ m|^rsync:(?:([^/#:]+):)?([^?#]*)(?:#(.*))?$|;
328 $dst = "$authority:";
329 }
330 &mkdir(File::Spec->catdir($tmp, $path));
331 IPC::Run::run([@{$ctx->{config}->{rsync}}
332 , '-i', '--recursive', '--relative'
333 , '--exclude=*', '.'
334 , $dst]
335 , '>&2'
336 , init => sub { chdir $tmp or die $!; })
337 }
338 sub grg_remote_init_sftp ($) {
339 my ($ctx) = @_;
340 my $path = $ctx->{remote}->{uri}->path;
341 my $uri = $ctx->{remote}->{uri}->clone;
342 $uri->fragment(undef);
343 $uri->path(undef);
344 $uri->query(undef);
345 IPC::Run::run([@{$ctx->{config}->{curl}}
346 , '--show-error', '--ftp-create-dirs'
347 , '-Q', "+mkdir ".$path
348 , $uri->as_string])
349 }
350 sub grg_remote_init ($) {
351 my ($ctx) = @_;
352 my $scheme = $ctx->{remote}->{uri}->scheme;
353 my $fct =
354 { file => \&grg_remote_init_file
355 , rsync => \&grg_remote_init_rsync
356 , sftp => \&grg_remote_init_sftp
357 }->{$scheme};
358 error("URL scheme not supported: `$scheme'")
359 unless $fct;
360 $fct->($ctx)
361 or error("remote init failed");
362 return;
363 }
364 sub grg_remote_push_file ($) {
365 my ($ctx) = @_;
366 my $ok = 1;
367 foreach my $file (@{$ctx->{remote}->{push}}) {
368 my $src = File::Spec->catfile($ctx->{'dir-cache'}, $file);
369 my $dst = File::Spec->catfile($ctx->{remote}->{uri}->file, $file);
370 debug(sub{"File::Copy::move('$src', '$dst')\n"});
371 if (not File::Copy::move($src, $dst)) {
372 $ok = 0;
373 last;
374 }
375 }
376 return $ok;
377 }
378 sub grg_remote_push_rsync ($) {
379 my ($ctx) = @_;
380 my $uri = $ctx->{remote}->{uri}->clone;
381 $uri->fragment(undef);
382 $uri->query(undef);
383 my ($path, $dst);
384 if ($uri->opaque =~ m{^//}) {
385 $uri->fragment(undef);
386 $uri->query(undef);
387 $dst = $uri->as_string;
388 }
389 else {
390 my ($authority, $path, $fragment)
391 = $uri->as_string =~ m|^rsync:(?:([^/#:]+):)?([^?#]*)(?:#(.*))?$|;
392 $dst = "$authority:$path/";
393 }
394 IPC::Run::run([@{$ctx->{config}->{rsync}}
395 , '-i', '--relative'
396 , (@{$ctx->{remote}->{push}})
397 , $dst]
398 , '>&2'
399 , init => sub { chdir $ctx->{'dir-cache'} or die $!; });
400 }
401 sub grg_remote_push_sftp ($) {
402 my ($ctx) = @_;
403 my $uri = $ctx->{remote}->{uri}->clone;
404 $uri->fragment('');
405 $uri->query('');
406 IPC::Run::run([@{$ctx->{config}->{curl}}
407 , '--show-error', '--ftp-create-dirs', '--upload-file'
408 , '{'.join(',', @{$ctx->{remote}->{push}}).'}'
409 , $uri->as_string.'/'])
410 }
411 sub grg_remote_push ($) {
412 my ($ctx) = @_;
413 my $scheme = $ctx->{remote}->{uri}->scheme;
414 grg_remote_init($ctx)
415 unless $ctx->{remote}->{checked};
416 return 1
417 if @{$ctx->{remote}->{push}} == 0;
418 my $fct =
419 { file => \&grg_remote_push_file
420 , rsync => \&grg_remote_push_rsync
421 , sftp => \&grg_remote_push_sftp
422 }->{$scheme};
423 error("URL scheme not supported: `$scheme'")
424 unless $fct;
425 $fct->($ctx)
426 or error("remote push failed");
427 rm(map {File::Spec->catfile($ctx->{'dir-cache'}, $_)} @{$ctx->{remote}->{push}});
428 return 1;
429 }
430 sub grg_remote_remove ($) {
431 my ($ctx) = @_;
432 #my $scheme = $ctx->{remote}->{uri}->scheme;
433 #my $fct =
434 # { file => sub {
435 # File::Copy::remove_tree
436 # ( map { File::Spec->catfile($ctx->{remote}->{uri}->path, $_) } @$files
437 # , verbose => 1 )
438 # }
439 # , rsync => sub {
440 # IPC::Run::run([@{$ctx->{config}->{rsync}}
441 # , '--verbose', '--ignore-times', '--recursive', '--delete'
442 # , @$files
443 # , $ctx->{remote}->{uri}])
444 # }
445 # , sftp => sub {
446 # IPC::Run::run([@{$ctx->{config}->{curl}}
447 # , '--show-error'
448 # , map { ('-Q', 'rm '.$_) } @$files
449 # , $ctx->{remote}->{uri}])
450 # }
451 # }->{$scheme};
452 #error("URL scheme not supported: `$scheme'")
453 # unless $fct;
454 #$fct->($ctx, $ctx->{remote}->{remove})
455 # or error("remote remove failed");
456 #return;
457 }
458 # grg packing
459 sub grg_pack_fetch ($$) {
460 my ($ctx, $fetch_objects) = @_;
461 local $_;
462 # %remote_objects
463 my %remote_objects = ();
464 while (my ($pack_id, $pack) = each %{$ctx->{manifest}->{packs}}) {
465 foreach my $obj (@{$pack->{objects}}) {
466 $remote_objects{$obj} = $pack_id;
467 }
468 }
469 # @packs_to_fetch
470 my %packs_to_fetch = ();
471 foreach my $obj (@$fetch_objects) {
472 my @packs = ($remote_objects{$obj});
473 while (my $pack_id = shift @packs) {
474 if (not exists $packs_to_fetch{$pack_id}) {
475 $packs_to_fetch{$pack_id} = 1;
476 my $manifest_pack = $ctx->{manifest}->{packs}->{$pack_id};
477 error("manifest is missing a dependency pack: $pack_id")
478 unless defined $manifest_pack;
479 @packs = (@packs, @{$manifest_pack->{deps}});
480 }
481 }
482 }
483 my @packs_to_fetch = keys %packs_to_fetch;
484 my $packs_fetched = grg_remote_fetch($ctx, [@packs_to_fetch]);
485 foreach my $pack_id (@packs_to_fetch) {
486 my $pack_fetched
487 = exists $packs_fetched->{$pack_id}
488 ? $packs_fetched->{$pack_id}
489 : {path => File::Spec->catfile($ctx->{'dir-cache'}, $pack_id), preserve => 0};
490 my $manifest_pack = $ctx->{manifest}->{packs}->{$pack_id};
491 my $pack_key = $manifest_pack->{key};
492 my $pack_data;
493 grg_decrypt_symmetric($ctx, $pack_key, sub {
494 push @{$_[0]}, ($pack_fetched->{path});
495 return (@_, '>', \$pack_data);
496 });
497 my $pack_hash_algo = $manifest_pack->{hash_algo};
498 my $pack_hash = grg_hash($ctx
499 , $pack_hash_algo
500 , sub { return (@_, '<', \$pack_data); });
501 error("pack data hash differs from pack manifest hash")
502 unless $pack_hash eq $manifest_pack->{hash};
503 rm($pack_fetched)
504 unless $pack_fetched->{preserve};
505 IPC::Run::run(['git', 'index-pack', '-v', '--stdin']
506 , '<', \$pack_data
507 , '>&2');
508 }
509 }
510 sub grg_pack_push ($$) {
511 my ($ctx, $push_objects) = @_;
512 local $_;
513 debug(sub{"push_objects=\n"}, $push_objects);
514 # %remote_objects
515 my %remote_objects = ();
516 while (my ($pack_id, $pack) = each %{$ctx->{manifest}->{packs}}) {
517 foreach my $obj (@{$pack->{objects}}) {
518 $remote_objects{$obj} = $pack_id;
519 }
520 }
521 # @common_objects
522 IPC::Run::run(['git', 'cat-file', '--batch-check']
523 , '<', \join("\n", keys %remote_objects)
524 , '>', \$_)
525 or error("failed to query local git objects");
526 my @common_objects
527 = map {
528 if ($_ =~ m/ missing$/) { () }
529 else { s/ .*//; $_ }
530 } (split(/\n/, $_));
531 # @pack_objects, @pack_deps_objects
532 IPC::Run::run(['git', 'rev-list', '--objects-edge', '--stdin', '--']
533 , '<', \join("\n", ((map {'^'.$_} @common_objects), @$push_objects))
534 , '>', \$_)
535 or error("failed to query objects to pack");
536 my @pack_objects_edge = split(/\n/, $_);
537 foreach (@pack_objects_edge) {s/ .*//}
538 my @pack_objects = grep {m/^[^-]/} @pack_objects_edge;
539 my @pack_deps_objects = grep {s/^-//} @pack_objects_edge;
540 # %pack_deps
541 my %pack_deps = ();
542 foreach my $obj (@pack_deps_objects) {
543 my $pack = $remote_objects{$obj};
544 error("manifest is missing object dependencies")
545 unless defined $pack;
546 $pack_deps{$pack} = 1;
547 }
548 if (@pack_objects > 0) {
549 # $pack_id
550 my $pack_id;
551 my $pack_id_try = 0;
552 while (not defined $pack_id
553 or exists $ctx->{manifest}->{packs}->{$pack_id}) {
554 $pack_id = grg_rand($ctx, $ctx->{config}->{'pack-filename-size'});
555 $pack_id =~ s{/}{-}g;
556 error("failed to pick an unused random pack filename after 512 tries; retry or increase grg.pack-filename-size")
557 if $pack_id_try++ >= 512;
558 }
559 my $pack_key = grg_rand($ctx, $ctx->{config}->{'pack-key-size'});
560 my $pack_data;
561 IPC::Run::run(['git', 'pack-objects', '--stdout']
562 , '<', \join("\n", @pack_objects)
563 , '>', \$pack_data)
564 or error("failed to pack objects to push");
565 my $pack_hash = grg_hash($ctx
566 , $ctx->{config}->{'pack-hash-algo'}
567 , sub { return (@_, '<', \$pack_data); });
568 grg_encrypt_symmetric($ctx, $pack_data, $pack_key, sub {
569 push @{$_[0]}, ('--output', File::Spec->catfile($ctx->{'dir-cache'}, $pack_id));
570 return @_;
571 });
572 push @{$ctx->{remote}->{push}}, $pack_id;
573 $ctx->{manifest}->{packs}->{$pack_id} =
574 { deps => [keys %pack_deps]
575 , hash => $pack_hash
576 , hash_algo => $ctx->{config}->{'pack-hash-algo'}
577 , key => $pack_key
578 , objects => \@pack_objects
579 };
580 }
581 }
582 # grg manifest
583 sub grg_manifest_fetch ($) {
584 my ($ctx) = @_;
585 $ctx->{manifest} =
586 { 'hidden-keys' => {}
587 , keys => {}
588 , packs => {}
589 , refs => {}
590 , version => undef
591 };
592 my $fetched = grg_remote_fetch($ctx, [$ctx->{'manifest-file'}]);
593 my $crypt = $fetched->{$ctx->{'manifest-file'}}->{path};
594 if (defined $crypt) {
595 $ctx->{remote}->{checked} = 1;
596 my $json;
597 grg_decrypt_asymmetric($ctx, sub {
598 push @{$_[0]}, $crypt;
599 return (@_, '>', \$json); });
600 rm($fetched->{$ctx->{'manifest-file'}}->{path})
601 unless $fetched->{$ctx->{'manifest-file'}}->{preserve};
602 my $manifest;
603 ($manifest = JSON::decode_json($json) and ref $manifest eq 'HASH')
604 or error("failed to decode JSON manifest");
605 $ctx->{manifest} = {%{$ctx->{manifest}}, %$manifest};
606 foreach my $slot (qw(keys hidden-keys)) {
607 while (my ($fpr, $uid) = each %{$ctx->{manifest}->{$slot}}) {
608 my %keys = gpg_fingerprint($ctx, '0x'.$fpr, ['E']);
609 my ($fpr, $uid) = each %keys;
610 $ctx->{config}->{$slot}->{$fpr} = $uid;
611 }
612 }
613 }
614 else {
615 debug(sub{'ctx='}, $ctx);
616 if ($ctx->{command} eq 'push' or $ctx->{command} eq 'list for-push') {
617 $ctx->{remote}->{checked} = 0;
618 }
619 elsif ($ctx->{remote}->{checking}) {
620 exit 100;
621 }
622 else {
623 error("remote checking failed");
624 }
625 }
626 }
627 sub grg_manifest_push ($) {
628 my ($ctx) = @_;
629 foreach my $slot (qw(keys hidden-keys)) {
630 $ctx->{manifest}->{$slot} = {};
631 while (my ($fpr, $uid) = each %{$ctx->{config}->{$slot}}) {
632 $ctx->{manifest}->{$slot}->{$fpr} = $uid;
633 }
634 }
635 my $json = JSON::encode_json($ctx->{manifest})
636 or error("failed to encode JSON manifest");
637 grg_encrypt_asymmetric($ctx, $json, sub {
638 push @{$_[0]}
639 , ('--output', File::Spec->catfile($ctx->{'dir-cache'}, $ctx->{'manifest-file'}));
640 return @_; });
641 push @{$ctx->{remote}->{push}}, $ctx->{'manifest-file'};
642 }
643 # grg config
644 sub grg_config_read($) {
645 my ($ctx) = @_;
646 my $cfg = $ctx->{config};
647 local $/ = "\n";
648
649 foreach my $name (qw(gpg signingkey keys)
650 , grep { !m/^(gpg|signingkey|keys)$/ } (keys %$cfg)) {
651 my $value;
652 IPC::Run::run(['git', 'config', '--get', 'remote.'.$ctx->{remote}->{name}.'.'.$name, '.+'], '>', \$value) or
653 IPC::Run::run(['git', 'config', '--get', 'grg.'.$name, '.+'], '>', \$value) or 1;
654 if ($name eq 'signingkey') {
655 IPC::Run::run(['git', 'config', '--get', 'user.'.$name, '.+'], '>', \$value)
656 if (not $value);
657 chomp $value;
658 my %keys = gpg_fingerprint($ctx, $value, ['S']);
659 warning("signing key ID is not matching a unique key: taking only one")
660 unless scalar(keys %keys) == 1;
661 my ($fpr, $uid) = each %keys;
662 $cfg->{$name} = {fpr => $fpr, uid => $uid};
663 }
664 elsif ($name eq 'keys' or $name eq 'hidden-keys') {
665 IPC::Run::run(['git', 'config', '--get', 'user.'.$name, '.+'], '>', \$value)
666 if (not $value);
667 chomp $value;
668 my @ids = split(/,/, $value);
669 if (@ids > 0) {
670 foreach my $key (@ids) {
671 my %keys = gpg_fingerprint($ctx, $key, ['E']);
672 while (my ($fpr, $uid) = each %keys) {
673 $cfg->{$name}->{$fpr} = $uid;
674 }
675 }
676 }
677 }
678 elsif (grep(/^$name$/, qw(curl gpg rsync))) {
679 IPC::Run::run(['git', 'config', '--get', $name.'.program', '.+'], '>', \$value)
680 if (not $value);
681 $cfg->{$name} = [split(' ', $value)]
682 if $value;
683 }
684 else {
685 chomp $value;
686 $cfg->{$name} = $value
687 if $value;
688 }
689 }
690 error("no signingkey configured; to do so you may use one of following commands:\n"
691 , "\t\$ git config remote.'$ctx->{remote}->{name}'.signingkey \$your_openpgp_id\n"
692 , "\t\$ git config grg.signingkey \$your_openpgp_id\n"
693 , "\t\$ git config user.signingkey \$your_openpgp_id"
694 ) unless defined $cfg->{signingkey};
695 if ( (scalar (keys %{$cfg->{keys}}) == 0)
696 and (scalar (keys %{$cfg->{'hidden-keys'}}) == 0) ) {
697 $cfg->{keys} = { $cfg->{signingkey}->{fpr} => $cfg->{signingkey}->{uid} };
698 }
699
700 debug(sub{'config='},$cfg);
701 }
702 # grg system
703 sub grg_connect ($) {
704 my ($ctx) = @_;
705 grg_config_read($ctx);
706 grg_manifest_fetch($ctx);
707 }
708 sub grg_disconnect ($) {
709 my ($ctx) = @_;
710 grg_remote_push($ctx);
711 }
712 # grg commands
713 sub gpg_command_answer ($) {
714 my @cmd = @_;
715 debug(sub{join('', @cmd)."\n"});
716 print STDOUT (@cmd, "\n");
717 }
718 sub grg_command_capabilities ($) {
719 my ($ctx) = @_;
720 $ctx->{command} = 'capabilities';
721 gpg_command_answer("fetch");
722 gpg_command_answer("push");
723 gpg_command_answer("");
724 STDOUT->flush;
725 }
726 sub grg_command_fetch ($$) {
727 my ($ctx, $fetch_refs) = @_;
728 $ctx->{command} = 'fetch';
729 debug(sub{"fetch_refs="}, $fetch_refs);
730 grg_connect($ctx);
731 # @fetch_objects
732 my @fetch_objects= ();
733 foreach my $ref (@$fetch_refs) {
734 push @fetch_objects, $ref->{sha1};
735 }
736 grg_pack_fetch($ctx, \@fetch_objects);
737 }
738 sub grg_command_list ($$) {
739 my ($ctx, $command) = @_;
740 $ctx->{command} = $command;
741 grg_connect($ctx);
742 while (my ($ref, $obj) = each %{$ctx->{manifest}->{refs}}) {
743 gpg_command_answer("$obj $ref");
744 };
745 gpg_command_answer("");
746 }
747 sub grg_command_push ($$) {
748 my ($ctx, $push_refs) = @_;
749 local $_;
750 $ctx->{command} = 'push';
751 debug(sub{"push_refs="}, $push_refs);
752 grg_connect($ctx);
753 # @push_objects
754 my @push_objects= ();
755 foreach my $ref (@$push_refs) {
756 IPC::Run::run(['git', 'rev-list', '--ignore-missing', '--max-count=1', $ref->{src}, '--']
757 , '>', \$_)
758 or error("failed to dereference ref to push: ".$ref->{src});
759 chomp;
760 $ref->{src_obj} = $_;
761 push @push_objects, $_;
762 }
763 grg_pack_push($ctx, \@push_objects);
764 my $manifest_refs = $ctx->{manifest}->{refs};
765 foreach my $ref (@$push_refs) {
766 $manifest_refs->{$ref->{dst}} = $ref->{src_obj};
767 }
768 $manifest_refs->{HEAD}
769 = $push_refs->[-1]->{src_obj}
770 unless exists $manifest_refs->{HEAD}
771 or @$push_refs == 0;
772 grg_manifest_push($ctx);
773 grg_disconnect($ctx);
774 }
775 sub grg_commands(@) {
776 my ($ctx) = @_;
777 my $line = undef;
778 local $/ = "\n";
779 #STDOUT->autoflush(1);
780 while (defined $line or (not eof(*STDIN) and
781 (defined($line = readline(*STDIN)))
782 ? (chomp $line or 1)
783 : error("readline failed: $!")
784 )) {
785 debug(sub{"line=\"",$line,"\"\n"});
786 $ctx->{command} = undef;
787 if ($line eq 'capabilities') {
788 grg_command_capabilities($ctx);
789 $line = undef;
790 }
791 elsif ($line =~ m/^fetch .*$/) {
792 my @refs = ();
793 my ($sha1, $name);
794 while ((defined $line or (not eof(*STDIN) and
795 ((defined($line = readline(*STDIN)))
796 ? (chomp $line or 1)
797 : error("readline failed: $!")))) and
798 (($sha1, $name) = ($line =~ m/^fetch ([0-9a-f]{40}) (.+)$/))
799 ) {
800 debug(sub{"fetch line=\"",$line,"\"\n"});
801 push @refs, {sha1=>$sha1, name=>$name};
802 $line = undef;
803 }
804 error("failed to parse command: $line")
805 if @refs == 0;
806 grg_command_fetch($ctx, \@refs);
807 }
808 elsif ($line eq 'list' or $line eq 'list for-push') {
809 grg_command_list($ctx, $line);
810 $line = undef;
811 }
812 elsif ($line =~ m/^push .*$/) {
813 my @refs = ();
814 my ($force, $src, $dst);
815 while ((defined $line or (not eof(*STDIN) and
816 ((defined($line = readline(*STDIN)))
817 ? (chomp $line or 1)
818 : error("readline failed: $!")))) and
819 (($force, $src, $dst) = ($line =~ m/^push (\+)?([^:]+):(.+)$/))
820 ) {
821 debug(sub{"push line=\"",$line,"\"\n"});
822 push @refs, {force=>(defined $force), src=>$src, dst=>$dst};
823 $line = undef;
824 }
825 error("failed to parse command: $line")
826 if @refs == 0;
827 grg_command_push($ctx, \@refs);
828 }
829 elsif ($line =~ m/^$/) {
830 $line = undef;
831 {
832 local $SIG{'PIPE'} = 'IGNORE';
833 gpg_command_answer("");
834 }
835 return 0;
836 }
837 else {
838 warning("unsupported command supplied: `$line'");
839 $line = undef;
840 }
841 }
842 }
843 sub main {
844 $ENV{GIT_DIR} = $ENV{GIT_DIR} || '.git';
845 $ENV{GITCEPTION} = ($ENV{GITCEPTION} || '') . '+';
846 my $ctx =
847 { command => undef
848 , config =>
849 { curl => ['curl']
850 , gpg => ['gpg']
851 , keys => {}
852 , 'hidden-keys' => {}
853 , 'manifest-hash-algo' => 'SHA224' # NOTE: SHA512, SHA384, SHA256, SHA224 supported.
854 , 'pack-filename-size' => 42
855 , 'pack-hash-algo' => 'SHA224' # NOTE: SHA512, SHA384, SHA256, SHA224 supported.
856 , 'pack-key-size' => 64
857 , signingkey => undef
858 , rsync => ['rsync']
859 }
860 , 'dir-cache' => undef
861 , manifest => {}
862 , 'manifest-file' => undef
863 , remote =>
864 { checking => 0
865 , checked => undef
866 , name => undef
867 , uri => undef
868 , push => []
869 }
870 };
871 Getopt::Long::Configure
872 ( 'auto_version'
873 , 'pass_through'
874 , 'require_order'
875 );
876 Getopt::Long::GetOptions
877 ( help => sub { Pod::Usage::pod2usage
878 ( -exitstatus => 0
879 , -sections => ['SYNOPSIS', 'OPTIONS', 'REMOTES', 'CONFIG']
880 , -verbose => 99 ); }
881 , man => sub { Pod::Usage::pod2usage(-verbose => 2); }
882 , check => sub {
883 $ctx->{remote}->{checking} = 1;
884 }
885 );
886 if (not $ctx->{remote}->{checking}) {
887 my $name = shift @ARGV;
888 Pod::Usage::pod2usage(-verbose => 1)
889 unless defined $name;
890 ($ctx->{remote}->{name}) = ($name =~ m/^((\w|-)+)$/);
891 error("valid name of remote Git required, got: `$name'")
892 unless $ctx->{remote}->{name};
893 }
894 my $uri = shift @ARGV;
895 Pod::Usage::pod2usage(-verbose => 1)
896 unless defined $uri;
897 $ctx->{remote}->{uri} = URI->new($uri);
898 error("valid URL of remote Git required, got: `$uri'")
899 unless $ctx->{remote}->{uri};
900 my $fragment = $ctx->{remote}->{uri}->fragment;
901 $fragment = ''
902 unless defined $fragment;
903 $ctx->{'manifest-file'} = grg_hash($ctx
904 , $ctx->{config}->{'manifest-hash-algo'}
905 , sub { return (@_, '<', \$fragment); });
906 if (-d $ENV{GIT_DIR}) {
907 $ctx->{'dir-cache'} = File::Spec->catdir
908 ( $ENV{GIT_DIR}, 'cache', 'remotes'
909 , $ctx->{remote}->{name}, 'gpg');
910 &mkdir($ctx->{'dir-cache'});
911 }
912 else {
913 $ctx->{'dir-cache'} = File::Temp->tempdir('grg_cache_XXXXXXXX', CLEANUP => 1);
914 }
915 debug(sub{"ctx="},$ctx);
916 grg_commands($ctx);
917 }
918 main;
919 1;
920 __END__
921
922 =encoding utf8
923
924 =head1 NAME
925
926 git-remote-gpg - git-remote-helpers(1) to encrypt remote repository through gpg(1)
927
928 =head1 SYNOPSIS
929
930 =item git-remote-gpg $gpg_remote $gpg_url
931
932 =item git-remote-gpg --check $gpg_url
933
934 =head1 OPTIONS
935
936 =over 8
937
938 =item B<-h>, B<--help>
939
940 =item B<--version>
941
942 =back
943
944 =head1 REMOTES
945
946 =head2 Via rsync(1)
947
948 =item git remote add $remote gpg::rsync:${user:+$user@}$host:$path
949
950 =item git remote add $remote gpg::rsync://${user:+$user@}$host${port:+:$port}/$path
951
952 =head2 Via curl(1)
953
954 =item git remote add $remote gpg::sftp://${user:+$user@}$host${port:+:$port}/$path
955
956 =head2 Via File::Copy(3pm)
957
958 =item git remote add $remote gpg::file://$path
959
960 =head1 CONFIG
961
962 =head2 git-config(1)
963
964 =over 8
965
966 =item B<grg.curl>
967
968 =item B<grg.gpg>
969
970 =item B<grg.keys>
971
972 =item B<grg.hidden-keys>
973
974 =item B<grg.manifest-hash-algo>
975
976 =item B<grg.pack-filename-size>
977
978 =item B<grg.pack-hash-algo>
979
980 =item B<grg.pack-key-size>
981
982 =item B<grg.signingkey>
983
984 =item B<grg.rsync>
985
986 =back
987
988 =cut