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