5 # .../dgit-repos-server DISTRO SUITES KEYRING-AUTH-SPEC \
6 # DGIT-REPOS-DIR POLICY-HOOK-SCRIPT --ssh
8 # .../dgit-repos-server --pre-receive-hook PACKAGE
10 # Invoked as the ssh restricted command
12 # Works like git-receive-pack
14 # SUITES is the name of a file which lists the permissible suites
15 # one per line (#-comments and blank lines ignored)
17 # KEYRING-AUTH-SPEC is a :-separated list of
18 # KEYRING.GPG,AUTH-SPEC
19 # where AUTH-SPEC is one of
25 # DGIT-REPOS-DIR contains:
26 # git tree (or other object) lock (in acquisition order, outer first)
28 # _tmp/PACKAGE_prospective ! } SAME.lock, held during receive-pack
30 # _tmp/PACKAGE_incoming$$ ! } SAME.lock, held during receive-pack
31 # _tmp/PACKAGE_incoming$$_fresh ! }
33 # PACKAGE.git } PACKAGE.git.lock
34 # PACKAGE_garbage } (also covers executions of
35 # PACKAGE_garbage-old } policy hook script for PACKAGE)
36 # PACKAGE_garbage-tmp }
38 # leaf locks, held during brief operaton only:
43 # _template } SAME.lock
45 # locks marked ! may be held during client data transfer
47 # What we do on push is this:
48 # - extract the destination repo name
49 # - make a hardlink clone of the destination repo
50 # - provide the destination with a stunt pre-receive hook
51 # - run actual git-receive-pack with that new destination
52 # as a result of this the stunt pre-receive hook runs; it does this:
53 # + understand what refs we are allegedly updating and
54 # check some correspondences:
55 # * we are updating only refs/tags/debian/* and refs/dgit/*
56 # * and only one of each
57 # * and the tag does not already exist
59 # * recover the suite name from the destination refs/dgit/ ref
60 # + disassemble the signed tag into its various fields and signature
62 # * parsing the first line of the tag message to recover
63 # the package name, version and suite
64 # * checking that the package name corresponds to the dest repo name
65 # * checking that the suite name is as recovered above
66 # + verify the signature on the signed tag
67 # and if necessary check that the keyid and package are listed in dm.txt
68 # + check various correspondences:
69 # * the signed tag must refer to a commit
70 # * the signed tag commit must be the refs/dgit value
71 # * the name in the signed tag must correspond to its ref name
72 # * the tag name must be debian/<version> (massaged as needed)
73 # * the suite is one of those permitted
74 # * the signed tag has a suitable name
75 # * run the "push" policy hook
76 # * replay prevention for --deliberately-not-fast-forward
77 # * check the commit is a fast forward
78 # * handle a request from the policy hook for a fresh repo
79 # + push the signed tag and new dgit branch to the actual repo
81 # If the destination repo does not already exist, we need to make
82 # sure that we create it reasonably atomically, and also that
83 # we don't every have a destination repo containing no refs at all
84 # (because such a thing causes git-fetch-pack to barf). So then we
85 # do as above, except:
86 # - before starting, we take out our own lock for the destination repo
87 # - we create a prospective new destination repo by making a copy
89 # - we use the prospective new destination repo instead of the
90 # actual new destination repo (since the latter doesn't exist)
91 # - after git-receive-pack exits, we
92 # + check that the prospective repo contains a tag and head
93 # + rename the prospective destination repo into place
97 # - Temporary working trees and their locks are cleaned up
98 # opportunistically by a program which tries to take each lock and
99 # if successful deletes both the tree and the lockfile
100 # - Prospective working trees and their locks are cleaned up by
101 # a program which tries to take each lock and if successful
102 # deletes any prospective working tree and the lock (but not
103 # of course any actual tree)
104 # - It is forbidden to _remove_ the lockfile without removing
105 # the corresponding temporary tree, as the lockfile is also
106 # a stampfile whose presence indicates that there may be
110 use Fcntl qw(:flock);
111 use File::Path qw(rmtree);
113 use Debian::Dgit qw(:DEFAULT :policyflags);
115 open DEBUG, ">/dev/null" or die $!;
132 #----- utilities -----
135 print DEBUG "$debug @_\n";
138 sub acquirelock ($$) {
139 my ($lock, $must) = @_;
141 printf DEBUG "$debug locking %s %d\n", $lock, $must;
144 $fh = new IO::File $lock, ">" or die "open $lock: $!";
145 my $ok = flock $fh, $must ? LOCK_EX : (LOCK_EX|LOCK_NB);
147 die "flock $lock: $!" if $must;
148 debug " locking $lock failed";
151 next unless stat_exists $lock;
152 my $want = (stat _)[1];
154 my $got = (stat _)[1];
155 last if $got == $want;
160 sub acquirermtree ($$) {
161 my ($tree, $must) = @_;
162 my $fh = acquirelock("$tree.lock", $must);
170 sub locksometree ($) {
172 acquirelock("$tree.lock", 1);
175 sub lockrealtree () {
176 locksometree($realdestrepo);
180 my $tmpdir = "$dgitrepos/_tmp";
181 return if mkdir $tmpdir;
182 return if $! == EEXIST;
186 sub recorderror ($) {
188 my $w = $ENV{'DGIT_DRS_WORK'}; # we are in stunthook
191 open ERR, ">", "$w/drs-error" or die $!;
192 print ERR $why, "\n" or die $!;
201 recorderror "reject: $why";
202 die "dgit-repos-server: reject: $why\n";
208 local $Data::Dumper::Indent = 0;
209 local $Data::Dumper::Terse = 1;
210 debug "|".Dumper(\@_);
218 die "@_ $? $!" if $r;
222 my ($policyallowbits, @polargs) = @_;
223 # => ($exitstatuspolicybitmap);
224 die if $policyallowbits & ~0x3e;
225 my @cmd = ($policyhook,$distro,$repos,@polargs);
228 die "system: $!" if $r < 0;
229 die "hook (@cmd) failed ($?)" if $r & ~($policyallowbits << 8);
233 sub mkemptyrepo ($$) {
234 my ($dir,$sharedperm) = @_;
235 runcmd qw(git init --bare --quiet), "--shared=$sharedperm", $dir;
238 sub mkrepo_fromtemplate ($) {
240 my $template = "$dgitrepos/_template";
241 locksometree($template);
242 debug "copy template $template -> $dir";
243 my $r = system qw(cp -a --), $template, $dir;
244 !$r or die "create new repo $dir failed: $r $!";
247 sub movetogarbage () {
248 # $realdestrepo must have been locked
249 my $garbagerepo = "$dgitrepos/${package}_garbage";
250 # We arrange to always keep at least one old tree, for anti-rewind
251 # purposes (and, I guess, recovery from mistakes). This is either
252 # $garbage or $garbage-old.
253 if (stat_exists "$garbagerepo") {
254 rmtree "$garbagerepo-tmp";
255 if (rename "$garbagerepo-old", "$garbagerepo-tmp") {
256 rmtree "$garbagerepo-tmp";
258 die "$garbagerepo $!" unless $!==ENOENT;
260 rename "$garbagerepo", "$garbagerepo-old" or die "$garbagerepo $!";
262 rename $realdestrepo, $garbagerepo
264 or die "$garbagerepo $!";
268 my @cmd = (qw(git send-pack), $destrepo);
269 push @cmd, qw(--force) if $policy & NOFFCHECK;
270 push @cmd, "$commit:refs/dgit/$suite",
271 "$tagval:refs/tags/$tagname");
275 !$r or die "onward push to $destrepo failed: $r $!";
278 #----- git-receive-pack -----
280 sub fixmissing__git_receive_pack () {
282 $destrepo = "$dgitrepos/_tmp/${package}_prospective";
283 acquirermtree($destrepo, 1);
284 mkrepo_fromtemplate($destrepo);
287 sub makeworkingclone () {
289 $workrepo = "$dgitrepos/_tmp/${package}_incoming$$";
290 acquirermtree($workrepo, 1);
291 my $lfh = lockrealtree();
292 runcmd qw(git clone -l -q --mirror), $destrepo, $workrepo;
294 rmtree "${workrepo}_fresh";
297 sub setupstunthook () {
298 my $prerecv = "$workrepo/hooks/pre-receive";
299 my $fh = new IO::File $prerecv, O_WRONLY|O_CREAT|O_TRUNC, 0777
300 or die "$prerecv: $!";
301 print $fh <<END or die "$prerecv: $!";
304 exec $0 --pre-receive-hook $package
306 close $fh or die "$prerecv: $!";
307 $ENV{'DGIT_DRS_WORK'}= $workrepo;
308 $ENV{'DGIT_DRS_DEST'}= $destrepo;
309 debug " stunt hook set up $prerecv";
312 sub dealwithfreshrepo () {
313 my $freshrepo = "${workrepo}_fresh";
314 return unless stat_exists $freshrepo;
315 $destrepo = $freshrepo;
318 sub maybeinstallprospective () {
319 return if $destrepo eq $realdestrepo;
321 if (open REJ, "<", "$workrepo/drs-error") {
324 REJ->error and die $!;
328 $!==&ENOENT or die $!;
331 debug " show-ref ($destrepo) ...";
333 my $child = open SR, "-|";
334 defined $child or die $!;
336 chdir $destrepo or die $!;
337 exec qw(git show-ref);
340 my %got = qw(tag 0 head 0);
343 debug " show-refs| $_";
344 s/^\S*[1-9a-f]\S* (\S+)$/$1/ or die;
346 m{^refs/tags/} ? 'tag' :
347 m{^refs/dgit/} ? 'head' :
351 $!=0; $?=0; close SR or $?==256 or die "$? $!";
353 debug "installprospective ?";
354 die Dumper(\%got)." -- missing refs in new repo"
355 if grep { !$_ } values %got;
359 if ($destrepo eq "${workrepo}_fresh") {
363 debug "install $destrepo => $realdestrepo";
364 rename $destrepo, $realdestrepo or die $!;
365 remove "$destrepo.lock" or die $!;
368 sub main__git_receive_pack () {
371 runcmd qw(git receive-pack), $workrepo;
373 maybeinstallprospective();
376 #----- stunt post-receive hook -----
378 our ($tagname, $tagval, $suite, $oldcommit, $commit);
379 our ($version, %tagh);
382 debug " updates ...";
386 m/^(\S+) (\S+) (\S+)$/ or die "$_ ?";
387 my ($old, $sha1, $refname) = ($1, $2, $3);
388 if ($refname =~ m{^refs/tags/(?=debian/)}) {
389 reject "pushing multiple tags!" if defined $tagname;
392 reject "tag $tagname already exists -".
393 " not replacing previously-pushed version"
395 } elsif ($refname =~ m{^refs/dgit/}) {
396 reject "pushing multiple heads!" if defined $suite;
401 reject "pushing unexpected ref!";
404 STDIN->error and die $!;
406 reject "push is missing tag ref update" unless defined $tagname;
407 reject "push is missing head ref update" unless defined $suite;
408 debug " updates ok.";
412 debug " parsetag...";
413 open PT, ">dgit-tmp/plaintext" or die $!;
414 open DS, ">dgit-tmp/plaintext.asc" or die $!;
415 open T, "-|", qw(git cat-file tag), $tagval or die $!;
417 $!=0; $_=<T>; defined or die $!;
419 if (m/^(\S+) (.*)/) {
420 push @{ $tagh{$1} }, $2;
427 $!=0; $_=<T>; defined or die $!;
428 m/^($package_re) release (\S+) for \S+ \((\S+)\) \[dgit\]$/ or
429 reject "tag message not in expected format";
431 die unless $1 eq $package;
433 die "$3 != $suite " unless $3 eq $suite;
437 $!=0; $_=<T>; defined or die "missing signature? $!";
438 if (m/^\[dgit ([^"].*)\]$/) { # [dgit "something"] is for future
441 if (s/^distro\=(\S+) //) {
442 die "$1 != $distro" unless $1 eq $distro;
443 } elsif (s/^(--deliberately-$package_re) //) {
444 push @deliberatelies, $1;
445 } elsif (s/^supersede:(\S+)=(\w+) //) {
446 die "supersede $1 twice" if defined $supersedes{$1};
447 $supersedes{$1} = $2;
448 } elsif (s/^[-+.=0-9a-z]\S* //) {
450 die "unknown dgit info in tag";
455 last if m/^-----BEGIN PGP/;
465 debug " parsetag ok.";
468 sub checksig_keyring ($) {
469 my ($keyringfile) = @_;
470 # returns primary-keyid if signed by a key in this keyring
472 # or dies on other errors
476 debug " checksig keyring $keyringfile...";
478 our @cmd = (qw(gpgv --status-fd=1 --keyring),
480 qw(dgit-tmp/plaintext.asc dgit-tmp/plaintext));
487 next unless s/^\[GNUPG:\] //;
489 debug " checksig| $_";
490 my @l = split / /, $_;
491 if ($l[0] eq 'NO_PUBKEY') {
493 } elsif ($l[0] eq 'VALIDSIG') {
495 $sigtype eq '00' or reject "signature is not of type 00!";
497 die unless defined $ok;
503 debug sprintf " checksig ok=%d", !!$ok;
508 sub dm_txt_check ($$) {
509 my ($keyid, $dmtxtfn) = @_;
510 debug " dm_txt_check $keyid $dmtxtfn";
511 open DT, '<', $dmtxtfn or die "$dmtxtfn $!";
513 m/^fingerprint:\s+$keyid$/oi
515 if (s/^allow:/ /i..0) {
518 or reject "key $keyid missing Allow section in permissions!";
523 or reject "package $package not allowed for key $keyid";
528 debug " dm_txt_check allow| $_";
529 foreach my $p (split /\s+/) {
530 if ($p eq $package) {
532 debug " dm_txt_check ok";
537 DT->error and die $!;
539 reject "key $keyid not in permissions list although in keyring!";
543 foreach my $kas (split /:/, $keyrings) {
544 debug "verifytag $kas...";
545 $kas =~ s/^([^,]+),// or die;
546 my $keyid = checksig_keyring $1;
547 if (defined $keyid) {
548 if ($kas =~ m/^a$/) {
549 debug "verifytag a ok";
551 } elsif ($kas =~ m/^m([^,]+)$/) {
552 dm_txt_check($keyid, $1);
553 debug "verifytag m ok";
560 reject "key not found in keyrings";
564 debug "checksuite ($suitesfile)";
565 open SUITES, "<", $suitesfile or die $!;
571 return if $_ eq $suite;
573 die $! if SUITES->error;
574 reject "unknown suite";
577 sub checktagnoreplay () {
578 # We check that the signed tag mentions the name and value of
579 # (a) in the case of FRESHREPO all tags in the repo;
580 # (b) in the case of just NOFFCHECK all tags referring to
581 # the current head for the suite (there must be at least one).
582 # This prevents a replay attack using an earlier signed tag.
583 return unless $policy & (FRESHREPO|NOFFCHECK);
585 my $garbagerepo = "$dgitrepos/${package}_garbage";
589 foreach my $garb ("$garbagerepo", "$garbagerepo-old") {
590 if (stat_exists $garb) {
591 $ENV{GIT_DIR} = $garb;
595 if (!defined $ENV{GIT_DIR}) {
596 # Nothing to overwrite so the FRESHREPO and NOFFCHECK were
597 # pointless. Oh well.
598 debug "checktagnoreplay - no garbage, ok";
603 if (!($policy & FRESHREPO)) {
604 my $branch = server_branch($suite);
606 `git for-each-ref --format='%(objectname)' '[r]efs/$branch'`;
607 defined or die "$branch $? $!";
608 $? and die "$branch $?";
610 # No such branch - NOFFCHECK was unnecessary. Oh well.
611 debug "checktagnoreplay - not FRESHREPO, new branch, ok";
614 m/^(\w+)\n$/ or die "$branch $_ ?";
616 debug "checktagnoreplay - not FRESHREPO,".
617 " checking for overwriting refs/$branch=$onlyreferring";
622 git_for_each_tag_referring($objreferring, sub {
623 my ($objid,$fullrefname,$tagname) = @_;
624 debug "checktagnoreplay - overwriting $fullrefname=$objid";
625 my $supers = $supersedes{$fullrefname};
626 if (!defined $supers) {
627 push @problems, "does not supersede $fullrefname";
628 } elsif ($supers ne $objid) {
630 "supersedes $fullrefname=$supers but previously $fullrefname=$objid";
637 reject "replay attack prevention check failed:".
638 " signed tag for $version: ".
639 join("; ", @problems).
642 debug "checktagnoreply - all ok"
647 my $vals = $tagh{$tag};
648 reject "missing header $tag in signed tag object" unless $vals;
649 reject "multiple headers $tag in signed tag object" unless @$vals == 1;
656 tagh1('type') eq 'commit' or reject "tag refers to wrong kind of object";
657 tagh1('object') eq $commit or reject "tag refers to wrong commit";
658 tagh1('tag') eq $tagname or reject "tag name in tag is wrong";
663 debug "translated version $v";
664 $tagname eq "debian/$v" or die;
668 $policy = policyhook(NOFFCHECK|FRESHREPO, 'push',$package,
669 $version,$suite,$tagname,
670 join(",",@delberatelies));
675 # check that our ref is being fast-forwarded
676 debug "oldcommit $oldcommit";
677 if (!($policy & NOFFCHECK) && $oldcommit =~ m/[^0]/) {
678 $?=0; $!=0; my $mb = `git merge-base $commit $oldcommit`;
680 $mb eq $oldcommit or reject "not fast forward on dgit branch";
683 if ($policy & FRESHREPO) {
684 # This is troublesome. We have been asked by the policy hook
685 # to receive the push into a fresh repo. But of course we
686 # have actually already mostly received the push into the working
687 # repo. (This is unavoidable because the instruction to use a new
688 # repo comes ultimately from the signed tag for the dgit push,
689 # which has to have been received into some repo.)
691 # So what we do is generate a fresh working repo right now and
692 # push the head and tag into it. The presence of this fresh
693 # working repo is detected by the parent, which responds by
694 # making a fresh master repo from the template.
696 $destrepo = "${workrepo}_fresh"; # workrepo lock covers
697 mkrepo_fromtemplate $destrepo;
703 chdir $workrepo or die "chdir $workrepo: $!";
704 mkdir "dgit-tmp" or $!==EEXIST or die $!;
710 debug "stunthook done.";
713 #----- git-upload-pack -----
715 sub fixmissing__git_upload_pack () {
716 $destrepo = "$dgitrepos/_empty";
717 my $lfh = locksometree($destrepo);
718 return if stat_exists $destrepo;
719 rmtree "$destrepo.new";
720 mkemptyrepo "$destrepo.new", "0644";
721 rename "$destrepo.new", $destrepo or die $!;
722 unlink "$destrepo.lock" or die $!;
726 sub main__git_upload_pack () {
727 my $lfh = locksometree($destrepo);
728 chdir $destrepo or die "$destrepo: $!";
730 runcmd qw(git upload-pack), ".";
733 #----- arg parsing and main program -----
742 sub parseargsdispatch () {
745 delete $ENV{'GIT_DIR'}; # if not run via ssh, our parent git process
746 delete $ENV{'GIT_PREFIX'}; # sets these and they mess things up
748 if ($ENV{'DGIT_DRS_DEBUG'}) {
750 open DEBUG, ">&STDERR" or die $!;
753 if ($ARGV[0] eq '--pre-receive-hook') {
754 if ($debug) { $debug.="="; }
757 $package = shift @ARGV;
758 defined($distro = $ENV{'DGIT_DRS_DISTRO'}) or die;
759 defined($suitesfile = $ENV{'DGIT_DRS_SUITES'}) or die;
760 defined($workrepo = $ENV{'DGIT_DRS_WORK'}) or die;
761 defined($destrepo = $ENV{'DGIT_DRS_DEST'}) or die;
762 defined($keyrings = $ENV{'DGIT_DRS_KEYRINGS'}) or die $!;
763 defined($policyhook = $ENV{'DGIT_DRS_POLICYHOOK'}) or die $!;
764 open STDOUT, ">&STDERR" or die $!;
769 recorderror "$@" or die;
775 $ENV{'DGIT_DRS_DISTRO'} = argval();
776 $ENV{'DGIT_DRS_SUITES'} = argval();
777 $ENV{'DGIT_DRS_KEYRINGS'} = argval();
778 $dgitrepos = argval();
779 $ENV{'DGIT_DRS_POLICYHOOK'} = $policyhook = argval();
781 die unless @ARGV==1 && $ARGV[0] eq '--ssh';
783 my $cmd = $ENV{'SSH_ORIGINAL_COMMAND'};
793 or reject "command string not understood";
796 $realdestrepo = "$dgitrepos/$package.git";
800 my $mainfunc = $main::{"main__$funcn"};
802 reject "unknown method" unless $mainfunc;
804 my $lfh = lockrealtree();
806 $policy = policyhook(FRESHREPO,'check-package',$package);
807 if ($policy & FRESHREPO) {
813 if (stat_exists $realdestrepo) {
814 $destrepo = $realdestrepo;
816 debug " fixmissing $funcn";
817 my $fixfunc = $main::{"fixmissing__$funcn"};
821 debug " running main $funcn";
826 while (my $fh = pop @lockfhs) { close $fh; }
831 if (!chdir "$dgitrepos/_tmp") {
832 $!==ENOENT or die $!;
835 foreach my $lf (<*.lock>) {
837 $tree =~ s/\.lock$//;
838 next unless acquirermtree($tree, 0);
839 remove $lf or warn $!;