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