chiark / gitweb /
dgit-repos-server: tag2upload: Check changelog info
[dgit.git] / infra / dgit-repos-server
1 #!/usr/bin/perl -w
2 # dgit-repos-server
3 #
4 # git protocol proxy to check dgit pushes etc.
5 #
6 # Copyright (C) 2014-2016  Ian Jackson
7 #
8 #    This program is free software; you can redistribute it and/or modify
9 #    it under the terms of the GNU General Public License as published by
10 #    the Free Software Foundation; either version 3 of the License, or
11 #    (at your option) any later version.
12 #
13 #    This program is distributed in the hope that it will be useful,
14 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
15 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 #    GNU General Public License for more details.
17 #
18 #    You should have received a copy of the GNU General Public License
19 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20
21 # usages:
22 #   dgit-repos-server DISTRO DISTRO-DIR AUTH-SPEC [<settings>] --ssh
23 #   dgit-repos-server DISTRO DISTRO-DIR AUTH-SPEC [<settings>] --cron
24 #   dgit-repos-server DISTRO DISTRO-DIR AUTH-SPEC [<settings>] \
25 #      --tag2upload URL TAGNAME
26 # settings
27 #   --repos=GIT-REPOS-DIR      default DISTRO-DIR/repos/
28 #   --suites=SUITES-FILE       default DISTRO-DIR/suites
29 #   --suites-master=SUITES-FILE default DISTRO-DIR/suites-master
30 #   --policy-hook=POLICY-HOOK  default DISTRO-DIR/policy-hook
31 #   --mirror-hook=MIRROR-HOOK  default DISTRO-DIR/mirror-hook
32 #   --dgit-live=DGIT-LIVE-DIR  default DISTRO-DIR/dgit-live
33 # (DISTRO-DIR is not used other than as default and to pass to policy
34 # and mirror hooks)
35 # internal usage:
36 #  .../dgit-repos-server --pre-receive-hook PACKAGE
37 #
38 # Invoked as the ssh restricted command
39 #
40 # Works like git-receive-pack
41 #
42 # SUITES-FILE is the name of a file which lists the permissible suites
43 # one per line (#-comments and blank lines ignored).  For --suites-master
44 # it is a list of the suite(s) which should, when pushed to, update
45 # `master' on the server (if fast forward).
46 #
47 # AUTH-SPEC is a :-separated list of
48 #   KEYRING.GPG,AUTH-SPEC
49 # where AUTH-SPEC is one of
50 #   a
51 #   mDM.TXT
52 # (With --cron AUTH-SPEC is not used and may be the empty string.)
53
54 use strict;
55 use Carp;
56 use IO::Handle;
57
58 use Debian::Dgit::Infra; # must precede Debian::Dgit; - can change @INC!
59 use Debian::Dgit qw(:DEFAULT :policyflags);
60 setup_sigwarn();
61
62 # DGIT-REPOS-DIR contains:
63 # git tree (or other object)      lock (in acquisition order, outer first)
64 #
65 #  _tmp/PACKAGE_prospective       ! } SAME.lock, held during receive-pack
66 #
67 #  _tmp/PACKAGE_incoming$$        ! } SAME.lock, held during receive-pack
68 #  _tmp/PACKAGE_incoming$$_fresh  ! }
69 #
70 #  PACKAGE.git                      } PACKAGE.git.lock
71 #  PACKAGE_garbage                  }   (also covers executions of
72 #  PACKAGE_garbage-old              }    policy hook script for PACKAGE)
73 #  PACKAGE_garbage-tmp              }
74 #  policy*                          } (for policy hook script, covered by
75 #                                   }  lock only when invoked for a package)
76 #
77 # leaf locks, held during brief operaton only:
78 #
79 #  _empty                           } SAME.lock
80 #  _empty.new                       }
81 #
82 #  _template                        } SAME.lock
83 #
84 # locks marked ! may be held during client data transfer
85
86 # What we do on push is this:
87 #  - extract the destination repo name
88 #  - make a hardlink clone of the destination repo
89 #  - provide the destination with a stunt pre-receive hook
90 #  - run actual git-receive-pack with that new destination
91 #   as a result of this the stunt pre-receive hook runs; it does this:
92 #    + understand what refs we are allegedly updating and
93 #      check some correspondences:
94 #        * we are updating only refs/tags/[archive/]DISTRO/* and refs/dgit/*
95 #        * and only one of each
96 #        * and the tag does not already exist
97 #      and
98 #        * recover the suite name from the destination refs/dgit/ ref
99 #    + disassemble the signed tag into its various fields and signature
100 #      including:
101 #        * parsing the first line of the tag message to recover
102 #          the package name, version and suite
103 #        * checking that the package name corresponds to the dest repo name
104 #        * checking that the suite name is as recovered above
105 #    + verify the signature on the signed tag
106 #      and if necessary check that the keyid and package are listed in dm.txt
107 #    + check various correspondences:
108 #        * the signed tag must refer to a commit
109 #        * the signed tag commit must be the refs/dgit value
110 #        * the name in the signed tag must correspond to its ref name
111 #        * the tag name must be [archive/]debian/<version> (massaged as needed)
112 #        * the suite is one of those permitted
113 #        * the signed tag has a suitable name
114 #        * run the "push" policy hook
115 #        * replay prevention for --deliberately-not-fast-forward
116 #        * check the commit is a fast forward
117 #        * handle a request from the policy hook for a fresh repo
118 #    + push the signed tag and new dgit branch to the actual repo
119 #
120 # If the destination repo does not already exist, we need to make
121 # sure that we create it reasonably atomically, and also that
122 # we don't every have a destination repo containing no refs at all
123 # (because such a thing causes git-fetch-pack to barf).  So then we
124 # do as above, except:
125 #  - before starting, we take out our own lock for the destination repo
126 #  - we create a prospective new destination repo by making a copy
127 #    of _template
128 #  - we use the prospective new destination repo instead of the
129 #    actual new destination repo (since the latter doesn't exist)
130 #  - after git-receive-pack exits, we
131 #    + check that the prospective repo contains a tag and head
132 #    + rename the prospective destination repo into place
133 #
134 # Cleanup strategy:
135 #  - We are crash-only
136 #  - Temporary working trees and their locks are cleaned up
137 #    opportunistically by a program which tries to take each lock and
138 #    if successful deletes both the tree and the lockfile
139 #  - Prospective working trees and their locks are cleaned up by
140 #    a program which tries to take each lock and if successful
141 #    deletes any prospective working tree and the lock (but not
142 #    of course any actual tree)
143 #  - It is forbidden to _remove_ the lockfile without removing
144 #    the corresponding temporary tree, as the lockfile is also
145 #    a stampfile whose presence indicates that there may be
146 #    cleanup to do
147 #
148 # Policy hook scripts are invoked like this:
149 #   POLICY-HOOK-SCRIPT DISTRO DGIT-REPOS-DIR DGIT-LIVE-DIR DISTRO-DIR ACTION...
150 # ie.
151 #   POLICY-HOOK-SCRIPT ... check-list [...]
152 #   POLICY-HOOK-SCRIPT ... check-package PACKAGE [...]
153 #   POLICY-HOOK-SCRIPT ... push PACKAGE \
154 #         VERSION SUITE TAGNAME DELIBERATELIES [...]
155 #   POLICY-HOOK-SCRIPT ... push-confirm PACKAGE \
156 #         VERSION SUITE TAGNAME DELIBERATELIES FRESH-REPO|'' [...]
157 #
158 # DELIBERATELIES is like this: --deliberately-foo,--deliberately-bar,...
159 #
160 # Exit status of policy hook is a bitmask.
161 # Bit weight constants are defined in Dgit.pm.
162 #    NOFFCHECK   (2)
163 #         suppress dgit-repos-server's fast-forward check ("push" only)
164 #    FRESHREPO   (4)
165 #         blow away repo right away (ie, as if before push or fetch)
166 #         ("check-package" and "push" only)
167 #    NOCOMMITCHECK   (8)
168 #         suppress dgit-repos-server's check that commits do
169 #         not lack "committer" info (eg as produced by #849041)
170 #         ("push" only)
171 # any unexpected bits mean failure, and then known set bits are ignored
172 # if no unexpected bits set, operation continues (subject to meaning
173 # of any expected bits set).  So, eg, exit 0 means "continue normally"
174 # and would be appropriate for an unknown action.
175 #
176 # cwd for push and push-confirm is a temporary repo where the incoming
177 # objects have been received; TAGNAME is the version-based tag.
178 #
179 # FRESH-REPO is '' iff the repo for this package already existed, or
180 # the pathname of the newly-created repo which will be renamed into
181 # place if everything goes well.  (NB that this is generally not the
182 # same repo as the cwd, because the objects are first received into a
183 # temporary repo so they can be examined.)  In this case FRESH-REPO
184 # contains exactly the objects and refs that will appear in the
185 # destination if push-confirm approves.
186
187 # if push requested FRESHREPO, push-confirm happens in the old working
188 # repo and FRESH-REPO is guaranteed not to be ''.
189 #
190 # policy hook for a particular package will be invoked only once at
191 # a time - (see comments about DGIT-REPOS-DIR, above)
192 #
193 # check-list and check-package are invoked via the --cron option.
194 # First, without any locking, check-list is called.  It should produce
195 # a list of package names (one per line).  Then check-package will be
196 # invoked for each named package, in each case after taking an
197 # appropriate lock.
198 #
199 # If policy hook wants to run dgit (or something else in the dgit
200 # package), it should use DGIT-LIVE-DIR/dgit (etc.), or if that is
201 # ENOENT, use the installed version.
202 #
203 # Mirror hook scripts are invoked like this:
204 #   MIRROR-HOOK-SCRIPT DISTRO-DIR ACTION...
205 # and currently there is only one action invoked by dgit-repos-server:
206 #   MIRROR-HOOK-SCRIPT DISTRO-DIR updated-hook PACKAGE [...]
207 #
208 # Exit status of the mirror hook is advisory only.  The mirror hook
209 # runs too late to do anything useful about a problem, so the only
210 # effect of a mirror hook exiting nonzero is a warning message to
211 # stderr (which the pushing user should end up seeing).
212 #
213 # If the mirror hook does not exist, it is silently skipped.
214
215 use POSIX;
216 use Fcntl qw(:flock);
217 use File::Path qw(rmtree);
218 use File::Temp qw(tempfile);
219
220 initdebug('');
221
222 our $func;
223 our $dgitrepos;
224 our $package;
225 our $distro;
226 our $suitesfile;
227 our $suitesformasterfile;
228 our $policyhook;
229 our $mirrorhook;
230 our $dgitlive;
231 our $distrodir;
232 our $destrepo;
233 our $workrepo;
234 our $keyrings;
235 our @lockfhs;
236
237 our @deliberatelies;
238 our %previously;
239 our $policy;
240 our @policy_args;
241
242 #----- utilities -----
243
244 sub realdestrepo () { "$dgitrepos/$package.git"; }
245
246 sub acquirelock ($$) {
247     my ($lock, $must) = @_;
248     my $fh;
249     printdebug sprintf "locking %s %d\n", $lock, $must;
250     for (;;) {
251         close $fh if $fh;
252         $fh = new IO::File $lock, ">" or die "open $lock: $!";
253         my $ok = flock $fh, $must ? LOCK_EX : (LOCK_EX|LOCK_NB);
254         if (!$ok) {
255             die "flock $lock: $!" if $must;
256             printdebug " locking $lock failed\n";
257             return undef;
258         }
259         next unless stat_exists $lock;
260         my $want = (stat _)[1];
261         stat $fh or die $!;
262         my $got = (stat _)[1];
263         last if $got == $want;
264     }
265     return $fh;
266 }
267
268 sub acquirermtree ($$) {
269     my ($tree, $must) = @_;
270     my $fh = acquirelock("$tree.lock", $must);
271     if ($fh) {
272         push @lockfhs, $fh;
273         rmtree $tree;
274     }
275     return $fh;
276 }
277
278 sub locksometree ($) {
279     my ($tree) = @_;
280     acquirelock("$tree.lock", 1);
281 }
282
283 sub lockrealtree () {
284     locksometree(realdestrepo);
285 }
286
287 sub mkrepotmp () { ensuredir "$dgitrepos/_tmp" };
288
289 sub removedtagsfile () { "$dgitrepos/_removed-tags/$package"; }
290
291 sub recorderror ($) {
292     my ($why) = @_;
293     my $w = $ENV{'DGIT_DRS_WORK'}; # we are in stunthook
294     if (defined $w) {
295         chomp $why;
296         open ERR, ">", "$w/drs-error" or die $!;
297         print ERR $why, "\n" or die $!;
298         close ERR or die $!;
299         return 1;
300     }
301     return 0;
302 }
303
304 sub reject ($) {
305     my ($why) = @_;
306     recorderror "reject: $why";
307     die "\ndgit-repos-server: reject: $why\n\n";
308 }
309
310 sub policyhook {
311     my ($policyallowbits, @polargs) = @_;
312     # => ($exitstatuspolicybitmap);
313     die if $policyallowbits & ~0x3e;
314     my @cmd = ($policyhook,$distro,$dgitrepos,$dgitlive,$distrodir,@polargs);
315     debugcmd '+M',@cmd;
316     my $r = system @cmd;
317     die "system: $!" if $r < 0;
318     die "dgit-repos-server: policy hook failed (or rejected) ($?)\n"
319         if $r & ~($policyallowbits << 8);
320     printdebug sprintf "hook => %#x\n", $r;
321     return $r >> 8;
322 }
323
324 sub mkemptyrepo ($$) {
325     my ($dir,$sharedperm) = @_;
326     runcmd qw(git init --bare --quiet), "--shared=$sharedperm", $dir;
327 }
328
329 sub mkrepo_fromtemplate ($) {
330     my ($dir) = @_;
331     my $template = "$dgitrepos/_template";
332     my $templatelock = locksometree($template);
333     printdebug "copy template $template -> $dir\n";
334     my $r = system qw(cp -a --), $template, $dir;
335     !$r or die "create new repo $dir failed: $r $!";
336     close $templatelock;
337 }
338
339 sub movetogarbage () {
340     # realdestrepo must have been locked
341
342     my $real = realdestrepo;
343     return unless stat_exists $real;
344
345     my $garbagerepo = "$dgitrepos/${package}_garbage";
346     # We arrange to always keep at least one old tree, for recovery
347     # from mistakes.  This is either $garbage or $garbage-old.
348     if (stat_exists "$garbagerepo") {
349         printdebug "movetogarbage: rmtree $garbagerepo-tmp\n";
350         rmtree "$garbagerepo-tmp";
351         if (rename "$garbagerepo-old", "$garbagerepo-tmp") {
352             printdebug "movetogarbage: $garbagerepo-old -> -tmp, rmtree\n";
353             rmtree "$garbagerepo-tmp";
354         } else {
355             die "$garbagerepo $!" unless $!==ENOENT;
356             printdebug "movetogarbage: $garbagerepo-old -> -tmp\n";
357         }
358         printdebug "movetogarbage: $garbagerepo -> -old\n";
359         rename "$garbagerepo", "$garbagerepo-old" or die "$garbagerepo $!";
360     }
361
362     ensuredir "$dgitrepos/_removed-tags";
363     open PREVIOUS, ">>", removedtagsfile or die removedtagsfile." $!";
364     git_for_each_ref([ map { 'refs/tags/'.$_ } debiantags('*',$distro) ],
365                      sub {
366         my ($objid,$objtype,$fullrefname,$reftail) = @_;
367         print PREVIOUS "\n$objid $reftail .\n" or die $!;
368     }, $real);
369     close PREVIOUS or die $!;
370
371     printdebug "movetogarbage: $real -> $garbagerepo\n";
372     rename $real, $garbagerepo
373         or $! == ENOENT
374         or die "$garbagerepo $!";
375 }
376
377 sub policy_checkpackage () {
378     my $lfh = lockrealtree();
379
380     $policy = policyhook(FRESHREPO,'check-package',$package);
381     if ($policy & FRESHREPO) {
382         movetogarbage();
383     }
384
385     close $lfh;
386 }
387
388 #----- git-receive-pack -----
389
390 sub fixmissing__git_receive_pack () {
391     mkrepotmp();
392     $destrepo = "$dgitrepos/_tmp/${package}_prospective";
393     acquirermtree($destrepo, 1);
394     mkrepo_fromtemplate($destrepo);
395 }
396
397 sub makeworkingclone () {
398     mkrepotmp();
399     $workrepo = "$dgitrepos/_tmp/${package}_incoming$$";
400     acquirermtree($workrepo, 1);
401     my $lfh = lockrealtree();
402     runcmd qw(git clone -l -q --mirror), $destrepo, $workrepo;
403     close $lfh;
404     rmtree "${workrepo}_fresh";
405 }
406
407 sub mkscript ($$) {
408     my ($path,$contents) = @_;
409     my $fh = new IO::File $path, O_WRONLY|O_CREAT|O_TRUNC, 0777
410         or die "$path: $!";
411     print $fh $contents or die "$path: $!";
412     close $fh or die "$path: $!";
413 }
414
415 sub setupstunthook () {
416     my $prerecv = "$workrepo/hooks/pre-receive";
417     mkscript $prerecv, <<END;
418 #!/bin/sh
419 set -e
420 exec $0 --pre-receive-hook $package
421 END
422     $ENV{'DGIT_DRS_WORK'}= $workrepo;
423     $ENV{'DGIT_DRS_DEST'}= $destrepo;
424     printdebug " stunt hook set up $prerecv\n";
425 }
426
427 sub dealwithfreshrepo () {
428     my $freshrepo = "${workrepo}_fresh";
429     return unless stat_exists $freshrepo;
430     $destrepo = $freshrepo;
431 }
432
433 sub mirrorhook {
434     my @cmd = ($mirrorhook,$distrodir,@_);
435     debugcmd '+',@cmd;
436     return unless stat_exists $mirrorhook;
437     my $r = system @cmd;
438     if ($r) {
439         printf STDERR <<END,
440 dgit-repos-server: warning: mirror hook failed: %s
441 dgit-repos-server: push complete but may not fully visible.
442 END
443             ($r < 0 ? "exec: $!" :
444              $r == (124 << 8) ? "exited status 124 (timeout?)" :
445              !($r & ~0xff00) ? "exited ".($? >> 8) :
446              "wait status $?");
447     }
448 }
449
450 sub maybeinstallprospective () {
451     return if $destrepo eq realdestrepo;
452
453     if (open REJ, "<", "$workrepo/drs-error") {
454         local $/ = undef;
455         my $msg = <REJ>;
456         REJ->error and die $!;
457         print STDERR $msg;
458         exit 1;
459     } else {
460         $!==&ENOENT or die $!;
461     }
462
463     printdebug " show-ref ($destrepo) ...\n";
464
465     my $child = open SR, "-|";
466     defined $child or die $!;
467     if (!$child) {
468         chdir $destrepo or die $!;
469         exec qw(git show-ref);
470         die $!;
471     }
472     my %got = qw(newtag 0 omtag 0 head 0);
473     while (<SR>) {
474         chomp or die;
475         printdebug " show-refs| $_\n";
476         s/^\S*[1-9a-f]\S* (\S+)$/$1/ or die;
477         next if m{^refs/heads/master$};
478         my $wh =
479             m{^refs/tags/archive/} ? 'newtag' :
480             m{^refs/tags/} ? 'omtag' :
481             m{^refs/dgit/} ? 'head' :
482             die;
483         use Data::Dumper;
484         die if $got{$wh}++;
485     }
486     $!=0; $?=0; close SR or $?==256 or die "$? $!";
487
488     printdebug "installprospective ?\n";
489     die Dumper(\%got)." -- missing refs in new repo"
490         unless $got{head} && grep { m/tag$/ && $got{$_} } keys %got;
491
492     lockrealtree();
493
494     if ($destrepo eq "${workrepo}_fresh") {
495         movetogarbage;
496     }
497
498     printdebug "install $destrepo => ".realdestrepo."\n";
499     rename $destrepo, realdestrepo or die $!;
500     remove realdestrepo.".lock" or die $!;
501 }
502
503 sub main__git_receive_pack () {
504     makeworkingclone();
505     setupstunthook();
506     runcmd qw(git receive-pack), $workrepo;
507     dealwithfreshrepo();
508     maybeinstallprospective();
509     mirrorhook('updated-hook', $package);
510 }
511
512 #----- stunt post-receive hook -----
513
514 our ($tagname, $tagval, $suite, $oldcommit, $commit);
515 our ($version, %tagh);
516 our ($maint_tagname, $maint_tagval);
517
518 our ($tagexists_error);
519
520 sub readupdates () {
521     printdebug " updates ...\n";
522     my %tags;
523     while (<STDIN>) {
524         chomp or die;
525         printdebug " upd.| $_\n";
526         m/^(\S+) (\S+) (\S+)$/ or die "$_ ?";
527         my ($old, $sha1, $refname) = ($1, $2, $3);
528         if ($refname =~ m{^refs/tags/(?=(?:archive/)?$distro/)}) {
529             my $tn = $'; #';
530             $tags{$tn} = $sha1;
531             $tagexists_error= "tag $tn already exists -".
532                 " not replacing previously-pushed version"
533                 if $old =~ m/[^0]/;
534         } elsif ($refname =~ m{^refs/dgit/}) {
535             reject "pushing multiple heads!" if defined $suite;
536             $suite = $'; #';
537             $oldcommit = $old;
538             $commit = $sha1;
539         } else {
540             reject "pushing unexpected ref!";
541         }
542     }
543     STDIN->error and die $!;
544
545     reject "push is missing tag ref update" unless %tags;
546     my @dtags = grep { m#^archive/# } keys %tags;
547     reject "need exactly one archive/* tag" if @dtags!=1;
548     my @mtags = grep { !m#^archive/# } keys %tags;
549     reject "pushing too many non-dgit tags" if @mtags>1;
550     ($tagname) = @dtags;
551     ($maint_tagname) = @mtags;
552     $tagval = $tags{$tagname};
553     $maint_tagval = $tags{$maint_tagname // ''};
554
555     reject "push is missing head ref update" unless defined $suite;
556     printdebug " updates ok.\n";
557 }
558
559 sub readtag () {
560     printdebug " readtag...\n";
561
562     open PT, ">dgit-tmp/plaintext" or die $!;
563     open DS, ">dgit-tmp/plaintext.asc" or die $!;
564     open T, "-|", qw(git cat-file tag), $tagval or die $!;
565     for (;;) {
566         $!=0; $_=<T>; defined or die $!;
567         print PT or die $!;
568         if (m/^(\S+) (.*)/) {
569             push @{ $tagh{$1} }, $2;
570         } elsif (!m/\S/) {
571             last;
572         } else {
573             die;
574         }
575     }
576     $!=0; $_=<T>; defined or die $!;
577 }
578
579 sub parsetag_general ($$) {
580     my ($dgititemfn, $distrofn) = @_;
581     printdebug " parsetag...\n";
582
583     my $copyl = $_;
584     for (;;) {
585         print PT $copyl or die $!;
586         $!=0; $_=<T>; defined or die "missing signature? $!";
587         $copyl = $_;
588         if (m/^\[dgit ([^"].*)\]$/) { # [dgit "something"] is for future
589             $_ = $1." ";
590             while (length) {
591                 if ($dgititemfn->()) {
592                 } elsif (s/^distro\=(\S+) //) {
593                     $distrofn->($1);
594                 } elsif (s/^[-+.=0-9a-z]\S* //) {
595                 } else {
596                     die "unknown dgit info in tag ($_)";
597                 }
598             }
599             next;
600         }
601         last if m/^-----BEGIN PGP/;
602     }
603
604     $_ = $copyl;
605     for (;;) {
606         print DS or die $!;
607         $!=0; $_=<T>;
608         last if !defined;
609     }
610     T->error and die $!;
611     close PT or die $!;
612     close DS or die $!;
613     printdebug " parsetag ok.\n";
614 }
615
616 sub parsetag () {
617     readtag();
618     m/^($package_re) release (\S+) for \S+ \((\S+)\) \[dgit\]$/ or
619         reject "tag message not in expected format";
620     die unless $1 eq $package;
621     $version = $2;
622     die "$3 != $suite " unless $3 eq $suite;
623
624     parsetag_general sub {
625         if (s/^(--deliberately-$deliberately_re) //) {
626             push @deliberatelies, $1;
627         } elsif (s/^previously:(\S+)=(\w+) //) {
628             die "previously $1 twice" if defined $previously{$1};
629             $previously{$1} = $2;
630         } else {
631             return 0;
632         }
633         return 1;
634     }, sub {
635         my ($gotdistro) = @_;
636         die "$gotdistro != $distro" unless $gotdistro eq $distro;
637     };
638 }
639
640 sub checksig_keyring ($) {
641     my ($keyringfile) = @_;
642     # returns primary-keyid if signed by a key in this keyring
643     # or undef if not
644     # or dies on other errors
645
646     my $ok = undef;
647
648     printdebug " checksig keyring $keyringfile...\n";
649
650     our @cmd = (qw(gpgv --status-fd=1 --keyring),
651                    $keyringfile,
652                    qw(dgit-tmp/plaintext.asc dgit-tmp/plaintext));
653     debugcmd '|',@cmd;
654
655     open P, "-|", @cmd
656         or die $!;
657
658     while (<P>) {
659         next unless s/^\[GNUPG:\] //;
660         chomp or die;
661         printdebug " checksig| $_\n";
662         my @l = split / /, $_;
663         if ($l[0] eq 'NO_PUBKEY') {
664             last;
665         } elsif ($l[0] eq 'VALIDSIG') {
666             my $sigtype = $l[9];
667             $sigtype eq '00' or reject "signature is not of type 00!";
668             $ok = $l[10];
669             die unless defined $ok;
670             last;
671         }
672     }
673     close P;
674
675     printdebug sprintf " checksig ok=%d\n", !!$ok;
676
677     return $ok;
678 }
679
680 sub dm_txt_check ($$) {
681     my ($keyid, $dmtxtfn) = @_;
682     printdebug " dm_txt_check $keyid $dmtxtfn\n";
683     open DT, '<', $dmtxtfn or die "$dmtxtfn $!";
684     while (<DT>) {
685         m/^fingerprint:\s+\Q$keyid\E$/oi
686             ..0 or next;
687         if (s/^allow:/ /i..0) {
688         } else {
689             m/^./
690                 or reject "key $keyid missing Allow section in permissions!";
691             next;
692         }
693         # in right stanza...
694         s/^[ \t]+//
695             or reject "package $package not allowed for key $keyid";
696         # in allow field...
697         s/\([^()]+\)//;
698         s/\,//;
699         chomp or die;
700         printdebug " dm_txt_check allow| $_\n";
701         foreach my $p (split /\s+/) {
702             if ($p eq $package) {
703                 # yay!
704                 printdebug " dm_txt_check ok\n";
705                 return;
706             }
707         }
708     }
709     DT->error and die $!;
710     close DT or die $!;
711     reject "key $keyid not in permissions list although in keyring!";
712 }
713
714 sub verifytag () {
715     foreach my $kas (split /:/, $keyrings) {
716         printdebug "verifytag $kas...\n";
717         $kas =~ s/^([^,]+),// or die;
718         my $keyid = checksig_keyring $1;
719         if (defined $keyid) {
720             if ($kas =~ m/^a$/) {
721                 printdebug "verifytag a ok\n";
722                 return; # yay
723             } elsif ($kas =~ m/^m([^,]+)$/) {
724                 dm_txt_check($keyid, $1);
725                 printdebug "verifytag m ok\n";
726                 return;
727             } else {
728                 die;
729             }
730         }   
731     }
732     reject "key not found in keyrings";
733 }
734
735 sub suite_is_in ($) {
736     my ($sf) = @_;
737     printdebug "suite_is_in ($sf)\n";
738     if (!open SUITES, "<", $sf) {
739         $!==ENOENT or die $!;
740         return 0;
741     }
742     while (<SUITES>) {
743         chomp;
744         next unless m/\S/;
745         next if m/^\#/;
746         s/\s+$//;
747         return 1 if $_ eq $suite;
748     }
749     die $! if SUITES->error;
750     return 0;
751 }
752
753 sub checksuite () {
754     printdebug "checksuite ($suitesfile)\n";
755     return if suite_is_in $suitesfile;
756     reject "unknown suite";
757 }
758
759 sub checktagnoreplay () {
760     # We need to prevent a replay attack using an earlier signed tag.
761     # We also want to archive in the history the object ids of
762     # anything we remove, even if we get rid of the actual objects.
763     #
764     # So, we check that the signed tag mentions the name and tag
765     # object id of:
766     #
767     # (a) In the case of FRESHREPO: all tags and refs/heads/* in
768     #     the repo.  That is, effectively, all the things we are
769     #     deleting.
770     #
771     #     This prevents any tag implying a FRESHREPO push
772     #     being replayed into a different state of the repo.
773     #
774     #     There is still the folowing risk: If a non-ff push is of a
775     #     head which is an ancestor of a previous ff-only push, the
776     #     previous push can be replayed.
777     #
778     #     So we keep a separate list, as a file in the repo, of all
779     #     the tag object ids we have ever seen and removed.  Any such
780     #     tag object id will be rejected even for ff-only pushes.
781     #
782     # (b) In the case of just NOFFCHECK: all tags referring to the
783     #     current head for the suite (there must be at least one).
784     #
785     #     This prevents any tag implying a NOFFCHECK push being
786     #     replayed to rewind from a different head.
787     #
788     #     The possibility of an earlier ff-only push being replayed is
789     #     eliminated as follows: the tag from such a push would still
790     #     be in our repo, and therefore the replayed push would be
791     #     rejected because the set of refs being updated would be
792     #     wrong.
793
794     if (!open PREVIOUS, "<", removedtagsfile) {
795         die removedtagsfile." $!" unless $!==ENOENT;
796     } else {
797         # Protocol for updating this file is to append to it, not
798         # write-new-and-rename.  So all updates are prefixed with \n
799         # and suffixed with " .\n" so that partial writes can be
800         # ignored.
801         while (<PREVIOUS>) {
802             next unless m/^(\w+) (.*) \.\n/;
803             next unless $1 eq $tagval;
804             reject "Replay of previously-rewound upload ($tagval $2)";
805         }
806         die removedtagsfile." $!" if PREVIOUS->error;
807         close PREVIOUS;
808     }
809
810     return unless $policy & (FRESHREPO|NOFFCHECK);
811
812     my $garbagerepo = "$dgitrepos/${package}_garbage";
813     lockrealtree();
814
815     my $nchecked = 0;
816     my @problems;
817
818     my $check_ref_previously= sub {
819         my ($objid,$objtype,$fullrefname,$reftail) = @_;
820         my $supkey = $fullrefname;
821         $supkey =~ s{^refs/}{} or die "$supkey $objid ?";
822         my $supobjid = $previously{$supkey};
823         if (!defined $supobjid) {
824             printdebug "checktagnoreply - missing\n";
825             push @problems, "does not declare previously $supkey";
826         } elsif ($supobjid ne $objid) {
827             push @problems, "declared previously $supkey=$supobjid".
828                 " but actually previously $supkey=$objid";
829         } else {
830             $nchecked++;
831         }
832     };
833
834     if ($policy & FRESHREPO) {
835         foreach my $kind (qw(tags heads)) {
836             git_for_each_ref("refs/$kind", $check_ref_previously);
837         }
838     } else {
839         my $branch= server_branch($suite);
840         my $branchhead= git_get_ref(server_ref($suite));
841         if (!length $branchhead) {
842             # No such branch - NOFFCHECK was unnecessary.  Oh well.
843             printdebug "checktagnoreplay - not FRESHREPO, new branch, ok\n";
844         } else {
845             printdebug "checktagnoreplay - not FRESHREPO,".
846                 " checking for overwriting refs/$branch=$branchhead\n";
847             git_for_each_tag_referring($branchhead, sub {
848                 my ($tagobjid,$refobjid,$fullrefname,$tagname) = @_;
849                 $check_ref_previously->($tagobjid,undef,$fullrefname,undef);
850             });
851             printdebug "checktagnoreplay - not FRESHREPO, nchecked=$nchecked";
852             push @problems, "does not declare previously any tag".
853                 " referring to branch head $branch=$branchhead"
854                 unless $nchecked;
855         }
856     }
857
858     if (@problems) {
859         reject "replay attack prevention check failed:".
860             " signed tag for $version: ".
861             join("; ", @problems).
862             "\n";
863     }
864     printdebug "checktagnoreplay - all ok ($tagval)\n"
865 }
866
867 sub tagh1 ($) {
868     my ($tag) = @_;
869     my $vals = $tagh{$tag};
870     reject "missing header $tag in signed tag object" unless $vals;
871     reject "multiple headers $tag in signed tag object" unless @$vals == 1;
872     return $vals->[0];
873 }
874
875 sub basic_tag_checks() {
876     printdebug "checks\n";
877
878     tagh1('type') eq 'commit' or reject "tag refers to wrong kind of object";
879     tagh1('object') eq $commit or reject "tag refers to wrong commit";
880     tagh1('tag') eq $tagname or reject "tag name in tag is wrong";
881 }
882
883 sub checks () {
884     basic_tag_checks();
885
886     my @expecttagnames = debiantags($version, $distro);
887     printdebug "expected tag @expecttagnames\n";
888     grep { $tagname eq $_ } @expecttagnames or die;
889
890     foreach my $othertag (grep { $_ ne $tagname } @expecttagnames) {
891         reject "tag $othertag already exists -".
892             " not replacing previously-pushed version"
893             if git_get_ref "refs/tags/".$othertag;
894     }
895
896     lockrealtree();
897
898     @policy_args = ($package,$version,$suite,$tagname,
899                     join(",",@deliberatelies));
900     $policy = policyhook(NOFFCHECK|FRESHREPO|NOCOMMITCHECK, 'push', @policy_args);
901
902     if (defined $tagexists_error) {
903         if ($policy & FRESHREPO) {
904             printdebug "ignoring tagexists_error: $tagexists_error\n";
905         } else {
906             reject $tagexists_error;
907         }
908     }
909
910     checktagnoreplay();
911     checksuite();
912
913     # check that our ref is being fast-forwarded
914     printdebug "oldcommit $oldcommit\n";
915     if (!($policy & NOFFCHECK) && $oldcommit =~ m/[^0]/) {
916         $?=0; $!=0; my $mb = `git merge-base $commit $oldcommit`;
917         chomp $mb;
918         $mb eq $oldcommit or reject "not fast forward on dgit branch";
919     }
920
921     # defend against commits generated by #849041
922     if (!($policy & NOCOMMITCHECK)) {
923         my @checks = qw(%at
924                         %ct);
925         my @chk = qw(git log -z);
926         push @chk, '--pretty=tformat:%H%n'.
927             (join "", map { $_, '%n' } @checks);
928         push @chk, "^$oldcommit" if $oldcommit =~ m/[^0]/;
929         push @chk, $commit;;
930         printdebug " ~NOCOMMITCHECK @chk\n";
931         open CHK, "-|", @chk or die $!;
932         local $/ = "\0";
933         while (<CHK>) {
934             next unless m/^$/m;
935             m/^\w+(?=\n)/ or die;
936             reject "corrupted object $& (missing metadata)";
937         }
938         $!=0; $?=0; close CHK or $?==256 or die "$? $!";
939     }
940
941     if ($policy & FRESHREPO) {
942         # It's a bit late to be discovering this here, isn't it ?
943         #
944         # What we do is: Generate a fresh destination repo right now,
945         # and arrange to treat it from now on as if it were a
946         # prospective repo.
947         #
948         # The presence of this fresh destination repo is detected by
949         # the parent, which responds by making a fresh master repo
950         # from the template.  (If the repo didn't already exist then
951         # $destrepo was _prospective, and we change it here.  This is
952         # OK because the parent's check for _fresh persuades it not to
953         # use _prospective.)
954         #
955         $destrepo = "${workrepo}_fresh"; # workrepo lock covers
956         mkrepo_fromtemplate $destrepo;
957     }
958 }
959
960 sub onwardpush () {
961     my @cmdbase = (qw(git send-pack), $destrepo);
962     push @cmdbase, qw(--force) if $policy & NOFFCHECK;
963
964     if ($ENV{GIT_QUARANTINE_PATH}) {
965         my $recv_wrapper = "$ENV{GIT_QUARANTINE_PATH}/dgit-recv-wrapper";
966         mkscript $recv_wrapper, <<'END';
967 #!/bin/sh
968 set -e
969 unset GIT_QUARANTINE_PATH
970 exec git receive-pack "$@"
971 END
972         push @cmdbase, "--receive-pack=$recv_wrapper";
973     }
974
975     my @cmd = @cmdbase;
976     push @cmd, "$commit:refs/dgit/$suite",
977                "$tagval:refs/tags/$tagname";
978     push @cmd, "$maint_tagval:refs/tags/$maint_tagname"
979         if defined $maint_tagname;
980     debugcmd '+',@cmd;
981     $!=0;
982     my $r = system @cmd;
983     !$r or die "onward push to $destrepo failed: $r $!";
984
985     if (suite_is_in $suitesformasterfile) {
986         @cmd = @cmdbase;
987         push @cmd, "$commit:refs/heads/master";
988         debugcmd '+', @cmd;
989         $!=0; my $r = system @cmd;
990         # tolerate errors (might be not ff)
991         !($r & ~0xff00) or die
992             "onward push to $destrepo#master failed: $r $!";
993     }
994 }
995
996 sub finalisepush () {
997     if ($destrepo eq realdestrepo) {
998         policyhook(0, 'push-confirm', @policy_args, '');
999         onwardpush();
1000     } else {
1001         # We are to receive the push into a new repo (perhaps
1002         # because the policy push hook asked us to with FRESHREPO, or
1003         # perhaps because the repo didn't exist before).
1004         #
1005         # We want to provide the policy push-confirm hook with a repo
1006         # which looks like the one which is going to be installed.
1007         # The working repo is no good because it might contain
1008         # previous history.
1009         #
1010         # So we push the objects into the prospective new repo right
1011         # away.  If the hook declines, we decline, and the prospective
1012         # repo is never installed.
1013         onwardpush();
1014         policyhook(0, 'push-confirm', @policy_args, $destrepo);
1015     }
1016 }
1017
1018 sub stunthook () {
1019     printdebug "stunthook in $workrepo\n";
1020     chdir $workrepo or die "chdir $workrepo: $!";
1021     mkdir "dgit-tmp" or $!==EEXIST or die $!;
1022     readupdates();
1023     parsetag();
1024     verifytag();
1025     checks();
1026     finalisepush();
1027     printdebug "stunthook done.\n";
1028 }
1029
1030 #----- git-upload-pack -----
1031
1032 sub fixmissing__git_upload_pack () {
1033     $destrepo = "$dgitrepos/_empty";
1034     my $lfh = locksometree($destrepo);
1035     return if stat_exists $destrepo;
1036     rmtree "$destrepo.new";
1037     mkemptyrepo "$destrepo.new", "0644";
1038     rename "$destrepo.new", $destrepo or die $!;
1039     unlink "$destrepo.lock" or die $!;
1040     close $lfh;
1041 }
1042
1043 sub main__git_upload_pack () {
1044     my $lfh = locksometree($destrepo);
1045     printdebug "git-upload-pack in $destrepo\n";
1046     chdir $destrepo or die "$destrepo: $!";
1047     close $lfh;
1048     runcmd qw(git upload-pack), ".";
1049 }
1050
1051 #----- arg parsing and main program -----
1052
1053 sub argval () {
1054     die unless @ARGV;
1055     my $v = shift @ARGV;
1056     die if $v =~ m/^-/;
1057     return $v;
1058 }
1059
1060 our %indistrodir = (
1061     # keys are used for DGIT_DRS_XXX too
1062     'repos' => \$dgitrepos,
1063     'suites' => \$suitesfile,
1064     'suites-master' => \$suitesformasterfile,
1065     'policy-hook' => \$policyhook,
1066     'mirror-hook' => \$mirrorhook,
1067     'dgit-live' => \$dgitlive,
1068     );
1069
1070 our @hookenvs = qw(distro suitesfile suitesformasterfile policyhook
1071                    mirrorhook dgitlive keyrings dgitrepos distrodir);
1072
1073 # workrepo and destrepo handled ad-hoc
1074
1075 sub mode_tag2upload () {
1076     # PROTOTYPE
1077     # CALLER MUST PREVENT MULTIPLE CONCURRENT RUNS IN SAME CWD
1078     # If we fail (exit nonzero), caller should capture our stderr,
1079     #  and retry some bounded number of times in some appropriate way
1080     @ARGV==2 or die;
1081
1082     my $url;
1083     ($url,$tagval) = @ARGV;
1084
1085     $ENV{DGIT_DRS_EMAIL_NOREPLY} // die;
1086
1087     my $start = time // die;
1088     my @t = gmtime $start;
1089
1090     die if $url =~ m/[^[:graph:]]/;
1091     die if $tagval =~ m/[^[:graph:]]/;
1092
1093     open OL, ">>overall.log" or die $!;
1094     autoflush OL 1;
1095     my $quit = sub {
1096         printf OL "%04d-%02d-%02d %02d:%02d:%02d (%04ds): %s %s: %s\n",
1097             $t[5] + 1900, @t[4,3,2,1,0], (time-$start), $url, $tagval, $_[0];
1098         exit 0;
1099     };
1100
1101     $ENV{DGIT_DRS_ANY_URL} or $url =~ m{^https://}s
1102         or $quit->("url scheme not as expected");
1103
1104     $tagval =~ m{^$distro/($versiontag_re)$}s
1105         or $quit->("tag name not for us");
1106
1107     $version = $1;
1108     $version =~ y/_\%\#/:~/d;
1109
1110     my $work = 'work';
1111
1112     my $tagref = "refs/tags/$tagval";
1113
1114     rmtree $work;
1115     rmtree 'bpd';
1116     mkdir $work or die $!;
1117     mkdir 'bpd' or die $!;
1118     unlink <*.orig*>;
1119     dif $! if <*.orig*>;
1120     changedir $work;
1121     runcmd qw(git init -q);
1122     runcmd qw(git remote add origin), $url;
1123     runcmd qw(git fetch --depth=1 origin), "$tagref:$tagref";
1124     changedir ".git";
1125     mkdir 'dgit-tmp' or die $!;
1126
1127     my $tagger;
1128     open T, "-|", qw(git cat-file tag), $tagval or die $!;
1129     {
1130         local $/ = undef;
1131         $!=0; $_=<T>; defined or die $!;
1132
1133         # quick and dirty check, will check properly later
1134         m/^\[dgit[^"]* please-upload(?:\]| )/m or
1135             $quit->("tag missing please-upload request");
1136
1137         m/^tagger (.*) \d+ [-+]\d+$/m or
1138             $quit->("failed to fish tagger out of tag");
1139         $tagger = $1;
1140     };
1141
1142     readtag();
1143     m/^($package_re) release (\S+) for ($suite_re)$/ or
1144         $quit->("tag headline not for us");
1145     $package = $1;
1146     my $tagmversion = $2;
1147     $suite = $3;
1148
1149
1150     # This is for us.  From now on, we will capture errors to
1151     # be emailed to the tagger.
1152
1153     open H, ">>dgit-tmp/tagupl.email" or die $!;
1154     print H <<END or die $!;
1155 Subject: push-to-upload failed, $package $version ($distro)
1156 X-Debian-Push-Distro: $distro
1157 X-Debian-Push-Package: $package
1158 END
1159     printf H "To: %s", $tagger or die $!; # no newline
1160     flush H or die $!;
1161
1162     open L, ">>dgit-tmp/tagupl.log" or die $!;
1163
1164     my $child = fork() // die $!;
1165     if ($child) {
1166         # we are the parent
1167         # if child exits 0, it has called $quit->()
1168         $!=0; waitpid $child, 0 == $child or die $!;
1169         printdebug "child $child ?=$?\n";
1170         exit 0 unless $?;
1171         print L "execution child: ", waitstatusmsg(), "\n" or die $!;
1172         close L or die $!;
1173         print H <<END or die $!;
1174
1175
1176 Processing of tag $tagval
1177 From url $url
1178 Was not successful:
1179
1180 END
1181         $ENV{DGIT_DRS_SENDMAIL} //= '/usr/lib/sendmail';
1182
1183         close H or die $!;
1184         runcmd qw(sh -ec), <<"END";
1185             cd dgit-tmp
1186             cat tagupl.log >>tagupl.email
1187             $ENV{DGIT_DRS_SENDMAIL} -oee -odb -oi -t  \\
1188                 -f$ENV{DGIT_DRS_EMAIL_NOREPLY}        \\
1189                 <tagupl.email
1190 END
1191         $quit->("failed, emailed");
1192     }
1193
1194     open STDERR, ">&L" or die $!;
1195     open STDOUT, ">&STDERR" or die $!;
1196     open DEBUG, ">&STDERR" if $debuglevel;
1197
1198     reject "version mismatch $tagmversion != $version "
1199         unless $tagmversion eq $version;
1200
1201     my %need = map { $_ => 1 } qw(please-upload split);
1202     my ($upstreamc, $upstreamt);
1203     my $quilt;
1204     my $distro_ok;
1205
1206     confess if defined $upstreamt;
1207
1208     parsetag_general sub {
1209         if (m/^(\S+) / && exists $need{$1}) {
1210             $_ = $';
1211             delete $need{$1};
1212         } elsif (s/^upstream=(\w+) //) {
1213             $upstreamc = $1;
1214         } elsif (s/^upstream-tag=(\S+) //) {
1215             $upstreamt = $1;
1216         } elsif (s/^quilt=([-+0-9a-z]+) //) {
1217             $quilt = $1;
1218         } else {
1219             return 0;
1220         }
1221         return 1;
1222     }, sub {
1223         my ($gotdistro) = @_;
1224         $distro_ok ||= $gotdistro eq $distro;
1225     };
1226
1227     $quit->("not for this distro") unless $distro_ok;
1228
1229     reject "missing \"$_\"" foreach keys %need;
1230
1231     verifytag();
1232
1233     reject "upstream tag and not commitish, or v-v"
1234         unless defined $upstreamt == defined $upstreamc;
1235
1236     my @dgit;
1237     push @dgit, $ENV{DGIT_DRS_DGIT} // 'dgit';
1238     push @dgit, '-wn';
1239     push @dgit, "-p$package";
1240     push @dgit, '--build-products-dir=../bpd';
1241
1242     changedir "..";
1243     runcmd (@dgit, qw(setup-gitattributes));
1244
1245     my @fetch = qw(git fetch origin --unshallow);
1246     if (defined $upstreamt) {
1247         runcmd qw(git check-ref-format), "refs/tags/$upstreamt";
1248         my $utagref = "refs/tags/$upstreamt";
1249         push @fetch, "$utagref:$utagref";
1250     }
1251     runcmd @fetch;
1252
1253     runcmd qw(git checkout -q), "refs/tags/$tagval";
1254
1255     my $clogp = parsechangelog();
1256     my $clogf = sub {
1257         my ($f, $exp) = @_;
1258         my $got = getfield $clogp, $f;
1259         return if $got eq $exp;
1260         reject "mismatch: changelog $f $got != $exp";
1261     };
1262     $clogf->('Version', $version);
1263     $clogf->('Source',  $package);
1264
1265     @fetch = (@dgit, qw(fetch), $suite);
1266     debugcmd "+",@_;
1267     $!=0; $?=-1;
1268     if (system @fetch) {
1269         failedcmd @fetch unless $? == 4*256;
1270     }
1271     # this is just to get the orig, so we don't really care about the ref
1272     if (defined $upstreamc) {
1273         my $need_upstreamc = git_rev_parse "refs/tags/$upstreamt";
1274         $upstreamc eq $need_upstreamc or reject
1275             "upstream-commitish=$upstreamc but tag refers to $need_upstreamc";
1276         runcmd qw(git deborig), "$upstreamc";
1277     }
1278
1279     my @dgitcmd;
1280     push @dgitcmd, @dgit;
1281     push @dgitcmd, qw(--force-uploading-source-only);
1282     if (defined $quilt) {
1283         push @dgitcmd, "--quilt=$quilt";
1284         if ($quilt =~ m/baredebian/) {
1285             die "needed upstream commmitish with --quilt=baredebian";
1286             push @dgitcmd, "--upstream-commitish=$upstreamc";
1287         }
1288     }
1289     push @dgitcmd, qw(push-source --new --overwrite), $suite;
1290     # xxx what about the key to use?
1291     
1292     runcmd @dgitcmd;
1293
1294     $quit->('done');
1295 }
1296
1297 sub mode_ssh () {
1298     die if @ARGV;
1299
1300     my $cmd = $ENV{'SSH_ORIGINAL_COMMAND'};
1301     $cmd =~ m{
1302         ^
1303         (?: \S* / )?
1304         ( [-0-9a-z]+ )
1305         \s+
1306         '? (?: \S* / )?
1307         ($package_re) \.git
1308         '?$
1309     }ox 
1310     or reject "command string not understood";
1311     my $method = $1;
1312     $package = $2;
1313
1314     my $funcn = $method;
1315     $funcn =~ y/-/_/;
1316     my $mainfunc = $main::{"main__$funcn"};
1317
1318     reject "unknown method" unless $mainfunc;
1319
1320     policy_checkpackage();
1321
1322     if (stat_exists realdestrepo) {
1323         $destrepo = realdestrepo;
1324     } else {
1325         printdebug " fixmissing $funcn\n";
1326         my $fixfunc = $main::{"fixmissing__$funcn"};
1327         &$fixfunc;
1328     }
1329
1330     printdebug " running main $funcn\n";
1331     &$mainfunc;
1332 }
1333
1334 sub mode_cron () {
1335     die if @ARGV;
1336
1337     my $listfh = tempfile();
1338     open STDOUT, ">&", $listfh or die $!;
1339     policyhook(0,'check-list');
1340     open STDOUT, ">&STDERR" or die $!;
1341
1342     seek $listfh, 0, 0 or die $!;
1343     while (<$listfh>) {
1344         chomp or die;
1345         next if m/^\s*\#/;
1346         next unless m/\S/;
1347         die unless m/^($package_re)$/;
1348         
1349         $package = $1;
1350         policy_checkpackage();
1351     }
1352     die $! if $listfh->error;
1353 }    
1354
1355 sub parseargsdispatch () {
1356     die unless @ARGV;
1357
1358     delete $ENV{'GIT_DIR'}; # if not run via ssh, our parent git process
1359     delete $ENV{'GIT_PREFIX'}; # sets these and they mess things up
1360
1361     if ($ENV{'DGIT_DRS_DEBUG'}) {
1362         enabledebug();
1363     }
1364
1365     if ($ARGV[0] eq '--pre-receive-hook') {
1366         if ($debuglevel) {
1367             $debugprefix.="=";
1368             printdebug "in stunthook ".(shellquote @ARGV)."\n";
1369             foreach my $k (sort keys %ENV) {
1370                 printdebug "$k=$ENV{$k}\n" if $k =~  m/^DGIT/;
1371             }
1372         }
1373         shift @ARGV;
1374         @ARGV == 1 or die;
1375         $package = shift @ARGV;
1376         ${ $main::{$_} } = $ENV{"DGIT_DRS_\U$_"} foreach @hookenvs;
1377         defined($workrepo = $ENV{'DGIT_DRS_WORK'}) or die;
1378         defined($destrepo = $ENV{'DGIT_DRS_DEST'}) or die;
1379         open STDOUT, ">&STDERR" or die $!;
1380         eval {
1381             stunthook();
1382         };
1383         if ($@) {
1384             recorderror "$@" or die;
1385             die $@;
1386         }
1387         exit 0;
1388     }
1389
1390     $distro    = argval();
1391     $distrodir = argval();
1392     $keyrings  = argval();
1393
1394     foreach my $dk (keys %indistrodir) {
1395         ${ $indistrodir{$dk} } = "$distrodir/$dk";
1396     }
1397
1398     while (@ARGV && $ARGV[0] =~ m/^--([-0-9a-z]+)=/ && $indistrodir{$1}) {
1399         ${ $indistrodir{$1} } = $'; #';
1400         shift @ARGV;
1401     }
1402
1403     $ENV{"DGIT_DRS_\U$_"} = ${ $main::{$_} } foreach @hookenvs;
1404
1405     die unless @ARGV>=1;
1406
1407     my $mode = shift @ARGV;
1408     die unless $mode =~ m/^--(\w+)$/;
1409     my $fn = ${*::}{"mode_$1"};
1410     die unless $fn;
1411     $fn->();
1412 }
1413
1414 sub unlockall () {
1415     while (my $fh = pop @lockfhs) { close $fh; }
1416 }
1417
1418 sub cleanup () {
1419     unlockall();
1420     if (!chdir "$dgitrepos/_tmp") {
1421         $!==ENOENT or die $!;
1422         return;
1423     }
1424     foreach my $lf (<*.lock>) {
1425         my $tree = $lf;
1426         $tree =~ s/\.lock$//;
1427         next unless acquirermtree($tree, 0);
1428         remove $lf or warn $!;
1429         unlockall();
1430     }
1431 }
1432
1433 parseargsdispatch();
1434 cleanup();