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