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