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