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