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