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