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