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