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