chiark / gitweb /
dgit-repos-server: Break out policy_checkpackage() (nfc)
[dgit.git] / infra / dgit-repos-server
1 #!/usr/bin/perl -w
2 # dgit-repos-server
3 #
4 # usages:
5 #   dgit-repos-server DISTRO DISTRO-DIR AUTH-SPEC [<settings>] --ssh
6 #   dgit-repos-server DISTRO DISTRO-DIR AUTH-SPEC [<settings>] --cron
7 # settings
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 #   --dgit-live=DGIT-LIVE-DIR  default DISTRO-DIR/dgit-live
12 # (DISTRO-DIR is not used other than as default)
13 # internal usage:
14 #  .../dgit-repos-server --pre-receive-hook PACKAGE
15 #
16 # Invoked as the ssh restricted command
17 #
18 # Works like git-receive-pack
19 #
20 # SUITES is the name of a file which lists the permissible suites
21 # one per line (#-comments and blank lines ignored)
22 #
23 # AUTH-SPEC is a :-separated list of
24 #   KEYRING.GPG,AUTH-SPEC
25 # where AUTH-SPEC is one of
26 #   a
27 #   mDM.TXT
28
29 use strict;
30 $SIG{__WARN__} = sub { die $_[0]; };
31
32 # DGIT-REPOS-DIR contains:
33 # git tree (or other object)      lock (in acquisition order, outer first)
34 #
35 #  _tmp/PACKAGE_prospective       ! } SAME.lock, held during receive-pack
36 #
37 #  _tmp/PACKAGE_incoming$$        ! } SAME.lock, held during receive-pack
38 #  _tmp/PACKAGE_incoming$$_fresh  ! }
39 #
40 #  PACKAGE.git                      } PACKAGE.git.lock
41 #  PACKAGE_garbage                  }   (also covers executions of
42 #  PACKAGE_garbage-old              }    policy hook script for PACKAGE)
43 #  PACKAGE_garbage-tmp              }
44 #  policy*                          } (for policy hook script, covered by
45 #                                   }  lock only when invoked for a package)
46 #
47 # leaf locks, held during brief operaton only:
48 #
49 #  _empty                           } SAME.lock
50 #  _empty.new                       }
51 #
52 #  _template                        } SAME.lock
53 #
54 # locks marked ! may be held during client data transfer
55
56 # What we do on push is this:
57 #  - extract the destination repo name
58 #  - make a hardlink clone of the destination repo
59 #  - provide the destination with a stunt pre-receive hook
60 #  - run actual git-receive-pack with that new destination
61 #   as a result of this the stunt pre-receive hook runs; it does this:
62 #    + understand what refs we are allegedly updating and
63 #      check some correspondences:
64 #        * we are updating only refs/tags/debian/* and refs/dgit/*
65 #        * and only one of each
66 #        * and the tag does not already exist
67 #      and
68 #        * recover the suite name from the destination refs/dgit/ ref
69 #    + disassemble the signed tag into its various fields and signature
70 #      including:
71 #        * parsing the first line of the tag message to recover
72 #          the package name, version and suite
73 #        * checking that the package name corresponds to the dest repo name
74 #        * checking that the suite name is as recovered above
75 #    + verify the signature on the signed tag
76 #      and if necessary check that the keyid and package are listed in dm.txt
77 #    + check various correspondences:
78 #        * the signed tag must refer to a commit
79 #        * the signed tag commit must be the refs/dgit value
80 #        * the name in the signed tag must correspond to its ref name
81 #        * the tag name must be debian/<version> (massaged as needed)
82 #        * the suite is one of those permitted
83 #        * the signed tag has a suitable name
84 #        * run the "push" policy hook
85 #        * replay prevention for --deliberately-not-fast-forward
86 #        * check the commit is a fast forward
87 #        * handle a request from the policy hook for a fresh repo
88 #    + push the signed tag and new dgit branch to the actual repo
89 #
90 # If the destination repo does not already exist, we need to make
91 # sure that we create it reasonably atomically, and also that
92 # we don't every have a destination repo containing no refs at all
93 # (because such a thing causes git-fetch-pack to barf).  So then we
94 # do as above, except:
95 #  - before starting, we take out our own lock for the destination repo
96 #  - we create a prospective new destination repo by making a copy
97 #    of _template
98 #  - we use the prospective new destination repo instead of the
99 #    actual new destination repo (since the latter doesn't exist)
100 #  - after git-receive-pack exits, we
101 #    + check that the prospective repo contains a tag and head
102 #    + rename the prospective destination repo into place
103 #
104 # Cleanup strategy:
105 #  - We are crash-only
106 #  - Temporary working trees and their locks are cleaned up
107 #    opportunistically by a program which tries to take each lock and
108 #    if successful deletes both the tree and the lockfile
109 #  - Prospective working trees and their locks are cleaned up by
110 #    a program which tries to take each lock and if successful
111 #    deletes any prospective working tree and the lock (but not
112 #    of course any actual tree)
113 #  - It is forbidden to _remove_ the lockfile without removing
114 #    the corresponding temporary tree, as the lockfile is also
115 #    a stampfile whose presence indicates that there may be
116 #    cleanup to do
117 #
118 # Policy hook script is invoked like this:
119 #   POLICY-HOOK-SCRIPT DISTRO DGIT-REPOS-DIR DGIT-LIVE-DIR ACTION...
120 # ie.
121 #   POLICY-HOOK-SCRIPT ... check-list [...]
122 #   POLICY-HOOK-SCRIPT ... check-package PACKAGE [...]
123 #   POLICY-HOOK-SCRIPT ... push PACKAGE \
124 #         VERSION SUITE TAGNAME DELIBERATELIES [...]
125 #   POLICY-HOOK-SCRIPT ... push-confirm PACKAGE \
126 #         VERSION SUITE TAGNAME DELIBERATELIES FRESH-REPO|'' [...]
127 #
128 # Exit status is a bitmask.  Bit weight constants are defined in Dgit.pm.
129 #    NOFFCHECK   (2)
130 #         suppress dgit-repos-server's fast-forward check ("push" only)
131 #    FRESHREPO   (4)
132 #         blow away repo right away (ie, as if before push or fetch)
133 #         ("check-package" and "push" only)
134 # any unexpected bits mean failure, and then known set bits are ignored
135 # if no unexpected bits set, operation continues (subject to meaning
136 # of any expected bits set).  So, eg, exit 0 means "continue normally"
137 # and would be appropriate for an unknown action.
138 #
139 # cwd for push and push-confirm is a temporary repo where the
140 # to-be-pushed objects have been received; TAGNAME is the
141 # version-based tag
142 #
143 # FRESH-REPO is '' iff the repo for this package already existed, or
144 # the pathname of the newly-created repo which will be renamed into
145 # place if everything goes well.  (NB that this is generally not the
146 # same repo as the cwd, because the objects are first received into a
147 # temporary repo so they can be examined.)
148
149 # if push requested FRESHREPO, push-confirm happens in said fresh repo
150 # and FRESH-REPO is guaranteed not to be ''.
151 #
152 # policy hook for a particular package will be invoked only once at
153 # a time - (see comments about DGIT-REPOS-DIR, above)
154 #
155 # check-list and check-package are invoked via the --cron option.
156 # First, without any locking, check-list is called.  It should produce
157 # a list of package names.  Then check-package will be invoked for
158 # each named package, in each case after taking an appropriate lock.
159 #
160 # If policy hook wants to run dgit (or something else in the dgit
161 # package), it should use DGIT-LIVE-DIR/dgit (etc.)
162
163
164 use POSIX;
165 use Fcntl qw(:flock);
166 use File::Path qw(rmtree);
167
168 use Debian::Dgit qw(:DEFAULT :policyflags);
169
170 open DEBUG, ">/dev/null" or die $!;
171
172 our $func;
173 our $dgitrepos;
174 our $package;
175 our $distro;
176 our $suitesfile;
177 our $policyhook;
178 our $dgitlive;
179 our $destrepo;
180 our $workrepo;
181 our $keyrings;
182 our @lockfhs;
183 our $debug='';
184 our @deliberatelies;
185 our %supersedes;
186 our $policy;
187
188 #----- utilities -----
189
190 sub debug {
191     print DEBUG "$debug @_\n";
192 }
193
194 sub realdestrepo () { "$dgitrepos/$package.git"; }
195
196 sub acquirelock ($$) {
197     my ($lock, $must) = @_;
198     my $fh;
199     printf DEBUG "$debug locking %s %d\n", $lock, $must;
200     for (;;) {
201         close $fh if $fh;
202         $fh = new IO::File $lock, ">" or die "open $lock: $!";
203         my $ok = flock $fh, $must ? LOCK_EX : (LOCK_EX|LOCK_NB);
204         if (!$ok) {
205             die "flock $lock: $!" if $must;
206             debug " locking $lock failed";
207             return undef;
208         }
209         next unless stat_exists $lock;
210         my $want = (stat _)[1];
211         stat $fh or die $!;
212         my $got = (stat _)[1];
213         last if $got == $want;
214     }
215     return $fh;
216 }
217
218 sub acquirermtree ($$) {
219     my ($tree, $must) = @_;
220     my $fh = acquirelock("$tree.lock", $must);
221     if ($fh) {
222         push @lockfhs, $fh;
223         rmtree $tree;
224     }
225     return $fh;
226 }
227
228 sub locksometree ($) {
229     my ($tree) = @_;
230     acquirelock("$tree.lock", 1);
231 }
232
233 sub lockrealtree () {
234     locksometree(realdestrepo);
235 }
236
237 sub mkrepotmp () {
238     my $tmpdir = "$dgitrepos/_tmp";
239     return if mkdir $tmpdir;
240     return if $! == EEXIST;
241     die $!;
242 }
243
244 sub recorderror ($) {
245     my ($why) = @_;
246     my $w = $ENV{'DGIT_DRS_WORK'}; # we are in stunthook
247     if (defined $w) {
248         chomp $why;
249         open ERR, ">", "$w/drs-error" or die $!;
250         print ERR $why, "\n" or die $!;
251         close ERR or die $!;
252         return 1;
253     }
254     return 0;
255 }
256
257 sub reject ($) {
258     my ($why) = @_;
259     recorderror "reject: $why";
260     die "dgit-repos-server: reject: $why\n";
261 }
262
263 sub debugcmd {
264     if ($debug) {
265         use Data::Dumper;
266         local $Data::Dumper::Indent = 0;
267         local $Data::Dumper::Terse = 1;
268         debug "|".Dumper(\@_);
269     }
270 }
271
272 sub runcmd {
273     debugcmd @_;
274     $!=0; $?=0;
275     my $r = system @_;
276     die "@_ $? $!" if $r;
277 }
278
279 sub policyhook {
280     my ($policyallowbits, @polargs) = @_;
281     # => ($exitstatuspolicybitmap);
282     die if $policyallowbits & ~0x3e;
283     my @cmd = ($policyhook,$distro,$dgitrepos,$dgitlive,@polargs);
284     debugcmd @cmd;
285     my $r = system @cmd;
286     die "system: $!" if $r < 0;
287     die "hook (@cmd) failed ($?)" if $r & ~($policyallowbits << 8);
288     debug sprintf "hook (%s) => %#x", "@polargs", $r;
289     return $r >> 8;
290 }
291
292 sub mkemptyrepo ($$) {
293     my ($dir,$sharedperm) = @_;
294     runcmd qw(git init --bare --quiet), "--shared=$sharedperm", $dir;
295 }
296
297 sub mkrepo_fromtemplate ($) {
298     my ($dir) = @_;
299     my $template = "$dgitrepos/_template";
300     locksometree($template);
301     debug "copy template $template -> $dir";
302     my $r = system qw(cp -a --), $template, $dir;
303     !$r or die "create new repo $dir failed: $r $!";
304 }
305
306 sub movetogarbage () {
307     # realdestrepo must have been locked
308     my $garbagerepo = "$dgitrepos/${package}_garbage";
309     # We arrange to always keep at least one old tree, for anti-rewind
310     # purposes (and, I guess, recovery from mistakes).  This is either
311     # $garbage or $garbage-old.
312     if (stat_exists "$garbagerepo") {
313         rmtree "$garbagerepo-tmp";
314         if (rename "$garbagerepo-old", "$garbagerepo-tmp") {
315             rmtree "$garbagerepo-tmp";
316         } else {
317             die "$garbagerepo $!" unless $!==ENOENT;
318         }
319         rename "$garbagerepo", "$garbagerepo-old" or die "$garbagerepo $!";
320     }
321     rename realdestrepo, $garbagerepo
322         or $! == ENOENT
323         or die "$garbagerepo $!";
324 }
325
326 sub policy_checkpackage () {
327     my $lfh = lockrealtree();
328
329     $policy = policyhook(FRESHREPO,'check-package',$package);
330     if ($policy & FRESHREPO) {
331         movetogarbage();
332     }
333
334     close $lfh;
335 }
336
337 #----- git-receive-pack -----
338
339 sub fixmissing__git_receive_pack () {
340     mkrepotmp();
341     $destrepo = "$dgitrepos/_tmp/${package}_prospective";
342     acquirermtree($destrepo, 1);
343     mkrepo_fromtemplate($destrepo);
344 }
345
346 sub makeworkingclone () {
347     mkrepotmp();
348     $workrepo = "$dgitrepos/_tmp/${package}_incoming$$";
349     acquirermtree($workrepo, 1);
350     my $lfh = lockrealtree();
351     runcmd qw(git clone -l -q --mirror), $destrepo, $workrepo;
352     close $lfh;
353     rmtree "${workrepo}_fresh";
354 }
355
356 sub setupstunthook () {
357     my $prerecv = "$workrepo/hooks/pre-receive";
358     my $fh = new IO::File $prerecv, O_WRONLY|O_CREAT|O_TRUNC, 0777
359         or die "$prerecv: $!";
360     print $fh <<END or die "$prerecv: $!";
361 #!/bin/sh
362 set -e
363 exec $0 --pre-receive-hook $package
364 END
365     close $fh or die "$prerecv: $!";
366     $ENV{'DGIT_DRS_WORK'}= $workrepo;
367     $ENV{'DGIT_DRS_DEST'}= $destrepo;
368     debug " stunt hook set up $prerecv";
369 }
370
371 sub dealwithfreshrepo () {
372     my $freshrepo = "${workrepo}_fresh";
373     return unless stat_exists $freshrepo;
374     $destrepo = $freshrepo;
375 }
376
377 sub maybeinstallprospective () {
378     return if $destrepo eq realdestrepo;
379
380     if (open REJ, "<", "$workrepo/drs-error") {
381         local $/ = undef;
382         my $msg = <REJ>;
383         REJ->error and die $!;
384         print STDERR $msg;
385         exit 1;
386     } else {
387         $!==&ENOENT or die $!;
388     }
389
390     debug " show-ref ($destrepo) ...";
391
392     my $child = open SR, "-|";
393     defined $child or die $!;
394     if (!$child) {
395         chdir $destrepo or die $!;
396         exec qw(git show-ref);
397         die $!;
398     }
399     my %got = qw(tag 0 head 0);
400     while (<SR>) {
401         chomp or die;
402         debug " show-refs| $_";
403         s/^\S*[1-9a-f]\S* (\S+)$/$1/ or die;
404         my $wh =
405             m{^refs/tags/} ? 'tag' :
406             m{^refs/dgit/} ? 'head' :
407             die;
408         die if $got{$wh}++;
409     }
410     $!=0; $?=0; close SR or $?==256 or die "$? $!";
411
412     debug "installprospective ?";
413     die Dumper(\%got)." -- missing refs in new repo"
414         if grep { !$_ } values %got;
415
416     lockrealtree();
417
418     if ($destrepo eq "${workrepo}_fresh") {
419         movetogarbage;
420     }
421
422     debug "install $destrepo => ".realdestrepo;
423     rename $destrepo, realdestrepo or die $!;
424     remove "$destrepo.lock" or die $!;
425 }
426
427 sub main__git_receive_pack () {
428     makeworkingclone();
429     setupstunthook();
430     runcmd qw(git receive-pack), $workrepo;
431     dealwithfreshrepo();
432     maybeinstallprospective();
433 }
434
435 #----- stunt post-receive hook -----
436
437 our ($tagname, $tagval, $suite, $oldcommit, $commit);
438 our ($version, %tagh);
439
440 sub readupdates () {
441     debug " updates ...";
442     while (<STDIN>) {
443         chomp or die;
444         debug " upd.| $_";
445         m/^(\S+) (\S+) (\S+)$/ or die "$_ ?";
446         my ($old, $sha1, $refname) = ($1, $2, $3);
447         if ($refname =~ m{^refs/tags/(?=debian/)}) {
448             reject "pushing multiple tags!" if defined $tagname;
449             $tagname = $'; #';
450             $tagval = $sha1;
451             reject "tag $tagname already exists -".
452                 " not replacing previously-pushed version"
453                 if $old =~ m/[^0]/;
454         } elsif ($refname =~ m{^refs/dgit/}) {
455             reject "pushing multiple heads!" if defined $suite;
456             $suite = $'; #';
457             $oldcommit = $old;
458             $commit = $sha1;
459         } else {
460             reject "pushing unexpected ref!";
461         }
462     }
463     STDIN->error and die $!;
464
465     reject "push is missing tag ref update" unless defined $tagname;
466     reject "push is missing head ref update" unless defined $suite;
467     debug " updates ok.";
468 }
469
470 sub parsetag () {
471     debug " parsetag...";
472     open PT, ">dgit-tmp/plaintext" or die $!;
473     open DS, ">dgit-tmp/plaintext.asc" or die $!;
474     open T, "-|", qw(git cat-file tag), $tagval or die $!;
475     for (;;) {
476         $!=0; $_=<T>; defined or die $!;
477         print PT or die $!;
478         if (m/^(\S+) (.*)/) {
479             push @{ $tagh{$1} }, $2;
480         } elsif (!m/\S/) {
481             last;
482         } else {
483             die;
484         }
485     }
486     $!=0; $_=<T>; defined or die $!;
487     m/^($package_re) release (\S+) for \S+ \((\S+)\) \[dgit\]$/ or
488         reject "tag message not in expected format";
489
490     die unless $1 eq $package;
491     $version = $2;
492     die "$3 != $suite " unless $3 eq $suite;
493
494     my $copyl = $_;
495     for (;;) {
496         print PT $copyl or die $!;
497         $!=0; $_=<T>; defined or die "missing signature? $!";
498         $copyl = $_;
499         if (m/^\[dgit ([^"].*)\]$/) { # [dgit "something"] is for future
500             $_ = $1." ";
501             while (length) {
502                 if (s/^distro\=(\S+) //) {
503                     die "$1 != $distro" unless $1 eq $distro;
504                 } elsif (s/^(--deliberately-$package_re) //) {
505                     push @deliberatelies, $1;
506                 } elsif (s/^supersede:(\S+)=(\w+) //) {
507                     die "supersede $1 twice" if defined $supersedes{$1};
508                     $supersedes{$1} = $2;
509                 } elsif (s/^[-+.=0-9a-z]\S* //) {
510                 } else {
511                     die "unknown dgit info in tag ($_)";
512                 }
513             }
514             next;
515         }
516         last if m/^-----BEGIN PGP/;
517     }
518     $_ = $copyl;
519     for (;;) {
520         print DS or die $!;
521         $!=0; $_=<T>;
522         last if !defined;
523     }
524     T->error and die $!;
525     close PT or die $!;
526     close DS or die $!;
527     debug " parsetag ok.";
528 }
529
530 sub checksig_keyring ($) {
531     my ($keyringfile) = @_;
532     # returns primary-keyid if signed by a key in this keyring
533     # or undef if not
534     # or dies on other errors
535
536     my $ok = undef;
537
538     debug " checksig keyring $keyringfile...";
539
540     our @cmd = (qw(gpgv --status-fd=1 --keyring),
541                    $keyringfile,
542                    qw(dgit-tmp/plaintext.asc dgit-tmp/plaintext));
543     debugcmd @cmd;
544
545     open P, "-|", @cmd
546         or die $!;
547
548     while (<P>) {
549         next unless s/^\[GNUPG:\] //;
550         chomp or die;
551         debug " checksig| $_";
552         my @l = split / /, $_;
553         if ($l[0] eq 'NO_PUBKEY') {
554             last;
555         } elsif ($l[0] eq 'VALIDSIG') {
556             my $sigtype = $l[9];
557             $sigtype eq '00' or reject "signature is not of type 00!";
558             $ok = $l[10];
559             die unless defined $ok;
560             last;
561         }
562     }
563     close P;
564
565     debug sprintf " checksig ok=%d", !!$ok;
566
567     return $ok;
568 }
569
570 sub dm_txt_check ($$) {
571     my ($keyid, $dmtxtfn) = @_;
572     debug " dm_txt_check $keyid $dmtxtfn";
573     open DT, '<', $dmtxtfn or die "$dmtxtfn $!";
574     while (<DT>) {
575         m/^fingerprint:\s+$keyid$/oi
576             ..0 or next;
577         if (s/^allow:/ /i..0) {
578         } else {
579             m/^./
580                 or reject "key $keyid missing Allow section in permissions!";
581             next;
582         }
583         # in right stanza...
584         s/^[ \t]+//
585             or reject "package $package not allowed for key $keyid";
586         # in allow field...
587         s/\([^()]+\)//;
588         s/\,//;
589         chomp or die;
590         debug " dm_txt_check allow| $_";
591         foreach my $p (split /\s+/) {
592             if ($p eq $package) {
593                 # yay!
594                 debug " dm_txt_check ok";
595                 return;
596             }
597         }
598     }
599     DT->error and die $!;
600     close DT or die $!;
601     reject "key $keyid not in permissions list although in keyring!";
602 }
603
604 sub verifytag () {
605     foreach my $kas (split /:/, $keyrings) {
606         debug "verifytag $kas...";
607         $kas =~ s/^([^,]+),// or die;
608         my $keyid = checksig_keyring $1;
609         if (defined $keyid) {
610             if ($kas =~ m/^a$/) {
611                 debug "verifytag a ok";
612                 return; # yay
613             } elsif ($kas =~ m/^m([^,]+)$/) {
614                 dm_txt_check($keyid, $1);
615                 debug "verifytag m ok";
616                 return;
617             } else {
618                 die;
619             }
620         }   
621     }
622     reject "key not found in keyrings";
623 }
624
625 sub checksuite () {
626     debug "checksuite ($suitesfile)";
627     open SUITES, "<", $suitesfile or die $!;
628     while (<SUITES>) {
629         chomp;
630         next unless m/\S/;
631         next if m/^\#/;
632         s/\s+$//;
633         return if $_ eq $suite;
634     }
635     die $! if SUITES->error;
636     reject "unknown suite";
637 }
638
639 sub checktagnoreplay () {
640     # We check that the signed tag mentions the name and value of
641     # (a) in the case of FRESHREPO all tags in the repo;
642     # (b) in the case of just NOFFCHECK all tags referring to
643     # the current head for the suite (there must be at least one).
644     # This prevents a replay attack using an earlier signed tag.
645     return unless $policy & (FRESHREPO|NOFFCHECK);
646
647     my $garbagerepo = "$dgitrepos/${package}_garbage";
648     lockrealtree();
649
650     local $ENV{GIT_DIR};
651     foreach my $garb ("$garbagerepo", "$garbagerepo-old") {
652         if (stat_exists $garb) {
653             $ENV{GIT_DIR} = $garb;
654             last;
655         }
656     }
657     if (!defined $ENV{GIT_DIR}) {
658         # Nothing to overwrite so the FRESHREPO and NOFFCHECK were
659         # pointless.  Oh well.
660         debug "checktagnoreplay - no garbage, ok";
661         return;
662     }
663
664     my $onlyreferring;
665     if (!($policy & FRESHREPO)) {
666         my $branch = server_branch($suite);
667         $!=0; $?=0; $_ =
668             `git for-each-ref --format='%(objectname)' '[r]efs/$branch'`;
669         defined or die "$branch $? $!";
670         $? and die "$branch $?";
671         if (!length) {
672             # No such branch - NOFFCHECK was unnecessary.  Oh well.
673             debug "checktagnoreplay - not FRESHREPO, new branch, ok";
674             return;
675         }
676         m/^(\w+)\n$/ or die "$branch $_ ?";
677         $onlyreferring = $1;
678         debug "checktagnoreplay - not FRESHREPO,".
679             " checking for overwriting refs/$branch=$onlyreferring";
680     }
681
682     my @problems;
683
684     git_for_each_tag_referring($onlyreferring, sub {
685         my ($objid,$fullrefname,$tagname) = @_;
686         debug "checktagnoreplay - overwriting $fullrefname=$objid";
687         my $supers = $supersedes{$fullrefname};
688         if (!defined $supers) {
689             push @problems, "does not supersede $fullrefname";
690         } elsif ($supers ne $objid) {
691             push @problems,
692  "supersedes $fullrefname=$supers but previously $fullrefname=$objid";
693         } else {
694             # ok;
695         }
696     });
697
698     if (@problems) {
699         reject "replay attack prevention check failed:".
700             " signed tag for $version: ".
701             join("; ", @problems).
702             "\n";
703     }
704     debug "checktagnoreply - all ok"
705 }
706
707 sub tagh1 ($) {
708     my ($tag) = @_;
709     my $vals = $tagh{$tag};
710     reject "missing header $tag in signed tag object" unless $vals;
711     reject "multiple headers $tag in signed tag object" unless @$vals == 1;
712     return $vals->[0];
713 }
714
715 sub checks () {
716     debug "checks";
717
718     tagh1('type') eq 'commit' or reject "tag refers to wrong kind of object";
719     tagh1('object') eq $commit or reject "tag refers to wrong commit";
720     tagh1('tag') eq $tagname or reject "tag name in tag is wrong";
721
722     my $v = $version;
723     $v =~ y/~:/_%/;
724
725     debug "translated version $v";
726     $tagname eq "debian/$v" or die;
727
728     lockrealtree();
729
730     my @policy_args = ($package,$version,$suite,$tagname,
731                        join(",",@deliberatelies));
732     $policy = policyhook(NOFFCHECK|FRESHREPO, 'push', @policy_args);
733
734     checktagnoreplay();
735     checksuite();
736
737     # check that our ref is being fast-forwarded
738     debug "oldcommit $oldcommit";
739     if (!($policy & NOFFCHECK) && $oldcommit =~ m/[^0]/) {
740         $?=0; $!=0; my $mb = `git merge-base $commit $oldcommit`;
741         chomp $mb;
742         $mb eq $oldcommit or reject "not fast forward on dgit branch";
743     }
744
745     if ($policy & FRESHREPO) {
746         # This is troublesome.  We have been asked by the policy hook
747         # to receive the push into a fresh repo.  But of course we
748         # have actually already mostly received the push into the working
749         # repo.  (This is unavoidable because the instruction to use a new
750         # repo comes ultimately from the signed tag for the dgit push,
751         # which has to have been received into some repo.)
752         #
753         # So what we do is generate a fresh working repo right now and
754         # push the head and tag into it.  The presence of this fresh
755         # working repo is detected by the parent, which responds by
756         # making a fresh master repo from the template.
757
758         $destrepo = "${workrepo}_fresh"; # workrepo lock covers
759         mkrepo_fromtemplate $destrepo;
760     }
761
762     my $willinstall = ($destrepo eq realdestrepo ? '' : $destrepo);
763     policyhook(0, 'push-confirm', @policy_args, $willinstall);
764 }
765
766 sub onwardpush () {
767     my @cmd = (qw(git send-pack), $destrepo);
768     push @cmd, qw(--force) if $policy & NOFFCHECK;
769     push @cmd, "$commit:refs/dgit/$suite",
770                "$tagval:refs/tags/$tagname";
771     debugcmd @cmd;
772     $!=0;
773     my $r = system @cmd;
774     !$r or die "onward push to $destrepo failed: $r $!";
775 }
776
777 sub stunthook () {
778     debug "stunthook";
779     chdir $workrepo or die "chdir $workrepo: $!";
780     mkdir "dgit-tmp" or $!==EEXIST or die $!;
781     readupdates();
782     parsetag();
783     verifytag();
784     checks();
785     onwardpush();
786     debug "stunthook done.";
787 }
788
789 #----- git-upload-pack -----
790
791 sub fixmissing__git_upload_pack () {
792     $destrepo = "$dgitrepos/_empty";
793     my $lfh = locksometree($destrepo);
794     return if stat_exists $destrepo;
795     rmtree "$destrepo.new";
796     mkemptyrepo "$destrepo.new", "0644";
797     rename "$destrepo.new", $destrepo or die $!;
798     unlink "$destrepo.lock" or die $!;
799     close $lfh;
800 }
801
802 sub main__git_upload_pack () {
803     my $lfh = locksometree($destrepo);
804     chdir $destrepo or die "$destrepo: $!";
805     close $lfh;
806     runcmd qw(git upload-pack), ".";
807 }
808
809 #----- arg parsing and main program -----
810
811 sub argval () {
812     die unless @ARGV;
813     my $v = shift @ARGV;
814     die if $v =~ m/^-/;
815     return $v;
816 }
817
818 our %indistrodir = (
819     # keys are used for DGIT_DRS_XXX too
820     'repos' => \$dgitrepos,
821     'suites' => \$suitesfile,
822     'policy-hook' => \$policyhook,
823     'dgit-live' => \$dgitlive,
824     );
825
826 our @hookenvs = qw(distro suitesfile policyhook dgitlive keyrings dgitrepos);
827
828 # workrepo and destrepo handled ad-hoc
829
830 sub mode_ssh () {
831     die if @ARGV;
832
833     my $cmd = $ENV{'SSH_ORIGINAL_COMMAND'};
834     $cmd =~ m{
835         ^
836         (?: \S* / )?
837         ( [-0-9a-z]+ )
838         \s+
839         '? (?: \S* / )?
840         ($package_re) \.git
841         '?$
842     }ox 
843     or reject "command string not understood";
844     my $method = $1;
845     $package = $2;
846
847     my $funcn = $method;
848     $funcn =~ y/-/_/;
849     my $mainfunc = $main::{"main__$funcn"};
850
851     reject "unknown method" unless $mainfunc;
852
853     policy_checkpackage();
854
855     if (stat_exists realdestrepo) {
856         $destrepo = realdestrepo;
857     } else {
858         debug " fixmissing $funcn";
859         my $fixfunc = $main::{"fixmissing__$funcn"};
860         &$fixfunc;
861     }
862
863     debug " running main $funcn";
864     &$mainfunc;
865 }
866
867 sub parseargsdispatch () {
868     die unless @ARGV;
869
870     delete $ENV{'GIT_DIR'}; # if not run via ssh, our parent git process
871     delete $ENV{'GIT_PREFIX'}; # sets these and they mess things up
872
873     if ($ENV{'DGIT_DRS_DEBUG'}) {
874         $debug='=';
875         open DEBUG, ">&STDERR" or die $!;
876     }
877
878     if ($ARGV[0] eq '--pre-receive-hook') {
879         if ($debug) { $debug.="="; }
880         shift @ARGV;
881         @ARGV == 1 or die;
882         $package = shift @ARGV;
883         ${ $main::{$_} } = $ENV{"DGIT_DRS_\U$_"} foreach @hookenvs;
884         defined($workrepo = $ENV{'DGIT_DRS_WORK'}) or die;
885         defined($destrepo = $ENV{'DGIT_DRS_DEST'}) or die;
886         open STDOUT, ">&STDERR" or die $!;
887         eval {
888             stunthook();
889         };
890         if ($@) {
891             recorderror "$@" or die;
892             die $@;
893         }
894         exit 0;
895     }
896
897     $distro = $ENV{'DGIT_DRS_DISTRO'}     = argval();
898     my $distrodir                         = argval();
899     $keyrings = $ENV{'DGIT_DRS_KEYRINGS'} = argval();
900
901     foreach my $dk (keys %indistrodir) {
902         ${ $indistrodir{$dk} } = "$distrodir/$dk";
903     }
904
905     while (@ARGV && $ARGV[0] =~ m/^--([-0-9a-z]+)=/ && $indistrodir{$1}) {
906         ${ $indistrodir{$1} } = $'; #';
907         shift @ARGV;
908     }
909
910     $ENV{"DGIT_DRS_\U$_"} = ${ $main::{$_} } foreach @hookenvs;
911
912     die unless @ARGV==1;
913
914     my $mode = shift @ARGV;
915     die unless $mode =~ m/^--(\w+)$/;
916     my $fn = ${*::}{"mode_$1"};
917     die unless $fn;
918     $fn->();
919 }
920
921 sub unlockall () {
922     while (my $fh = pop @lockfhs) { close $fh; }
923 }
924
925 sub cleanup () {
926     unlockall();
927     if (!chdir "$dgitrepos/_tmp") {
928         $!==ENOENT or die $!;
929         return;
930     }
931     foreach my $lf (<*.lock>) {
932         my $tree = $lf;
933         $tree =~ s/\.lock$//;
934         next unless acquirermtree($tree, 0);
935         remove $lf or warn $!;
936         unlockall();
937     }
938 }
939
940 parseargsdispatch();
941 cleanup();