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 acquiretree ($$) {
161 my ($tree, $must) = @_;
162 my $fh = acquirelock("$tree.lock", $must);
171 my $tmpdir = "$dgitrepos/_tmp";
172 return if mkdir $tmpdir;
173 return if $! == EEXIST;
177 sub recorderror ($) {
179 my $w = $ENV{'DGIT_DRS_WORK'}; # we are in stunthook
182 open ERR, ">", "$w/drs-error" or die $!;
183 print ERR $why, "\n" or die $!;
192 recorderror "reject: $why";
193 die "dgit-repos-server: reject: $why\n";
199 local $Data::Dumper::Indent = 0;
200 local $Data::Dumper::Terse = 1;
201 debug "|".Dumper(\@_);
209 die "@_ $? $!" if $r;
213 my ($policyallowbits, @polargs) = @_;
214 # => ($exitstatuspolicybitmap, $policylockfh);
215 die if $policyallowbits & ~0x3e;
216 my @cmd = ($policyhook,$distro,$repos,@polargs);
219 die "system: $!" if $r < 0;
220 die "hook (@cmd) failed ($?)" if $r & ~($policyallowbits << 8);
224 sub mkemptyrepo ($$) {
225 my ($dir,$sharedperm) = @_;
226 runcmd qw(git init --bare --quiet), "--shared=$sharedperm", $dir;
229 sub mkrepo_fromtemplate ($) {
231 my $template = "$dgitrepos/_template";
232 acquiretree($template,1);
233 debug "copy template $template -> $dir";
234 my $r = system qw(cp -a --), $template, $dir;
235 !$r or die "create new repo $dir failed: $r $!";
238 sub movetogarbage () {
239 # $realdestrepo must have been locked
240 my $garbagerepo = "$dgitrepos/${package}_garbage";
241 # We arrange to always keep at least one old tree, for anti-rewind
242 # purposes (and, I guess, recovery from mistakes). This is either
243 # $garbage or $garbage-old.
244 if (stat_exists "$garbagerepo") {
245 rmtree "$garbagerepo-tmp";
246 if (rename "$garbagerepo-old", "$garbagerepo-tmp") {
247 rmtree "$garbagerepo-tmp";
249 die "$garbagerepo $!" unless $!==ENOENT;
251 rename "$garbagerepo", "$garbagerepo-old" or die "$garbagerepo $!";
253 rename $realdestrepo, $garbagerepo
255 or die "$garbagerepo $!";
259 my @cmd = (qw(git send-pack), $destrepo);
260 push @cmd, qw(--force) if $policy & NOFFCHECK;
261 push @cmd, "$commit:refs/dgit/$suite",
262 "$tagval:refs/tags/$tagname");
266 !$r or die "onward push to $destrepo failed: $r $!";
269 #----- git-receive-pack -----
271 sub fixmissing__git_receive_pack () {
273 $destrepo = "$dgitrepos/_tmp/${package}_prospective";
274 acquiretree($destrepo, 1);
275 mkrepo_fromtemplate($destrepo);
278 sub makeworkingclone () {
280 $workrepo = "$dgitrepos/_tmp/${package}_incoming$$";
281 acquiretree($workrepo, 1);
282 my $lfh = acquiretree($realdestrepo, 1);
283 runcmd qw(git clone -l -q --mirror), $destrepo, $workrepo;
285 rmtree "${workrepo}_fresh";
288 sub setupstunthook () {
289 my $prerecv = "$workrepo/hooks/pre-receive";
290 my $fh = new IO::File $prerecv, O_WRONLY|O_CREAT|O_TRUNC, 0777
291 or die "$prerecv: $!";
292 print $fh <<END or die "$prerecv: $!";
295 exec $0 --pre-receive-hook $package
297 close $fh or die "$prerecv: $!";
298 $ENV{'DGIT_DRS_WORK'}= $workrepo;
299 $ENV{'DGIT_DRS_DEST'}= $destrepo;
300 debug " stunt hook set up $prerecv";
303 sub dealwithfreshrepo () {
304 my $freshrepo = "${workrepo}_fresh";
305 return unless stat_exists $freshrepo;
306 $destrepo = $freshrepo;
309 sub maybeinstallprospective () {
310 return if $destrepo eq $realdestrepo;
312 if (open REJ, "<", "$workrepo/drs-error") {
315 REJ->error and die $!;
319 $!==&ENOENT or die $!;
322 debug " show-ref ($destrepo) ...";
324 my $child = open SR, "-|";
325 defined $child or die $!;
327 chdir $destrepo or die $!;
328 exec qw(git show-ref);
331 my %got = qw(tag 0 head 0);
334 debug " show-refs| $_";
335 s/^\S*[1-9a-f]\S* (\S+)$/$1/ or die;
337 m{^refs/tags/} ? 'tag' :
338 m{^refs/dgit/} ? 'head' :
342 $!=0; $?=0; close SR or $?==256 or die "$? $!";
344 debug "installprospective ?";
345 die Dumper(\%got)." -- missing refs in new repo"
346 if grep { !$_ } values %got;
348 acquiretree($realdestrepo,1);
350 if ($destrepo eq "${workrepo}_fresh") {
354 debug "install $destrepo => $realdestrepo";
355 rename $destrepo, $realdestrepo or die $!;
356 remove "$destrepo.lock" or die $!;
359 sub main__git_receive_pack () {
362 runcmd qw(git receive-pack), $workrepo;
364 maybeinstallprospective();
367 #----- stunt post-receive hook -----
369 our ($tagname, $tagval, $suite, $oldcommit, $commit);
370 our ($version, %tagh);
373 debug " updates ...";
377 m/^(\S+) (\S+) (\S+)$/ or die "$_ ?";
378 my ($old, $sha1, $refname) = ($1, $2, $3);
379 if ($refname =~ m{^refs/tags/(?=debian/)}) {
380 reject "pushing multiple tags!" if defined $tagname;
383 reject "tag $tagname already exists -".
384 " not replacing previously-pushed version"
386 } elsif ($refname =~ m{^refs/dgit/}) {
387 reject "pushing multiple heads!" if defined $suite;
392 reject "pushing unexpected ref!";
395 STDIN->error and die $!;
397 reject "push is missing tag ref update" unless defined $tagname;
398 reject "push is missing head ref update" unless defined $suite;
399 debug " updates ok.";
403 debug " parsetag...";
404 open PT, ">dgit-tmp/plaintext" or die $!;
405 open DS, ">dgit-tmp/plaintext.asc" or die $!;
406 open T, "-|", qw(git cat-file tag), $tagval or die $!;
408 $!=0; $_=<T>; defined or die $!;
410 if (m/^(\S+) (.*)/) {
411 push @{ $tagh{$1} }, $2;
418 $!=0; $_=<T>; defined or die $!;
419 m/^($package_re) release (\S+) for \S+ \((\S+)\) \[dgit\]$/ or
420 reject "tag message not in expected format";
422 die unless $1 eq $package;
424 die "$3 != $suite " unless $3 eq $suite;
428 $!=0; $_=<T>; defined or die "missing signature? $!";
429 if (m/^\[dgit ([^"].*)\]$/) { # [dgit "something"] is for future
432 if (s/^distro\=(\S+) //) {
433 die "$1 != $distro" unless $1 eq $distro;
434 } elsif (s/^(--deliberately-$package_re) //) {
435 push @deliberatelies, $1;
436 } elsif (s/^supersede:(\S+)=(\w+) //) {
437 die "supersede $1 twice" if defined $supersedes{$1};
438 $supersedes{$1} = $2;
439 } elsif (s/^[-+.=0-9a-z]\S* //) {
441 die "unknown dgit info in tag";
446 last if m/^-----BEGIN PGP/;
456 debug " parsetag ok.";
459 sub checksig_keyring ($) {
460 my ($keyringfile) = @_;
461 # returns primary-keyid if signed by a key in this keyring
463 # or dies on other errors
467 debug " checksig keyring $keyringfile...";
469 our @cmd = (qw(gpgv --status-fd=1 --keyring),
471 qw(dgit-tmp/plaintext.asc dgit-tmp/plaintext));
478 next unless s/^\[GNUPG:\] //;
480 debug " checksig| $_";
481 my @l = split / /, $_;
482 if ($l[0] eq 'NO_PUBKEY') {
484 } elsif ($l[0] eq 'VALIDSIG') {
486 $sigtype eq '00' or reject "signature is not of type 00!";
488 die unless defined $ok;
494 debug sprintf " checksig ok=%d", !!$ok;
499 sub dm_txt_check ($$) {
500 my ($keyid, $dmtxtfn) = @_;
501 debug " dm_txt_check $keyid $dmtxtfn";
502 open DT, '<', $dmtxtfn or die "$dmtxtfn $!";
504 m/^fingerprint:\s+$keyid$/oi
506 if (s/^allow:/ /i..0) {
509 or reject "key $keyid missing Allow section in permissions!";
514 or reject "package $package not allowed for key $keyid";
519 debug " dm_txt_check allow| $_";
520 foreach my $p (split /\s+/) {
521 if ($p eq $package) {
523 debug " dm_txt_check ok";
528 DT->error and die $!;
530 reject "key $keyid not in permissions list although in keyring!";
534 foreach my $kas (split /:/, $keyrings) {
535 debug "verifytag $kas...";
536 $kas =~ s/^([^,]+),// or die;
537 my $keyid = checksig_keyring $1;
538 if (defined $keyid) {
539 if ($kas =~ m/^a$/) {
540 debug "verifytag a ok";
542 } elsif ($kas =~ m/^m([^,]+)$/) {
543 dm_txt_check($keyid, $1);
544 debug "verifytag m ok";
551 reject "key not found in keyrings";
555 debug "checksuite ($suitesfile)";
556 open SUITES, "<", $suitesfile or die $!;
562 return if $_ eq $suite;
564 die $! if SUITES->error;
565 reject "unknown suite";
568 sub checktagnoreplay () {
569 # We check that the signed tag mentions the name and value of
570 # (a) in the case of FRESHREPO all tags in the repo;
571 # (b) in the case of just NOFFCHECK all tags referring to
572 # the current head for the suite (there must be at least one).
573 # This prevents a replay attack using an earlier signed tag.
574 return unless $policy & (FRESHREPO|NOFFCHECK);
576 my $garbagerepo = "$dgitrepos/${package}_garbage";
577 acquiretree($realdestrepo,1);
580 foreach my $garb ("$garbagerepo", "$garbagerepo-old") {
581 if (stat_exists $garb) {
582 $ENV{GIT_DIR} = $garb;
586 if (!defined $ENV{GIT_DIR}) {
587 # Nothing to overwrite so the FRESHREPO and NOFFCHECK were
588 # pointless. Oh well.
589 debug "checktagnoreplay - no garbage, ok";
594 if (!($policy & FRESHREPO)) {
595 my $branch = server_branch($suite);
597 `git for-each-ref --format='%(objectname)' '[r]efs/$branch'`;
598 defined or die "$branch $? $!";
599 $? and die "$branch $?";
601 # No such branch - NOFFCHECK was unnecessary. Oh well.
602 debug "checktagnoreplay - not FRESHREPO, new branch, ok";
605 m/^(\w+)\n$/ or die "$branch $_ ?";
607 debug "checktagnoreplay - not FRESHREPO,".
608 " checking for overwriting refs/$branch=$onlyreferring";
613 git_for_each_tag_referring($objreferring, sub {
614 my ($objid,$fullrefname,$tagname) = @_;
615 debug "checktagnoreplay - overwriting $fullrefname=$objid";
616 my $supers = $supersedes{$fullrefname};
617 if (!defined $supers) {
618 push @problems, "does not supersede $fullrefname";
619 } elsif ($supers ne $objid) {
621 "supersedes $fullrefname=$supers but previously $fullrefname=$objid";
628 reject "replay attack prevention check failed:".
629 " signed tag for $version: ".
630 join("; ", @problems).
633 debug "checktagnoreply - all ok"
638 my $vals = $tagh{$tag};
639 reject "missing header $tag in signed tag object" unless $vals;
640 reject "multiple headers $tag in signed tag object" unless @$vals == 1;
647 tagh1('type') eq 'commit' or reject "tag refers to wrong kind of object";
648 tagh1('object') eq $commit or reject "tag refers to wrong commit";
649 tagh1('tag') eq $tagname or reject "tag name in tag is wrong";
654 debug "translated version $v";
655 $tagname eq "debian/$v" or die;
657 acquiretree($realdestrepo,1);
659 $policy = policyhook(NOFFCHECK|FRESHREPO, 'push',$package,
660 $version,$suite,$tagname,
661 join(",",@delberatelies));
666 # check that our ref is being fast-forwarded
667 debug "oldcommit $oldcommit";
668 if (!($policy & NOFFCHECK) && $oldcommit =~ m/[^0]/) {
669 $?=0; $!=0; my $mb = `git merge-base $commit $oldcommit`;
671 $mb eq $oldcommit or reject "not fast forward on dgit branch";
674 if ($policy & FRESHREPO) {
675 # This is troublesome. We have been asked by the policy hook
676 # to receive the push into a fresh repo. But of course we
677 # have actually already mostly received the push into the working
678 # repo. (This is unavoidable because the instruction to use a new
679 # repo comes ultimately from the signed tag for the dgit push,
680 # which has to have been received into some repo.)
682 # So what we do is generate a fresh working repo right now and
683 # push the head and tag into it. The presence of this fresh
684 # working repo is detected by the parent, which responds by
685 # making a fresh master repo from the template.
687 $destrepo = "${workrepo}_fresh"; # workrepo lock covers
688 mkrepo_fromtemplate $destrepo;
694 chdir $workrepo or die "chdir $workrepo: $!";
695 mkdir "dgit-tmp" or $!==EEXIST or die $!;
701 debug "stunthook done.";
704 #----- git-upload-pack -----
706 sub fixmissing__git_upload_pack () {
707 $destrepo = "$dgitrepos/_empty";
708 my $lfh = acquiretree($destrepo,1);
709 return if stat_exists $destrepo;
710 rmtree "$destrepo.new";
711 mkemptyrepo "$destrepo.new", "0644";
712 rename "$destrepo.new", $destrepo or die $!;
713 unlink "$destrepo.lock" or die $!;
717 sub main__git_upload_pack () {
718 my $lfh = acquiretree($destrepo,1);
719 chdir $destrepo or die "$destrepo: $!";
721 runcmd qw(git upload-pack), ".";
724 #----- arg parsing and main program -----
733 sub parseargsdispatch () {
736 delete $ENV{'GIT_DIR'}; # if not run via ssh, our parent git process
737 delete $ENV{'GIT_PREFIX'}; # sets these and they mess things up
739 if ($ENV{'DGIT_DRS_DEBUG'}) {
741 open DEBUG, ">&STDERR" or die $!;
744 if ($ARGV[0] eq '--pre-receive-hook') {
745 if ($debug) { $debug.="="; }
748 $package = shift @ARGV;
749 defined($distro = $ENV{'DGIT_DRS_DISTRO'}) or die;
750 defined($suitesfile = $ENV{'DGIT_DRS_SUITES'}) or die;
751 defined($workrepo = $ENV{'DGIT_DRS_WORK'}) or die;
752 defined($destrepo = $ENV{'DGIT_DRS_DEST'}) or die;
753 defined($keyrings = $ENV{'DGIT_DRS_KEYRINGS'}) or die $!;
754 defined($policyhook = $ENV{'DGIT_DRS_POLICYHOOK'}) or die $!;
755 open STDOUT, ">&STDERR" or die $!;
760 recorderror "$@" or die;
766 $ENV{'DGIT_DRS_DISTRO'} = argval();
767 $ENV{'DGIT_DRS_SUITES'} = argval();
768 $ENV{'DGIT_DRS_KEYRINGS'} = argval();
769 $dgitrepos = argval();
770 $ENV{'DGIT_DRS_POLICYHOOK'} = $policyhook = argval();
772 die unless @ARGV==1 && $ARGV[0] eq '--ssh';
774 my $cmd = $ENV{'SSH_ORIGINAL_COMMAND'};
784 or reject "command string not understood";
787 $realdestrepo = "$dgitrepos/$package.git";
791 my $mainfunc = $main::{"main__$funcn"};
793 reject "unknown method" unless $mainfunc;
795 my $lfh = acquiretree($realdestrepo,1);
797 my ($policy, $pollock) = policyhook(FRESHREPO,'check-package',$package);
798 if ($policy & FRESHREPO) {
801 close $pollock or die $!;
805 if (stat_exists $realdestrepo) {
806 $destrepo = $realdestrepo;
808 debug " fixmissing $funcn";
809 my $fixfunc = $main::{"fixmissing__$funcn"};
813 debug " running main $funcn";
818 while (my $fh = pop @lockfhs) { close $fh; }
823 if (!chdir "$dgitrepos/_tmp") {
824 $!==ENOENT or die $!;
827 foreach my $lf (<*.lock>) {
829 $tree =~ s/\.lock$//;
830 next unless acquiretree($tree, 0);
831 remove $lf or warn $!;