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