chiark / gitweb /
Repos policy machinery: better docs, etc.
[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 # internal usage:
8 #  .../dgit-repos-server --pre-receive-hook PACKAGE
9 #
10 # Invoked as the ssh restricted command
11 #
12 # Works like git-receive-pack
13 #
14 # SUITES is the name of a file which lists the permissible suites
15 # one per line (#-comments and blank lines ignored)
16 #
17 # KEYRING-AUTH-SPEC is a :-separated list of
18 #   KEYRING.GPG,AUTH-SPEC
19 # where AUTH-SPEC is one of
20 #   a
21 #   mDM.TXT
22
23 use strict;
24
25 # DGIT-REPOS-DIR contains:
26 # git tree (or other object)      lock (in acquisition order, outer first)
27 #
28 #  _tmp/PACKAGE_prospective       ! } SAME.lock, held during receive-pack
29 #
30 #  _tmp/PACKAGE_incoming$$        ! } SAME.lock, held during receive-pack
31 #  _tmp/PACKAGE_incoming$$_fresh  ! }
32 #
33 #  PACKAGE.git                      } PACKAGE.git.lock
34 #  PACKAGE_garbage                  }   (also covers executions of
35 #  PACKAGE_garbage-old              }    policy hook script for PACKAGE)
36 #  PACKAGE_garbage-tmp              }
37 #  policy*                          } (for policy hook script, covered by
38 #                                   }  lock only when invoked for a package)
39 #
40 # leaf locks, held during brief operaton only:
41 #
42 #  _empty                           } SAME.lock
43 #  _empty.new                       }
44 #
45 #  _template                        } SAME.lock
46 #
47 # locks marked ! may be held during client data transfer
48
49 # What we do on push is this:
50 #  - extract the destination repo name
51 #  - make a hardlink clone of the destination repo
52 #  - provide the destination with a stunt pre-receive hook
53 #  - run actual git-receive-pack with that new destination
54 #   as a result of this the stunt pre-receive hook runs; it does this:
55 #    + understand what refs we are allegedly updating and
56 #      check some correspondences:
57 #        * we are updating only refs/tags/debian/* and refs/dgit/*
58 #        * and only one of each
59 #        * and the tag does not already exist
60 #      and
61 #        * recover the suite name from the destination refs/dgit/ ref
62 #    + disassemble the signed tag into its various fields and signature
63 #      including:
64 #        * parsing the first line of the tag message to recover
65 #          the package name, version and suite
66 #        * checking that the package name corresponds to the dest repo name
67 #        * checking that the suite name is as recovered above
68 #    + verify the signature on the signed tag
69 #      and if necessary check that the keyid and package are listed in dm.txt
70 #    + check various correspondences:
71 #        * the signed tag must refer to a commit
72 #        * the signed tag commit must be the refs/dgit value
73 #        * the name in the signed tag must correspond to its ref name
74 #        * the tag name must be debian/<version> (massaged as needed)
75 #        * the suite is one of those permitted
76 #        * the signed tag has a suitable name
77 #        * run the "push" policy hook
78 #        * replay prevention for --deliberately-not-fast-forward
79 #        * check the commit is a fast forward
80 #        * handle a request from the policy hook for a fresh repo
81 #    + push the signed tag and new dgit branch to the actual repo
82 #
83 # If the destination repo does not already exist, we need to make
84 # sure that we create it reasonably atomically, and also that
85 # we don't every have a destination repo containing no refs at all
86 # (because such a thing causes git-fetch-pack to barf).  So then we
87 # do as above, except:
88 #  - before starting, we take out our own lock for the destination repo
89 #  - we create a prospective new destination repo by making a copy
90 #    of _template
91 #  - we use the prospective new destination repo instead of the
92 #    actual new destination repo (since the latter doesn't exist)
93 #  - after git-receive-pack exits, we
94 #    + check that the prospective repo contains a tag and head
95 #    + rename the prospective destination repo into place
96 #
97 # Cleanup strategy:
98 #  - We are crash-only
99 #  - Temporary working trees and their locks are cleaned up
100 #    opportunistically by a program which tries to take each lock and
101 #    if successful deletes both the tree and the lockfile
102 #  - Prospective working trees and their locks are cleaned up by
103 #    a program which tries to take each lock and if successful
104 #    deletes any prospective working tree and the lock (but not
105 #    of course any actual tree)
106 #  - It is forbidden to _remove_ the lockfile without removing
107 #    the corresponding temporary tree, as the lockfile is also
108 #    a stampfile whose presence indicates that there may be
109 #    cleanup to do
110 #
111 # Policy hook script is invoked like this:
112 #   POLICY-HOOK-SCRIPT DISTRO DGIT-REPOS-DIR ACTION...
113 # ie.
114 #   POLICY-HOOK-SCRIPT ... check-list [...]
115 #   POLICY-HOOK-SCRIPT ... check-package PACKAGE [...]
116 #   POLICY-HOOK-SCRIPT ... push|push-confirm PACKAGE \
117 #         VERSION SUITE TAGNAME DELIBERATELIES [...]
118 #
119 # Exit status is a bitmask.  Bit weight constants are defined in Dgit.pm.
120 #    NOFFCHECK   (2)
121 #         suppress dgit-repos-server's fast-forward check ("push" only)
122 #    FRESHREPO   (4)
123 #         blow away repo right away (ie, as if before push or fetch)
124 #         ("check-package" and "push" only)
125 # any unexpected bits mean failure, and then known set bits are ignored
126 # if no unexpected bits set, operation continues (subject to meaning
127 # of any expected bits set).  So, eg, exit 0 means "continue normally"
128 # and would be appropriate for an unknown action.
129 #
130 # cwd for push and push-confirm is a temporary repo where the
131 # to-be-pushed objects have been received; TAGNAME is the
132 # version-based tag
133 #
134 # if push requested FRESHREPO, push-confirm happens in said fresh repo
135 #
136 # policy hook for a particular package will be invoked only once at
137 # a time - (see comments about DGIT-REPOS-DIR, above)
138
139
140 use POSIX;
141 use Fcntl qw(:flock);
142 use File::Path qw(rmtree);
143
144 use Debian::Dgit qw(:DEFAULT :policyflags);
145
146 open DEBUG, ">/dev/null" or die $!;
147
148 our $func;
149 our $dgitrepos;
150 our $package;
151 our $suitesfile;
152 our $policyhook;
153 our $realdestrepo;
154 our $destrepo;
155 our $workrepo;
156 our $keyrings;
157 our @lockfhs;
158 our $debug='';
159 our @deliberatelies;
160 our %supersedes;
161 our $policy;
162
163 #----- utilities -----
164
165 sub debug {
166     print DEBUG "$debug @_\n";
167 }
168
169 sub acquirelock ($$) {
170     my ($lock, $must) = @_;
171     my $fh;
172     printf DEBUG "$debug locking %s %d\n", $lock, $must;
173     for (;;) {
174         close $fh if $fh;
175         $fh = new IO::File $lock, ">" or die "open $lock: $!";
176         my $ok = flock $fh, $must ? LOCK_EX : (LOCK_EX|LOCK_NB);
177         if (!$ok) {
178             die "flock $lock: $!" if $must;
179             debug " locking $lock failed";
180             return undef;
181         }
182         next unless stat_exists $lock;
183         my $want = (stat _)[1];
184         stat $fh or die $!;
185         my $got = (stat _)[1];
186         last if $got == $want;
187     }
188     return $fh;
189 }
190
191 sub acquirermtree ($$) {
192     my ($tree, $must) = @_;
193     my $fh = acquirelock("$tree.lock", $must);
194     if ($fh) {
195         push @lockfhs, $fh;
196         rmtree $tree;
197     }
198     return $fh;
199 }
200
201 sub locksometree ($) {
202     my ($tree) = @_;
203     acquirelock("$tree.lock", 1);
204 }
205
206 sub lockrealtree () {
207     locksometree($realdestrepo);
208 }
209
210 sub mkrepotmp () {
211     my $tmpdir = "$dgitrepos/_tmp";
212     return if mkdir $tmpdir;
213     return if $! == EEXIST;
214     die $!;
215 }
216
217 sub recorderror ($) {
218     my ($why) = @_;
219     my $w = $ENV{'DGIT_DRS_WORK'}; # we are in stunthook
220     if (defined $w) {
221         chomp $why;
222         open ERR, ">", "$w/drs-error" or die $!;
223         print ERR $why, "\n" or die $!;
224         close ERR or die $!;
225         return 1;
226     }
227     return 0;
228 }
229
230 sub reject ($) {
231     my ($why) = @_;
232     recorderror "reject: $why";
233     die "dgit-repos-server: reject: $why\n";
234 }
235
236 sub debugcmd {
237     if ($debug) {
238         use Data::Dumper;
239         local $Data::Dumper::Indent = 0;
240         local $Data::Dumper::Terse = 1;
241         debug "|".Dumper(\@_);
242     }
243 }
244
245 sub runcmd {
246     debugcmd @_;
247     $!=0; $?=0;
248     my $r = system @_;
249     die "@_ $? $!" if $r;
250 }
251
252 sub policyhook {
253     my ($policyallowbits, @polargs) = @_;
254     # => ($exitstatuspolicybitmap);
255     die if $policyallowbits & ~0x3e;
256     my @cmd = ($policyhook,$distro,$repos,@polargs);
257     debugcmd @_;
258     my $r = system @_;
259     die "system: $!" if $r < 0;
260     die "hook (@cmd) failed ($?)" if $r & ~($policyallowbits << 8);
261     return $r >> 8;
262 }
263
264 sub mkemptyrepo ($$) {
265     my ($dir,$sharedperm) = @_;
266     runcmd qw(git init --bare --quiet), "--shared=$sharedperm", $dir;
267 }
268
269 sub mkrepo_fromtemplate ($) {
270     my ($dir) = @_;
271     my $template = "$dgitrepos/_template";
272     locksometree($template);
273     debug "copy template $template -> $dir";
274     my $r = system qw(cp -a --), $template, $dir;
275     !$r or die "create new repo $dir failed: $r $!";
276 }
277
278 sub movetogarbage () {
279     # $realdestrepo must have been locked
280     my $garbagerepo = "$dgitrepos/${package}_garbage";
281     # We arrange to always keep at least one old tree, for anti-rewind
282     # purposes (and, I guess, recovery from mistakes).  This is either
283     # $garbage or $garbage-old.
284     if (stat_exists "$garbagerepo") {
285         rmtree "$garbagerepo-tmp";
286         if (rename "$garbagerepo-old", "$garbagerepo-tmp") {
287             rmtree "$garbagerepo-tmp";
288         } else {
289             die "$garbagerepo $!" unless $!==ENOENT;
290         }
291         rename "$garbagerepo", "$garbagerepo-old" or die "$garbagerepo $!";
292     }
293     rename $realdestrepo, $garbagerepo
294         or $! == ENOENT
295         or die "$garbagerepo $!";
296 }
297
298 sub onwardpush () {
299     my @cmd = (qw(git send-pack), $destrepo);
300     push @cmd, qw(--force) if $policy & NOFFCHECK;
301     push @cmd, "$commit:refs/dgit/$suite",
302                "$tagval:refs/tags/$tagname");
303     debugcmd @cmd;
304     $!=0;
305     my $r = system @cmd;
306     !$r or die "onward push to $destrepo failed: $r $!";
307 }
308
309 #----- git-receive-pack -----
310
311 sub fixmissing__git_receive_pack () {
312     mkrepotmp();
313     $destrepo = "$dgitrepos/_tmp/${package}_prospective";
314     acquirermtree($destrepo, 1);
315     mkrepo_fromtemplate($destrepo);
316 }
317
318 sub makeworkingclone () {
319     mkrepotmp();
320     $workrepo = "$dgitrepos/_tmp/${package}_incoming$$";
321     acquirermtree($workrepo, 1);
322     my $lfh = lockrealtree();
323     runcmd qw(git clone -l -q --mirror), $destrepo, $workrepo;
324     close $lfh;
325     rmtree "${workrepo}_fresh";
326 }
327
328 sub setupstunthook () {
329     my $prerecv = "$workrepo/hooks/pre-receive";
330     my $fh = new IO::File $prerecv, O_WRONLY|O_CREAT|O_TRUNC, 0777
331         or die "$prerecv: $!";
332     print $fh <<END or die "$prerecv: $!";
333 #!/bin/sh
334 set -e
335 exec $0 --pre-receive-hook $package
336 END
337     close $fh or die "$prerecv: $!";
338     $ENV{'DGIT_DRS_WORK'}= $workrepo;
339     $ENV{'DGIT_DRS_DEST'}= $destrepo;
340     debug " stunt hook set up $prerecv";
341 }
342
343 sub dealwithfreshrepo () {
344     my $freshrepo = "${workrepo}_fresh";
345     return unless stat_exists $freshrepo;
346     $destrepo = $freshrepo;
347 }
348
349 sub maybeinstallprospective () {
350     return if $destrepo eq $realdestrepo;
351
352     if (open REJ, "<", "$workrepo/drs-error") {
353         local $/ = undef;
354         my $msg = <REJ>;
355         REJ->error and die $!;
356         print STDERR $msg;
357         exit 1;
358     } else {
359         $!==&ENOENT or die $!;
360     }
361
362     debug " show-ref ($destrepo) ...";
363
364     my $child = open SR, "-|";
365     defined $child or die $!;
366     if (!$child) {
367         chdir $destrepo or die $!;
368         exec qw(git show-ref);
369         die $!;
370     }
371     my %got = qw(tag 0 head 0);
372     while (<SR>) {
373         chomp or die;
374         debug " show-refs| $_";
375         s/^\S*[1-9a-f]\S* (\S+)$/$1/ or die;
376         my $wh =
377             m{^refs/tags/} ? 'tag' :
378             m{^refs/dgit/} ? 'head' :
379             die;
380         die if $got{$wh}++;
381     }
382     $!=0; $?=0; close SR or $?==256 or die "$? $!";
383
384     debug "installprospective ?";
385     die Dumper(\%got)." -- missing refs in new repo"
386         if grep { !$_ } values %got;
387
388     lockrealtree();
389
390     if ($destrepo eq "${workrepo}_fresh") {
391         movetogarbage;
392     }
393
394     debug "install $destrepo => $realdestrepo";
395     rename $destrepo, $realdestrepo or die $!;
396     remove "$destrepo.lock" or die $!;
397 }
398
399 sub main__git_receive_pack () {
400     makeworkingclone();
401     setupstunthook();
402     runcmd qw(git receive-pack), $workrepo;
403     dealwithfreshrepo();
404     maybeinstallprospective();
405 }
406
407 #----- stunt post-receive hook -----
408
409 our ($tagname, $tagval, $suite, $oldcommit, $commit);
410 our ($version, %tagh);
411
412 sub readupdates () {
413     debug " updates ...";
414     while (<STDIN>) {
415         chomp or die;
416         debug " upd.| $_";
417         m/^(\S+) (\S+) (\S+)$/ or die "$_ ?";
418         my ($old, $sha1, $refname) = ($1, $2, $3);
419         if ($refname =~ m{^refs/tags/(?=debian/)}) {
420             reject "pushing multiple tags!" if defined $tagname;
421             $tagname = $'; #';
422             $tagval = $sha1;
423             reject "tag $tagname already exists -".
424                 " not replacing previously-pushed version"
425                 if $old =~ m/[^0]/;
426         } elsif ($refname =~ m{^refs/dgit/}) {
427             reject "pushing multiple heads!" if defined $suite;
428             $suite = $'; #';
429             $oldcommit = $old;
430             $commit = $sha1;
431         } else {
432             reject "pushing unexpected ref!";
433         }
434     }
435     STDIN->error and die $!;
436
437     reject "push is missing tag ref update" unless defined $tagname;
438     reject "push is missing head ref update" unless defined $suite;
439     debug " updates ok.";
440 }
441
442 sub parsetag () {
443     debug " parsetag...";
444     open PT, ">dgit-tmp/plaintext" or die $!;
445     open DS, ">dgit-tmp/plaintext.asc" or die $!;
446     open T, "-|", qw(git cat-file tag), $tagval or die $!;
447     for (;;) {
448         $!=0; $_=<T>; defined or die $!;
449         print PT or die $!;
450         if (m/^(\S+) (.*)/) {
451             push @{ $tagh{$1} }, $2;
452         } elsif (!m/\S/) {
453             last;
454         } else {
455             die;
456         }
457     }
458     $!=0; $_=<T>; defined or die $!;
459     m/^($package_re) release (\S+) for \S+ \((\S+)\) \[dgit\]$/ or
460         reject "tag message not in expected format";
461
462     die unless $1 eq $package;
463     $version = $2;
464     die "$3 != $suite " unless $3 eq $suite;
465
466     for (;;) {
467         print PT or die $!;
468         $!=0; $_=<T>; defined or die "missing signature? $!";
469         if (m/^\[dgit ([^"].*)\]$/) { # [dgit "something"] is for future
470             $_ = $1." ";
471             for (;;) {
472                 if (s/^distro\=(\S+) //) {
473                     die "$1 != $distro" unless $1 eq $distro;
474                 } elsif (s/^(--deliberately-$package_re) //) {
475                     push @deliberatelies, $1;
476                 } elsif (s/^supersede:(\S+)=(\w+) //) {
477                     die "supersede $1 twice" if defined $supersedes{$1};
478                     $supersedes{$1} = $2;
479                 } elsif (s/^[-+.=0-9a-z]\S* //) {
480                 } else {
481                     die "unknown dgit info in tag";
482                 }
483             }
484             next;
485         }
486         last if m/^-----BEGIN PGP/;
487     }
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($objreferring, 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(",",@delberatelies));
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 stunthook () {
735     debug "stunthook";
736     chdir $workrepo or die "chdir $workrepo: $!";
737     mkdir "dgit-tmp" or $!==EEXIST or die $!;
738     readupdates();
739     parsetag();
740     verifytag();
741     checks();
742     onwardpush();
743     debug "stunthook done.";
744 }
745
746 #----- git-upload-pack -----
747
748 sub fixmissing__git_upload_pack () {
749     $destrepo = "$dgitrepos/_empty";
750     my $lfh = locksometree($destrepo);
751     return if stat_exists $destrepo;
752     rmtree "$destrepo.new";
753     mkemptyrepo "$destrepo.new", "0644";
754     rename "$destrepo.new", $destrepo or die $!;
755     unlink "$destrepo.lock" or die $!;
756     close $lfh;
757 }
758
759 sub main__git_upload_pack () {
760     my $lfh = locksometree($destrepo);
761     chdir $destrepo or die "$destrepo: $!";
762     close $lfh;
763     runcmd qw(git upload-pack), ".";
764 }
765
766 #----- arg parsing and main program -----
767
768 sub argval () {
769     die unless @ARGV;
770     my $v = shift @ARGV;
771     die if $v =~ m/^-/;
772     return $v;
773 }
774
775 sub parseargsdispatch () {
776     die unless @ARGV;
777
778     delete $ENV{'GIT_DIR'}; # if not run via ssh, our parent git process
779     delete $ENV{'GIT_PREFIX'}; # sets these and they mess things up
780
781     if ($ENV{'DGIT_DRS_DEBUG'}) {
782         $debug='=';
783         open DEBUG, ">&STDERR" or die $!;
784     }
785
786     if ($ARGV[0] eq '--pre-receive-hook') {
787         if ($debug) { $debug.="="; }
788         shift @ARGV;
789         @ARGV == 1 or die;
790         $package = shift @ARGV;
791         defined($distro = $ENV{'DGIT_DRS_DISTRO'}) or die;
792         defined($suitesfile = $ENV{'DGIT_DRS_SUITES'}) or die;
793         defined($workrepo = $ENV{'DGIT_DRS_WORK'}) or die;
794         defined($destrepo = $ENV{'DGIT_DRS_DEST'}) or die;
795         defined($keyrings = $ENV{'DGIT_DRS_KEYRINGS'}) or die $!;
796         defined($policyhook = $ENV{'DGIT_DRS_POLICYHOOK'}) or die $!;
797         open STDOUT, ">&STDERR" or die $!;
798         eval {
799             stunthook();
800         };
801         if ($@) {
802             recorderror "$@" or die;
803             die $@;
804         }
805         exit 0;
806     }
807
808     $ENV{'DGIT_DRS_DISTRO'} = argval();
809     $ENV{'DGIT_DRS_SUITES'} = argval();
810     $ENV{'DGIT_DRS_KEYRINGS'} = argval();
811     $dgitrepos = argval();
812     $ENV{'DGIT_DRS_POLICYHOOK'} = $policyhook = argval();
813
814     die unless @ARGV==1 && $ARGV[0] eq '--ssh';
815
816     my $cmd = $ENV{'SSH_ORIGINAL_COMMAND'};
817     $cmd =~ m{
818         ^
819         (?: \S* / )?
820         ( [-0-9a-z]+ )
821         \s+
822         '? (?: \S* / )?
823         ($package_re) \.git
824         '?$
825     }ox 
826     or reject "command string not understood";
827     my $method = $1;
828     $package = $2;
829     $realdestrepo = "$dgitrepos/$package.git";
830
831     my $funcn = $method;
832     $funcn =~ y/-/_/;
833     my $mainfunc = $main::{"main__$funcn"};
834
835     reject "unknown method" unless $mainfunc;
836
837     my $lfh = lockrealtree();
838
839     $policy = policyhook(FRESHREPO,'check-package',$package);
840     if ($policy & FRESHREPO) {
841         movetogarbage;
842     }
843
844     close $lfh;
845
846     if (stat_exists $realdestrepo) {
847         $destrepo = $realdestrepo;
848     } else {
849         debug " fixmissing $funcn";
850         my $fixfunc = $main::{"fixmissing__$funcn"};
851         &$fixfunc;
852     }
853
854     debug " running main $funcn";
855     &$mainfunc;
856 }
857
858 sub unlockall () {
859     while (my $fh = pop @lockfhs) { close $fh; }
860 }
861
862 sub cleanup () {
863     unlockall();
864     if (!chdir "$dgitrepos/_tmp") {
865         $!==ENOENT or die $!;
866         return;
867     }
868     foreach my $lf (<*.lock>) {
869         my $tree = $lf;
870         $tree =~ s/\.lock$//;
871         next unless acquirermtree($tree, 0);
872         remove $lf or warn $!;
873         unlockall();
874     }
875 }
876
877 parseargsdispatch();
878 cleanup();