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