]> Git — Sourcephile - git-remote-gpg.git/blob - git-remote-gpg
fix useless re-fetching manifest
[git-remote-gpg.git] / git-remote-gpg
1 #!/usr/bin/perl
2 our $VERSION = '2014.04.29';
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 (-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 $run = sub {return @_} unless defined $run;
177 IPC::Run::run($run->([@{$ctx->{config}->{gpg}}
178 , '--batch', '--no-default-keyring', '--keyring', '/dev/null', '--secret-keyring', '/dev/null'
179 , '--passphrase-fd', '3', '--quiet', '--decrypt']
180 , '3<', \$key))
181 or error("failed to decrypt symmetrically data");
182 }
183 sub grg_encrypt_asymmetric ($$;$) {
184 my ($ctx, $clear, $run) = @_;
185 $run = sub {return @_} unless defined $run;
186 my @recipients =
187 ( (map { ('--recipient', '0x'.$_) } (keys %{$ctx->{config}->{keys}}))
188 , (map { ('--hidden-recipient', '0x'.$_) } (keys %{$ctx->{config}->{'hidden-keys'}})) );
189 @recipients = ('--default-recipient-self')
190 if @recipients == 0;
191 IPC::Run::run($run->([@{$ctx->{config}->{gpg}}
192 , '--batch', '--yes'
193 , '--compress-algo', 'none'
194 , '--trust-model', 'always'
195 , '--sign', '--encrypt'
196 , ($ctx->{config}->{signingkey}->{fpr} ? ('--local-user', $ctx->{config}->{signingkey}->{fpr}) : ())
197 , @recipients ]
198 , '<', \$clear))
199 or error("failed to encrypt asymmetrically data");
200 }
201 sub grg_decrypt_asymmetric ($$;$) {
202 my ($ctx, $run) = @_;
203 my ($clear, $status);
204 $run = sub {return @_} unless defined $run;
205 IPC::Run::run($run->([@{$ctx->{config}->{gpg}}
206 , '--batch', '--no-default-keyring',
207 , '--status-fd', '3', '--quiet', '--decrypt']
208 , '>', \$clear, '3>', \$status))
209 or error("failed to decrypt asymmetrically data");
210 debug(sub{"status=\n$status"});
211 my @lines = split(/\n/,$status);
212 my ($enc_to, $goodsig, $validsig, $validpub, $goodmdc);
213 foreach my $line (@lines) {
214 (not defined $enc_to and (($enc_to) = $line =~ m/^\[GNUPG:\] ENC_TO ([0-9A-F]+).*$/)) or
215 (not defined $goodsig and (($goodsig) = $line =~ m/^\[GNUPG:\] GOODSIG ([0-9A-F]+).*$/)) or
216 (not defined $goodmdc and (($goodmdc) = $line =~ m/^\[GNUPG:\] (GOODMDC)$/)) or
217 (not defined $validsig and not defined $validpub and (($validsig, $validpub)
218 = $line =~ m/^\[GNUPG:\] VALIDSIG ([0-9A-F]+) [^ ]+ [^ ]+ [^ ]+ [^ ]+ [^ ]+ [^ ]+ [^ ]+ [^ ]+ ([0-9A-F]+).*$/)) or
219 1;
220 }
221 error("data expected to be encrypted")
222 unless $enc_to;
223 debug(sub{"enc_to=$enc_to\n"});
224 error("data expected to be signed")
225 unless $goodsig;
226 debug(sub{"goodsig=$goodsig\n"});
227 error("modification detection code incorrect")
228 unless $goodmdc;
229 debug(sub{"good_mdc=$goodmdc\n"});
230 error("data signature invalid")
231 unless $validsig and $validpub;
232 debug(sub{"validsig=$validsig\n"});
233 debug(sub{"validpub=$validpub\n"});
234 error("data signature refused")
235 unless exists $ctx->{config}->{keys}->{$validpub}
236 or exists $ctx->{config}->{'hidden-keys'}->{$validpub};
237 debug(sub{"accepted:$validpub\n"});
238 return $clear;
239 }
240 # grg remote I/O
241 # XXX: there is no locking mechanism
242 sub grg_remote_fetch_file ($) {
243 my ($ctx) = @_;
244 # NOTE: avoid File::Copy::copy().
245 while (my ($file, undef) = each %{$ctx->{remote}->{fetch}}) {
246 my $path = File::Spec->catfile($ctx->{remote}->{uri}->file, $file);
247 if (-r $path) {
248 my $h = $ctx->{remote}->{fetch}->{$file};
249 $h->{path} = $path;
250 $h->{preserve} = 1;
251 }
252 else { return 0; }
253 }
254 return 1;
255 }
256 sub grg_remote_fetch_rsync ($) {
257 my ($ctx) = @_;
258 my $uri = $ctx->{remote}->{uri}->clone;
259 my @src;
260 if ($uri->opaque =~ m{^//}) {
261 $uri->fragment(undef);
262 $uri->query(undef);
263 @src = map { $uri->path($_); $uri->as_string; }
264 (keys %{$ctx->{remote}->{fetch}});
265 }
266 else {
267 my ($authority, $path, $fragment)
268 = $uri->as_string =~ m|^rsync:(?:([^/#:]+):)?([^?#]*)(?:#(.*))?$|;
269 @src = map { "$authority:$path/$_" }
270 (keys %{$ctx->{remote}->{fetch}});
271 }
272 IPC::Run::run([@{$ctx->{config}->{rsync}}
273 , '-i', '--ignore-times', '--inplace', '--progress'
274 , @src
275 , $ctx->{'dir-cache'}.'/']
276 , '>&2')
277 }
278 sub grg_remote_fetch_sftp ($) {
279 my ($ctx) = @_;
280 IPC::Run::run([@{$ctx->{config}->{curl}}
281 , '--show-error'
282 , '--output', File::Spec->catfile($ctx->{'dir-cache'}, '#1')
283 , $ctx->{remote}->{uri}->as_string.'/'.'{'.join(',', (keys %{$ctx->{remote}->{fetch}})).'}' ]
284 , '>&2')
285 }
286 sub grg_remote_fetch ($$) {
287 my ($ctx, $files) = @_;
288 debug(sub{'files='}, $files);
289 my $scheme = $ctx->{remote}->{uri}->scheme;
290 $ctx->{remote}->{fetch}
291 = {map { $_ =>
292 { path => File::Spec->catfile($ctx->{'dir-cache'}, $_)
293 , preserve => 0 }
294 } @$files};
295 my $fct =
296 { file => \&grg_remote_fetch_file
297 , rsync => \&grg_remote_fetch_rsync
298 , sftp => \&grg_remote_fetch_sftp
299 }->{$scheme};
300 error("URL scheme not supported: `$scheme'")
301 unless $fct;
302 $fct->($ctx)
303 or $ctx->{remote}->{fetch} = {};
304 return $ctx->{remote}->{fetch};
305 }
306 sub grg_remote_init_file ($) {
307 my ($ctx) = @_;
308 my $dst = $ctx->{remote}->{uri}->file;
309 &mkdir($dst);
310 return 1;
311 }
312 sub grg_remote_init_rsync ($) {
313 my ($ctx) = @_;
314 my $tmp = File::Temp->tempdir('grg_rsync_XXXXXXXX', CLEANUP => 1);
315 my $uri = $ctx->{remote}->{uri}->clone;
316 my ($path, $dst);
317 if ($uri->opaque =~ m{^//}) {
318 $uri->fragment(undef);
319 $uri->query(undef);
320 $path = $uri->path;
321 $dst = $uri->as_string;
322 }
323 else {
324 my ($authority, $fragment);
325 ($authority, $path, $fragment)
326 = $uri->as_string =~ m|^rsync:(?:([^/#:]+):)?([^?#]*)(?:#(.*))?$|;
327 $dst = "$authority:";
328 }
329 &mkdir(File::Spec->catdir($tmp, $path));
330 IPC::Run::run([@{$ctx->{config}->{rsync}}
331 , '-i', '--recursive', '--relative'
332 , '--exclude=*', '.'
333 , $dst]
334 , '>&2'
335 , init => sub { chdir $tmp or die $!; })
336 }
337 sub grg_remote_init_sftp ($) {
338 my ($ctx) = @_;
339 my $uri = $ctx->{remote}->{uri}->clone;
340 my ($path) = $uri->path =~ m|^/?(.*)$|;
341 $uri->fragment(undef);
342 $uri->path(undef);
343 $uri->query(undef);
344 IPC::Run::run([@{$ctx->{config}->{curl}}
345 , '--show-error', '--ftp-create-dirs'
346 , '-Q', "+mkdir ".$path
347 , $uri->as_string]
348 , '>&2')
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(undef);
405 $uri->query(undef);
406 IPC::Run::run([@{$ctx->{config}->{curl}}
407 , '--show-error', '--ftp-create-dirs', '--upload-file'
408 , File::Spec->catfile($ctx->{'dir-cache'},'{'.join(',', @{$ctx->{remote}->{push}}).'}')
409 , $uri->as_string.'/']
410 , '>&2')
411 }
412 sub grg_remote_push ($) {
413 my ($ctx) = @_;
414 my $scheme = $ctx->{remote}->{uri}->scheme;
415 grg_remote_init($ctx)
416 unless $ctx->{remote}->{checked};
417 return 1
418 if @{$ctx->{remote}->{push}} == 0;
419 my $fct =
420 { file => \&grg_remote_push_file
421 , rsync => \&grg_remote_push_rsync
422 , sftp => \&grg_remote_push_sftp
423 }->{$scheme};
424 error("URL scheme not supported: `$scheme'")
425 unless $fct;
426 $fct->($ctx)
427 or error("remote push failed");
428 rm(map {File::Spec->catfile($ctx->{'dir-cache'}, $_)} @{$ctx->{remote}->{push}});
429 return 1;
430 }
431 sub grg_remote_remove ($) {
432 my ($ctx) = @_;
433 #my $scheme = $ctx->{remote}->{uri}->scheme;
434 #my $fct =
435 # { file => sub {
436 # File::Copy::remove_tree
437 # ( map { File::Spec->catfile($ctx->{remote}->{uri}->path, $_) } @$files
438 # , verbose => 1 )
439 # }
440 # , rsync => sub {
441 # IPC::Run::run([@{$ctx->{config}->{rsync}}
442 # , '--verbose', '--ignore-times', '--recursive', '--delete'
443 # , @$files
444 # , $ctx->{remote}->{uri}])
445 # }
446 # , sftp => sub {
447 # IPC::Run::run([@{$ctx->{config}->{curl}}
448 # , '--show-error'
449 # , map { ('-Q', 'rm '.$_) } @$files
450 # , $ctx->{remote}->{uri}])
451 # }
452 # }->{$scheme};
453 #error("URL scheme not supported: `$scheme'")
454 # unless $fct;
455 #$fct->($ctx, $ctx->{remote}->{remove})
456 # or error("remote remove failed");
457 #return;
458 }
459 # grg packing
460 sub grg_pack_fetch ($$) {
461 my ($ctx, $fetch_objects) = @_;
462 local $_;
463 # %remote_objects
464 my %remote_objects = ();
465 while (my ($pack_id, $pack) = each %{$ctx->{manifest}->{packs}}) {
466 foreach my $obj (@{$pack->{objects}}) {
467 $remote_objects{$obj} = $pack_id;
468 }
469 }
470 # @packs_to_fetch
471 my %packs_to_fetch = ();
472 foreach my $obj (@$fetch_objects) {
473 my @packs = ($remote_objects{$obj});
474 while (my $pack_id = shift @packs) {
475 if (not exists $packs_to_fetch{$pack_id}) {
476 $packs_to_fetch{$pack_id} = 1;
477 my $manifest_pack = $ctx->{manifest}->{packs}->{$pack_id};
478 error("manifest is missing a dependency pack: $pack_id")
479 unless defined $manifest_pack;
480 @packs = (@packs, @{$manifest_pack->{deps}});
481 }
482 }
483 }
484 my @packs_to_fetch = keys %packs_to_fetch;
485 my $packs_fetched = grg_remote_fetch($ctx, [@packs_to_fetch]);
486 foreach my $pack_id (@packs_to_fetch) {
487 my $pack_fetched
488 = exists $packs_fetched->{$pack_id}
489 ? $packs_fetched->{$pack_id}
490 : {path => File::Spec->catfile($ctx->{'dir-cache'}, $pack_id), preserve => 0};
491 my $manifest_pack = $ctx->{manifest}->{packs}->{$pack_id};
492 my $pack_key = $manifest_pack->{key};
493 my $pack_data;
494 grg_decrypt_symmetric($ctx, $pack_key, sub {
495 push @{$_[0]}, ($pack_fetched->{path});
496 return (@_, '>', \$pack_data);
497 });
498 my $pack_hash_algo = $manifest_pack->{hash_algo};
499 my $pack_hash = grg_hash($ctx
500 , $pack_hash_algo
501 , sub { return (@_, '<', \$pack_data); });
502 error("pack data hash differs from pack manifest hash")
503 unless $pack_hash eq $manifest_pack->{hash};
504 rm($pack_fetched->{path})
505 unless $pack_fetched->{preserve};
506 IPC::Run::run(['git', 'index-pack', '-v', '--stdin']
507 , '<', \$pack_data
508 , '>&2');
509 }
510 }
511 sub grg_pack_push ($$) {
512 my ($ctx, $push_objects) = @_;
513 local $_;
514 debug(sub{"push_objects=\n"}, $push_objects);
515 # %remote_objects
516 my %remote_objects = ();
517 while (my ($pack_id, $pack) = each %{$ctx->{manifest}->{packs}}) {
518 foreach my $obj (@{$pack->{objects}}) {
519 $remote_objects{$obj} = $pack_id;
520 }
521 }
522 # @common_objects
523 IPC::Run::run(['git', 'cat-file', '--batch-check']
524 , '<', \join("\n", keys %remote_objects)
525 , '>', \$_)
526 or error("failed to query local git objects");
527 my @common_objects
528 = map {
529 if ($_ =~ m/ missing$/) { () }
530 else { s/ .*//; $_ }
531 } (split(/\n/, $_));
532 # @pack_objects, @pack_deps_objects
533 IPC::Run::run(['git', 'rev-list', '--objects-edge', '--stdin', '--']
534 , '<', \join("\n", ((map {'^'.$_} @common_objects), @$push_objects))
535 , '>', \$_)
536 or error("failed to query objects to pack");
537 my @pack_objects_edge = split(/\n/, $_);
538 foreach (@pack_objects_edge) {s/ .*//}
539 my @pack_objects = grep {m/^[^-]/} @pack_objects_edge;
540 my @pack_deps_objects = grep {s/^-//} @pack_objects_edge;
541 # %pack_deps
542 my %pack_deps = ();
543 foreach my $obj (@pack_deps_objects) {
544 my $pack = $remote_objects{$obj};
545 error("manifest is missing object dependencies")
546 unless defined $pack;
547 $pack_deps{$pack} = 1;
548 }
549 if (@pack_objects > 0) {
550 # $pack_id
551 my $pack_id;
552 my $pack_id_try = 0;
553 while (not defined $pack_id
554 or exists $ctx->{manifest}->{packs}->{$pack_id}) {
555 $pack_id = grg_rand($ctx, $ctx->{config}->{'pack-filename-size'});
556 $pack_id =~ s{/}{-}g;
557 error("failed to pick an unused random pack filename after 512 tries; retry or increase grg.pack-filename-size")
558 if $pack_id_try++ >= 512;
559 }
560 my $pack_key = grg_rand($ctx, $ctx->{config}->{'pack-key-size'});
561 my $pack_data;
562 IPC::Run::run(['git', 'pack-objects', '--stdout']
563 , '<', \join("\n", @pack_objects)
564 , '>', \$pack_data)
565 or error("failed to pack objects to push");
566 my $pack_hash = grg_hash($ctx
567 , $ctx->{config}->{'pack-hash-algo'}
568 , sub { return (@_, '<', \$pack_data); });
569 grg_encrypt_symmetric($ctx, $pack_data, $pack_key, sub {
570 push @{$_[0]}, ('--output', File::Spec->catfile($ctx->{'dir-cache'}, $pack_id));
571 return @_;
572 });
573 push @{$ctx->{remote}->{push}}, $pack_id;
574 $ctx->{manifest}->{packs}->{$pack_id} =
575 { deps => [keys %pack_deps]
576 , hash => $pack_hash
577 , hash_algo => $ctx->{config}->{'pack-hash-algo'}
578 , key => $pack_key
579 , objects => \@pack_objects
580 };
581 }
582 }
583 # grg manifest
584 sub grg_manifest_fetch ($) {
585 my ($ctx) = @_;
586 debug(sub{'remote->checked='},$ctx->{remote}->{checked});
587 return
588 if defined $ctx->{remote}->{checked};
589 $ctx->{manifest} =
590 { 'hidden-keys' => {}
591 , keys => {}
592 , packs => {}
593 , refs => {}
594 , version => $VERSION
595 };
596 my $fetched = grg_remote_fetch($ctx, [$ctx->{'manifest-file'}]);
597 my $crypt = $fetched->{$ctx->{'manifest-file'}}->{path};
598 if (defined $crypt) {
599 my $json;
600 grg_decrypt_asymmetric($ctx, sub {
601 push @{$_[0]}, $crypt;
602 return (@_, '>', \$json); });
603 my $manifest;
604 ($manifest = JSON::decode_json($json) and ref $manifest eq 'HASH')
605 or error("failed to decode JSON manifest");
606 $ctx->{remote}->{checked} = 1;
607 rm($fetched->{$ctx->{'manifest-file'}}->{path})
608 unless $fetched->{$ctx->{'manifest-file'}}->{preserve};
609 $ctx->{manifest} = {%{$ctx->{manifest}}, %$manifest};
610 foreach my $slot (qw(keys hidden-keys)) {
611 while (my ($fpr, $uid) = each %{$ctx->{manifest}->{$slot}}) {
612 my %keys = gpg_fingerprint($ctx, '0x'.$fpr, ['E']);
613 my ($fpr, $uid) = each %keys;
614 $ctx->{config}->{$slot}->{$fpr} = $uid;
615 }
616 }
617 }
618 else {
619 if ($ctx->{command} eq 'push' or $ctx->{command} eq 'list for-push') {
620 $ctx->{remote}->{checked} = 0;
621 }
622 elsif ($ctx->{remote}->{checking}) {
623 exit 100;
624 }
625 else {
626 error("remote checking failed");
627 }
628 }
629 }
630 sub grg_manifest_push ($) {
631 my ($ctx) = @_;
632 foreach my $slot (qw(keys hidden-keys)) {
633 $ctx->{manifest}->{$slot} = {};
634 while (my ($fpr, $uid) = each %{$ctx->{config}->{$slot}}) {
635 $ctx->{manifest}->{$slot}->{$fpr} = $uid;
636 }
637 }
638 my $json = JSON::encode_json($ctx->{manifest})
639 or error("failed to encode JSON manifest");
640 grg_encrypt_asymmetric($ctx, $json, sub {
641 push @{$_[0]}
642 , ('--output', File::Spec->catfile($ctx->{'dir-cache'}, $ctx->{'manifest-file'}));
643 return @_; });
644 push @{$ctx->{remote}->{push}}, $ctx->{'manifest-file'};
645 }
646 # grg config
647 sub grg_config_read($) {
648 my ($ctx) = @_;
649 my $cfg = $ctx->{config};
650 local $/ = "\n";
651
652 foreach my $name (qw(gpg signingkey keys)
653 , grep { !m/^(gpg|signingkey|keys)$/ } (keys %$cfg)) {
654 my $value;
655 IPC::Run::run(['git', 'config', '--get', 'remote.'.$ctx->{remote}->{name}.'.'.$name, '.+'], '>', \$value) or
656 IPC::Run::run(['git', 'config', '--get', 'grg.'.$name, '.+'], '>', \$value) or 1;
657 if ($name eq 'signingkey') {
658 IPC::Run::run(['git', 'config', '--get', 'user.'.$name, '.+'], '>', \$value)
659 if (not $value);
660 chomp $value;
661 my %keys = gpg_fingerprint($ctx, $value, ['S']);
662 warning("signing key ID is not matching a unique key: taking only one")
663 unless scalar(keys %keys) == 1;
664 my ($fpr, $uid) = each %keys;
665 $cfg->{$name} = {fpr => $fpr, uid => $uid};
666 }
667 elsif ($name eq 'keys' or $name eq 'hidden-keys') {
668 IPC::Run::run(['git', 'config', '--get', 'user.'.$name, '.+'], '>', \$value)
669 if (not $value);
670 chomp $value;
671 my @ids = split(/,/, $value);
672 if (@ids > 0) {
673 foreach my $key (@ids) {
674 my %keys = gpg_fingerprint($ctx, $key, ['E']);
675 while (my ($fpr, $uid) = each %keys) {
676 $cfg->{$name}->{$fpr} = $uid;
677 }
678 }
679 }
680 }
681 elsif (grep(/^$name$/, qw(curl gpg rsync))) {
682 IPC::Run::run(['git', 'config', '--get', $name.'.program', '.+'], '>', \$value)
683 if (not $value);
684 $cfg->{$name} = [split(' ', $value)]
685 if $value;
686 }
687 else {
688 chomp $value;
689 $cfg->{$name} = $value
690 if $value;
691 }
692 }
693 error("no signingkey configured; to do so you may use one of following commands:\n"
694 , "\t\$ git config remote.'$ctx->{remote}->{name}'.signingkey \$your_openpgp_id\n"
695 , "\t\$ git config grg.signingkey \$your_openpgp_id\n"
696 , "\t\$ git config user.signingkey \$your_openpgp_id"
697 ) unless defined $cfg->{signingkey};
698 if ( (scalar (keys %{$cfg->{keys}}) == 0)
699 and (scalar (keys %{$cfg->{'hidden-keys'}}) == 0) ) {
700 $cfg->{keys} = { $cfg->{signingkey}->{fpr} => $cfg->{signingkey}->{uid} };
701 }
702
703 debug(sub{'config='},$cfg);
704 }
705 # grg system
706 sub grg_connect ($) {
707 my ($ctx) = @_;
708 grg_config_read($ctx);
709 grg_manifest_fetch($ctx);
710 }
711 sub grg_disconnect ($) {
712 my ($ctx) = @_;
713 grg_remote_push($ctx);
714 }
715 # grg commands
716 sub gpg_command_answer ($) {
717 my @cmd = @_;
718 debug(sub{join('', @cmd)."\n"});
719 print STDOUT (@cmd, "\n");
720 }
721 sub grg_command_capabilities ($) {
722 my ($ctx) = @_;
723 $ctx->{command} = 'capabilities';
724 gpg_command_answer("fetch");
725 gpg_command_answer("push");
726 gpg_command_answer("");
727 STDOUT->flush;
728 }
729 sub grg_command_fetch ($$) {
730 my ($ctx, $fetch_refs) = @_;
731 $ctx->{command} = 'fetch';
732 debug(sub{"fetch_refs="}, $fetch_refs);
733 grg_connect($ctx);
734 # @fetch_objects
735 my @fetch_objects= ();
736 foreach my $ref (@$fetch_refs) {
737 push @fetch_objects, $ref->{sha1};
738 }
739 grg_pack_fetch($ctx, \@fetch_objects);
740 }
741 sub grg_command_list ($$) {
742 my ($ctx, $command) = @_;
743 $ctx->{command} = $command;
744 grg_connect($ctx);
745 my $manifest_refs = $ctx->{manifest}->{refs};
746 while (my ($ref, $obj) = each %$manifest_refs) {
747 if ($obj =~ m|^ref: *(.*) *$|) {
748 $obj = $manifest_refs->{$1};
749 }
750 gpg_command_answer("$obj $ref")
751 if defined $obj;
752 };
753 gpg_command_answer("");
754 }
755 sub grg_command_push ($$) {
756 my ($ctx, $push_refs) = @_;
757 local $_;
758 $ctx->{command} = 'push';
759 debug(sub{"push_refs="}, $push_refs);
760 grg_connect($ctx);
761 # @push_objects
762 my @push_objects= ();
763 foreach my $ref (@$push_refs) {
764 IPC::Run::run(['git', 'rev-list', '--ignore-missing', '--max-count=1', $ref->{src}, '--']
765 , '>', \$_)
766 or error("failed to dereference ref to push: ".$ref->{src});
767 chomp;
768 $ref->{src_obj} = $_;
769 push @push_objects, $_;
770 }
771 grg_pack_push($ctx, \@push_objects);
772 my $manifest_refs = $ctx->{manifest}->{refs};
773 foreach my $ref (@$push_refs) {
774 $manifest_refs->{$ref->{dst}} = $ref->{src_obj};
775 }
776 $manifest_refs->{HEAD} = 'ref: refs/heads/master'
777 unless defined $manifest_refs->{HEAD};
778 grg_manifest_push($ctx);
779 grg_disconnect($ctx);
780 }
781 sub grg_commands(@) {
782 my ($ctx) = @_;
783 my $line = undef;
784 local $/ = "\n";
785 #STDOUT->autoflush(1);
786 while (defined $line or (not eof(*STDIN) and
787 (defined($line = readline(*STDIN)))
788 ? (chomp $line or 1)
789 : error("readline failed: $!")
790 )) {
791 debug(sub{"line=\"",$line,"\"\n"});
792 $ctx->{command} = undef;
793 if ($line eq 'capabilities') {
794 grg_command_capabilities($ctx);
795 $line = undef;
796 }
797 elsif ($line =~ m/^fetch .*$/) {
798 my @refs = ();
799 my ($sha1, $name);
800 while ((defined $line or (not eof(*STDIN) and
801 ((defined($line = readline(*STDIN)))
802 ? (chomp $line or 1)
803 : error("readline failed: $!")))) and
804 (($sha1, $name) = ($line =~ m/^fetch ([0-9a-f]{40}) (.+)$/))
805 ) {
806 debug(sub{"fetch line=\"",$line,"\"\n"});
807 push @refs, {sha1=>$sha1, name=>$name};
808 $line = undef;
809 }
810 error("failed to parse command: $line")
811 if @refs == 0;
812 grg_command_fetch($ctx, \@refs);
813 }
814 elsif ($line eq 'list' or $line eq 'list for-push') {
815 grg_command_list($ctx, $line);
816 $line = undef;
817 }
818 elsif ($line =~ m/^push .*$/) {
819 my @refs = ();
820 my ($force, $src, $dst);
821 while ((defined $line or (not eof(*STDIN) and
822 ((defined($line = readline(*STDIN)))
823 ? (chomp $line or 1)
824 : error("readline failed: $!")))) and
825 (($force, $src, $dst) = ($line =~ m/^push (\+)?([^:]+):(.+)$/))
826 ) {
827 debug(sub{"push line=\"",$line,"\"\n"});
828 push @refs, {force=>(defined $force), src=>$src, dst=>$dst};
829 $line = undef;
830 }
831 error("failed to parse command: $line")
832 if @refs == 0;
833 grg_command_push($ctx, \@refs);
834 }
835 elsif ($line =~ m/^$/) {
836 $line = undef;
837 {
838 local $SIG{'PIPE'} = 'IGNORE';
839 gpg_command_answer("");
840 }
841 return 0;
842 }
843 else {
844 warning("unsupported command supplied: `$line'");
845 $line = undef;
846 }
847 }
848 }
849 sub main {
850 $ENV{GIT_DIR} = $ENV{GIT_DIR} || '.git';
851 $ENV{GITCEPTION} = ($ENV{GITCEPTION} || '') . '+';
852 my $ctx =
853 { command => undef
854 , config =>
855 { curl => ['curl']
856 , gpg => ['gpg']
857 , keys => {}
858 , 'hidden-keys' => {}
859 , 'manifest-hash-algo' => 'SHA224' # NOTE: SHA512, SHA384, SHA256, SHA224 supported.
860 , 'pack-filename-size' => 42
861 , 'pack-hash-algo' => 'SHA224' # NOTE: SHA512, SHA384, SHA256, SHA224 supported.
862 , 'pack-key-size' => 64
863 , signingkey => undef
864 , rsync => ['rsync']
865 }
866 , 'dir-cache' => undef
867 , manifest => undef
868 , 'manifest-file' => undef
869 , remote =>
870 { checking => 0
871 , checked => undef
872 , name => undef
873 , uri => undef
874 , push => []
875 }
876 };
877 Getopt::Long::Configure
878 ( 'auto_version'
879 , 'pass_through'
880 , 'require_order'
881 );
882 Getopt::Long::GetOptions
883 ( help => sub { Pod::Usage::pod2usage
884 ( -exitstatus => 0
885 , -sections => ['SYNOPSIS', 'OPTIONS', 'REMOTES', 'CONFIG']
886 , -verbose => 99 ); }
887 , man => sub { Pod::Usage::pod2usage(-verbose => 2); }
888 , check => sub {
889 $ctx->{remote}->{checking} = 1;
890 }
891 );
892 if (not $ctx->{remote}->{checking}) {
893 my $name = shift @ARGV;
894 Pod::Usage::pod2usage(-verbose => 1)
895 unless defined $name;
896 ($ctx->{remote}->{name}) = ($name =~ m/^((\w|-)+)$/);
897 error("valid name of remote Git required, got: `$name'")
898 unless $ctx->{remote}->{name};
899 }
900 my $uri = shift @ARGV;
901 Pod::Usage::pod2usage(-verbose => 1)
902 unless defined $uri;
903 $ctx->{remote}->{uri} = URI->new($uri);
904 error("valid URL of remote Git required, got: `$uri'")
905 unless $ctx->{remote}->{uri};
906 my $fragment = $ctx->{remote}->{uri}->fragment;
907 $fragment = ''
908 unless defined $fragment;
909 $ctx->{'manifest-file'} = grg_hash($ctx
910 , $ctx->{config}->{'manifest-hash-algo'}
911 , sub { return (@_, '<', \$fragment); });
912 if (-d $ENV{GIT_DIR}) {
913 $ctx->{'dir-cache'} = File::Spec->catdir
914 ( $ENV{GIT_DIR}, 'cache', 'remotes'
915 , $ctx->{remote}->{name}, 'gpg');
916 &mkdir($ctx->{'dir-cache'});
917 }
918 else {
919 $ctx->{'dir-cache'} = File::Temp->tempdir('grg_cache_XXXXXXXX', CLEANUP => 1);
920 }
921 debug(sub{"ctx="},$ctx);
922 grg_commands($ctx);
923 }
924 main;
925 1;
926 __END__
927
928 =encoding utf8
929
930 =head1 NAME
931
932 git-remote-gpg - git-remote-helpers(1) to encrypt remote repository through gpg(1)
933
934 =head1 SYNOPSIS
935
936 =item git-remote-gpg $gpg_remote $gpg_url
937
938 =item git-remote-gpg --check $gpg_url
939
940 =head1 OPTIONS
941
942 =over 8
943
944 =item B<-h>, B<--help>
945
946 =item B<--version>
947
948 =back
949
950 =head1 REMOTES
951
952 =head2 Via rsync(1)
953
954 =item git remote add $remote gpg::rsync:${user:+$user@}$host:$path
955
956 =item git remote add $remote gpg::rsync://${user:+$user@}$host${port:+:$port}/$path
957
958 =head2 Via curl(1)
959
960 =item git remote add $remote gpg::sftp://${user:+$user@}$host${port:+:$port}/$path
961
962 =head2 Via File::Copy(3pm)
963
964 =item git remote add $remote gpg::file://$path
965
966 =head1 CONFIG
967
968 =head2 git-config(1)
969
970 =over 8
971
972 =item B<grg.curl>, B<remote.$remote.curl>
973
974 =item B<grg.gpg>, B<remote.$remote.gpg>
975
976 =item B<grg.keys>, B<remote.$remote.keys>
977
978 =item B<grg.hidden-keys>, B<remote.$remote.hidden-keys>
979
980 =item B<grg.manifest-hash-algo>, B<remote.$remote.manifest-hash-algo>
981
982 =item B<grg.pack-filename-size>, B<remote.$remote.pack-filename-size>
983
984 =item B<grg.pack-hash-algo>, B<remote.$remote.pack-hash-algo>
985
986 =item B<grg.pack-key-size>, B<remote.$remote.pack-key-size>
987
988 =item B<grg.signingkey>, B<remote.$remote.signingkey>
989
990 =item B<grg.rsync>, B<remote.$remote.rsync>
991
992 =back
993
994 =cut