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