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
30 # DGIT-REPOS-DIR contains:
31 # git tree (or other object) lock (in acquisition order, outer first)
33 # _tmp/PACKAGE_prospective ! } SAME.lock, held during receive-pack
35 # _tmp/PACKAGE_incoming$$ ! } SAME.lock, held during receive-pack
36 # _tmp/PACKAGE_incoming$$_fresh ! }
38 # PACKAGE.git } PACKAGE.git.lock
39 # PACKAGE_garbage } (also covers executions of
40 # PACKAGE_garbage-old } policy hook script for PACKAGE)
41 # PACKAGE_garbage-tmp }
42 # policy* } (for policy hook script, covered by
43 # } lock only when invoked for a package)
45 # leaf locks, held during brief operaton only:
50 # _template } SAME.lock
52 # locks marked ! may be held during client data transfer
54 # What we do on push is this:
55 # - extract the destination repo name
56 # - make a hardlink clone of the destination repo
57 # - provide the destination with a stunt pre-receive hook
58 # - run actual git-receive-pack with that new destination
59 # as a result of this the stunt pre-receive hook runs; it does this:
60 # + understand what refs we are allegedly updating and
61 # check some correspondences:
62 # * we are updating only refs/tags/debian/* and refs/dgit/*
63 # * and only one of each
64 # * and the tag does not already exist
66 # * recover the suite name from the destination refs/dgit/ ref
67 # + disassemble the signed tag into its various fields and signature
69 # * parsing the first line of the tag message to recover
70 # the package name, version and suite
71 # * checking that the package name corresponds to the dest repo name
72 # * checking that the suite name is as recovered above
73 # + verify the signature on the signed tag
74 # and if necessary check that the keyid and package are listed in dm.txt
75 # + check various correspondences:
76 # * the signed tag must refer to a commit
77 # * the signed tag commit must be the refs/dgit value
78 # * the name in the signed tag must correspond to its ref name
79 # * the tag name must be debian/<version> (massaged as needed)
80 # * the suite is one of those permitted
81 # * the signed tag has a suitable name
82 # * run the "push" policy hook
83 # * replay prevention for --deliberately-not-fast-forward
84 # * check the commit is a fast forward
85 # * handle a request from the policy hook for a fresh repo
86 # + push the signed tag and new dgit branch to the actual repo
88 # If the destination repo does not already exist, we need to make
89 # sure that we create it reasonably atomically, and also that
90 # we don't every have a destination repo containing no refs at all
91 # (because such a thing causes git-fetch-pack to barf). So then we
92 # do as above, except:
93 # - before starting, we take out our own lock for the destination repo
94 # - we create a prospective new destination repo by making a copy
96 # - we use the prospective new destination repo instead of the
97 # actual new destination repo (since the latter doesn't exist)
98 # - after git-receive-pack exits, we
99 # + check that the prospective repo contains a tag and head
100 # + rename the prospective destination repo into place
103 # - We are crash-only
104 # - Temporary working trees and their locks are cleaned up
105 # opportunistically by a program which tries to take each lock and
106 # if successful deletes both the tree and the lockfile
107 # - Prospective working trees and their locks are cleaned up by
108 # a program which tries to take each lock and if successful
109 # deletes any prospective working tree and the lock (but not
110 # of course any actual tree)
111 # - It is forbidden to _remove_ the lockfile without removing
112 # the corresponding temporary tree, as the lockfile is also
113 # a stampfile whose presence indicates that there may be
116 # Policy hook script is invoked like this:
117 # POLICY-HOOK-SCRIPT DISTRO DGIT-REPOS-DIR ACTION...
119 # POLICY-HOOK-SCRIPT ... check-list [...]
120 # POLICY-HOOK-SCRIPT ... check-package PACKAGE [...]
121 # POLICY-HOOK-SCRIPT ... push|push-confirm PACKAGE \
122 # VERSION SUITE TAGNAME DELIBERATELIES [...]
124 # Exit status is a bitmask. Bit weight constants are defined in Dgit.pm.
126 # suppress dgit-repos-server's fast-forward check ("push" only)
128 # blow away repo right away (ie, as if before push or fetch)
129 # ("check-package" and "push" only)
130 # any unexpected bits mean failure, and then known set bits are ignored
131 # if no unexpected bits set, operation continues (subject to meaning
132 # of any expected bits set). So, eg, exit 0 means "continue normally"
133 # and would be appropriate for an unknown action.
135 # cwd for push and push-confirm is a temporary repo where the
136 # to-be-pushed objects have been received; TAGNAME is the
139 # if push requested FRESHREPO, push-confirm happens in said fresh repo
141 # policy hook for a particular package will be invoked only once at
142 # a time - (see comments about DGIT-REPOS-DIR, above)
144 # check-list and check-package are invoked via the --cron option.
145 # First, without any locking, check-list is called. It should produce
146 # a list of package names. Then check-package will be invoked for
147 # each named package, in each case after taking an appropriate lock.
151 use Fcntl qw(:flock);
152 use File::Path qw(rmtree);
154 use Debian::Dgit qw(:DEFAULT :policyflags);
156 open DEBUG, ">/dev/null" or die $!;
174 #----- utilities -----
177 print DEBUG "$debug @_\n";
180 sub acquirelock ($$) {
181 my ($lock, $must) = @_;
183 printf DEBUG "$debug locking %s %d\n", $lock, $must;
186 $fh = new IO::File $lock, ">" or die "open $lock: $!";
187 my $ok = flock $fh, $must ? LOCK_EX : (LOCK_EX|LOCK_NB);
189 die "flock $lock: $!" if $must;
190 debug " locking $lock failed";
193 next unless stat_exists $lock;
194 my $want = (stat _)[1];
196 my $got = (stat _)[1];
197 last if $got == $want;
202 sub acquirermtree ($$) {
203 my ($tree, $must) = @_;
204 my $fh = acquirelock("$tree.lock", $must);
212 sub locksometree ($) {
214 acquirelock("$tree.lock", 1);
217 sub lockrealtree () {
218 locksometree($realdestrepo);
222 my $tmpdir = "$dgitrepos/_tmp";
223 return if mkdir $tmpdir;
224 return if $! == EEXIST;
228 sub recorderror ($) {
230 my $w = $ENV{'DGIT_DRS_WORK'}; # we are in stunthook
233 open ERR, ">", "$w/drs-error" or die $!;
234 print ERR $why, "\n" or die $!;
243 recorderror "reject: $why";
244 die "dgit-repos-server: reject: $why\n";
250 local $Data::Dumper::Indent = 0;
251 local $Data::Dumper::Terse = 1;
252 debug "|".Dumper(\@_);
260 die "@_ $? $!" if $r;
264 my ($policyallowbits, @polargs) = @_;
265 # => ($exitstatuspolicybitmap);
266 die if $policyallowbits & ~0x3e;
267 my @cmd = ($policyhook,$distro,$dgitrepos,@polargs);
270 die "system: $!" if $r < 0;
271 die "hook (@cmd) failed ($?)" if $r & ~($policyallowbits << 8);
275 sub mkemptyrepo ($$) {
276 my ($dir,$sharedperm) = @_;
277 runcmd qw(git init --bare --quiet), "--shared=$sharedperm", $dir;
280 sub mkrepo_fromtemplate ($) {
282 my $template = "$dgitrepos/_template";
283 locksometree($template);
284 debug "copy template $template -> $dir";
285 my $r = system qw(cp -a --), $template, $dir;
286 !$r or die "create new repo $dir failed: $r $!";
289 sub movetogarbage () {
290 # $realdestrepo must have been locked
291 my $garbagerepo = "$dgitrepos/${package}_garbage";
292 # We arrange to always keep at least one old tree, for anti-rewind
293 # purposes (and, I guess, recovery from mistakes). This is either
294 # $garbage or $garbage-old.
295 if (stat_exists "$garbagerepo") {
296 rmtree "$garbagerepo-tmp";
297 if (rename "$garbagerepo-old", "$garbagerepo-tmp") {
298 rmtree "$garbagerepo-tmp";
300 die "$garbagerepo $!" unless $!==ENOENT;
302 rename "$garbagerepo", "$garbagerepo-old" or die "$garbagerepo $!";
304 rename $realdestrepo, $garbagerepo
306 or die "$garbagerepo $!";
309 #----- git-receive-pack -----
311 sub fixmissing__git_receive_pack () {
313 $destrepo = "$dgitrepos/_tmp/${package}_prospective";
314 acquirermtree($destrepo, 1);
315 mkrepo_fromtemplate($destrepo);
318 sub makeworkingclone () {
320 $workrepo = "$dgitrepos/_tmp/${package}_incoming$$";
321 acquirermtree($workrepo, 1);
322 my $lfh = lockrealtree();
323 runcmd qw(git clone -l -q --mirror), $destrepo, $workrepo;
325 rmtree "${workrepo}_fresh";
328 sub setupstunthook () {
329 my $prerecv = "$workrepo/hooks/pre-receive";
330 my $fh = new IO::File $prerecv, O_WRONLY|O_CREAT|O_TRUNC, 0777
331 or die "$prerecv: $!";
332 print $fh <<END or die "$prerecv: $!";
335 exec $0 --pre-receive-hook $package
337 close $fh or die "$prerecv: $!";
338 $ENV{'DGIT_DRS_WORK'}= $workrepo;
339 $ENV{'DGIT_DRS_DEST'}= $destrepo;
340 debug " stunt hook set up $prerecv";
343 sub dealwithfreshrepo () {
344 my $freshrepo = "${workrepo}_fresh";
345 return unless stat_exists $freshrepo;
346 $destrepo = $freshrepo;
349 sub maybeinstallprospective () {
350 return if $destrepo eq $realdestrepo;
352 if (open REJ, "<", "$workrepo/drs-error") {
355 REJ->error and die $!;
359 $!==&ENOENT or die $!;
362 debug " show-ref ($destrepo) ...";
364 my $child = open SR, "-|";
365 defined $child or die $!;
367 chdir $destrepo or die $!;
368 exec qw(git show-ref);
371 my %got = qw(tag 0 head 0);
374 debug " show-refs| $_";
375 s/^\S*[1-9a-f]\S* (\S+)$/$1/ or die;
377 m{^refs/tags/} ? 'tag' :
378 m{^refs/dgit/} ? 'head' :
382 $!=0; $?=0; close SR or $?==256 or die "$? $!";
384 debug "installprospective ?";
385 die Dumper(\%got)." -- missing refs in new repo"
386 if grep { !$_ } values %got;
390 if ($destrepo eq "${workrepo}_fresh") {
394 debug "install $destrepo => $realdestrepo";
395 rename $destrepo, $realdestrepo or die $!;
396 remove "$destrepo.lock" or die $!;
399 sub main__git_receive_pack () {
402 runcmd qw(git receive-pack), $workrepo;
404 maybeinstallprospective();
407 #----- stunt post-receive hook -----
409 our ($tagname, $tagval, $suite, $oldcommit, $commit);
410 our ($version, %tagh);
413 debug " updates ...";
417 m/^(\S+) (\S+) (\S+)$/ or die "$_ ?";
418 my ($old, $sha1, $refname) = ($1, $2, $3);
419 if ($refname =~ m{^refs/tags/(?=debian/)}) {
420 reject "pushing multiple tags!" if defined $tagname;
423 reject "tag $tagname already exists -".
424 " not replacing previously-pushed version"
426 } elsif ($refname =~ m{^refs/dgit/}) {
427 reject "pushing multiple heads!" if defined $suite;
432 reject "pushing unexpected ref!";
435 STDIN->error and die $!;
437 reject "push is missing tag ref update" unless defined $tagname;
438 reject "push is missing head ref update" unless defined $suite;
439 debug " updates ok.";
443 debug " parsetag...";
444 open PT, ">dgit-tmp/plaintext" or die $!;
445 open DS, ">dgit-tmp/plaintext.asc" or die $!;
446 open T, "-|", qw(git cat-file tag), $tagval or die $!;
448 $!=0; $_=<T>; defined or die $!;
450 if (m/^(\S+) (.*)/) {
451 push @{ $tagh{$1} }, $2;
458 $!=0; $_=<T>; defined or die $!;
459 m/^($package_re) release (\S+) for \S+ \((\S+)\) \[dgit\]$/ or
460 reject "tag message not in expected format";
462 die unless $1 eq $package;
464 die "$3 != $suite " unless $3 eq $suite;
468 print PT $copyl or die $!;
469 $!=0; $_=<T>; defined or die "missing signature? $!";
471 if (m/^\[dgit ([^"].*)\]$/) { # [dgit "something"] is for future
474 if (s/^distro\=(\S+) //) {
475 die "$1 != $distro" unless $1 eq $distro;
476 } elsif (s/^(--deliberately-$package_re) //) {
477 push @deliberatelies, $1;
478 } elsif (s/^supersede:(\S+)=(\w+) //) {
479 die "supersede $1 twice" if defined $supersedes{$1};
480 $supersedes{$1} = $2;
481 } elsif (s/^[-+.=0-9a-z]\S* //) {
483 die "unknown dgit info in tag ($_)";
488 last if m/^-----BEGIN PGP/;
499 debug " parsetag ok.";
502 sub checksig_keyring ($) {
503 my ($keyringfile) = @_;
504 # returns primary-keyid if signed by a key in this keyring
506 # or dies on other errors
510 debug " checksig keyring $keyringfile...";
512 our @cmd = (qw(gpgv --status-fd=1 --keyring),
514 qw(dgit-tmp/plaintext.asc dgit-tmp/plaintext));
521 next unless s/^\[GNUPG:\] //;
523 debug " checksig| $_";
524 my @l = split / /, $_;
525 if ($l[0] eq 'NO_PUBKEY') {
527 } elsif ($l[0] eq 'VALIDSIG') {
529 $sigtype eq '00' or reject "signature is not of type 00!";
531 die unless defined $ok;
537 debug sprintf " checksig ok=%d", !!$ok;
542 sub dm_txt_check ($$) {
543 my ($keyid, $dmtxtfn) = @_;
544 debug " dm_txt_check $keyid $dmtxtfn";
545 open DT, '<', $dmtxtfn or die "$dmtxtfn $!";
547 m/^fingerprint:\s+$keyid$/oi
549 if (s/^allow:/ /i..0) {
552 or reject "key $keyid missing Allow section in permissions!";
557 or reject "package $package not allowed for key $keyid";
562 debug " dm_txt_check allow| $_";
563 foreach my $p (split /\s+/) {
564 if ($p eq $package) {
566 debug " dm_txt_check ok";
571 DT->error and die $!;
573 reject "key $keyid not in permissions list although in keyring!";
577 foreach my $kas (split /:/, $keyrings) {
578 debug "verifytag $kas...";
579 $kas =~ s/^([^,]+),// or die;
580 my $keyid = checksig_keyring $1;
581 if (defined $keyid) {
582 if ($kas =~ m/^a$/) {
583 debug "verifytag a ok";
585 } elsif ($kas =~ m/^m([^,]+)$/) {
586 dm_txt_check($keyid, $1);
587 debug "verifytag m ok";
594 reject "key not found in keyrings";
598 debug "checksuite ($suitesfile)";
599 open SUITES, "<", $suitesfile or die $!;
605 return if $_ eq $suite;
607 die $! if SUITES->error;
608 reject "unknown suite";
611 sub checktagnoreplay () {
612 # We check that the signed tag mentions the name and value of
613 # (a) in the case of FRESHREPO all tags in the repo;
614 # (b) in the case of just NOFFCHECK all tags referring to
615 # the current head for the suite (there must be at least one).
616 # This prevents a replay attack using an earlier signed tag.
617 return unless $policy & (FRESHREPO|NOFFCHECK);
619 my $garbagerepo = "$dgitrepos/${package}_garbage";
623 foreach my $garb ("$garbagerepo", "$garbagerepo-old") {
624 if (stat_exists $garb) {
625 $ENV{GIT_DIR} = $garb;
629 if (!defined $ENV{GIT_DIR}) {
630 # Nothing to overwrite so the FRESHREPO and NOFFCHECK were
631 # pointless. Oh well.
632 debug "checktagnoreplay - no garbage, ok";
637 if (!($policy & FRESHREPO)) {
638 my $branch = server_branch($suite);
640 `git for-each-ref --format='%(objectname)' '[r]efs/$branch'`;
641 defined or die "$branch $? $!";
642 $? and die "$branch $?";
644 # No such branch - NOFFCHECK was unnecessary. Oh well.
645 debug "checktagnoreplay - not FRESHREPO, new branch, ok";
648 m/^(\w+)\n$/ or die "$branch $_ ?";
650 debug "checktagnoreplay - not FRESHREPO,".
651 " checking for overwriting refs/$branch=$onlyreferring";
656 git_for_each_tag_referring($onlyreferring, sub {
657 my ($objid,$fullrefname,$tagname) = @_;
658 debug "checktagnoreplay - overwriting $fullrefname=$objid";
659 my $supers = $supersedes{$fullrefname};
660 if (!defined $supers) {
661 push @problems, "does not supersede $fullrefname";
662 } elsif ($supers ne $objid) {
664 "supersedes $fullrefname=$supers but previously $fullrefname=$objid";
671 reject "replay attack prevention check failed:".
672 " signed tag for $version: ".
673 join("; ", @problems).
676 debug "checktagnoreply - all ok"
681 my $vals = $tagh{$tag};
682 reject "missing header $tag in signed tag object" unless $vals;
683 reject "multiple headers $tag in signed tag object" unless @$vals == 1;
690 tagh1('type') eq 'commit' or reject "tag refers to wrong kind of object";
691 tagh1('object') eq $commit or reject "tag refers to wrong commit";
692 tagh1('tag') eq $tagname or reject "tag name in tag is wrong";
697 debug "translated version $v";
698 $tagname eq "debian/$v" or die;
702 my @policy_args = ($package,$version,$suite,$tagname,
703 join(",",@deliberatelies));
704 $policy = policyhook(NOFFCHECK|FRESHREPO, 'push', @policy_args);
709 # check that our ref is being fast-forwarded
710 debug "oldcommit $oldcommit";
711 if (!($policy & NOFFCHECK) && $oldcommit =~ m/[^0]/) {
712 $?=0; $!=0; my $mb = `git merge-base $commit $oldcommit`;
714 $mb eq $oldcommit or reject "not fast forward on dgit branch";
717 if ($policy & FRESHREPO) {
718 # This is troublesome. We have been asked by the policy hook
719 # to receive the push into a fresh repo. But of course we
720 # have actually already mostly received the push into the working
721 # repo. (This is unavoidable because the instruction to use a new
722 # repo comes ultimately from the signed tag for the dgit push,
723 # which has to have been received into some repo.)
725 # So what we do is generate a fresh working repo right now and
726 # push the head and tag into it. The presence of this fresh
727 # working repo is detected by the parent, which responds by
728 # making a fresh master repo from the template.
730 $destrepo = "${workrepo}_fresh"; # workrepo lock covers
731 mkrepo_fromtemplate $destrepo;
734 policyhook(0, 'push-confirm', @policy_args);
738 my @cmd = (qw(git send-pack), $destrepo);
739 push @cmd, qw(--force) if $policy & NOFFCHECK;
740 push @cmd, "$commit:refs/dgit/$suite",
741 "$tagval:refs/tags/$tagname";
745 !$r or die "onward push to $destrepo failed: $r $!";
750 chdir $workrepo or die "chdir $workrepo: $!";
751 mkdir "dgit-tmp" or $!==EEXIST or die $!;
757 debug "stunthook done.";
760 #----- git-upload-pack -----
762 sub fixmissing__git_upload_pack () {
763 $destrepo = "$dgitrepos/_empty";
764 my $lfh = locksometree($destrepo);
765 return if stat_exists $destrepo;
766 rmtree "$destrepo.new";
767 mkemptyrepo "$destrepo.new", "0644";
768 rename "$destrepo.new", $destrepo or die $!;
769 unlink "$destrepo.lock" or die $!;
773 sub main__git_upload_pack () {
774 my $lfh = locksometree($destrepo);
775 chdir $destrepo or die "$destrepo: $!";
777 runcmd qw(git upload-pack), ".";
780 #----- arg parsing and main program -----
790 # keys are used for DGIT_DRS_XXX too
791 'repos' => \$dgitrepos,
792 'suites' => \$suitesfile,
793 'policy-hook' => \$policyhook,
796 our @hookenvs = qw(distro suitesfile policyhook keyrings dgitrepos);
798 # workrepo and destrepo handled ad-hoc
800 sub parseargsdispatch () {
803 delete $ENV{'GIT_DIR'}; # if not run via ssh, our parent git process
804 delete $ENV{'GIT_PREFIX'}; # sets these and they mess things up
806 if ($ENV{'DGIT_DRS_DEBUG'}) {
808 open DEBUG, ">&STDERR" or die $!;
811 if ($ARGV[0] eq '--pre-receive-hook') {
812 if ($debug) { $debug.="="; }
815 $package = shift @ARGV;
816 ${ $main::{$_} } = $ENV{"DGIT_DRS_\U$_"} foreach @hookenvs;
817 defined($workrepo = $ENV{'DGIT_DRS_WORK'}) or die;
818 defined($destrepo = $ENV{'DGIT_DRS_DEST'}) or die;
819 open STDOUT, ">&STDERR" or die $!;
824 recorderror "$@" or die;
830 $distro = $ENV{'DGIT_DRS_DISTRO'} = argval();
831 my $distrodir = argval();
832 $keyrings = $ENV{'DGIT_DRS_KEYRINGS'} = argval();
834 foreach my $dk (keys %indistrodir) {
835 ${ $indistrodir{$dk} } = "$distrodir/$dk";
838 while (@ARGV && $ARGV[0] =~ m/^--([-0-9a-z]+)=/ && $indistrodir{$1}) {
839 ${ $indistrodir{$1} } = $'; #';
843 $ENV{"DGIT_DRS_\U$_"} = ${ $main::{$_} } foreach @hookenvs;
845 die unless @ARGV==1 && $ARGV[0] eq '--ssh';
847 my $cmd = $ENV{'SSH_ORIGINAL_COMMAND'};
857 or reject "command string not understood";
860 $realdestrepo = "$dgitrepos/$package.git";
864 my $mainfunc = $main::{"main__$funcn"};
866 reject "unknown method" unless $mainfunc;
868 my $lfh = lockrealtree();
870 $policy = policyhook(FRESHREPO,'check-package',$package);
871 if ($policy & FRESHREPO) {
877 if (stat_exists $realdestrepo) {
878 $destrepo = $realdestrepo;
880 debug " fixmissing $funcn";
881 my $fixfunc = $main::{"fixmissing__$funcn"};
885 debug " running main $funcn";
890 while (my $fh = pop @lockfhs) { close $fh; }
895 if (!chdir "$dgitrepos/_tmp") {
896 $!==ENOENT or die $!;
899 foreach my $lf (<*.lock>) {
901 $tree =~ s/\.lock$//;
902 next unless acquirermtree($tree, 0);
903 remove $lf or warn $!;