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