chiark / gitweb /
dgit: Introduce "deliberatelies"
[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 DGIT-REPOS-DIR --ssh
6 # internal usage:
7 #  .../dgit-repos-server --pre-receive-hook PACKAGE
8 #
9 # Invoked as the ssh restricted command
10 #
11 # Works like git-receive-pack
12 #
13 # SUITES is the name of a file which lists the permissible suites
14 # one per line (#-comments and blank lines ignored)
15 #
16 # KEYRING-AUTH-SPEC is a :-separated list of
17 #   KEYRING.GPG,AUTH-SPEC
18 # where AUTH-SPEC is one of
19 #   a
20 #   mDM.TXT
21
22 use strict;
23
24 # What we do is this:
25 #  - extract the destination repo name
26 #  - make a hardlink clone of the destination repo
27 #  - provide the destination with a stunt pre-receive hook
28 #  - run actual git-receive-pack with that new destination
29 #   as a result of this the stunt pre-receive hook runs; it does this:
30 #    + understand what refs we are allegedly updating and
31 #      check some correspondences:
32 #        * we are updating only refs/tags/debian/* and refs/dgit/*
33 #        * and only one of each
34 #        * and the tag does not already exist
35 #      and
36 #        * recover the suite name from the destination refs/dgit/ ref
37 #    + disassemble the signed tag into its various fields and signature
38 #      including:
39 #        * parsing the first line of the tag message to recover
40 #          the package name, version and suite
41 #        * checking that the package name corresponds to the dest repo name
42 #        * checking that the suite name is as recovered above
43 #    + verify the signature on the signed tag
44 #      and if necessary check that the keyid and package are listed in dm.txt
45 #    + check various correspondences:
46 #        * the suite is one of those permitted
47 #        * the signed tag must refer to a commit
48 #        * the signed tag commit must be the refs/dgit value
49 #        * the name in the signed tag must correspond to its ref name
50 #        * the tag name must be debian/<version> (massaged as needed)
51 #        * the signed tag has a suitable name
52 #        * the commit is a fast forward
53 #    + push the signed tag and new dgit branch to the actual repo
54 #
55 # If the destination repo does not already exist, we need to make
56 # sure that we create it reasonably atomically, and also that
57 # we don't every have a destination repo containing no refs at all
58 # (because such a thing causes git-fetch-pack to barf).  So then we
59 # do as above, except:
60 #  - before starting, we take out our own lock for the destination repo
61 #  - we create a prospective new destination repo by making a copy
62 #    of _template
63 #  - we use the prospective new destination repo instead of the
64 #    actual new destination repo (since the latter doesn't exist)
65 #  - we set up a post-receive hook as well, which
66 #    + touches a stamp file
67 #  - after git-receive-pack exits, we
68 #    + check that the prospective repo contains a tag and head
69 #    + rename the prospective destination repo into place
70 #
71 # Cleanup strategy:
72 #  - We are crash-only
73 #  - Temporary working trees and their locks are cleaned up
74 #    opportunistically by a program which tries to take each lock and
75 #    if successful deletes both the tree and the lockfile
76 #  - Prospective working trees and their locks are cleaned up by
77 #    a program which tries to take each lock and if successful
78 #    deletes any prospective working tree and the lock (but not
79 #    of course any actual tree)
80 #  - It is forbidden to _remove_ the lockfile without removing
81 #    the corresponding temporary tree, as the lockfile is also
82 #    a stampfile whose presence indicates that there may be
83 #    cleanup to do
84
85 use POSIX;
86 use Fcntl qw(:flock);
87 use File::Path qw(rmtree);
88
89 open DEBUG, ">/dev/null" or die $!;
90
91 our $package_re = '[0-9a-z][-+.0-9a-z]+';
92
93 our $func;
94 our $dgitrepos;
95 our $package;
96 our $suitesfile;
97 our $realdestrepo;
98 our $destrepo;
99 our $workrepo;
100 our $keyrings;
101 our @lockfhs;
102 our $debug='';
103 our @deliberatelies;
104 our $policy;
105
106 #----- utilities -----
107
108 sub debug {
109     print DEBUG "$debug @_\n";
110 }
111
112 sub acquirelock ($$) {
113     my ($lock, $must) = @_;
114     my $fh;
115     printf DEBUG "$debug locking %s %d\n", $lock, $must;
116     for (;;) {
117         close $fh if $fh;
118         $fh = new IO::File $lock, ">" or die "open $lock: $!";
119         my $ok = flock $fh, $must ? LOCK_EX : (LOCK_EX|LOCK_NB);
120         if (!$ok) {
121             die "flock $lock: $!" if $must;
122             debug " locking $lock failed";
123             return undef;
124         }
125         if (!stat $lock) {
126             next if $! == ENOENT;
127             die "stat $lock: $!";
128         }
129         my $want = (stat _)[1];
130         stat $fh or die $!;
131         my $got = (stat _)[1];
132         last if $got == $want;
133     }
134     return $fh;
135 }
136
137 sub acquiretree ($$) {
138     my ($tree, $must) = @_;
139     my $fh = acquirelock("$tree.lock", $must);
140     if ($fh) {
141         push @lockfhs, $fh;
142         rmtree $tree;
143     }
144     return $fh;
145 }
146
147 sub mkrepotmp () {
148     my $tmpdir = "$dgitrepos/_tmp";
149     return if mkdir $tmpdir;
150     return if $! == EEXIST;
151     die $!;
152 }
153
154 sub recorderror ($) {
155     my ($why) = @_;
156     my $w = $ENV{'DGIT_DRS_WORK'}; # we are in stunthook
157     if (defined $w) {
158         chomp $why;
159         open ERR, ">", "$w/drs-error" or die $!;
160         print ERR $why, "\n" or die $!;
161         close ERR or die $!;
162         return 1;
163     }
164     return 0;
165 }
166
167 sub reject ($) {
168     my ($why) = @_;
169     recorderror "reject: $why";
170     die "dgit-repos-server: reject: $why\n";
171 }
172
173 sub debugcmd {
174     if ($debug) {
175         use Data::Dumper;
176         local $Data::Dumper::Indent = 0;
177         local $Data::Dumper::Terse = 1;
178         debug "|".Dumper(\@_);
179     }
180 }
181
182 sub runcmd {
183     debugcmd @_;
184     $!=0; $?=0;
185     my $r = system @_;
186     die "@_ $? $!" if $r;
187 }
188
189 #----- git-receive-pack -----
190
191 sub fixmissing__git_receive_pack () {
192     mkrepotmp();
193     $destrepo = "$dgitrepos/_tmp/${package}_prospective";
194     acquiretree($destrepo, 1);
195     my $template = "$dgitrepos/_template";
196     debug "fixmissing copy tempalate $template -> $destrepo";
197     my $r = system qw(cp -a --), $template, $destrepo;
198     !$r or die "create new repo failed failed: $r $!";
199 }
200
201 sub makeworkingclone () {
202     mkrepotmp();
203     $workrepo = "$dgitrepos/_tmp/${package}_incoming$$";
204     acquiretree($workrepo, 1);
205     runcmd qw(git clone -l -q --mirror), $destrepo, $workrepo;
206 }
207
208 sub setupstunthook () {
209     my $prerecv = "$workrepo/hooks/pre-receive";
210     my $fh = new IO::File $prerecv, O_WRONLY|O_CREAT|O_TRUNC, 0777
211         or die "$prerecv: $!";
212     print $fh <<END or die "$prerecv: $!";
213 #!/bin/sh
214 set -e
215 exec $0 --pre-receive-hook $package
216 END
217     close $fh or die "$prerecv: $!";
218     $ENV{'DGIT_DRS_WORK'}= $workrepo;
219     $ENV{'DGIT_DRS_DEST'}= $destrepo;
220     debug " stunt hook set up $prerecv";
221 }
222
223 sub maybeinstallprospective () {
224     return if $destrepo eq $realdestrepo;
225
226     if (open REJ, "<", "$workrepo/drs-error") {
227         local $/ = undef;
228         my $msg = <REJ>;
229         REJ->error and die $!;
230         print STDERR $msg;
231         exit 1;
232     } else {
233         $!==&ENOENT or die $!;
234     }
235
236     debug " show-ref ($destrepo) ...";
237
238     my $child = open SR, "-|";
239     defined $child or die $!;
240     if (!$child) {
241         chdir $destrepo or die $!;
242         exec qw(git show-ref);
243         die $!;
244     }
245     my %got = qw(tag 0 head 0);
246     while (<SR>) {
247         chomp or die;
248         debug " show-refs| $_";
249         s/^\S*[1-9a-f]\S* (\S+)$/$1/ or die;
250         my $wh =
251             m{^refs/tags/} ? 'tag' :
252             m{^refs/dgit/} ? 'head' :
253             die;
254         die if $got{$wh}++;
255     }
256     $!=0; $?=0; close SR or $?==256 or die "$? $!";
257
258     debug "installprospective ?";
259     die Dumper(\%got)." -- missing refs in new repo"
260         if grep { !$_ } values %got;
261
262     debug "install $destrepo => $realdestrepo";
263     rename $destrepo, $realdestrepo or die $!;
264     remove "$destrepo.lock" or die $!;
265 }
266
267 sub main__git_receive_pack () {
268     makeworkingclone();
269     setupstunthook();
270     runcmd qw(git receive-pack), $workrepo;
271     maybeinstallprospective();
272 }
273
274 #----- stunt post-receive hook -----
275
276 our ($tagname, $tagval, $suite, $oldcommit, $commit);
277 our ($version, %tagh);
278
279 sub readupdates () {
280     debug " updates ...";
281     while (<STDIN>) {
282         chomp or die;
283         debug " upd.| $_";
284         m/^(\S+) (\S+) (\S+)$/ or die "$_ ?";
285         my ($old, $sha1, $refname) = ($1, $2, $3);
286         if ($refname =~ m{^refs/tags/(?=debian/)}) {
287             reject "pushing multiple tags!" if defined $tagname;
288             $tagname = $'; #';
289             $tagval = $sha1;
290             reject "tag $tagname already exists -".
291                 " not replacing previously-pushed version"
292                 if $old =~ m/[^0]/;
293         } elsif ($refname =~ m{^refs/dgit/}) {
294             reject "pushing multiple heads!" if defined $suite;
295             $suite = $'; #';
296             $oldcommit = $old;
297             $commit = $sha1;
298         } else {
299             reject "pushing unexpected ref!";
300         }
301     }
302     STDIN->error and die $!;
303
304     reject "push is missing tag ref update" unless defined $tagname;
305     reject "push is missing head ref update" unless defined $suite;
306     debug " updates ok.";
307 }
308
309 sub parsetag () {
310     debug " parsetag...";
311     open PT, ">dgit-tmp/plaintext" or die $!;
312     open DS, ">dgit-tmp/plaintext.asc" or die $!;
313     open T, "-|", qw(git cat-file tag), $tagval or die $!;
314     for (;;) {
315         $!=0; $_=<T>; defined or die $!;
316         print PT or die $!;
317         if (m/^(\S+) (.*)/) {
318             push @{ $tagh{$1} }, $2;
319         } elsif (!m/\S/) {
320             last;
321         } else {
322             die;
323         }
324     }
325     $!=0; $_=<T>; defined or die $!;
326     m/^($package_re) release (\S+) for \S+ \((\S+)\) \[dgit\]$/ or
327         reject "tag message not in expected format";
328
329     die unless $1 eq $package;
330     $version = $2;
331     die "$3 != $suite " unless $3 eq $suite;
332
333     for (;;) {
334         print PT or die $!;
335         $!=0; $_=<T>; defined or die "missing signature? $!";
336         if (m/^\[dgit ([^"].*)\]$/) { # [dgit "something"] is for future
337             $_ = $1." ";
338             for (;;) {
339                 if (s/^distro\=(\S+) //) {
340                     die "$1 != $distro" unless $1 eq $distro;
341                 } elsif (s/^(--deliberately-$package_re) //) {
342                     push @deliberatelies, $1;
343                 } elsif (s/^[-+.=0-9a-z]\S* //) {
344                 } else {
345                     die "unknown dgit info in tag";
346                 }
347             }
348             next;
349         }
350         last if m/^-----BEGIN PGP/;
351     }
352     for (;;) {
353         print DS or die $!;
354         $!=0; $_=<T>;
355         last if !defined;
356     }
357     T->error and die $!;
358     close PT or die $!;
359     close DS or die $!;
360     debug " parsetag ok.";
361 }
362
363 sub checksig_keyring ($) {
364     my ($keyringfile) = @_;
365     # returns primary-keyid if signed by a key in this keyring
366     # or undef if not
367     # or dies on other errors
368
369     my $ok = undef;
370
371     debug " checksig keyring $keyringfile...";
372
373     our @cmd = (qw(gpgv --status-fd=1 --keyring),
374                    $keyringfile,
375                    qw(dgit-tmp/plaintext.asc dgit-tmp/plaintext));
376     debugcmd @cmd;
377
378     open P, "-|", @cmd
379         or die $!;
380
381     while (<P>) {
382         next unless s/^\[GNUPG:\] //;
383         chomp or die;
384         debug " checksig| $_";
385         my @l = split / /, $_;
386         if ($l[0] eq 'NO_PUBKEY') {
387             last;
388         } elsif ($l[0] eq 'VALIDSIG') {
389             my $sigtype = $l[9];
390             $sigtype eq '00' or reject "signature is not of type 00!";
391             $ok = $l[10];
392             die unless defined $ok;
393             last;
394         }
395     }
396     close P;
397
398     debug sprintf " checksig ok=%d", !!$ok;
399
400     return $ok;
401 }
402
403 sub dm_txt_check ($$) {
404     my ($keyid, $dmtxtfn) = @_;
405     debug " dm_txt_check $keyid $dmtxtfn";
406     open DT, '<', $dmtxtfn or die "$dmtxtfn $!";
407     while (<DT>) {
408         m/^fingerprint:\s+$keyid$/oi
409             ..0 or next;
410         if (s/^allow:/ /i..0) {
411         } else {
412             m/^./
413                 or reject "key $keyid missing Allow section in permissions!";
414             next;
415         }
416         # in right stanza...
417         s/^[ \t]+//
418             or reject "package $package not allowed for key $keyid";
419         # in allow field...
420         s/\([^()]+\)//;
421         s/\,//;
422         chomp or die;
423         debug " dm_txt_check allow| $_";
424         foreach my $p (split /\s+/) {
425             if ($p eq $package) {
426                 # yay!
427                 debug " dm_txt_check ok";
428                 return;
429             }
430         }
431     }
432     DT->error and die $!;
433     close DT or die $!;
434     reject "key $keyid not in permissions list although in keyring!";
435 }
436
437 sub verifytag () {
438     foreach my $kas (split /:/, $keyrings) {
439         debug "verifytag $kas...";
440         $kas =~ s/^([^,]+),// or die;
441         my $keyid = checksig_keyring $1;
442         if (defined $keyid) {
443             if ($kas =~ m/^a$/) {
444                 debug "verifytag a ok";
445                 return; # yay
446             } elsif ($kas =~ m/^m([^,]+)$/) {
447                 dm_txt_check($keyid, $1);
448                 debug "verifytag m ok";
449                 return;
450             } else {
451                 die;
452             }
453         }   
454     }
455     reject "key not found in keyrings";
456 }
457
458 sub checksuite () {
459     debug "checksuite ($suitesfile)";
460     open SUITES, "<", $suitesfile or die $!;
461     while (<SUITES>) {
462         chomp;
463         next unless m/\S/;
464         next if m/^\#/;
465         s/\s+$//;
466         return if $_ eq $suite;
467     }
468     die $! if SUITES->error;
469     reject "unknown suite";
470 }
471
472 sub tagh1 ($) {
473     my ($tag) = @_;
474     my $vals = $tagh{$tag};
475     reject "missing header $tag in signed tag object" unless $vals;
476     reject "multiple headers $tag in signed tag object" unless @$vals == 1;
477     return $vals->[0];
478 }
479
480 sub checks () {
481     debug "checks";
482
483     tagh1('type') eq 'commit' or reject "tag refers to wrong kind of object";
484     tagh1('object') eq $commit or reject "tag refers to wrong commit";
485     tagh1('tag') eq $tagname or reject "tag name in tag is wrong";
486
487     my $v = $version;
488     $v =~ y/~:/_%/;
489
490     debug "translated version $v";
491     $tagname eq "debian/$v" or die;
492
493     checksuite();
494
495     # check that our ref is being fast-forwarded
496     debug "oldcommit $oldcommit";
497     if ($oldcommit =~ m/[^0]/) {
498         $?=0; $!=0; my $mb = `git merge-base $commit $oldcommit`;
499         chomp $mb;
500         $mb eq $oldcommit or reject "not fast forward on dgit branch";
501     }
502 }
503
504 sub onwardpush () {
505     my @cmd = (qw(git send-pack), $destrepo,
506                "$commit:refs/dgit/$suite",
507                "$tagval:refs/tags/$tagname");
508     debugcmd @cmd;
509     $!=0;
510     my $r = system @cmd;
511     !$r or die "onward push failed: $r $!";
512 }       
513
514 sub stunthook () {
515     debug "stunthook";
516     chdir $workrepo or die "chdir $workrepo: $!";
517     mkdir "dgit-tmp" or $!==EEXIST or die $!;
518     readupdates();
519     parsetag();
520     verifytag();
521     checks();
522     onwardpush();
523     debug "stunthook done.";
524 }
525
526 #----- git-upload-pack -----
527
528 sub fixmissing__git_upload_pack () {
529     $destrepo = "$dgitrepos/_empty";
530     my $lfh = acquiretree($destrepo,1);
531     return if stat $destrepo;
532     die $! unless $!==ENOENT;
533     rmtree "$destrepo.new";
534     umask 022;
535     runcmd qw(git init --bare --quiet), "$destrepo.new";
536     rename "$destrepo.new", $destrepo or die $!;
537     unlink "$destrepo.lock" or die $!;
538     close $lfh;
539 }
540
541 sub main__git_upload_pack () {
542     runcmd qw(git upload-pack), $destrepo;
543 }
544
545 #----- arg parsing and main program -----
546
547 sub argval () {
548     die unless @ARGV;
549     my $v = shift @ARGV;
550     die if $v =~ m/^-/;
551     return $v;
552 }
553
554 sub parseargsdispatch () {
555     die unless @ARGV;
556
557     delete $ENV{'GIT_DIR'}; # if not run via ssh, our parent git process
558     delete $ENV{'GIT_PREFIX'}; # sets these and they mess things up
559
560     if ($ENV{'DGIT_DRS_DEBUG'}) {
561         $debug='=';
562         open DEBUG, ">&STDERR" or die $!;
563     }
564
565     if ($ARGV[0] eq '--pre-receive-hook') {
566         if ($debug) { $debug.="="; }
567         shift @ARGV;
568         @ARGV == 1 or die;
569         $package = shift @ARGV;
570         defined($distro = $ENV{'DGIT_DRS_DISTRO'}) or die;
571         defined($suitesfile = $ENV{'DGIT_DRS_SUITES'}) or die;
572         defined($workrepo = $ENV{'DGIT_DRS_WORK'}) or die;
573         defined($destrepo = $ENV{'DGIT_DRS_DEST'}) or die;
574         defined($keyrings = $ENV{'DGIT_DRS_KEYRINGS'}) or die $!;
575         open STDOUT, ">&STDERR" or die $!;
576         eval {
577             stunthook();
578         };
579         if ($@) {
580             recorderror "$@" or die;
581             die $@;
582         }
583         exit 0;
584     }
585
586     $ENV{'DGIT_DRS_DISTRO'} = argval();
587     $ENV{'DGIT_DRS_SUITES'} = argval();
588     $ENV{'DGIT_DRS_KEYRINGS'} = argval();
589     $dgitrepos = argval();
590
591     die unless @ARGV==1 && $ARGV[0] eq '--ssh';
592
593     my $cmd = $ENV{'SSH_ORIGINAL_COMMAND'};
594     $cmd =~ m{
595         ^
596         (?: \S* / )?
597         ( [-0-9a-z]+ )
598         \s+
599         '? (?: \S* / )?
600         ($package_re) \.git
601         '?$
602     }ox 
603     or reject "command string not understood";
604     my $method = $1;
605     $package = $2;
606     $realdestrepo = "$dgitrepos/$package.git";
607
608     my $funcn = $method;
609     $funcn =~ y/-/_/;
610     my $mainfunc = $main::{"main__$funcn"};
611
612     reject "unknown method" unless $mainfunc;
613
614     if (stat $realdestrepo) {
615         $destrepo = $realdestrepo;
616     } else {
617         $! == ENOENT or die "stat dest repo $destrepo: $!";
618         debug " fixmissing $funcn";
619         my $fixfunc = $main::{"fixmissing__$funcn"};
620         &$fixfunc;
621     }
622
623     debug " running main $funcn";
624     &$mainfunc;
625 }
626
627 sub unlockall () {
628     while (my $fh = pop @lockfhs) { close $fh; }
629 }
630
631 sub cleanup () {
632     unlockall();
633     if (!chdir "$dgitrepos/_tmp") {
634         $!==ENOENT or die $!;
635         return;
636     }
637     foreach my $lf (<*.lock>) {
638         my $tree = $lf;
639         $tree =~ s/\.lock$//;
640         next unless acquiretree($tree, 0);
641         remove $lf or warn $!;
642         unlockall();
643     }
644 }
645
646 parseargsdispatch();
647 cleanup();