chiark / gitweb /
dgit-repos-server: Move onwardpush and break up its @cmd construction
[dgit.git] / infra / dgit-repos-server
1 #!/usr/bin/perl -w
2 # dgit-repos-server
3 #
4 # usages:
5 #  .../dgit-repos-server DISTRO SUITES KEYRING-AUTH-SPEC \
6 #      DGIT-REPOS-DIR POLICY-HOOK-SCRIPT --ssh
7 # internal usage:
8 #  .../dgit-repos-server --pre-receive-hook PACKAGE
9 #
10 # Invoked as the ssh restricted command
11 #
12 # Works like git-receive-pack
13 #
14 # SUITES is the name of a file which lists the permissible suites
15 # one per line (#-comments and blank lines ignored)
16 #
17 # KEYRING-AUTH-SPEC is a :-separated list of
18 #   KEYRING.GPG,AUTH-SPEC
19 # where AUTH-SPEC is one of
20 #   a
21 #   mDM.TXT
22
23 use strict;
24
25 # What we do is this:
26 #  - extract the destination repo name
27 #  - make a hardlink clone of the destination repo
28 #  - provide the destination with a stunt pre-receive hook
29 #  - run actual git-receive-pack with that new destination
30 #   as a result of this the stunt pre-receive hook runs; it does this:
31 #    + understand what refs we are allegedly updating and
32 #      check some correspondences:
33 #        * we are updating only refs/tags/debian/* and refs/dgit/*
34 #        * and only one of each
35 #        * and the tag does not already exist
36 #      and
37 #        * recover the suite name from the destination refs/dgit/ ref
38 #    + disassemble the signed tag into its various fields and signature
39 #      including:
40 #        * parsing the first line of the tag message to recover
41 #          the package name, version and suite
42 #        * checking that the package name corresponds to the dest repo name
43 #        * checking that the suite name is as recovered above
44 #    + verify the signature on the signed tag
45 #      and if necessary check that the keyid and package are listed in dm.txt
46 #    + check various correspondences:
47 #        * the suite is one of those permitted
48 #        * the signed tag must refer to a commit
49 #        * the signed tag commit must be the refs/dgit value
50 #        * the name in the signed tag must correspond to its ref name
51 #        * the tag name must be debian/<version> (massaged as needed)
52 #        * the signed tag has a suitable name
53 #        * the commit is a fast forward
54 #    + push the signed tag and new dgit branch to the actual repo
55 #
56 # If the destination repo does not already exist, we need to make
57 # sure that we create it reasonably atomically, and also that
58 # we don't every have a destination repo containing no refs at all
59 # (because such a thing causes git-fetch-pack to barf).  So then we
60 # do as above, except:
61 #  - before starting, we take out our own lock for the destination repo
62 #  - we create a prospective new destination repo by making a copy
63 #    of _template
64 #  - we use the prospective new destination repo instead of the
65 #    actual new destination repo (since the latter doesn't exist)
66 #  - we set up a post-receive hook as well, which
67 #    + touches a stamp file
68 #  - after git-receive-pack exits, we
69 #    + check that the prospective repo contains a tag and head
70 #    + rename the prospective destination repo into place
71 #
72 # Cleanup strategy:
73 #  - We are crash-only
74 #  - Temporary working trees and their locks are cleaned up
75 #    opportunistically by a program which tries to take each lock and
76 #    if successful deletes both the tree and the lockfile
77 #  - Prospective working trees and their locks are cleaned up by
78 #    a program which tries to take each lock and if successful
79 #    deletes any prospective working tree and the lock (but not
80 #    of course any actual tree)
81 #  - It is forbidden to _remove_ the lockfile without removing
82 #    the corresponding temporary tree, as the lockfile is also
83 #    a stampfile whose presence indicates that there may be
84 #    cleanup to do
85
86 use POSIX;
87 use Fcntl qw(:flock);
88 use File::Path qw(rmtree);
89
90 use Debian::Dgit qw(:DEFAULT :policyflags);
91
92 open DEBUG, ">/dev/null" or die $!;
93
94 our $func;
95 our $dgitrepos;
96 our $package;
97 our $suitesfile;
98 our $policyhook;
99 our $realdestrepo;
100 our $destrepo;
101 our $workrepo;
102 our $keyrings;
103 our @lockfhs;
104 our $debug='';
105 our @deliberatelies;
106 our $policy;
107
108 #----- utilities -----
109
110 sub debug {
111     print DEBUG "$debug @_\n";
112 }
113
114 sub acquirelock ($$) {
115     my ($lock, $must) = @_;
116     my $fh;
117     printf DEBUG "$debug locking %s %d\n", $lock, $must;
118     for (;;) {
119         close $fh if $fh;
120         $fh = new IO::File $lock, ">" or die "open $lock: $!";
121         my $ok = flock $fh, $must ? LOCK_EX : (LOCK_EX|LOCK_NB);
122         if (!$ok) {
123             die "flock $lock: $!" if $must;
124             debug " locking $lock failed";
125             return undef;
126         }
127         if (!stat $lock) {
128             next if $! == ENOENT;
129             die "stat $lock: $!";
130         }
131         my $want = (stat _)[1];
132         stat $fh or die $!;
133         my $got = (stat _)[1];
134         last if $got == $want;
135     }
136     return $fh;
137 }
138
139 sub acquiretree ($$) {
140     my ($tree, $must) = @_;
141     my $fh = acquirelock("$tree.lock", $must);
142     if ($fh) {
143         push @lockfhs, $fh;
144         rmtree $tree;
145     }
146     return $fh;
147 }
148
149 sub mkrepotmp () {
150     my $tmpdir = "$dgitrepos/_tmp";
151     return if mkdir $tmpdir;
152     return if $! == EEXIST;
153     die $!;
154 }
155
156 sub recorderror ($) {
157     my ($why) = @_;
158     my $w = $ENV{'DGIT_DRS_WORK'}; # we are in stunthook
159     if (defined $w) {
160         chomp $why;
161         open ERR, ">", "$w/drs-error" or die $!;
162         print ERR $why, "\n" or die $!;
163         close ERR or die $!;
164         return 1;
165     }
166     return 0;
167 }
168
169 sub reject ($) {
170     my ($why) = @_;
171     recorderror "reject: $why";
172     die "dgit-repos-server: reject: $why\n";
173 }
174
175 sub debugcmd {
176     if ($debug) {
177         use Data::Dumper;
178         local $Data::Dumper::Indent = 0;
179         local $Data::Dumper::Terse = 1;
180         debug "|".Dumper(\@_);
181     }
182 }
183
184 sub runcmd {
185     debugcmd @_;
186     $!=0; $?=0;
187     my $r = system @_;
188     die "@_ $? $!" if $r;
189 }
190
191 sub policyhook {
192     my ($policyallowbits, @polargs) = @_;
193     # => ($exitstatuspolicybitmap, $policylockfh);
194     die if $policyallowbits & ~0x3e;
195     my @cmd = ($policyhook,$distro,$repos,@polargs);
196     debugcmd @_;
197     my $r = system @_;
198     die "system: $!" if $r < 0;
199     die "hook (@cmd) failed ($?)" if $r & ~($policyallowbits << 8);
200     return $r >> 8;
201 }
202
203 sub mkemptyrepo ($$) {
204     my ($dir,$sharedperm) = @_;
205     runcmd qw(git init --bare --quiet), "--shared=$sharedperm", $dir;
206 }
207
208 sub mkrepo_fromtemplate ($) {
209     my ($dir) = @_;
210     my $template = "$dgitrepos/_template";
211     debug "copy tempalate $template -> $dir";
212     my $r = system qw(cp -a --), $template, $dir;
213     !$r or die "create new repo $dir failed: $r $!";
214 }
215
216 sub movetogarbage () {
217     my $garbagerepo = "$dgitrepos/_tmp/${package}_garbage";
218     acquiretree($garbagerepo,1);
219     rmtree $garbagerepo;
220     rename $realdestrepo, $garbagerepo
221         or $! == ENOENT
222         or die "rename repo $realdestrepo to $garbagerepo: $!";
223 }
224
225 sub onwardpush () {
226     my @cmd = (qw(git send-pack), $destrepo);
227     push @cmd, qw(--force) if $policy & NOFFCHECK;
228     push @cmd, "$commit:refs/dgit/$suite",
229                "$tagval:refs/tags/$tagname");
230     debugcmd @cmd;
231     $!=0;
232     my $r = system @cmd;
233     !$r or die "onward push to $destrepo failed: $r $!";
234 }
235
236 #----- git-receive-pack -----
237
238 sub fixmissing__git_receive_pack () {
239     mkrepotmp();
240     $destrepo = "$dgitrepos/_tmp/${package}_prospective";
241     acquiretree($destrepo, 1);
242     mkrepo_fromtemplate($destrepo);
243 }
244
245 sub makeworkingclone () {
246     mkrepotmp();
247     $workrepo = "$dgitrepos/_tmp/${package}_incoming$$";
248     acquiretree($workrepo, 1);
249     runcmd qw(git clone -l -q --mirror), $destrepo, $workrepo;
250 }
251
252 sub setupstunthook () {
253     my $prerecv = "$workrepo/hooks/pre-receive";
254     my $fh = new IO::File $prerecv, O_WRONLY|O_CREAT|O_TRUNC, 0777
255         or die "$prerecv: $!";
256     print $fh <<END or die "$prerecv: $!";
257 #!/bin/sh
258 set -e
259 exec $0 --pre-receive-hook $package
260 END
261     close $fh or die "$prerecv: $!";
262     $ENV{'DGIT_DRS_WORK'}= $workrepo;
263     $ENV{'DGIT_DRS_DEST'}= $destrepo;
264     debug " stunt hook set up $prerecv";
265 }
266
267 sub maybeinstallprospective () {
268     return if $destrepo eq $realdestrepo;
269
270     if (open REJ, "<", "$workrepo/drs-error") {
271         local $/ = undef;
272         my $msg = <REJ>;
273         REJ->error and die $!;
274         print STDERR $msg;
275         exit 1;
276     } else {
277         $!==&ENOENT or die $!;
278     }
279
280     debug " show-ref ($destrepo) ...";
281
282     my $child = open SR, "-|";
283     defined $child or die $!;
284     if (!$child) {
285         chdir $destrepo or die $!;
286         exec qw(git show-ref);
287         die $!;
288     }
289     my %got = qw(tag 0 head 0);
290     while (<SR>) {
291         chomp or die;
292         debug " show-refs| $_";
293         s/^\S*[1-9a-f]\S* (\S+)$/$1/ or die;
294         my $wh =
295             m{^refs/tags/} ? 'tag' :
296             m{^refs/dgit/} ? 'head' :
297             die;
298         die if $got{$wh}++;
299     }
300     $!=0; $?=0; close SR or $?==256 or die "$? $!";
301
302     debug "installprospective ?";
303     die Dumper(\%got)." -- missing refs in new repo"
304         if grep { !$_ } values %got;
305
306     debug "install $destrepo => $realdestrepo";
307     rename $destrepo, $realdestrepo or die $!;
308     remove "$destrepo.lock" or die $!;
309 }
310
311 sub main__git_receive_pack () {
312     makeworkingclone();
313     setupstunthook();
314     runcmd qw(git receive-pack), $workrepo;
315     maybeinstallprospective();
316 }
317
318 #----- stunt post-receive hook -----
319
320 our ($tagname, $tagval, $suite, $oldcommit, $commit);
321 our ($version, %tagh);
322
323 sub readupdates () {
324     debug " updates ...";
325     while (<STDIN>) {
326         chomp or die;
327         debug " upd.| $_";
328         m/^(\S+) (\S+) (\S+)$/ or die "$_ ?";
329         my ($old, $sha1, $refname) = ($1, $2, $3);
330         if ($refname =~ m{^refs/tags/(?=debian/)}) {
331             reject "pushing multiple tags!" if defined $tagname;
332             $tagname = $'; #';
333             $tagval = $sha1;
334             reject "tag $tagname already exists -".
335                 " not replacing previously-pushed version"
336                 if $old =~ m/[^0]/;
337         } elsif ($refname =~ m{^refs/dgit/}) {
338             reject "pushing multiple heads!" if defined $suite;
339             $suite = $'; #';
340             $oldcommit = $old;
341             $commit = $sha1;
342         } else {
343             reject "pushing unexpected ref!";
344         }
345     }
346     STDIN->error and die $!;
347
348     reject "push is missing tag ref update" unless defined $tagname;
349     reject "push is missing head ref update" unless defined $suite;
350     debug " updates ok.";
351 }
352
353 sub parsetag () {
354     debug " parsetag...";
355     open PT, ">dgit-tmp/plaintext" or die $!;
356     open DS, ">dgit-tmp/plaintext.asc" or die $!;
357     open T, "-|", qw(git cat-file tag), $tagval or die $!;
358     for (;;) {
359         $!=0; $_=<T>; defined or die $!;
360         print PT or die $!;
361         if (m/^(\S+) (.*)/) {
362             push @{ $tagh{$1} }, $2;
363         } elsif (!m/\S/) {
364             last;
365         } else {
366             die;
367         }
368     }
369     $!=0; $_=<T>; defined or die $!;
370     m/^($package_re) release (\S+) for \S+ \((\S+)\) \[dgit\]$/ or
371         reject "tag message not in expected format";
372
373     die unless $1 eq $package;
374     $version = $2;
375     die "$3 != $suite " unless $3 eq $suite;
376
377     for (;;) {
378         print PT or die $!;
379         $!=0; $_=<T>; defined or die "missing signature? $!";
380         if (m/^\[dgit ([^"].*)\]$/) { # [dgit "something"] is for future
381             $_ = $1." ";
382             for (;;) {
383                 if (s/^distro\=(\S+) //) {
384                     die "$1 != $distro" unless $1 eq $distro;
385                 } elsif (s/^(--deliberately-$package_re) //) {
386                     push @deliberatelies, $1;
387                 } elsif (s/^[-+.=0-9a-z]\S* //) {
388                 } else {
389                     die "unknown dgit info in tag";
390                 }
391             }
392             next;
393         }
394         last if m/^-----BEGIN PGP/;
395     }
396     for (;;) {
397         print DS or die $!;
398         $!=0; $_=<T>;
399         last if !defined;
400     }
401     T->error and die $!;
402     close PT or die $!;
403     close DS or die $!;
404     debug " parsetag ok.";
405 }
406
407 sub checksig_keyring ($) {
408     my ($keyringfile) = @_;
409     # returns primary-keyid if signed by a key in this keyring
410     # or undef if not
411     # or dies on other errors
412
413     my $ok = undef;
414
415     debug " checksig keyring $keyringfile...";
416
417     our @cmd = (qw(gpgv --status-fd=1 --keyring),
418                    $keyringfile,
419                    qw(dgit-tmp/plaintext.asc dgit-tmp/plaintext));
420     debugcmd @cmd;
421
422     open P, "-|", @cmd
423         or die $!;
424
425     while (<P>) {
426         next unless s/^\[GNUPG:\] //;
427         chomp or die;
428         debug " checksig| $_";
429         my @l = split / /, $_;
430         if ($l[0] eq 'NO_PUBKEY') {
431             last;
432         } elsif ($l[0] eq 'VALIDSIG') {
433             my $sigtype = $l[9];
434             $sigtype eq '00' or reject "signature is not of type 00!";
435             $ok = $l[10];
436             die unless defined $ok;
437             last;
438         }
439     }
440     close P;
441
442     debug sprintf " checksig ok=%d", !!$ok;
443
444     return $ok;
445 }
446
447 sub dm_txt_check ($$) {
448     my ($keyid, $dmtxtfn) = @_;
449     debug " dm_txt_check $keyid $dmtxtfn";
450     open DT, '<', $dmtxtfn or die "$dmtxtfn $!";
451     while (<DT>) {
452         m/^fingerprint:\s+$keyid$/oi
453             ..0 or next;
454         if (s/^allow:/ /i..0) {
455         } else {
456             m/^./
457                 or reject "key $keyid missing Allow section in permissions!";
458             next;
459         }
460         # in right stanza...
461         s/^[ \t]+//
462             or reject "package $package not allowed for key $keyid";
463         # in allow field...
464         s/\([^()]+\)//;
465         s/\,//;
466         chomp or die;
467         debug " dm_txt_check allow| $_";
468         foreach my $p (split /\s+/) {
469             if ($p eq $package) {
470                 # yay!
471                 debug " dm_txt_check ok";
472                 return;
473             }
474         }
475     }
476     DT->error and die $!;
477     close DT or die $!;
478     reject "key $keyid not in permissions list although in keyring!";
479 }
480
481 sub verifytag () {
482     foreach my $kas (split /:/, $keyrings) {
483         debug "verifytag $kas...";
484         $kas =~ s/^([^,]+),// or die;
485         my $keyid = checksig_keyring $1;
486         if (defined $keyid) {
487             if ($kas =~ m/^a$/) {
488                 debug "verifytag a ok";
489                 return; # yay
490             } elsif ($kas =~ m/^m([^,]+)$/) {
491                 dm_txt_check($keyid, $1);
492                 debug "verifytag m ok";
493                 return;
494             } else {
495                 die;
496             }
497         }   
498     }
499     reject "key not found in keyrings";
500 }
501
502 sub checksuite () {
503     debug "checksuite ($suitesfile)";
504     open SUITES, "<", $suitesfile or die $!;
505     while (<SUITES>) {
506         chomp;
507         next unless m/\S/;
508         next if m/^\#/;
509         s/\s+$//;
510         return if $_ eq $suite;
511     }
512     die $! if SUITES->error;
513     reject "unknown suite";
514 }
515
516 sub tagh1 ($) {
517     my ($tag) = @_;
518     my $vals = $tagh{$tag};
519     reject "missing header $tag in signed tag object" unless $vals;
520     reject "multiple headers $tag in signed tag object" unless @$vals == 1;
521     return $vals->[0];
522 }
523
524 sub checks () {
525     debug "checks";
526
527     tagh1('type') eq 'commit' or reject "tag refers to wrong kind of object";
528     tagh1('object') eq $commit or reject "tag refers to wrong commit";
529     tagh1('tag') eq $tagname or reject "tag name in tag is wrong";
530
531     my $v = $version;
532     $v =~ y/~:/_%/;
533
534     debug "translated version $v";
535     $tagname eq "debian/$v" or die;
536
537     my ($policy) = policyhook(NOFFCHECK, 'push',$package,
538                               $version,$suite,$tagname,
539                               join(",",@delberatelies));
540
541     checksuite();
542
543     # check that our ref is being fast-forwarded
544     debug "oldcommit $oldcommit";
545     if (!($policy & NOFFCHECK) && $oldcommit =~ m/[^0]/) {
546         $?=0; $!=0; my $mb = `git merge-base $commit $oldcommit`;
547         chomp $mb;
548         $mb eq $oldcommit or reject "not fast forward on dgit branch";
549     }
550 }
551
552 sub stunthook () {
553     debug "stunthook";
554     chdir $workrepo or die "chdir $workrepo: $!";
555     mkdir "dgit-tmp" or $!==EEXIST or die $!;
556     readupdates();
557     parsetag();
558     verifytag();
559     checks();
560     onwardpush();
561     debug "stunthook done.";
562 }
563
564 #----- git-upload-pack -----
565
566 sub fixmissing__git_upload_pack () {
567     $destrepo = "$dgitrepos/_empty";
568     my $lfh = acquiretree($destrepo,1);
569     return if stat $destrepo;
570     die $! unless $!==ENOENT;
571     rmtree "$destrepo.new";
572     mkemptyrepo "$destrepo.new", "0644";
573     rename "$destrepo.new", $destrepo or die $!;
574     unlink "$destrepo.lock" or die $!;
575     close $lfh;
576 }
577
578 sub main__git_upload_pack () {
579     runcmd qw(git upload-pack), $destrepo;
580 }
581
582 #----- arg parsing and main program -----
583
584 sub argval () {
585     die unless @ARGV;
586     my $v = shift @ARGV;
587     die if $v =~ m/^-/;
588     return $v;
589 }
590
591 sub parseargsdispatch () {
592     die unless @ARGV;
593
594     delete $ENV{'GIT_DIR'}; # if not run via ssh, our parent git process
595     delete $ENV{'GIT_PREFIX'}; # sets these and they mess things up
596
597     if ($ENV{'DGIT_DRS_DEBUG'}) {
598         $debug='=';
599         open DEBUG, ">&STDERR" or die $!;
600     }
601
602     if ($ARGV[0] eq '--pre-receive-hook') {
603         if ($debug) { $debug.="="; }
604         shift @ARGV;
605         @ARGV == 1 or die;
606         $package = shift @ARGV;
607         defined($distro = $ENV{'DGIT_DRS_DISTRO'}) or die;
608         defined($suitesfile = $ENV{'DGIT_DRS_SUITES'}) or die;
609         defined($workrepo = $ENV{'DGIT_DRS_WORK'}) or die;
610         defined($destrepo = $ENV{'DGIT_DRS_DEST'}) or die;
611         defined($keyrings = $ENV{'DGIT_DRS_KEYRINGS'}) or die $!;
612         defined($policyhook = $ENV{'DGIT_DRS_POLICYHOOK'}) or die $!;
613         open STDOUT, ">&STDERR" or die $!;
614         eval {
615             stunthook();
616         };
617         if ($@) {
618             recorderror "$@" or die;
619             die $@;
620         }
621         exit 0;
622     }
623
624     $ENV{'DGIT_DRS_DISTRO'} = argval();
625     $ENV{'DGIT_DRS_SUITES'} = argval();
626     $ENV{'DGIT_DRS_KEYRINGS'} = argval();
627     $dgitrepos = argval();
628     $ENV{'DGIT_DRS_POLICYHOOK'} = $policyhook = argval();
629
630     die unless @ARGV==1 && $ARGV[0] eq '--ssh';
631
632     my $cmd = $ENV{'SSH_ORIGINAL_COMMAND'};
633     $cmd =~ m{
634         ^
635         (?: \S* / )?
636         ( [-0-9a-z]+ )
637         \s+
638         '? (?: \S* / )?
639         ($package_re) \.git
640         '?$
641     }ox 
642     or reject "command string not understood";
643     my $method = $1;
644     $package = $2;
645     $realdestrepo = "$dgitrepos/$package.git";
646
647     my $funcn = $method;
648     $funcn =~ y/-/_/;
649     my $mainfunc = $main::{"main__$funcn"};
650
651     reject "unknown method" unless $mainfunc;
652
653     my ($policy, $pollock) = policyhook(FRESHREPO,'check-package',$package);
654     if ($policy & FRESHREPO) {
655         movetogarbage;
656     }
657     close $pollock or die $!;
658
659     if (stat $realdestrepo) {
660         $destrepo = $realdestrepo;
661     } else {
662         $! == ENOENT or die "stat dest repo $destrepo: $!";
663         debug " fixmissing $funcn";
664         my $fixfunc = $main::{"fixmissing__$funcn"};
665         &$fixfunc;
666     }
667
668     debug " running main $funcn";
669     &$mainfunc;
670 }
671
672 sub unlockall () {
673     while (my $fh = pop @lockfhs) { close $fh; }
674 }
675
676 sub cleanup () {
677     unlockall();
678     if (!chdir "$dgitrepos/_tmp") {
679         $!==ENOENT or die $!;
680         return;
681     }
682     foreach my $lf (<*.lock>) {
683         my $tree = $lf;
684         $tree =~ s/\.lock$//;
685         next unless acquiretree($tree, 0);
686         remove $lf or warn $!;
687         unlockall();
688     }
689 }
690
691 parseargsdispatch();
692 cleanup();