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