chiark / gitweb /
5599061de2a68cb8e997c66f2d81e48c489688a9
[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     rmtree "${workrepo}_fresh";
251 }
252
253 sub setupstunthook () {
254     my $prerecv = "$workrepo/hooks/pre-receive";
255     my $fh = new IO::File $prerecv, O_WRONLY|O_CREAT|O_TRUNC, 0777
256         or die "$prerecv: $!";
257     print $fh <<END or die "$prerecv: $!";
258 #!/bin/sh
259 set -e
260 exec $0 --pre-receive-hook $package
261 END
262     close $fh or die "$prerecv: $!";
263     $ENV{'DGIT_DRS_WORK'}= $workrepo;
264     $ENV{'DGIT_DRS_DEST'}= $destrepo;
265     debug " stunt hook set up $prerecv";
266 }
267
268 sub dealwithfreshrepo () {
269     my $freshrepo = "${workrepo}_fresh";
270     if (!stat $freshrepo) {
271         $!==ENOENT or die "$freshrepo $!";
272         return;
273     }
274     $destrepo = $freshrepo;
275 }
276
277 sub maybeinstallprospective () {
278     return if $destrepo eq $realdestrepo;
279
280     if (open REJ, "<", "$workrepo/drs-error") {
281         local $/ = undef;
282         my $msg = <REJ>;
283         REJ->error and die $!;
284         print STDERR $msg;
285         exit 1;
286     } else {
287         $!==&ENOENT or die $!;
288     }
289
290     debug " show-ref ($destrepo) ...";
291
292     my $child = open SR, "-|";
293     defined $child or die $!;
294     if (!$child) {
295         chdir $destrepo or die $!;
296         exec qw(git show-ref);
297         die $!;
298     }
299     my %got = qw(tag 0 head 0);
300     while (<SR>) {
301         chomp or die;
302         debug " show-refs| $_";
303         s/^\S*[1-9a-f]\S* (\S+)$/$1/ or die;
304         my $wh =
305             m{^refs/tags/} ? 'tag' :
306             m{^refs/dgit/} ? 'head' :
307             die;
308         die if $got{$wh}++;
309     }
310     $!=0; $?=0; close SR or $?==256 or die "$? $!";
311
312     debug "installprospective ?";
313     die Dumper(\%got)." -- missing refs in new repo"
314         if grep { !$_ } values %got;
315
316     movetogarbage; # in case of FRESHREPO
317
318     debug "install $destrepo => $realdestrepo";
319     rename $destrepo, $realdestrepo or die $!;
320     remove "$destrepo.lock" or die $!;
321 }
322
323 sub main__git_receive_pack () {
324     makeworkingclone();
325     setupstunthook();
326     runcmd qw(git receive-pack), $workrepo;
327     dealwithfreshrepo();
328     maybeinstallprospective();
329 }
330
331 #----- stunt post-receive hook -----
332
333 our ($tagname, $tagval, $suite, $oldcommit, $commit);
334 our ($version, %tagh);
335
336 sub readupdates () {
337     debug " updates ...";
338     while (<STDIN>) {
339         chomp or die;
340         debug " upd.| $_";
341         m/^(\S+) (\S+) (\S+)$/ or die "$_ ?";
342         my ($old, $sha1, $refname) = ($1, $2, $3);
343         if ($refname =~ m{^refs/tags/(?=debian/)}) {
344             reject "pushing multiple tags!" if defined $tagname;
345             $tagname = $'; #';
346             $tagval = $sha1;
347             reject "tag $tagname already exists -".
348                 " not replacing previously-pushed version"
349                 if $old =~ m/[^0]/;
350         } elsif ($refname =~ m{^refs/dgit/}) {
351             reject "pushing multiple heads!" if defined $suite;
352             $suite = $'; #';
353             $oldcommit = $old;
354             $commit = $sha1;
355         } else {
356             reject "pushing unexpected ref!";
357         }
358     }
359     STDIN->error and die $!;
360
361     reject "push is missing tag ref update" unless defined $tagname;
362     reject "push is missing head ref update" unless defined $suite;
363     debug " updates ok.";
364 }
365
366 sub parsetag () {
367     debug " parsetag...";
368     open PT, ">dgit-tmp/plaintext" or die $!;
369     open DS, ">dgit-tmp/plaintext.asc" or die $!;
370     open T, "-|", qw(git cat-file tag), $tagval or die $!;
371     for (;;) {
372         $!=0; $_=<T>; defined or die $!;
373         print PT or die $!;
374         if (m/^(\S+) (.*)/) {
375             push @{ $tagh{$1} }, $2;
376         } elsif (!m/\S/) {
377             last;
378         } else {
379             die;
380         }
381     }
382     $!=0; $_=<T>; defined or die $!;
383     m/^($package_re) release (\S+) for \S+ \((\S+)\) \[dgit\]$/ or
384         reject "tag message not in expected format";
385
386     die unless $1 eq $package;
387     $version = $2;
388     die "$3 != $suite " unless $3 eq $suite;
389
390     for (;;) {
391         print PT or die $!;
392         $!=0; $_=<T>; defined or die "missing signature? $!";
393         if (m/^\[dgit ([^"].*)\]$/) { # [dgit "something"] is for future
394             $_ = $1." ";
395             for (;;) {
396                 if (s/^distro\=(\S+) //) {
397                     die "$1 != $distro" unless $1 eq $distro;
398                 } elsif (s/^(--deliberately-$package_re) //) {
399                     push @deliberatelies, $1;
400                 } elsif (s/^[-+.=0-9a-z]\S* //) {
401                 } else {
402                     die "unknown dgit info in tag";
403                 }
404             }
405             next;
406         }
407         last if m/^-----BEGIN PGP/;
408     }
409     for (;;) {
410         print DS or die $!;
411         $!=0; $_=<T>;
412         last if !defined;
413     }
414     T->error and die $!;
415     close PT or die $!;
416     close DS or die $!;
417     debug " parsetag ok.";
418 }
419
420 sub checksig_keyring ($) {
421     my ($keyringfile) = @_;
422     # returns primary-keyid if signed by a key in this keyring
423     # or undef if not
424     # or dies on other errors
425
426     my $ok = undef;
427
428     debug " checksig keyring $keyringfile...";
429
430     our @cmd = (qw(gpgv --status-fd=1 --keyring),
431                    $keyringfile,
432                    qw(dgit-tmp/plaintext.asc dgit-tmp/plaintext));
433     debugcmd @cmd;
434
435     open P, "-|", @cmd
436         or die $!;
437
438     while (<P>) {
439         next unless s/^\[GNUPG:\] //;
440         chomp or die;
441         debug " checksig| $_";
442         my @l = split / /, $_;
443         if ($l[0] eq 'NO_PUBKEY') {
444             last;
445         } elsif ($l[0] eq 'VALIDSIG') {
446             my $sigtype = $l[9];
447             $sigtype eq '00' or reject "signature is not of type 00!";
448             $ok = $l[10];
449             die unless defined $ok;
450             last;
451         }
452     }
453     close P;
454
455     debug sprintf " checksig ok=%d", !!$ok;
456
457     return $ok;
458 }
459
460 sub dm_txt_check ($$) {
461     my ($keyid, $dmtxtfn) = @_;
462     debug " dm_txt_check $keyid $dmtxtfn";
463     open DT, '<', $dmtxtfn or die "$dmtxtfn $!";
464     while (<DT>) {
465         m/^fingerprint:\s+$keyid$/oi
466             ..0 or next;
467         if (s/^allow:/ /i..0) {
468         } else {
469             m/^./
470                 or reject "key $keyid missing Allow section in permissions!";
471             next;
472         }
473         # in right stanza...
474         s/^[ \t]+//
475             or reject "package $package not allowed for key $keyid";
476         # in allow field...
477         s/\([^()]+\)//;
478         s/\,//;
479         chomp or die;
480         debug " dm_txt_check allow| $_";
481         foreach my $p (split /\s+/) {
482             if ($p eq $package) {
483                 # yay!
484                 debug " dm_txt_check ok";
485                 return;
486             }
487         }
488     }
489     DT->error and die $!;
490     close DT or die $!;
491     reject "key $keyid not in permissions list although in keyring!";
492 }
493
494 sub verifytag () {
495     foreach my $kas (split /:/, $keyrings) {
496         debug "verifytag $kas...";
497         $kas =~ s/^([^,]+),// or die;
498         my $keyid = checksig_keyring $1;
499         if (defined $keyid) {
500             if ($kas =~ m/^a$/) {
501                 debug "verifytag a ok";
502                 return; # yay
503             } elsif ($kas =~ m/^m([^,]+)$/) {
504                 dm_txt_check($keyid, $1);
505                 debug "verifytag m ok";
506                 return;
507             } else {
508                 die;
509             }
510         }   
511     }
512     reject "key not found in keyrings";
513 }
514
515 sub checksuite () {
516     debug "checksuite ($suitesfile)";
517     open SUITES, "<", $suitesfile or die $!;
518     while (<SUITES>) {
519         chomp;
520         next unless m/\S/;
521         next if m/^\#/;
522         s/\s+$//;
523         return if $_ eq $suite;
524     }
525     die $! if SUITES->error;
526     reject "unknown suite";
527 }
528
529 sub tagh1 ($) {
530     my ($tag) = @_;
531     my $vals = $tagh{$tag};
532     reject "missing header $tag in signed tag object" unless $vals;
533     reject "multiple headers $tag in signed tag object" unless @$vals == 1;
534     return $vals->[0];
535 }
536
537 sub checks () {
538     debug "checks";
539
540     tagh1('type') eq 'commit' or reject "tag refers to wrong kind of object";
541     tagh1('object') eq $commit or reject "tag refers to wrong commit";
542     tagh1('tag') eq $tagname or reject "tag name in tag is wrong";
543
544     my $v = $version;
545     $v =~ y/~:/_%/;
546
547     debug "translated version $v";
548     $tagname eq "debian/$v" or die;
549
550     $policy = policyhook(NOFFCHECK|FRESHREPO, 'push',$package,
551                          $version,$suite,$tagname,
552                          join(",",@delberatelies));
553
554     checksuite();
555
556     # check that our ref is being fast-forwarded
557     debug "oldcommit $oldcommit";
558     if (!($policy & NOFFCHECK) && $oldcommit =~ m/[^0]/) {
559         $?=0; $!=0; my $mb = `git merge-base $commit $oldcommit`;
560         chomp $mb;
561         $mb eq $oldcommit or reject "not fast forward on dgit branch";
562     }
563
564     if ($policy & FRESHREPO) {
565         # This is troublesome.  We have been asked by the policy hook
566         # to receive the push into a fresh repo.  But of course we
567         # have actually already mostly received the push into the working
568         # repo.  (This is unavoidable because the instruction to use a new
569         # repo comes ultimately from the signed tag for the dgit push,
570         # which has to have been received into some repo.)
571         #
572         # So what we do is generate a fresh working repo right now and
573         # push the head and tag into it.  The presence of this fresh
574         # working repo is detected by the parent, which responds by
575         # making a fresh master repo from the template.
576
577         $destrepo = "${workrepo}_fresh"; # workrepo lock covers
578         mkrepo_fromtemplate $destrepo;
579     }
580 }
581
582 sub stunthook () {
583     debug "stunthook";
584     chdir $workrepo or die "chdir $workrepo: $!";
585     mkdir "dgit-tmp" or $!==EEXIST or die $!;
586     readupdates();
587     parsetag();
588     verifytag();
589     checks();
590     onwardpush();
591     debug "stunthook done.";
592 }
593
594 #----- git-upload-pack -----
595
596 sub fixmissing__git_upload_pack () {
597     $destrepo = "$dgitrepos/_empty";
598     my $lfh = acquiretree($destrepo,1);
599     return if stat $destrepo;
600     die $! unless $!==ENOENT;
601     rmtree "$destrepo.new";
602     mkemptyrepo "$destrepo.new", "0644";
603     rename "$destrepo.new", $destrepo or die $!;
604     unlink "$destrepo.lock" or die $!;
605     close $lfh;
606 }
607
608 sub main__git_upload_pack () {
609     runcmd qw(git upload-pack), $destrepo;
610 }
611
612 #----- arg parsing and main program -----
613
614 sub argval () {
615     die unless @ARGV;
616     my $v = shift @ARGV;
617     die if $v =~ m/^-/;
618     return $v;
619 }
620
621 sub parseargsdispatch () {
622     die unless @ARGV;
623
624     delete $ENV{'GIT_DIR'}; # if not run via ssh, our parent git process
625     delete $ENV{'GIT_PREFIX'}; # sets these and they mess things up
626
627     if ($ENV{'DGIT_DRS_DEBUG'}) {
628         $debug='=';
629         open DEBUG, ">&STDERR" or die $!;
630     }
631
632     if ($ARGV[0] eq '--pre-receive-hook') {
633         if ($debug) { $debug.="="; }
634         shift @ARGV;
635         @ARGV == 1 or die;
636         $package = shift @ARGV;
637         defined($distro = $ENV{'DGIT_DRS_DISTRO'}) or die;
638         defined($suitesfile = $ENV{'DGIT_DRS_SUITES'}) or die;
639         defined($workrepo = $ENV{'DGIT_DRS_WORK'}) or die;
640         defined($destrepo = $ENV{'DGIT_DRS_DEST'}) or die;
641         defined($keyrings = $ENV{'DGIT_DRS_KEYRINGS'}) or die $!;
642         defined($policyhook = $ENV{'DGIT_DRS_POLICYHOOK'}) or die $!;
643         open STDOUT, ">&STDERR" or die $!;
644         eval {
645             stunthook();
646         };
647         if ($@) {
648             recorderror "$@" or die;
649             die $@;
650         }
651         exit 0;
652     }
653
654     $ENV{'DGIT_DRS_DISTRO'} = argval();
655     $ENV{'DGIT_DRS_SUITES'} = argval();
656     $ENV{'DGIT_DRS_KEYRINGS'} = argval();
657     $dgitrepos = argval();
658     $ENV{'DGIT_DRS_POLICYHOOK'} = $policyhook = argval();
659
660     die unless @ARGV==1 && $ARGV[0] eq '--ssh';
661
662     my $cmd = $ENV{'SSH_ORIGINAL_COMMAND'};
663     $cmd =~ m{
664         ^
665         (?: \S* / )?
666         ( [-0-9a-z]+ )
667         \s+
668         '? (?: \S* / )?
669         ($package_re) \.git
670         '?$
671     }ox 
672     or reject "command string not understood";
673     my $method = $1;
674     $package = $2;
675     $realdestrepo = "$dgitrepos/$package.git";
676
677     my $funcn = $method;
678     $funcn =~ y/-/_/;
679     my $mainfunc = $main::{"main__$funcn"};
680
681     reject "unknown method" unless $mainfunc;
682
683     my ($policy, $pollock) = policyhook(FRESHREPO,'check-package',$package);
684     if ($policy & FRESHREPO) {
685         movetogarbage;
686     }
687     close $pollock or die $!;
688
689     if (stat $realdestrepo) {
690         $destrepo = $realdestrepo;
691     } else {
692         $! == ENOENT or die "stat dest repo $destrepo: $!";
693         debug " fixmissing $funcn";
694         my $fixfunc = $main::{"fixmissing__$funcn"};
695         &$fixfunc;
696     }
697
698     debug " running main $funcn";
699     &$mainfunc;
700 }
701
702 sub unlockall () {
703     while (my $fh = pop @lockfhs) { close $fh; }
704 }
705
706 sub cleanup () {
707     unlockall();
708     if (!chdir "$dgitrepos/_tmp") {
709         $!==ENOENT or die $!;
710         return;
711     }
712     foreach my $lf (<*.lock>) {
713         my $tree = $lf;
714         $tree =~ s/\.lock$//;
715         next unless acquiretree($tree, 0);
716         remove $lf or warn $!;
717         unlockall();
718     }
719 }
720
721 parseargsdispatch();
722 cleanup();