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