chiark / gitweb /
f700df81ca1f507e711afff2bceea5097919f0ee
[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 and to pass to policy hook)
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 DISTRO-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 $distrodir;
183 our $destrepo;
184 our $workrepo;
185 our $keyrings;
186 our @lockfhs;
187
188 our @deliberatelies;
189 our %supersedes;
190 our $policy;
191
192 #----- utilities -----
193
194 sub realdestrepo () { "$dgitrepos/$package.git"; }
195
196 sub acquirelock ($$) {
197     my ($lock, $must) = @_;
198     my $fh;
199     printdebug sprintf "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             printdebug " locking $lock failed\n";
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 runcmd {
264     debugcmd '+',@_;
265     $!=0; $?=0;
266     my $r = system @_;
267     die (shellquote @_)." $? $!" if $r;
268 }
269
270 sub policyhook {
271     my ($policyallowbits, @polargs) = @_;
272     # => ($exitstatuspolicybitmap);
273     die if $policyallowbits & ~0x3e;
274     my @cmd = ($policyhook,$distro,$dgitrepos,$dgitlive,$distrodir,@polargs);
275     debugcmd '+',@cmd;
276     my $r = system @cmd;
277     die "system: $!" if $r < 0;
278     die "dgit-repos-server: policy hook failed (or rejected) ($?)\n"
279         if $r & ~($policyallowbits << 8);
280     printdebug sprintf "hook => %#x\n", $r;
281     return $r >> 8;
282 }
283
284 sub mkemptyrepo ($$) {
285     my ($dir,$sharedperm) = @_;
286     runcmd qw(git init --bare --quiet), "--shared=$sharedperm", $dir;
287 }
288
289 sub mkrepo_fromtemplate ($) {
290     my ($dir) = @_;
291     my $template = "$dgitrepos/_template";
292     locksometree($template);
293     printdebug "copy template $template -> $dir\n";
294     my $r = system qw(cp -a --), $template, $dir;
295     !$r or die "create new repo $dir failed: $r $!";
296 }
297
298 sub movetogarbage () {
299     # realdestrepo must have been locked
300     my $garbagerepo = "$dgitrepos/${package}_garbage";
301     # We arrange to always keep at least one old tree, for anti-rewind
302     # purposes (and, I guess, recovery from mistakes).  This is either
303     # $garbage or $garbage-old.
304     if (stat_exists "$garbagerepo") {
305         printdebug "movetogarbage: rmtree $garbagerepo-tmp\n";
306         rmtree "$garbagerepo-tmp";
307         if (rename "$garbagerepo-old", "$garbagerepo-tmp") {
308             printdebug "movetogarbage: $garbagerepo-old -> -tmp, rmtree\n";
309             rmtree "$garbagerepo-tmp";
310         } else {
311             die "$garbagerepo $!" unless $!==ENOENT;
312             printdebug "movetogarbage: $garbagerepo-old -> -tmp\n";
313         }
314         printdebug "movetogarbage: $garbagerepo -> -old\n";
315         rename "$garbagerepo", "$garbagerepo-old" or die "$garbagerepo $!";
316     }
317     my $real = realdestrepo;
318     printdebug "movetogarbage: $real -> $garbagerepo\n";
319     rename $real, $garbagerepo
320         or $! == ENOENT
321         or die "$garbagerepo $!";
322 }
323
324 sub policy_checkpackage () {
325     my $lfh = lockrealtree();
326
327     $policy = policyhook(FRESHREPO,'check-package',$package);
328     if ($policy & FRESHREPO) {
329         movetogarbage();
330     }
331
332     close $lfh;
333 }
334
335 #----- git-receive-pack -----
336
337 sub fixmissing__git_receive_pack () {
338     mkrepotmp();
339     $destrepo = "$dgitrepos/_tmp/${package}_prospective";
340     acquirermtree($destrepo, 1);
341     mkrepo_fromtemplate($destrepo);
342 }
343
344 sub makeworkingclone () {
345     mkrepotmp();
346     $workrepo = "$dgitrepos/_tmp/${package}_incoming$$";
347     acquirermtree($workrepo, 1);
348     my $lfh = lockrealtree();
349     runcmd qw(git clone -l -q --mirror), $destrepo, $workrepo;
350     close $lfh;
351     rmtree "${workrepo}_fresh";
352 }
353
354 sub setupstunthook () {
355     my $prerecv = "$workrepo/hooks/pre-receive";
356     my $fh = new IO::File $prerecv, O_WRONLY|O_CREAT|O_TRUNC, 0777
357         or die "$prerecv: $!";
358     print $fh <<END or die "$prerecv: $!";
359 #!/bin/sh
360 set -e
361 exec $0 --pre-receive-hook $package
362 END
363     close $fh or die "$prerecv: $!";
364     $ENV{'DGIT_DRS_WORK'}= $workrepo;
365     $ENV{'DGIT_DRS_DEST'}= $destrepo;
366     printdebug " stunt hook set up $prerecv\n";
367 }
368
369 sub dealwithfreshrepo () {
370     my $freshrepo = "${workrepo}_fresh";
371     return unless stat_exists $freshrepo;
372     $destrepo = $freshrepo;
373 }
374
375 sub maybeinstallprospective () {
376     return if $destrepo eq realdestrepo;
377
378     if (open REJ, "<", "$workrepo/drs-error") {
379         local $/ = undef;
380         my $msg = <REJ>;
381         REJ->error and die $!;
382         print STDERR $msg;
383         exit 1;
384     } else {
385         $!==&ENOENT or die $!;
386     }
387
388     printdebug " show-ref ($destrepo) ...\n";
389
390     my $child = open SR, "-|";
391     defined $child or die $!;
392     if (!$child) {
393         chdir $destrepo or die $!;
394         exec qw(git show-ref);
395         die $!;
396     }
397     my %got = qw(tag 0 head 0);
398     while (<SR>) {
399         chomp or die;
400         printdebug " show-refs| $_\n";
401         s/^\S*[1-9a-f]\S* (\S+)$/$1/ or die;
402         my $wh =
403             m{^refs/tags/} ? 'tag' :
404             m{^refs/dgit/} ? 'head' :
405             die;
406         die if $got{$wh}++;
407     }
408     $!=0; $?=0; close SR or $?==256 or die "$? $!";
409
410     printdebug "installprospective ?\n";
411     die Dumper(\%got)." -- missing refs in new repo"
412         if grep { !$_ } values %got;
413
414     lockrealtree();
415
416     if ($destrepo eq "${workrepo}_fresh") {
417         movetogarbage;
418     }
419
420     printdebug "install $destrepo => ".realdestrepo."\n";
421     rename $destrepo, realdestrepo or die $!;
422     remove "$destrepo.lock" or die $!;
423 }
424
425 sub main__git_receive_pack () {
426     makeworkingclone();
427     setupstunthook();
428     runcmd qw(git receive-pack), $workrepo;
429     dealwithfreshrepo();
430     maybeinstallprospective();
431 }
432
433 #----- stunt post-receive hook -----
434
435 our ($tagname, $tagval, $suite, $oldcommit, $commit);
436 our ($version, %tagh);
437
438 sub readupdates () {
439     printdebug " updates ...\n";
440     while (<STDIN>) {
441         chomp or die;
442         printdebug " upd.| $_\n";
443         m/^(\S+) (\S+) (\S+)$/ or die "$_ ?";
444         my ($old, $sha1, $refname) = ($1, $2, $3);
445         if ($refname =~ m{^refs/tags/(?=debian/)}) {
446             reject "pushing multiple tags!" if defined $tagname;
447             $tagname = $'; #';
448             $tagval = $sha1;
449             reject "tag $tagname already exists -".
450                 " not replacing previously-pushed version"
451                 if $old =~ m/[^0]/;
452         } elsif ($refname =~ m{^refs/dgit/}) {
453             reject "pushing multiple heads!" if defined $suite;
454             $suite = $'; #';
455             $oldcommit = $old;
456             $commit = $sha1;
457         } else {
458             reject "pushing unexpected ref!";
459         }
460     }
461     STDIN->error and die $!;
462
463     reject "push is missing tag ref update" unless defined $tagname;
464     reject "push is missing head ref update" unless defined $suite;
465     printdebug " updates ok.\n";
466 }
467
468 sub parsetag () {
469     printdebug " parsetag...\n";
470     open PT, ">dgit-tmp/plaintext" or die $!;
471     open DS, ">dgit-tmp/plaintext.asc" or die $!;
472     open T, "-|", qw(git cat-file tag), $tagval or die $!;
473     for (;;) {
474         $!=0; $_=<T>; defined or die $!;
475         print PT or die $!;
476         if (m/^(\S+) (.*)/) {
477             push @{ $tagh{$1} }, $2;
478         } elsif (!m/\S/) {
479             last;
480         } else {
481             die;
482         }
483     }
484     $!=0; $_=<T>; defined or die $!;
485     m/^($package_re) release (\S+) for \S+ \((\S+)\) \[dgit\]$/ or
486         reject "tag message not in expected format";
487
488     die unless $1 eq $package;
489     $version = $2;
490     die "$3 != $suite " unless $3 eq $suite;
491
492     my $copyl = $_;
493     for (;;) {
494         print PT $copyl or die $!;
495         $!=0; $_=<T>; defined or die "missing signature? $!";
496         $copyl = $_;
497         if (m/^\[dgit ([^"].*)\]$/) { # [dgit "something"] is for future
498             $_ = $1." ";
499             while (length) {
500                 if (s/^distro\=(\S+) //) {
501                     die "$1 != $distro" unless $1 eq $distro;
502                 } elsif (s/^(--deliberately-$deliberately_re) //) {
503                     push @deliberatelies, $1;
504                 } elsif (s/^supersede:(\S+)=(\w+) //) {
505                     die "supersede $1 twice" if defined $supersedes{$1};
506                     $supersedes{$1} = $2;
507                 } elsif (s/^[-+.=0-9a-z]\S* //) {
508                 } else {
509                     die "unknown dgit info in tag ($_)";
510                 }
511             }
512             next;
513         }
514         last if m/^-----BEGIN PGP/;
515     }
516     $_ = $copyl;
517     for (;;) {
518         print DS or die $!;
519         $!=0; $_=<T>;
520         last if !defined;
521     }
522     T->error and die $!;
523     close PT or die $!;
524     close DS or die $!;
525     printdebug " parsetag ok.\n";
526 }
527
528 sub checksig_keyring ($) {
529     my ($keyringfile) = @_;
530     # returns primary-keyid if signed by a key in this keyring
531     # or undef if not
532     # or dies on other errors
533
534     my $ok = undef;
535
536     printdebug " checksig keyring $keyringfile...\n";
537
538     our @cmd = (qw(gpgv --status-fd=1 --keyring),
539                    $keyringfile,
540                    qw(dgit-tmp/plaintext.asc dgit-tmp/plaintext));
541     debugcmd '|',@cmd;
542
543     open P, "-|", @cmd
544         or die $!;
545
546     while (<P>) {
547         next unless s/^\[GNUPG:\] //;
548         chomp or die;
549         printdebug " checksig| $_\n";
550         my @l = split / /, $_;
551         if ($l[0] eq 'NO_PUBKEY') {
552             last;
553         } elsif ($l[0] eq 'VALIDSIG') {
554             my $sigtype = $l[9];
555             $sigtype eq '00' or reject "signature is not of type 00!";
556             $ok = $l[10];
557             die unless defined $ok;
558             last;
559         }
560     }
561     close P;
562
563     printdebug sprintf " checksig ok=%d\n", !!$ok;
564
565     return $ok;
566 }
567
568 sub dm_txt_check ($$) {
569     my ($keyid, $dmtxtfn) = @_;
570     printdebug " dm_txt_check $keyid $dmtxtfn\n";
571     open DT, '<', $dmtxtfn or die "$dmtxtfn $!";
572     while (<DT>) {
573         m/^fingerprint:\s+$keyid$/oi
574             ..0 or next;
575         if (s/^allow:/ /i..0) {
576         } else {
577             m/^./
578                 or reject "key $keyid missing Allow section in permissions!";
579             next;
580         }
581         # in right stanza...
582         s/^[ \t]+//
583             or reject "package $package not allowed for key $keyid";
584         # in allow field...
585         s/\([^()]+\)//;
586         s/\,//;
587         chomp or die;
588         printdebug " dm_txt_check allow| $_\n";
589         foreach my $p (split /\s+/) {
590             if ($p eq $package) {
591                 # yay!
592                 printdebug " dm_txt_check ok\n";
593                 return;
594             }
595         }
596     }
597     DT->error and die $!;
598     close DT or die $!;
599     reject "key $keyid not in permissions list although in keyring!";
600 }
601
602 sub verifytag () {
603     foreach my $kas (split /:/, $keyrings) {
604         printdebug "verifytag $kas...\n";
605         $kas =~ s/^([^,]+),// or die;
606         my $keyid = checksig_keyring $1;
607         if (defined $keyid) {
608             if ($kas =~ m/^a$/) {
609                 printdebug "verifytag a ok\n";
610                 return; # yay
611             } elsif ($kas =~ m/^m([^,]+)$/) {
612                 dm_txt_check($keyid, $1);
613                 printdebug "verifytag m ok\n";
614                 return;
615             } else {
616                 die;
617             }
618         }   
619     }
620     reject "key not found in keyrings";
621 }
622
623 sub checksuite () {
624     printdebug "checksuite ($suitesfile)\n";
625     open SUITES, "<", $suitesfile or die $!;
626     while (<SUITES>) {
627         chomp;
628         next unless m/\S/;
629         next if m/^\#/;
630         s/\s+$//;
631         return if $_ eq $suite;
632     }
633     die $! if SUITES->error;
634     reject "unknown suite";
635 }
636
637 sub checktagnoreplay () {
638     # We check that the signed tag mentions the name and value of
639     # (a) in the case of FRESHREPO all tags in the repo;
640     # (b) in the case of just NOFFCHECK all tags referring to
641     # the current head for the suite (there must be at least one).
642     # This prevents a replay attack using an earlier signed tag.
643     return unless $policy & (FRESHREPO|NOFFCHECK);
644
645     my $garbagerepo = "$dgitrepos/${package}_garbage";
646     lockrealtree();
647
648     local $ENV{GIT_DIR};
649     foreach my $garb ("$garbagerepo", "$garbagerepo-old") {
650         if (stat_exists $garb) {
651             $ENV{GIT_DIR} = $garb;
652             last;
653         }
654     }
655     if (!defined $ENV{GIT_DIR}) {
656         # Nothing to overwrite so the FRESHREPO and NOFFCHECK were
657         # pointless.  Oh well.
658         printdebug "checktagnoreplay - no garbage, ok\n";
659         return;
660     }
661
662     my $onlyreferring;
663     if (!($policy & FRESHREPO)) {
664         my $branch = server_branch($suite);
665         $!=0; $?=0; $_ =
666             `git for-each-ref --format='%(objectname)' '[r]efs/$branch'`;
667         defined or die "$branch $? $!";
668         $? and die "$branch $?";
669         if (!length) {
670             # No such branch - NOFFCHECK was unnecessary.  Oh well.
671             printdebug "checktagnoreplay - not FRESHREPO, new branch, ok\n";
672             return;
673         }
674         m/^(\w+)\n$/ or die "$branch $_ ?";
675         $onlyreferring = $1;
676         printdebug "checktagnoreplay - not FRESHREPO,".
677             " checking for overwriting refs/$branch=$onlyreferring\n";
678     }
679
680     my @problems;
681
682     git_for_each_tag_referring($onlyreferring, sub {
683         my ($objid,$refobjid,$fullrefname,$tagname) = @_;
684         printdebug "checktagnoreplay - overwriting $fullrefname=$objid\n";
685         my $supers = $supersedes{$fullrefname};
686         if (!defined $supers) {
687             push @problems, "does not supersede $fullrefname";
688         } elsif ($supers ne $objid) {
689             push @problems,
690  "supersedes $fullrefname=$supers but previously $fullrefname=$objid";
691         } else {
692             # ok;
693         }
694     });
695
696     if (@problems) {
697         reject "replay attack prevention check failed:".
698             " signed tag for $version: ".
699             join("; ", @problems).
700             "\n";
701     }
702     printdebug "checktagnoreply - all ok\n"
703 }
704
705 sub tagh1 ($) {
706     my ($tag) = @_;
707     my $vals = $tagh{$tag};
708     reject "missing header $tag in signed tag object" unless $vals;
709     reject "multiple headers $tag in signed tag object" unless @$vals == 1;
710     return $vals->[0];
711 }
712
713 sub checks () {
714     printdebug "checks\n";
715
716     tagh1('type') eq 'commit' or reject "tag refers to wrong kind of object";
717     tagh1('object') eq $commit or reject "tag refers to wrong commit";
718     tagh1('tag') eq $tagname or reject "tag name in tag is wrong";
719
720     my $v = $version;
721     $v =~ y/~:/_%/;
722
723     printdebug "translated version $v\n";
724     $tagname eq "debian/$v" or die;
725
726     lockrealtree();
727
728     my @policy_args = ($package,$version,$suite,$tagname,
729                        join(",",@deliberatelies));
730     $policy = policyhook(NOFFCHECK|FRESHREPO, 'push', @policy_args);
731
732     checktagnoreplay();
733     checksuite();
734
735     # check that our ref is being fast-forwarded
736     printdebug "oldcommit $oldcommit\n";
737     if (!($policy & NOFFCHECK) && $oldcommit =~ m/[^0]/) {
738         $?=0; $!=0; my $mb = `git merge-base $commit $oldcommit`;
739         chomp $mb;
740         $mb eq $oldcommit or reject "not fast forward on dgit branch";
741     }
742
743     if ($policy & FRESHREPO) {
744         # This is troublesome.  We have been asked by the policy hook
745         # to receive the push into a fresh repo.  But of course we
746         # have actually already mostly received the push into the working
747         # repo.  (This is unavoidable because the instruction to use a new
748         # repo comes ultimately from the signed tag for the dgit push,
749         # which has to have been received into some repo.)
750         #
751         # So what we do is generate a fresh working repo right now and
752         # push the head and tag into it.  The presence of this fresh
753         # working repo is detected by the parent, which responds by
754         # making a fresh master repo from the template.
755
756         $destrepo = "${workrepo}_fresh"; # workrepo lock covers
757         mkrepo_fromtemplate $destrepo;
758     }
759
760     my $willinstall = ($destrepo eq realdestrepo ? '' : $destrepo);
761     policyhook(0, 'push-confirm', @policy_args, $willinstall);
762 }
763
764 sub onwardpush () {
765     my @cmd = (qw(git send-pack), $destrepo);
766     push @cmd, qw(--force) if $policy & NOFFCHECK;
767     push @cmd, "$commit:refs/dgit/$suite",
768                "$tagval:refs/tags/$tagname";
769     debugcmd '+',@cmd;
770     $!=0;
771     my $r = system @cmd;
772     !$r or die "onward push to $destrepo failed: $r $!";
773 }
774
775 sub stunthook () {
776     printdebug "stunthook in $workrepo\n";
777     chdir $workrepo or die "chdir $workrepo: $!";
778     mkdir "dgit-tmp" or $!==EEXIST or die $!;
779     readupdates();
780     parsetag();
781     verifytag();
782     checks();
783     onwardpush();
784     printdebug "stunthook done.\n";
785 }
786
787 #----- git-upload-pack -----
788
789 sub fixmissing__git_upload_pack () {
790     $destrepo = "$dgitrepos/_empty";
791     my $lfh = locksometree($destrepo);
792     return if stat_exists $destrepo;
793     rmtree "$destrepo.new";
794     mkemptyrepo "$destrepo.new", "0644";
795     rename "$destrepo.new", $destrepo or die $!;
796     unlink "$destrepo.lock" or die $!;
797     close $lfh;
798 }
799
800 sub main__git_upload_pack () {
801     my $lfh = locksometree($destrepo);
802     printdebug "git-upload-pack in $destrepo\n";
803     chdir $destrepo or die "$destrepo: $!";
804     close $lfh;
805     runcmd qw(git upload-pack), ".";
806 }
807
808 #----- arg parsing and main program -----
809
810 sub argval () {
811     die unless @ARGV;
812     my $v = shift @ARGV;
813     die if $v =~ m/^-/;
814     return $v;
815 }
816
817 our %indistrodir = (
818     # keys are used for DGIT_DRS_XXX too
819     'repos' => \$dgitrepos,
820     'suites' => \$suitesfile,
821     'policy-hook' => \$policyhook,
822     'dgit-live' => \$dgitlive,
823     );
824
825 our @hookenvs = qw(distro suitesfile policyhook
826                    dgitlive keyrings dgitrepos distrodir);
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         printdebug " fixmissing $funcn\n";
859         my $fixfunc = $main::{"fixmissing__$funcn"};
860         &$fixfunc;
861     }
862
863     printdebug " running main $funcn\n";
864     &$mainfunc;
865 }
866
867 sub mode_cron () {
868     die if @ARGV;
869
870     my $listfh = tempfile();
871     open STDOUT, ">&", $listfh or die $!;
872     policyhook(0,'check-list');
873     open STDOUT, ">&STDERR" or die $!;
874
875     seek $listfh, 0, 0 or die $!;
876     while (<$listfh>) {
877         chomp or die;
878         next if m/^\s*\#/;
879         next unless m/\S/;
880         die unless m/^($package_re)$/;
881         
882         $package = $1;
883         policy_checkpackage();
884     }
885     die $! if $listfh->error;
886 }    
887
888 sub parseargsdispatch () {
889     die unless @ARGV;
890
891     delete $ENV{'GIT_DIR'}; # if not run via ssh, our parent git process
892     delete $ENV{'GIT_PREFIX'}; # sets these and they mess things up
893
894     if ($ENV{'DGIT_DRS_DEBUG'}) {
895         enabledebug();
896     }
897
898     if ($ARGV[0] eq '--pre-receive-hook') {
899         if ($debuglevel) {
900             $debugprefix.="=";
901             printdebug "in stunthook ".(shellquote @ARGV)."\n";
902             foreach my $k (sort keys %ENV) {
903                 printdebug "$k=$ENV{$k}\n" if $k =~  m/^DGIT/;
904             }
905         }
906         shift @ARGV;
907         @ARGV == 1 or die;
908         $package = shift @ARGV;
909         ${ $main::{$_} } = $ENV{"DGIT_DRS_\U$_"} foreach @hookenvs;
910         defined($workrepo = $ENV{'DGIT_DRS_WORK'}) or die;
911         defined($destrepo = $ENV{'DGIT_DRS_DEST'}) or die;
912         open STDOUT, ">&STDERR" or die $!;
913         eval {
914             stunthook();
915         };
916         if ($@) {
917             recorderror "$@" or die;
918             die $@;
919         }
920         exit 0;
921     }
922
923     $distro    = argval();
924     $distrodir = argval();
925     $keyrings  = argval();
926
927     foreach my $dk (keys %indistrodir) {
928         ${ $indistrodir{$dk} } = "$distrodir/$dk";
929     }
930
931     while (@ARGV && $ARGV[0] =~ m/^--([-0-9a-z]+)=/ && $indistrodir{$1}) {
932         ${ $indistrodir{$1} } = $'; #';
933         shift @ARGV;
934     }
935
936     $ENV{"DGIT_DRS_\U$_"} = ${ $main::{$_} } foreach @hookenvs;
937
938     die unless @ARGV==1;
939
940     my $mode = shift @ARGV;
941     die unless $mode =~ m/^--(\w+)$/;
942     my $fn = ${*::}{"mode_$1"};
943     die unless $fn;
944     $fn->();
945 }
946
947 sub unlockall () {
948     while (my $fh = pop @lockfhs) { close $fh; }
949 }
950
951 sub cleanup () {
952     unlockall();
953     if (!chdir "$dgitrepos/_tmp") {
954         $!==ENOENT or die $!;
955         return;
956     }
957     foreach my $lf (<*.lock>) {
958         my $tree = $lf;
959         $tree =~ s/\.lock$//;
960         next unless acquirermtree($tree, 0);
961         remove $lf or warn $!;
962         unlockall();
963     }
964 }
965
966 parseargsdispatch();
967 cleanup();