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