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