chiark / gitweb /
51160be419e3941a608c20f382a3f1861fd31acc
[dgit.git] / dgit-repos-server
1 #!/usr/bin/perl -w
2 # dgit-repos-push-receiver
3 #
4 # usages:
5 #  .../dgit-repos-push-receiver SUITES KEYRING-AUTH-SPEC DGIT-REPOS-DIR --ssh
6 #  .../dgit-repos-push-receiver SUITES KEYRING-AUTH-SPEC DGIT-REPOS-DIR PACKAGE
7 # internal usage:
8 #  .../dgit-repos-push-receiver --pre-receive-hook PACKAGE
9 #
10 # Invoked as the ssh restricted command
11 #
12 # Works like git-receive-pack
13 #
14 # SUITES is the name of a file which lists the permissible suites
15 # one per line (#-comments and blank lines ignored)
16 #
17 # KEYRING-AUTH-SPEC is a :-separated list of
18 #   KEYRING.GPG,AUTH-SPEC
19 # where AUTH-SPEC is one of
20 #   a
21 #   mDM.TXT
22
23 use strict;
24
25 # What we do is this:
26 #  - extract the destination repo name
27 #  - make a hardlink clone of the destination repo
28 #  - provide the destination with a stunt pre-receive hook
29 #  - run actual git-receive-pack with that new destination
30 #   as a result of this the stunt pre-receive hook runs; it does this
31 #    + understand what refs we are allegedly updating and
32 #      check some correspondences:
33 #        * we are updating only refs/tags/debian/* and refs/dgit/*
34 #        * and only one of each
35 #        * and the tag does not already exist
36 #      and
37 #        * recovering the suite name from the destination refs/dgit/ ref
38 #    + disassemble the signed tag into its various fields and signature
39 #      including:
40 #        * parsing the first line of the tag message to recover
41 #          the package name, version and suite
42 #        * checking that the package name corresponds to the dest repo name
43 #        * checking that the suite name is as recovered above
44 #    + verify the signature on the signed tag
45 #      and if necessary check that the keyid and package are listed in dm.txt
46 #    + check various correspondences:
47 #        * the suite is one of those permitted
48 #        * the signed tag must refer to a commit
49 #        * the signed tag commit must be the refs/dgit value
50 #        * the name in the signed tag must correspond to its ref name
51 #        * the tag name must be debian/<version> (massaged as needed)
52 #        * the signed tag has a suitable name
53 #        * the commit is a fast forward
54 #    + push the signed tag and new dgit branch to the actual repo
55 #
56 # If the destination repo does not already exist, we need to make
57 # sure that we create it reasonably atomically, and also that
58 # we don't every have a destination repo containing no refs at all
59 # (because such a thing causes git-fetch-pack to barf).  So then we
60 # do as above, except:
61 #  - before starting, we take out our own lock for the destination repo
62 #  - we create a prospective new destination repo by making a copy
63 #    of _template
64 #  - we use the prospective new destination repo instead of the
65 #    actual new destination repo (since the latter doesn't exist)
66 #  - we set up a post-receive hook as well, which
67 #    + checks that exactly two refs were updated
68 #    + touches a stamp file
69 #  - after git-receive-pack exits, we rename the prospective
70 #    destination repo into place
71 #
72 # Cleanup strategy:
73 #  - We are crash-only
74 #  - Temporary working trees and their locks are cleaned up
75 #    opportunistically by a program which tries to take each lock and
76 #    if successful deletes both the tree and the lockfile
77 #  - Prospective working trees and their locks are cleaned up by
78 #    a program which tries to take each lock and if successful
79 #    deletes any prospective working tree and the lock (but not
80 #    of course any actual tree)
81 #  - It is forbidden to _remove_ the lockfile without removing
82 #    the corresponding temporary tree, as the lockfile is also
83 #    a stampfile whose presence indicates that there may be
84 #    cleanup to do
85
86 use POSIX;
87 use Fcntl qw(:flock);
88
89 our $package_re = '[0-9a-z][-+.0-9a-z]+';
90
91 our $dgitrepos;
92 our $pkg;
93 our $destrepo;
94 our $workrepo;
95 our @keyrings;
96
97 sub acquirelock ($$) {
98     my ($lock, $must) = @_;
99     for (;;) {
100         my $fh = new IO::File, ">", $lock or die "open $lock: $!";
101         my $ok = flock $fh, $must ? LOCK_EX : (LOCK_EX|LOCK_NB);
102         if (!$ok) {
103             return unless $must;
104             die "flock $lock: $!";
105         }
106         if (!stat $lock) {
107             next if $! == ENOENT;
108             die "stat $lock: $!";
109         }
110         my $want = (stat _)[1];
111         stat $fh or die $!;
112         my $got = (stat _)[1];
113         return $fh if $got == $want;
114     }
115 }
116
117 sub makeworkingclone () {
118     $workrepo = "$dgitrepos/_tmp/${pkg}_incoming$$";
119     my $lock = "$workrepo.lock";
120     my $lockfh = acquirelock($lock, 1);
121     if (!stat $destrepo) {
122         $! == ENOENT or die "stat dest repo $destrepo: $!";
123         mkdir $workrepo or die "create work repo $workrepo: $!";
124         runcmd qw(git init --bare), $workrepo;
125     } else {
126         runcmd qw(git clone -l -q --mirror), $destrepo, $workrepo;
127     }
128 }
129
130 sub setupstunthook () {
131     my $prerecv = "$workrepo/hooks/pre-receive";
132     my $fh = new IO::File, $prerecv, O_WRONLY|O_CREAT|O_TRUNC, 0777
133         or die "$prerecv: $!";
134     print $fh <<END or die "$prerecv: $!";
135 #!/bin/sh
136 set -e
137 exec $0 --pre-receive-hook $pkg
138 END
139     close $fh or die "$prerecv: $!";
140     $ENV{'DGIT_RPR_WORK'}= $workrepo;
141     $ENV{'DGIT_RPR_DEST'}= $destrepo;
142 }
143
144 #----- stunt post-receive hook -----
145
146 our ($tagname, $tagval, $suite, $oldcommit, $commit);
147 our ($version, %tagh);
148
149 sub readupdates () {
150     while (<STDIN>) {
151         m/^(\S+) (\S+) (\S+)$/ or die "$_ ?";
152         my ($old, $sha1, $refname) = ($1, $2, $3);
153         if ($refname =~ m{^refs/tags/(?=debian/)}) {
154             die if defined $tagname;
155             $tagname = $'; #';
156             $tagval = $sha1;
157             reject "tag $tagname already exists -".
158                 " not replacing previously-pushed version"
159                 if $old =~ m/[^0]/;
160         } elsif ($refname =~ m{^refs/dgit/}) {
161             die if defined $suite;
162             $suite = $'; #';
163             $oldcommit = $old;
164             $commit = $sha1;
165         } else {
166             die;
167         }
168     }
169     STDIN->error and die $!;
170
171     die unless defined $refname;
172     die unless defined $branchname;
173 }
174
175 sub parsetag () {
176     open PT, ">dgit-tmp/plaintext" or die $!;
177     open DS, ">dgit-tmp/plaintext.asc" or die $!;
178     open T, "-|", qw(git cat-file tag), $tagval or die $!;
179     for (;;) {
180         $!=0; $_=<T>; defined or die $!;
181         print PT or die $!;
182         if (m/^(\S+) (.*)/) {
183             push @{ $tagh{$1} }, $2;
184         } elsif (!m/\S/) {
185             last;
186         } else {
187             die;
188         }
189     }
190     $!=0; $_=<T>; defined or die $!;
191     m/^($package_re) release (\S+) for (\S+) \[dgit\]$/ or die;
192
193     die unless $1 eq $pkg;
194     $version = $2;
195     die unless $3 eq $suite;
196
197     for (;;) {
198         print PT or die $!;
199         $!=0; $_=<T>; defined or die $!;
200         last if m/^-----BEGIN PGP/;
201     }
202     for (;;) {
203         print DS or die $!;
204         $!=0; $_=<T>;
205         last if !defined;
206     }
207     T->error and die $!;
208     close PT or die $!;
209     close DS or die $!;
210 }
211
212 sub checksig_keyring ($) {
213     my ($keyringfile) = @_;
214     # returns primary-keyid if signed by a key in this keyring
215     # or undef if not
216     # or dies on other errors
217
218     my $ok = undef;
219
220     open P, "-|", (qw(gpgv --status-fd=1),
221                    map { '--keyring', $_ }, @keyrings,
222                    qw(dgit-tmp/plaintext.asc dgit-tmp/plaintext))
223         or die $!;
224
225     while (<P>) {
226         next unless s/^\[GNUPG:\]: //;
227         chomp or die;
228         my @l = split / /, $_;
229         if ($l[0] eq 'NO_PUBKEY') {
230             last;
231         } elsif ($l[0] eq 'VALIDSIG') {
232             my $sigtype = $l[9];
233             $sigtype eq '00' or reject "signature is not of type 00!";
234             $ok = $l[10];
235             die unless defined $ok;
236             last;
237         }
238     }
239     close P;
240
241     return $ok;
242 }
243
244 sub dm_txt_check ($$) {
245     my ($keyid, $dmtxtfn) = @_;
246     open DT, '<', $dmtxtfn or die "$dmtxtfn $!";
247     while (<DT>) {
248         m/^fingerprint:\s+$keyid$/oi
249             ..0 or next;
250         m/^\S/
251             or reject "key $keyid missing Allow section in permissions!";
252         # in right stanza...
253         s/^allow:/ /i
254             ..0 or next;
255         s/^\s+//
256             or reject "package $package not allowed for key $keyid";
257         # in allow field...
258         s/\([^()]+\)//;
259         s/\,//;
260         foreach my $p (split /\s+/) {
261             return if $p eq $package; # yay!
262         }
263     }
264     DT->error and die $!;
265     close DT or die $!;
266     reject "key $keyid not in permissions list although in keyring!";
267 }
268
269 sub verifytag () {
270     foreach my $kas (split /:/, $keyrings) {
271         $kas =~ s/^([^,]+),// or die;
272         my $keyid = checksig_keyring $1;
273         if (defined $keyid) {
274             if ($kas =~ m/^a$/) {
275                 return; # yay
276             } elsif ($kas =~ m/^m([^,]+)$/) {
277                 dm_txt_check($keyid, $1);
278                 return;
279             } else {
280                 die;
281             }
282         }   
283     }
284     reject "key not found in keyrings";
285 }
286
287 sub checks () {
288 fixme check the suite against the approved list
289     tagh1('type') eq 'commit' or die;
290     tagh1('object') eq $commit or die;
291     tagh1('tag') eq $tagname or die;
292
293     my $v = $version;
294     $v =~ y/~:/_%/;
295     $tagname eq "debian/$v" or die;
296
297     # check that our ref is being fast-forwarded
298     if ($oldcommit =~ m/[^0]/) {
299         $?=0; $!=0; my $mb = `git merge-base $commit $oldcommit`;
300         chomp $mb;
301         $mb eq $oldcommit or reject "not fast forward on dgit branch";
302     }
303 }
304
305 sub onwardpush () {
306     $!=0;
307     my $r = system (qw(git send-pack),
308                     $destrepo,
309                     "$commit:refs/dgit/$suite",
310                     "$tagval:refs/tags/$tagname");
311     !$r or die "onward push failed: $r $!";
312 }       
313
314 sub stunthook () {
315     chdir $workrepo or die "chdir $workrepo: $!";
316     mkdir "dgit-tmp" or $!==EEXIST or die $!;
317     readupdates();
318     parsetag();
319     verifytag();
320     checks();
321     onwardpush();
322 }
323
324 #----- arg parsing and main program -----
325
326 sub parseargs () {
327     die unless @ARGV;
328
329     if ($ARGV[0] eq '--pre-receive-hook') {
330         shift @ARGV;
331         @ARGV == 1 or die;
332         $pkg = shift @ARGV;
333         defined($workrepo = $ENV{'DGIT_RPR_WORK'}) or die;
334         defined($destrepo = $ENV{'DGIT_RPR_DEST'}) or die;
335         defined($keyrings = $ENV{'DGIT_RPR_KEYRINGS'}) or die $!;
336         open STDOUT, ">&STDERR" or die $!;
337         stunthook();
338         exit 0;
339     }
340
341     die unless @ARGV>=3;
342
343     die if $ARGV[0] =~ m/^-/;
344     $suitesfile = shift @ARGV;
345
346     die if $ARGV[0] =~ m/^-/;
347     $ENV{'DGIT_RPR_KEYRINGS'} = shift @ARGV;
348
349     die if $ARGV[0] =~ m/^-/;
350     $dgitrepos = shift @ARGV;
351
352     die unless @ARGV;
353     if ($ARGV[0] != m/^-/) {
354         @ARGV == 1 or die;
355         $pkg = shift @ARGV;
356     } elsif ($ARGV[0] eq '--ssh') {
357         shift @ARGV;
358         !@ARGV or die;
359         my $cmd = $ENV{'SSH_ORIGINAL_COMMAND'};
360         $cmd =~ m{
361             ^
362             (?:\S*/)?
363             (git-receive-pack|git-upload-pack)
364             \s+
365             (?:\S*/)?
366             ($package_re)\.git
367             $
368         }ox 
369             or die "requested command $cmd not understood";
370         $method = $1;
371         $pkg = $2;
372         my $func = $method;
373         $func =~ y/-/_/;
374         $func = $main::{"main__$func"};
375         &$func;
376     } else {
377         die;
378     }
379
380     $destrepo = "$dgitrepos/$pkg.git";
381 }
382
383 sub main__git_receive_pack () {
384     parseargs();
385 fixme check method;
386     makeworkingclone();
387     setupstunthook();
388     runcmd qw(git receive-pack), $destdir;
389 }