chiark / gitweb /
Merge branch 'stable'
[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 mkscript ($$) {
411     my ($path,$contents) = @_;
412     my $fh = new IO::File $path, O_WRONLY|O_CREAT|O_TRUNC, 0777
413         or die "$path: $!";
414     print $fh $contents or die "$path: $!";
415     close $fh or die "$path: $!";
416 }
417
418 sub setupstunthook () {
419     my $prerecv = "$workrepo/hooks/pre-receive";
420     mkscript $prerecv, <<END;
421 #!/bin/sh
422 set -e
423 exec $0 --pre-receive-hook $package
424 END
425     $ENV{'DGIT_DRS_WORK'}= $workrepo;
426     $ENV{'DGIT_DRS_DEST'}= $destrepo;
427     printdebug " stunt hook set up $prerecv\n";
428 }
429
430 sub dealwithfreshrepo () {
431     my $freshrepo = "${workrepo}_fresh";
432     return unless stat_exists $freshrepo;
433     $destrepo = $freshrepo;
434 }
435
436 sub mirrorhook {
437     my @cmd = ($mirrorhook,$distrodir,@_);
438     debugcmd '+',@cmd;
439     return unless stat_exists $mirrorhook;
440     my $r = system @cmd;
441     if ($r) {
442         printf STDERR <<END,
443 dgit-repos-server: warning: mirror hook failed: %s
444 dgit-repos-server: push complete but may not fully visible.
445 END
446             ($r < 0 ? "exec: $!" :
447              $r == (124 << 8) ? "exited status 124 (timeout?)" :
448              !($r & ~0xff00) ? "exited ".($? >> 8) :
449              "wait status $?");
450     }
451 }
452
453 sub maybeinstallprospective () {
454     return if $destrepo eq realdestrepo;
455
456     if (open REJ, "<", "$workrepo/drs-error") {
457         local $/ = undef;
458         my $msg = <REJ>;
459         REJ->error and die $!;
460         print STDERR $msg;
461         exit 1;
462     } else {
463         $!==&ENOENT or die $!;
464     }
465
466     printdebug " show-ref ($destrepo) ...\n";
467
468     my $child = open SR, "-|";
469     defined $child or die $!;
470     if (!$child) {
471         chdir $destrepo or die $!;
472         exec qw(git show-ref);
473         die $!;
474     }
475     my %got = qw(newtag 0 omtag 0 head 0);
476     while (<SR>) {
477         chomp or die;
478         printdebug " show-refs| $_\n";
479         s/^\S*[1-9a-f]\S* (\S+)$/$1/ or die;
480         next if m{^refs/heads/master$};
481         my $wh =
482             m{^refs/tags/archive/} ? 'newtag' :
483             m{^refs/tags/} ? 'omtag' :
484             m{^refs/dgit/} ? 'head' :
485             die;
486         use Data::Dumper;
487         die if $got{$wh}++;
488     }
489     $!=0; $?=0; close SR or $?==256 or die "$? $!";
490
491     printdebug "installprospective ?\n";
492     die Dumper(\%got)." -- missing refs in new repo"
493         unless $got{head} && grep { m/tag$/ && $got{$_} } keys %got;
494
495     lockrealtree();
496
497     if ($destrepo eq "${workrepo}_fresh") {
498         movetogarbage;
499     }
500
501     printdebug "install $destrepo => ".realdestrepo."\n";
502     rename $destrepo, realdestrepo or die $!;
503     remove realdestrepo.".lock" or die $!;
504 }
505
506 sub main__git_receive_pack () {
507     makeworkingclone();
508     setupstunthook();
509     runcmd qw(git receive-pack), $workrepo;
510     dealwithfreshrepo();
511     maybeinstallprospective();
512     mirrorhook('updated-hook', $package);
513 }
514
515 #----- stunt post-receive hook -----
516
517 our ($tagname, $tagval, $suite, $oldcommit, $commit);
518 our ($version, %tagh);
519 our ($maint_tagname, $maint_tagval);
520
521 our ($tagexists_error);
522
523 sub readupdates () {
524     printdebug " updates ...\n";
525     my %tags;
526     while (<STDIN>) {
527         chomp or die;
528         printdebug " upd.| $_\n";
529         m/^(\S+) (\S+) (\S+)$/ or die "$_ ?";
530         my ($old, $sha1, $refname) = ($1, $2, $3);
531         if ($refname =~ m{^refs/tags/(?=(?:archive/)?$distro/)}) {
532             my $tn = $'; #';
533             $tags{$tn} = $sha1;
534             $tagexists_error= "tag $tn already exists -".
535                 " not replacing previously-pushed version"
536                 if $old =~ m/[^0]/;
537         } elsif ($refname =~ m{^refs/dgit/}) {
538             reject "pushing multiple heads!" if defined $suite;
539             $suite = $'; #';
540             $oldcommit = $old;
541             $commit = $sha1;
542         } else {
543             reject "pushing unexpected ref!";
544         }
545     }
546     STDIN->error and die $!;
547
548     reject "push is missing tag ref update" unless %tags;
549     my @newtags = grep { m#^archive/# } keys %tags;
550     my @omtags = grep { !m#^archive/# } keys %tags;
551     reject "pushing too many similar tags" if @newtags>1 || @omtags>1;
552     if (@newtags) {
553         ($tagname) = @newtags;
554         ($maint_tagname) = @omtags;
555     } else {
556         ($tagname) = @omtags or die;
557     }
558     $tagval = $tags{$tagname};
559     $maint_tagval = $tags{$maint_tagname // ''};
560
561     reject "push is missing head ref update" unless defined $suite;
562     printdebug " updates ok.\n";
563 }
564
565 sub parsetag () {
566     printdebug " parsetag...\n";
567     open PT, ">dgit-tmp/plaintext" or die $!;
568     open DS, ">dgit-tmp/plaintext.asc" or die $!;
569     open T, "-|", qw(git cat-file tag), $tagval or die $!;
570     for (;;) {
571         $!=0; $_=<T>; defined or die $!;
572         print PT or die $!;
573         if (m/^(\S+) (.*)/) {
574             push @{ $tagh{$1} }, $2;
575         } elsif (!m/\S/) {
576             last;
577         } else {
578             die;
579         }
580     }
581     $!=0; $_=<T>; defined or die $!;
582     m/^($package_re) release (\S+) for \S+ \((\S+)\) \[dgit\]$/ or
583         reject "tag message not in expected format";
584
585     die unless $1 eq $package;
586     $version = $2;
587     die "$3 != $suite " unless $3 eq $suite;
588
589     my $copyl = $_;
590     for (;;) {
591         print PT $copyl or die $!;
592         $!=0; $_=<T>; defined or die "missing signature? $!";
593         $copyl = $_;
594         if (m/^\[dgit ([^"].*)\]$/) { # [dgit "something"] is for future
595             $_ = $1." ";
596             while (length) {
597                 if (s/^distro\=(\S+) //) {
598                     die "$1 != $distro" unless $1 eq $distro;
599                 } elsif (s/^(--deliberately-$deliberately_re) //) {
600                     push @deliberatelies, $1;
601                 } elsif (s/^previously:(\S+)=(\w+) //) {
602                     die "previously $1 twice" if defined $previously{$1};
603                     $previously{$1} = $2;
604                 } elsif (s/^[-+.=0-9a-z]\S* //) {
605                 } else {
606                     die "unknown dgit info in tag ($_)";
607                 }
608             }
609             next;
610         }
611         last if m/^-----BEGIN PGP/;
612     }
613     $_ = $copyl;
614     for (;;) {
615         print DS or die $!;
616         $!=0; $_=<T>;
617         last if !defined;
618     }
619     T->error and die $!;
620     close PT or die $!;
621     close DS or die $!;
622     printdebug " parsetag ok.\n";
623 }
624
625 sub checksig_keyring ($) {
626     my ($keyringfile) = @_;
627     # returns primary-keyid if signed by a key in this keyring
628     # or undef if not
629     # or dies on other errors
630
631     my $ok = undef;
632
633     printdebug " checksig keyring $keyringfile...\n";
634
635     our @cmd = (qw(gpgv --status-fd=1 --keyring),
636                    $keyringfile,
637                    qw(dgit-tmp/plaintext.asc dgit-tmp/plaintext));
638     debugcmd '|',@cmd;
639
640     open P, "-|", @cmd
641         or die $!;
642
643     while (<P>) {
644         next unless s/^\[GNUPG:\] //;
645         chomp or die;
646         printdebug " checksig| $_\n";
647         my @l = split / /, $_;
648         if ($l[0] eq 'NO_PUBKEY') {
649             last;
650         } elsif ($l[0] eq 'VALIDSIG') {
651             my $sigtype = $l[9];
652             $sigtype eq '00' or reject "signature is not of type 00!";
653             $ok = $l[10];
654             die unless defined $ok;
655             last;
656         }
657     }
658     close P;
659
660     printdebug sprintf " checksig ok=%d\n", !!$ok;
661
662     return $ok;
663 }
664
665 sub dm_txt_check ($$) {
666     my ($keyid, $dmtxtfn) = @_;
667     printdebug " dm_txt_check $keyid $dmtxtfn\n";
668     open DT, '<', $dmtxtfn or die "$dmtxtfn $!";
669     while (<DT>) {
670         m/^fingerprint:\s+\Q$keyid\E$/oi
671             ..0 or next;
672         if (s/^allow:/ /i..0) {
673         } else {
674             m/^./
675                 or reject "key $keyid missing Allow section in permissions!";
676             next;
677         }
678         # in right stanza...
679         s/^[ \t]+//
680             or reject "package $package not allowed for key $keyid";
681         # in allow field...
682         s/\([^()]+\)//;
683         s/\,//;
684         chomp or die;
685         printdebug " dm_txt_check allow| $_\n";
686         foreach my $p (split /\s+/) {
687             if ($p eq $package) {
688                 # yay!
689                 printdebug " dm_txt_check ok\n";
690                 return;
691             }
692         }
693     }
694     DT->error and die $!;
695     close DT or die $!;
696     reject "key $keyid not in permissions list although in keyring!";
697 }
698
699 sub verifytag () {
700     foreach my $kas (split /:/, $keyrings) {
701         printdebug "verifytag $kas...\n";
702         $kas =~ s/^([^,]+),// or die;
703         my $keyid = checksig_keyring $1;
704         if (defined $keyid) {
705             if ($kas =~ m/^a$/) {
706                 printdebug "verifytag a ok\n";
707                 return; # yay
708             } elsif ($kas =~ m/^m([^,]+)$/) {
709                 dm_txt_check($keyid, $1);
710                 printdebug "verifytag m ok\n";
711                 return;
712             } else {
713                 die;
714             }
715         }   
716     }
717     reject "key not found in keyrings";
718 }
719
720 sub suite_is_in ($) {
721     my ($sf) = @_;
722     printdebug "suite_is_in ($sf)\n";
723     if (!open SUITES, "<", $sf) {
724         $!==ENOENT or die $!;
725         return 0;
726     }
727     while (<SUITES>) {
728         chomp;
729         next unless m/\S/;
730         next if m/^\#/;
731         s/\s+$//;
732         return 1 if $_ eq $suite;
733     }
734     die $! if SUITES->error;
735     return 0;
736 }
737
738 sub checksuite () {
739     printdebug "checksuite ($suitesfile)\n";
740     return if suite_is_in $suitesfile;
741     reject "unknown suite";
742 }
743
744 sub checktagnoreplay () {
745     # We need to prevent a replay attack using an earlier signed tag.
746     # We also want to archive in the history the object ids of
747     # anything we remove, even if we get rid of the actual objects.
748     #
749     # So, we check that the signed tag mentions the name and tag
750     # object id of:
751     #
752     # (a) In the case of FRESHREPO: all tags and refs/heads/* in
753     #     the repo.  That is, effectively, all the things we are
754     #     deleting.
755     #
756     #     This prevents any tag implying a FRESHREPO push
757     #     being replayed into a different state of the repo.
758     #
759     #     There is still the folowing risk: If a non-ff push is of a
760     #     head which is an ancestor of a previous ff-only push, the
761     #     previous push can be replayed.
762     #
763     #     So we keep a separate list, as a file in the repo, of all
764     #     the tag object ids we have ever seen and removed.  Any such
765     #     tag object id will be rejected even for ff-only pushes.
766     #
767     # (b) In the case of just NOFFCHECK: all tags referring to the
768     #     current head for the suite (there must be at least one).
769     #
770     #     This prevents any tag implying a NOFFCHECK push being
771     #     replayed to rewind from a different head.
772     #
773     #     The possibility of an earlier ff-only push being replayed is
774     #     eliminated as follows: the tag from such a push would still
775     #     be in our repo, and therefore the replayed push would be
776     #     rejected because the set of refs being updated would be
777     #     wrong.
778
779     if (!open PREVIOUS, "<", removedtagsfile) {
780         die removedtagsfile." $!" unless $!==ENOENT;
781     } else {
782         # Protocol for updating this file is to append to it, not
783         # write-new-and-rename.  So all updates are prefixed with \n
784         # and suffixed with " .\n" so that partial writes can be
785         # ignored.
786         while (<PREVIOUS>) {
787             next unless m/^(\w+) (.*) \.\n/;
788             next unless $1 eq $tagval;
789             reject "Replay of previously-rewound upload ($tagval $2)";
790         }
791         die removedtagsfile." $!" if PREVIOUS->error;
792         close PREVIOUS;
793     }
794
795     return unless $policy & (FRESHREPO|NOFFCHECK);
796
797     my $garbagerepo = "$dgitrepos/${package}_garbage";
798     lockrealtree();
799
800     my $nchecked = 0;
801     my @problems;
802
803     my $check_ref_previously= sub {
804         my ($objid,$objtype,$fullrefname,$reftail) = @_;
805         my $supkey = $fullrefname;
806         $supkey =~ s{^refs/}{} or die "$supkey $objid ?";
807         my $supobjid = $previously{$supkey};
808         if (!defined $supobjid) {
809             printdebug "checktagnoreply - missing\n";
810             push @problems, "does not declare previously $supkey";
811         } elsif ($supobjid ne $objid) {
812             push @problems, "declared previously $supkey=$supobjid".
813                 " but actually previously $supkey=$objid";
814         } else {
815             $nchecked++;
816         }
817     };
818
819     if ($policy & FRESHREPO) {
820         foreach my $kind (qw(tags heads)) {
821             git_for_each_ref("refs/$kind", $check_ref_previously);
822         }
823     } else {
824         my $branch= server_branch($suite);
825         my $branchhead= git_get_ref(server_ref($suite));
826         if (!length $branchhead) {
827             # No such branch - NOFFCHECK was unnecessary.  Oh well.
828             printdebug "checktagnoreplay - not FRESHREPO, new branch, ok\n";
829         } else {
830             printdebug "checktagnoreplay - not FRESHREPO,".
831                 " checking for overwriting refs/$branch=$branchhead\n";
832             git_for_each_tag_referring($branchhead, sub {
833                 my ($tagobjid,$refobjid,$fullrefname,$tagname) = @_;
834                 $check_ref_previously->($tagobjid,undef,$fullrefname,undef);
835             });
836             printdebug "checktagnoreplay - not FRESHREPO, nchecked=$nchecked";
837             push @problems, "does not declare previously any tag".
838                 " referring to branch head $branch=$branchhead"
839                 unless $nchecked;
840         }
841     }
842
843     if (@problems) {
844         reject "replay attack prevention check failed:".
845             " signed tag for $version: ".
846             join("; ", @problems).
847             "\n";
848     }
849     printdebug "checktagnoreplay - all ok ($tagval)\n"
850 }
851
852 sub tagh1 ($) {
853     my ($tag) = @_;
854     my $vals = $tagh{$tag};
855     reject "missing header $tag in signed tag object" unless $vals;
856     reject "multiple headers $tag in signed tag object" unless @$vals == 1;
857     return $vals->[0];
858 }
859
860 sub checks () {
861     printdebug "checks\n";
862
863     tagh1('type') eq 'commit' or reject "tag refers to wrong kind of object";
864     tagh1('object') eq $commit or reject "tag refers to wrong commit";
865     tagh1('tag') eq $tagname or reject "tag name in tag is wrong";
866
867     my @expecttagnames = debiantags($version, $distro);
868     printdebug "expected tag @expecttagnames\n";
869     grep { $tagname eq $_ } @expecttagnames or die;
870
871     foreach my $othertag (grep { $_ ne $tagname } @expecttagnames) {
872         reject "tag $othertag (pushed with differing dgit version)".
873             " already exists -".
874             " not replacing previously-pushed version"
875             if git_get_ref "refs/tags/".$othertag;
876     }
877
878     lockrealtree();
879
880     @policy_args = ($package,$version,$suite,$tagname,
881                     join(",",@deliberatelies));
882     $policy = policyhook(NOFFCHECK|FRESHREPO|NOCOMMITCHECK, 'push', @policy_args);
883
884     if (defined $tagexists_error) {
885         if ($policy & FRESHREPO) {
886             printdebug "ignoring tagexists_error: $tagexists_error\n";
887         } else {
888             reject $tagexists_error;
889         }
890     }
891
892     checktagnoreplay();
893     checksuite();
894
895     # check that our ref is being fast-forwarded
896     printdebug "oldcommit $oldcommit\n";
897     if (!($policy & NOFFCHECK) && $oldcommit =~ m/[^0]/) {
898         $?=0; $!=0; my $mb = `git merge-base $commit $oldcommit`;
899         chomp $mb;
900         $mb eq $oldcommit or reject "not fast forward on dgit branch";
901     }
902
903     # defend against commits generated by #849041
904     if (!($policy & NOCOMMITCHECK)) {
905         my @checks = qw(%ae %at
906                         %ce %ct);
907         my @chk = qw(git log -z);
908         push @chk, '--pretty=tformat:%H%n'.
909             (join "", map { $_, '%n' } @checks);
910         push @chk, "^$oldcommit" if $oldcommit =~ m/[^0]/;
911         push @chk, $commit;;
912         printdebug " ~NOCOMMITCHECK @chk\n";
913         open CHK, "-|", @chk or die $!;
914         local $/ = "\0";
915         while (<CHK>) {
916             next unless m/^$/m;
917             m/^\w+(?=\n)/ or die;
918             reject "corrupted object $& (missing metadata)";
919         }
920         $!=0; $?=0; close CHK or $?==256 or die "$? $!";
921     }
922
923     if ($policy & FRESHREPO) {
924         # It's a bit late to be discovering this here, isn't it ?
925         #
926         # What we do is: Generate a fresh destination repo right now,
927         # and arrange to treat it from now on as if it were a
928         # prospective repo.
929         #
930         # The presence of this fresh destination repo is detected by
931         # the parent, which responds by making a fresh master repo
932         # from the template.  (If the repo didn't already exist then
933         # $destrepo was _prospective, and we change it here.  This is
934         # OK because the parent's check for _fresh persuades it not to
935         # use _prospective.)
936         #
937         $destrepo = "${workrepo}_fresh"; # workrepo lock covers
938         mkrepo_fromtemplate $destrepo;
939     }
940 }
941
942 sub onwardpush () {
943     my @cmdbase = (qw(git send-pack), $destrepo);
944     push @cmdbase, qw(--force) if $policy & NOFFCHECK;
945
946     if ($ENV{GIT_QUARANTINE_PATH}) {
947         my $recv_wrapper = "$ENV{GIT_QUARANTINE_PATH}/dgit-recv-wrapper";
948         mkscript $recv_wrapper, <<'END';
949 #!/bin/sh
950 set -e
951 unset GIT_QUARANTINE_PATH
952 exec git receive-pack "$@"
953 END
954         push @cmdbase, "--receive-pack=$recv_wrapper";
955     }
956
957     my @cmd = @cmdbase;
958     push @cmd, "$commit:refs/dgit/$suite",
959                "$tagval:refs/tags/$tagname";
960     push @cmd, "$maint_tagval:refs/tags/$maint_tagname"
961         if defined $maint_tagname;
962     debugcmd '+',@cmd;
963     $!=0;
964     my $r = system @cmd;
965     !$r or die "onward push to $destrepo failed: $r $!";
966
967     if (suite_is_in $suitesformasterfile) {
968         @cmd = @cmdbase;
969         push @cmd, "$commit:refs/heads/master";
970         debugcmd '+', @cmd;
971         $!=0; my $r = system @cmd;
972         # tolerate errors (might be not ff)
973         !($r & ~0xff00) or die
974             "onward push to $destrepo#master failed: $r $!";
975     }
976 }
977
978 sub finalisepush () {
979     if ($destrepo eq realdestrepo) {
980         policyhook(0, 'push-confirm', @policy_args, '');
981         onwardpush();
982     } else {
983         # We are to receive the push into a new repo (perhaps
984         # because the policy push hook asked us to with FRESHREPO, or
985         # perhaps because the repo didn't exist before).
986         #
987         # We want to provide the policy push-confirm hook with a repo
988         # which looks like the one which is going to be installed.
989         # The working repo is no good because it might contain
990         # previous history.
991         #
992         # So we push the objects into the prospective new repo right
993         # away.  If the hook declines, we decline, and the prospective
994         # repo is never installed.
995         onwardpush();
996         policyhook(0, 'push-confirm', @policy_args, $destrepo);
997     }
998 }
999
1000 sub stunthook () {
1001     printdebug "stunthook in $workrepo\n";
1002     chdir $workrepo or die "chdir $workrepo: $!";
1003     mkdir "dgit-tmp" or $!==EEXIST or die $!;
1004     readupdates();
1005     parsetag();
1006     verifytag();
1007     checks();
1008     finalisepush();
1009     printdebug "stunthook done.\n";
1010 }
1011
1012 #----- git-upload-pack -----
1013
1014 sub fixmissing__git_upload_pack () {
1015     $destrepo = "$dgitrepos/_empty";
1016     my $lfh = locksometree($destrepo);
1017     return if stat_exists $destrepo;
1018     rmtree "$destrepo.new";
1019     mkemptyrepo "$destrepo.new", "0644";
1020     rename "$destrepo.new", $destrepo or die $!;
1021     unlink "$destrepo.lock" or die $!;
1022     close $lfh;
1023 }
1024
1025 sub main__git_upload_pack () {
1026     my $lfh = locksometree($destrepo);
1027     printdebug "git-upload-pack in $destrepo\n";
1028     chdir $destrepo or die "$destrepo: $!";
1029     close $lfh;
1030     runcmd qw(git upload-pack), ".";
1031 }
1032
1033 #----- arg parsing and main program -----
1034
1035 sub argval () {
1036     die unless @ARGV;
1037     my $v = shift @ARGV;
1038     die if $v =~ m/^-/;
1039     return $v;
1040 }
1041
1042 our %indistrodir = (
1043     # keys are used for DGIT_DRS_XXX too
1044     'repos' => \$dgitrepos,
1045     'suites' => \$suitesfile,
1046     'suites-master' => \$suitesformasterfile,
1047     'policy-hook' => \$policyhook,
1048     'mirror-hook' => \$mirrorhook,
1049     'dgit-live' => \$dgitlive,
1050     );
1051
1052 our @hookenvs = qw(distro suitesfile suitesformasterfile policyhook
1053                    mirrorhook dgitlive keyrings dgitrepos distrodir);
1054
1055 # workrepo and destrepo handled ad-hoc
1056
1057 sub mode_ssh () {
1058     die if @ARGV;
1059
1060     my $cmd = $ENV{'SSH_ORIGINAL_COMMAND'};
1061     $cmd =~ m{
1062         ^
1063         (?: \S* / )?
1064         ( [-0-9a-z]+ )
1065         \s+
1066         '? (?: \S* / )?
1067         ($package_re) \.git
1068         '?$
1069     }ox 
1070     or reject "command string not understood";
1071     my $method = $1;
1072     $package = $2;
1073
1074     my $funcn = $method;
1075     $funcn =~ y/-/_/;
1076     my $mainfunc = $main::{"main__$funcn"};
1077
1078     reject "unknown method" unless $mainfunc;
1079
1080     policy_checkpackage();
1081
1082     if (stat_exists realdestrepo) {
1083         $destrepo = realdestrepo;
1084     } else {
1085         printdebug " fixmissing $funcn\n";
1086         my $fixfunc = $main::{"fixmissing__$funcn"};
1087         &$fixfunc;
1088     }
1089
1090     printdebug " running main $funcn\n";
1091     &$mainfunc;
1092 }
1093
1094 sub mode_cron () {
1095     die if @ARGV;
1096
1097     my $listfh = tempfile();
1098     open STDOUT, ">&", $listfh or die $!;
1099     policyhook(0,'check-list');
1100     open STDOUT, ">&STDERR" or die $!;
1101
1102     seek $listfh, 0, 0 or die $!;
1103     while (<$listfh>) {
1104         chomp or die;
1105         next if m/^\s*\#/;
1106         next unless m/\S/;
1107         die unless m/^($package_re)$/;
1108         
1109         $package = $1;
1110         policy_checkpackage();
1111     }
1112     die $! if $listfh->error;
1113 }    
1114
1115 sub parseargsdispatch () {
1116     die unless @ARGV;
1117
1118     delete $ENV{'GIT_DIR'}; # if not run via ssh, our parent git process
1119     delete $ENV{'GIT_PREFIX'}; # sets these and they mess things up
1120
1121     if ($ENV{'DGIT_DRS_DEBUG'}) {
1122         enabledebug();
1123     }
1124
1125     if ($ARGV[0] eq '--pre-receive-hook') {
1126         if ($debuglevel) {
1127             $debugprefix.="=";
1128             printdebug "in stunthook ".(shellquote @ARGV)."\n";
1129             foreach my $k (sort keys %ENV) {
1130                 printdebug "$k=$ENV{$k}\n" if $k =~  m/^DGIT/;
1131             }
1132         }
1133         shift @ARGV;
1134         @ARGV == 1 or die;
1135         $package = shift @ARGV;
1136         ${ $main::{$_} } = $ENV{"DGIT_DRS_\U$_"} foreach @hookenvs;
1137         defined($workrepo = $ENV{'DGIT_DRS_WORK'}) or die;
1138         defined($destrepo = $ENV{'DGIT_DRS_DEST'}) or die;
1139         open STDOUT, ">&STDERR" or die $!;
1140         eval {
1141             stunthook();
1142         };
1143         if ($@) {
1144             recorderror "$@" or die;
1145             die $@;
1146         }
1147         exit 0;
1148     }
1149
1150     $distro    = argval();
1151     $distrodir = argval();
1152     $keyrings  = argval();
1153
1154     foreach my $dk (keys %indistrodir) {
1155         ${ $indistrodir{$dk} } = "$distrodir/$dk";
1156     }
1157
1158     while (@ARGV && $ARGV[0] =~ m/^--([-0-9a-z]+)=/ && $indistrodir{$1}) {
1159         ${ $indistrodir{$1} } = $'; #';
1160         shift @ARGV;
1161     }
1162
1163     $ENV{"DGIT_DRS_\U$_"} = ${ $main::{$_} } foreach @hookenvs;
1164
1165     die unless @ARGV==1;
1166
1167     my $mode = shift @ARGV;
1168     die unless $mode =~ m/^--(\w+)$/;
1169     my $fn = ${*::}{"mode_$1"};
1170     die unless $fn;
1171     $fn->();
1172 }
1173
1174 sub unlockall () {
1175     while (my $fh = pop @lockfhs) { close $fh; }
1176 }
1177
1178 sub cleanup () {
1179     unlockall();
1180     if (!chdir "$dgitrepos/_tmp") {
1181         $!==ENOENT or die $!;
1182         return;
1183     }
1184     foreach my $lf (<*.lock>) {
1185         my $tree = $lf;
1186         $tree =~ s/\.lock$//;
1187         next unless acquirermtree($tree, 0);
1188         remove $lf or warn $!;
1189         unlockall();
1190     }
1191 }
1192
1193 parseargsdispatch();
1194 cleanup();