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