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