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