5 # dgit-repos-server DISTRO DISTRO-DIR AUTH-SPEC [<settings>] --ssh
6 # dgit-repos-server DISTRO DISTRO-DIR AUTH-SPEC [<settings>] --cron
8 # --repos=GIT-REPOS-DIR default DISTRO-DIR/repos/
9 # --suites=SUITES-FILE default DISTRO-DIR/suites
10 # --policy-hook=POLICY-HOOK default DISTRO-DIR/policy-hook
11 # (DISTRO-DIR is not used other than as default)
13 # .../dgit-repos-server --pre-receive-hook PACKAGE
15 # Invoked as the ssh restricted command
17 # Works like git-receive-pack
19 # SUITES is the name of a file which lists the permissible suites
20 # one per line (#-comments and blank lines ignored)
22 # AUTH-SPEC is a :-separated list of
23 # KEYRING.GPG,AUTH-SPEC
24 # where AUTH-SPEC is one of
29 $SIG{__WARN__} = sub { die $_[0]; };
31 # DGIT-REPOS-DIR contains:
32 # git tree (or other object) lock (in acquisition order, outer first)
34 # _tmp/PACKAGE_prospective ! } SAME.lock, held during receive-pack
36 # _tmp/PACKAGE_incoming$$ ! } SAME.lock, held during receive-pack
37 # _tmp/PACKAGE_incoming$$_fresh ! }
39 # PACKAGE.git } PACKAGE.git.lock
40 # PACKAGE_garbage } (also covers executions of
41 # PACKAGE_garbage-old } policy hook script for PACKAGE)
42 # PACKAGE_garbage-tmp }
43 # policy* } (for policy hook script, covered by
44 # } lock only when invoked for a package)
46 # leaf locks, held during brief operaton only:
51 # _template } SAME.lock
53 # locks marked ! may be held during client data transfer
55 # What we do on push is this:
56 # - extract the destination repo name
57 # - make a hardlink clone of the destination repo
58 # - provide the destination with a stunt pre-receive hook
59 # - run actual git-receive-pack with that new destination
60 # as a result of this the stunt pre-receive hook runs; it does this:
61 # + understand what refs we are allegedly updating and
62 # check some correspondences:
63 # * we are updating only refs/tags/debian/* and refs/dgit/*
64 # * and only one of each
65 # * and the tag does not already exist
67 # * recover the suite name from the destination refs/dgit/ ref
68 # + disassemble the signed tag into its various fields and signature
70 # * parsing the first line of the tag message to recover
71 # the package name, version and suite
72 # * checking that the package name corresponds to the dest repo name
73 # * checking that the suite name is as recovered above
74 # + verify the signature on the signed tag
75 # and if necessary check that the keyid and package are listed in dm.txt
76 # + check various correspondences:
77 # * the signed tag must refer to a commit
78 # * the signed tag commit must be the refs/dgit value
79 # * the name in the signed tag must correspond to its ref name
80 # * the tag name must be debian/<version> (massaged as needed)
81 # * the suite is one of those permitted
82 # * the signed tag has a suitable name
83 # * run the "push" policy hook
84 # * replay prevention for --deliberately-not-fast-forward
85 # * check the commit is a fast forward
86 # * handle a request from the policy hook for a fresh repo
87 # + push the signed tag and new dgit branch to the actual repo
89 # If the destination repo does not already exist, we need to make
90 # sure that we create it reasonably atomically, and also that
91 # we don't every have a destination repo containing no refs at all
92 # (because such a thing causes git-fetch-pack to barf). So then we
93 # do as above, except:
94 # - before starting, we take out our own lock for the destination repo
95 # - we create a prospective new destination repo by making a copy
97 # - we use the prospective new destination repo instead of the
98 # actual new destination repo (since the latter doesn't exist)
99 # - after git-receive-pack exits, we
100 # + check that the prospective repo contains a tag and head
101 # + rename the prospective destination repo into place
104 # - We are crash-only
105 # - Temporary working trees and their locks are cleaned up
106 # opportunistically by a program which tries to take each lock and
107 # if successful deletes both the tree and the lockfile
108 # - Prospective working trees and their locks are cleaned up by
109 # a program which tries to take each lock and if successful
110 # deletes any prospective working tree and the lock (but not
111 # of course any actual tree)
112 # - It is forbidden to _remove_ the lockfile without removing
113 # the corresponding temporary tree, as the lockfile is also
114 # a stampfile whose presence indicates that there may be
117 # Policy hook script is invoked like this:
118 # POLICY-HOOK-SCRIPT DISTRO DGIT-REPOS-DIR ACTION...
120 # POLICY-HOOK-SCRIPT ... check-list [...]
121 # POLICY-HOOK-SCRIPT ... check-package PACKAGE [...]
122 # POLICY-HOOK-SCRIPT ... push|push-confirm PACKAGE \
123 # VERSION SUITE TAGNAME DELIBERATELIES [...]
125 # Exit status is a bitmask. Bit weight constants are defined in Dgit.pm.
127 # suppress dgit-repos-server's fast-forward check ("push" only)
129 # blow away repo right away (ie, as if before push or fetch)
130 # ("check-package" and "push" only)
131 # any unexpected bits mean failure, and then known set bits are ignored
132 # if no unexpected bits set, operation continues (subject to meaning
133 # of any expected bits set). So, eg, exit 0 means "continue normally"
134 # and would be appropriate for an unknown action.
136 # cwd for push and push-confirm is a temporary repo where the
137 # to-be-pushed objects have been received; TAGNAME is the
140 # if push requested FRESHREPO, push-confirm happens in said fresh repo
142 # policy hook for a particular package will be invoked only once at
143 # a time - (see comments about DGIT-REPOS-DIR, above)
145 # check-list and check-package are invoked via the --cron option.
146 # First, without any locking, check-list is called. It should produce
147 # a list of package names. Then check-package will be invoked for
148 # each named package, in each case after taking an appropriate lock.
152 use Fcntl qw(:flock);
153 use File::Path qw(rmtree);
155 use Debian::Dgit qw(:DEFAULT :policyflags);
157 open DEBUG, ">/dev/null" or die $!;
174 #----- utilities -----
177 print DEBUG "$debug @_\n";
180 sub realdestrepo () { "$dgitrepos/$package.git"; }
182 sub acquirelock ($$) {
183 my ($lock, $must) = @_;
185 printf DEBUG "$debug locking %s %d\n", $lock, $must;
188 $fh = new IO::File $lock, ">" or die "open $lock: $!";
189 my $ok = flock $fh, $must ? LOCK_EX : (LOCK_EX|LOCK_NB);
191 die "flock $lock: $!" if $must;
192 debug " locking $lock failed";
195 next unless stat_exists $lock;
196 my $want = (stat _)[1];
198 my $got = (stat _)[1];
199 last if $got == $want;
204 sub acquirermtree ($$) {
205 my ($tree, $must) = @_;
206 my $fh = acquirelock("$tree.lock", $must);
214 sub locksometree ($) {
216 acquirelock("$tree.lock", 1);
219 sub lockrealtree () {
220 locksometree(realdestrepo);
224 my $tmpdir = "$dgitrepos/_tmp";
225 return if mkdir $tmpdir;
226 return if $! == EEXIST;
230 sub recorderror ($) {
232 my $w = $ENV{'DGIT_DRS_WORK'}; # we are in stunthook
235 open ERR, ">", "$w/drs-error" or die $!;
236 print ERR $why, "\n" or die $!;
245 recorderror "reject: $why";
246 die "dgit-repos-server: reject: $why\n";
252 local $Data::Dumper::Indent = 0;
253 local $Data::Dumper::Terse = 1;
254 debug "|".Dumper(\@_);
262 die "@_ $? $!" if $r;
266 my ($policyallowbits, @polargs) = @_;
267 # => ($exitstatuspolicybitmap);
268 die if $policyallowbits & ~0x3e;
269 my @cmd = ($policyhook,$distro,$dgitrepos,@polargs);
272 die "system: $!" if $r < 0;
273 die "hook (@cmd) failed ($?)" if $r & ~($policyallowbits << 8);
277 sub mkemptyrepo ($$) {
278 my ($dir,$sharedperm) = @_;
279 runcmd qw(git init --bare --quiet), "--shared=$sharedperm", $dir;
282 sub mkrepo_fromtemplate ($) {
284 my $template = "$dgitrepos/_template";
285 locksometree($template);
286 debug "copy template $template -> $dir";
287 my $r = system qw(cp -a --), $template, $dir;
288 !$r or die "create new repo $dir failed: $r $!";
291 sub movetogarbage () {
292 # realdestrepo must have been locked
293 my $garbagerepo = "$dgitrepos/${package}_garbage";
294 # We arrange to always keep at least one old tree, for anti-rewind
295 # purposes (and, I guess, recovery from mistakes). This is either
296 # $garbage or $garbage-old.
297 if (stat_exists "$garbagerepo") {
298 rmtree "$garbagerepo-tmp";
299 if (rename "$garbagerepo-old", "$garbagerepo-tmp") {
300 rmtree "$garbagerepo-tmp";
302 die "$garbagerepo $!" unless $!==ENOENT;
304 rename "$garbagerepo", "$garbagerepo-old" or die "$garbagerepo $!";
306 rename realdestrepo, $garbagerepo
308 or die "$garbagerepo $!";
311 #----- git-receive-pack -----
313 sub fixmissing__git_receive_pack () {
315 $destrepo = "$dgitrepos/_tmp/${package}_prospective";
316 acquirermtree($destrepo, 1);
317 mkrepo_fromtemplate($destrepo);
320 sub makeworkingclone () {
322 $workrepo = "$dgitrepos/_tmp/${package}_incoming$$";
323 acquirermtree($workrepo, 1);
324 my $lfh = lockrealtree();
325 runcmd qw(git clone -l -q --mirror), $destrepo, $workrepo;
327 rmtree "${workrepo}_fresh";
330 sub setupstunthook () {
331 my $prerecv = "$workrepo/hooks/pre-receive";
332 my $fh = new IO::File $prerecv, O_WRONLY|O_CREAT|O_TRUNC, 0777
333 or die "$prerecv: $!";
334 print $fh <<END or die "$prerecv: $!";
337 exec $0 --pre-receive-hook $package
339 close $fh or die "$prerecv: $!";
340 $ENV{'DGIT_DRS_WORK'}= $workrepo;
341 $ENV{'DGIT_DRS_DEST'}= $destrepo;
342 debug " stunt hook set up $prerecv";
345 sub dealwithfreshrepo () {
346 my $freshrepo = "${workrepo}_fresh";
347 return unless stat_exists $freshrepo;
348 $destrepo = $freshrepo;
351 sub maybeinstallprospective () {
352 return if $destrepo eq realdestrepo;
354 if (open REJ, "<", "$workrepo/drs-error") {
357 REJ->error and die $!;
361 $!==&ENOENT or die $!;
364 debug " show-ref ($destrepo) ...";
366 my $child = open SR, "-|";
367 defined $child or die $!;
369 chdir $destrepo or die $!;
370 exec qw(git show-ref);
373 my %got = qw(tag 0 head 0);
376 debug " show-refs| $_";
377 s/^\S*[1-9a-f]\S* (\S+)$/$1/ or die;
379 m{^refs/tags/} ? 'tag' :
380 m{^refs/dgit/} ? 'head' :
384 $!=0; $?=0; close SR or $?==256 or die "$? $!";
386 debug "installprospective ?";
387 die Dumper(\%got)." -- missing refs in new repo"
388 if grep { !$_ } values %got;
392 if ($destrepo eq "${workrepo}_fresh") {
396 debug "install $destrepo => ".realdestrepo;
397 rename $destrepo, realdestrepo or die $!;
398 remove "$destrepo.lock" or die $!;
401 sub main__git_receive_pack () {
404 runcmd qw(git receive-pack), $workrepo;
406 maybeinstallprospective();
409 #----- stunt post-receive hook -----
411 our ($tagname, $tagval, $suite, $oldcommit, $commit);
412 our ($version, %tagh);
415 debug " updates ...";
419 m/^(\S+) (\S+) (\S+)$/ or die "$_ ?";
420 my ($old, $sha1, $refname) = ($1, $2, $3);
421 if ($refname =~ m{^refs/tags/(?=debian/)}) {
422 reject "pushing multiple tags!" if defined $tagname;
425 reject "tag $tagname already exists -".
426 " not replacing previously-pushed version"
428 } elsif ($refname =~ m{^refs/dgit/}) {
429 reject "pushing multiple heads!" if defined $suite;
434 reject "pushing unexpected ref!";
437 STDIN->error and die $!;
439 reject "push is missing tag ref update" unless defined $tagname;
440 reject "push is missing head ref update" unless defined $suite;
441 debug " updates ok.";
445 debug " parsetag...";
446 open PT, ">dgit-tmp/plaintext" or die $!;
447 open DS, ">dgit-tmp/plaintext.asc" or die $!;
448 open T, "-|", qw(git cat-file tag), $tagval or die $!;
450 $!=0; $_=<T>; defined or die $!;
452 if (m/^(\S+) (.*)/) {
453 push @{ $tagh{$1} }, $2;
460 $!=0; $_=<T>; defined or die $!;
461 m/^($package_re) release (\S+) for \S+ \((\S+)\) \[dgit\]$/ or
462 reject "tag message not in expected format";
464 die unless $1 eq $package;
466 die "$3 != $suite " unless $3 eq $suite;
470 print PT $copyl or die $!;
471 $!=0; $_=<T>; defined or die "missing signature? $!";
473 if (m/^\[dgit ([^"].*)\]$/) { # [dgit "something"] is for future
476 if (s/^distro\=(\S+) //) {
477 die "$1 != $distro" unless $1 eq $distro;
478 } elsif (s/^(--deliberately-$package_re) //) {
479 push @deliberatelies, $1;
480 } elsif (s/^supersede:(\S+)=(\w+) //) {
481 die "supersede $1 twice" if defined $supersedes{$1};
482 $supersedes{$1} = $2;
483 } elsif (s/^[-+.=0-9a-z]\S* //) {
485 die "unknown dgit info in tag ($_)";
490 last if m/^-----BEGIN PGP/;
501 debug " parsetag ok.";
504 sub checksig_keyring ($) {
505 my ($keyringfile) = @_;
506 # returns primary-keyid if signed by a key in this keyring
508 # or dies on other errors
512 debug " checksig keyring $keyringfile...";
514 our @cmd = (qw(gpgv --status-fd=1 --keyring),
516 qw(dgit-tmp/plaintext.asc dgit-tmp/plaintext));
523 next unless s/^\[GNUPG:\] //;
525 debug " checksig| $_";
526 my @l = split / /, $_;
527 if ($l[0] eq 'NO_PUBKEY') {
529 } elsif ($l[0] eq 'VALIDSIG') {
531 $sigtype eq '00' or reject "signature is not of type 00!";
533 die unless defined $ok;
539 debug sprintf " checksig ok=%d", !!$ok;
544 sub dm_txt_check ($$) {
545 my ($keyid, $dmtxtfn) = @_;
546 debug " dm_txt_check $keyid $dmtxtfn";
547 open DT, '<', $dmtxtfn or die "$dmtxtfn $!";
549 m/^fingerprint:\s+$keyid$/oi
551 if (s/^allow:/ /i..0) {
554 or reject "key $keyid missing Allow section in permissions!";
559 or reject "package $package not allowed for key $keyid";
564 debug " dm_txt_check allow| $_";
565 foreach my $p (split /\s+/) {
566 if ($p eq $package) {
568 debug " dm_txt_check ok";
573 DT->error and die $!;
575 reject "key $keyid not in permissions list although in keyring!";
579 foreach my $kas (split /:/, $keyrings) {
580 debug "verifytag $kas...";
581 $kas =~ s/^([^,]+),// or die;
582 my $keyid = checksig_keyring $1;
583 if (defined $keyid) {
584 if ($kas =~ m/^a$/) {
585 debug "verifytag a ok";
587 } elsif ($kas =~ m/^m([^,]+)$/) {
588 dm_txt_check($keyid, $1);
589 debug "verifytag m ok";
596 reject "key not found in keyrings";
600 debug "checksuite ($suitesfile)";
601 open SUITES, "<", $suitesfile or die $!;
607 return if $_ eq $suite;
609 die $! if SUITES->error;
610 reject "unknown suite";
613 sub checktagnoreplay () {
614 # We check that the signed tag mentions the name and value of
615 # (a) in the case of FRESHREPO all tags in the repo;
616 # (b) in the case of just NOFFCHECK all tags referring to
617 # the current head for the suite (there must be at least one).
618 # This prevents a replay attack using an earlier signed tag.
619 return unless $policy & (FRESHREPO|NOFFCHECK);
621 my $garbagerepo = "$dgitrepos/${package}_garbage";
625 foreach my $garb ("$garbagerepo", "$garbagerepo-old") {
626 if (stat_exists $garb) {
627 $ENV{GIT_DIR} = $garb;
631 if (!defined $ENV{GIT_DIR}) {
632 # Nothing to overwrite so the FRESHREPO and NOFFCHECK were
633 # pointless. Oh well.
634 debug "checktagnoreplay - no garbage, ok";
639 if (!($policy & FRESHREPO)) {
640 my $branch = server_branch($suite);
642 `git for-each-ref --format='%(objectname)' '[r]efs/$branch'`;
643 defined or die "$branch $? $!";
644 $? and die "$branch $?";
646 # No such branch - NOFFCHECK was unnecessary. Oh well.
647 debug "checktagnoreplay - not FRESHREPO, new branch, ok";
650 m/^(\w+)\n$/ or die "$branch $_ ?";
652 debug "checktagnoreplay - not FRESHREPO,".
653 " checking for overwriting refs/$branch=$onlyreferring";
658 git_for_each_tag_referring($onlyreferring, sub {
659 my ($objid,$fullrefname,$tagname) = @_;
660 debug "checktagnoreplay - overwriting $fullrefname=$objid";
661 my $supers = $supersedes{$fullrefname};
662 if (!defined $supers) {
663 push @problems, "does not supersede $fullrefname";
664 } elsif ($supers ne $objid) {
666 "supersedes $fullrefname=$supers but previously $fullrefname=$objid";
673 reject "replay attack prevention check failed:".
674 " signed tag for $version: ".
675 join("; ", @problems).
678 debug "checktagnoreply - all ok"
683 my $vals = $tagh{$tag};
684 reject "missing header $tag in signed tag object" unless $vals;
685 reject "multiple headers $tag in signed tag object" unless @$vals == 1;
692 tagh1('type') eq 'commit' or reject "tag refers to wrong kind of object";
693 tagh1('object') eq $commit or reject "tag refers to wrong commit";
694 tagh1('tag') eq $tagname or reject "tag name in tag is wrong";
699 debug "translated version $v";
700 $tagname eq "debian/$v" or die;
704 my @policy_args = ($package,$version,$suite,$tagname,
705 join(",",@deliberatelies));
706 $policy = policyhook(NOFFCHECK|FRESHREPO, 'push', @policy_args);
711 # check that our ref is being fast-forwarded
712 debug "oldcommit $oldcommit";
713 if (!($policy & NOFFCHECK) && $oldcommit =~ m/[^0]/) {
714 $?=0; $!=0; my $mb = `git merge-base $commit $oldcommit`;
716 $mb eq $oldcommit or reject "not fast forward on dgit branch";
719 if ($policy & FRESHREPO) {
720 # This is troublesome. We have been asked by the policy hook
721 # to receive the push into a fresh repo. But of course we
722 # have actually already mostly received the push into the working
723 # repo. (This is unavoidable because the instruction to use a new
724 # repo comes ultimately from the signed tag for the dgit push,
725 # which has to have been received into some repo.)
727 # So what we do is generate a fresh working repo right now and
728 # push the head and tag into it. The presence of this fresh
729 # working repo is detected by the parent, which responds by
730 # making a fresh master repo from the template.
732 $destrepo = "${workrepo}_fresh"; # workrepo lock covers
733 mkrepo_fromtemplate $destrepo;
736 policyhook(0, 'push-confirm', @policy_args);
740 my @cmd = (qw(git send-pack), $destrepo);
741 push @cmd, qw(--force) if $policy & NOFFCHECK;
742 push @cmd, "$commit:refs/dgit/$suite",
743 "$tagval:refs/tags/$tagname";
747 !$r or die "onward push to $destrepo failed: $r $!";
752 chdir $workrepo or die "chdir $workrepo: $!";
753 mkdir "dgit-tmp" or $!==EEXIST or die $!;
759 debug "stunthook done.";
762 #----- git-upload-pack -----
764 sub fixmissing__git_upload_pack () {
765 $destrepo = "$dgitrepos/_empty";
766 my $lfh = locksometree($destrepo);
767 return if stat_exists $destrepo;
768 rmtree "$destrepo.new";
769 mkemptyrepo "$destrepo.new", "0644";
770 rename "$destrepo.new", $destrepo or die $!;
771 unlink "$destrepo.lock" or die $!;
775 sub main__git_upload_pack () {
776 my $lfh = locksometree($destrepo);
777 chdir $destrepo or die "$destrepo: $!";
779 runcmd qw(git upload-pack), ".";
782 #----- arg parsing and main program -----
792 # keys are used for DGIT_DRS_XXX too
793 'repos' => \$dgitrepos,
794 'suites' => \$suitesfile,
795 'policy-hook' => \$policyhook,
798 our @hookenvs = qw(distro suitesfile policyhook keyrings dgitrepos);
800 # workrepo and destrepo handled ad-hoc
805 my $cmd = $ENV{'SSH_ORIGINAL_COMMAND'};
815 or reject "command string not understood";
821 my $mainfunc = $main::{"main__$funcn"};
823 reject "unknown method" unless $mainfunc;
825 my $lfh = lockrealtree();
827 $policy = policyhook(FRESHREPO,'check-package',$package);
828 if ($policy & FRESHREPO) {
834 if (stat_exists realdestrepo) {
835 $destrepo = realdestrepo;
837 debug " fixmissing $funcn";
838 my $fixfunc = $main::{"fixmissing__$funcn"};
842 debug " running main $funcn";
846 sub parseargsdispatch () {
849 delete $ENV{'GIT_DIR'}; # if not run via ssh, our parent git process
850 delete $ENV{'GIT_PREFIX'}; # sets these and they mess things up
852 if ($ENV{'DGIT_DRS_DEBUG'}) {
854 open DEBUG, ">&STDERR" or die $!;
857 if ($ARGV[0] eq '--pre-receive-hook') {
858 if ($debug) { $debug.="="; }
861 $package = shift @ARGV;
862 ${ $main::{$_} } = $ENV{"DGIT_DRS_\U$_"} foreach @hookenvs;
863 defined($workrepo = $ENV{'DGIT_DRS_WORK'}) or die;
864 defined($destrepo = $ENV{'DGIT_DRS_DEST'}) or die;
865 open STDOUT, ">&STDERR" or die $!;
870 recorderror "$@" or die;
876 $distro = $ENV{'DGIT_DRS_DISTRO'} = argval();
877 my $distrodir = argval();
878 $keyrings = $ENV{'DGIT_DRS_KEYRINGS'} = argval();
880 foreach my $dk (keys %indistrodir) {
881 ${ $indistrodir{$dk} } = "$distrodir/$dk";
884 while (@ARGV && $ARGV[0] =~ m/^--([-0-9a-z]+)=/ && $indistrodir{$1}) {
885 ${ $indistrodir{$1} } = $'; #';
889 $ENV{"DGIT_DRS_\U$_"} = ${ $main::{$_} } foreach @hookenvs;
893 my $mode = shift @ARGV;
894 die unless $mode =~ m/^--(\w+)$/;
895 my $fn = ${*::}{"mode_$1"};
901 while (my $fh = pop @lockfhs) { close $fh; }
906 if (!chdir "$dgitrepos/_tmp") {
907 $!==ENOENT or die $!;
910 foreach my $lf (<*.lock>) {
912 $tree =~ s/\.lock$//;
913 next unless acquirermtree($tree, 0);
914 remove $lf or warn $!;