chiark / gitweb /
b0064e792b131020ae9db7ec02420d198a3beb7e
[dgit.git] / infra / dgit-repos-server
1 #!/usr/bin/perl -w
2 # dgit-repos-server
3 #
4 # usages:
5 #  .../dgit-repos-server DISTRO SUITES KEYRING-AUTH-SPEC \
6 #      DGIT-REPOS-DIR POLICY-HOOK-SCRIPT --ssh
7 # internal usage:
8 #  .../dgit-repos-server --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 # DGIT-REPOS-DIR contains:
26 # git tree (or other object)      lock (in acquisition order, outer first)
27 #
28 #  _tmp/PACKAGE_prospective       ! } SAME.lock, held during receive-pack
29 #
30 #  _tmp/PACKAGE_incoming$$        ! } SAME.lock, held during receive-pack
31 #  _tmp/PACKAGE_incoming$$_fresh  ! }
32 #
33 #  PACKAGE.git                      } PACKAGE.git.lock
34 #  PACKAGE_garbage                  }   (also covers executions of
35 #  PACKAGE_garbage-old              }    policy hook script for PACKAGE)
36 #  PACKAGE_garbage-tmp              }
37 #
38 # leaf locks, held during brief operaton only:
39 #
40 #  _empty                           } SAME.lock
41 #  _empty.new                       }
42 #
43 #  _template                        } SAME.lock
44 #
45 # locks marked ! may be held during client data transfer
46
47 # What we do on push is this:
48 #  - extract the destination repo name
49 #  - make a hardlink clone of the destination repo
50 #  - provide the destination with a stunt pre-receive hook
51 #  - run actual git-receive-pack with that new destination
52 #   as a result of this the stunt pre-receive hook runs; it does this:
53 #    + understand what refs we are allegedly updating and
54 #      check some correspondences:
55 #        * we are updating only refs/tags/debian/* and refs/dgit/*
56 #        * and only one of each
57 #        * and the tag does not already exist
58 #      and
59 #        * recover the suite name from the destination refs/dgit/ ref
60 #    + disassemble the signed tag into its various fields and signature
61 #      including:
62 #        * parsing the first line of the tag message to recover
63 #          the package name, version and suite
64 #        * checking that the package name corresponds to the dest repo name
65 #        * checking that the suite name is as recovered above
66 #    + verify the signature on the signed tag
67 #      and if necessary check that the keyid and package are listed in dm.txt
68 #    + check various correspondences:
69 #        * the signed tag must refer to a commit
70 #        * the signed tag commit must be the refs/dgit value
71 #        * the name in the signed tag must correspond to its ref name
72 #        * the tag name must be debian/<version> (massaged as needed)
73 #        * the suite is one of those permitted
74 #        * the signed tag has a suitable name
75 #        * run the "push" policy hook
76 #        * replay prevention for --deliberately-not-fast-forward
77 #        * check the commit is a fast forward
78 #        * handle a request from the policy hook for a fresh repo
79 #    + push the signed tag and new dgit branch to the actual repo
80 #
81 # If the destination repo does not already exist, we need to make
82 # sure that we create it reasonably atomically, and also that
83 # we don't every have a destination repo containing no refs at all
84 # (because such a thing causes git-fetch-pack to barf).  So then we
85 # do as above, except:
86 #  - before starting, we take out our own lock for the destination repo
87 #  - we create a prospective new destination repo by making a copy
88 #    of _template
89 #  - we use the prospective new destination repo instead of the
90 #    actual new destination repo (since the latter doesn't exist)
91 #  - after git-receive-pack exits, we
92 #    + check that the prospective repo contains a tag and head
93 #    + rename the prospective destination repo into place
94 #
95 # Cleanup strategy:
96 #  - We are crash-only
97 #  - Temporary working trees and their locks are cleaned up
98 #    opportunistically by a program which tries to take each lock and
99 #    if successful deletes both the tree and the lockfile
100 #  - Prospective working trees and their locks are cleaned up by
101 #    a program which tries to take each lock and if successful
102 #    deletes any prospective working tree and the lock (but not
103 #    of course any actual tree)
104 #  - It is forbidden to _remove_ the lockfile without removing
105 #    the corresponding temporary tree, as the lockfile is also
106 #    a stampfile whose presence indicates that there may be
107 #    cleanup to do
108
109 use POSIX;
110 use Fcntl qw(:flock);
111 use File::Path qw(rmtree);
112
113 use Debian::Dgit qw(:DEFAULT :policyflags);
114
115 open DEBUG, ">/dev/null" or die $!;
116
117 our $func;
118 our $dgitrepos;
119 our $package;
120 our $suitesfile;
121 our $policyhook;
122 our $realdestrepo;
123 our $destrepo;
124 our $workrepo;
125 our $keyrings;
126 our @lockfhs;
127 our $debug='';
128 our @deliberatelies;
129 our %supersedes;
130 our $policy;
131
132 #----- utilities -----
133
134 sub debug {
135     print DEBUG "$debug @_\n";
136 }
137
138 sub acquirelock ($$) {
139     my ($lock, $must) = @_;
140     my $fh;
141     printf DEBUG "$debug locking %s %d\n", $lock, $must;
142     for (;;) {
143         close $fh if $fh;
144         $fh = new IO::File $lock, ">" or die "open $lock: $!";
145         my $ok = flock $fh, $must ? LOCK_EX : (LOCK_EX|LOCK_NB);
146         if (!$ok) {
147             die "flock $lock: $!" if $must;
148             debug " locking $lock failed";
149             return undef;
150         }
151         next unless stat_exists $lock;
152         my $want = (stat _)[1];
153         stat $fh or die $!;
154         my $got = (stat _)[1];
155         last if $got == $want;
156     }
157     return $fh;
158 }
159
160 sub acquiretree ($$) {
161     my ($tree, $must) = @_;
162     my $fh = acquirelock("$tree.lock", $must);
163     if ($fh) {
164         push @lockfhs, $fh;
165         rmtree $tree;
166     }
167     return $fh;
168 }
169
170 sub mkrepotmp () {
171     my $tmpdir = "$dgitrepos/_tmp";
172     return if mkdir $tmpdir;
173     return if $! == EEXIST;
174     die $!;
175 }
176
177 sub recorderror ($) {
178     my ($why) = @_;
179     my $w = $ENV{'DGIT_DRS_WORK'}; # we are in stunthook
180     if (defined $w) {
181         chomp $why;
182         open ERR, ">", "$w/drs-error" or die $!;
183         print ERR $why, "\n" or die $!;
184         close ERR or die $!;
185         return 1;
186     }
187     return 0;
188 }
189
190 sub reject ($) {
191     my ($why) = @_;
192     recorderror "reject: $why";
193     die "dgit-repos-server: reject: $why\n";
194 }
195
196 sub debugcmd {
197     if ($debug) {
198         use Data::Dumper;
199         local $Data::Dumper::Indent = 0;
200         local $Data::Dumper::Terse = 1;
201         debug "|".Dumper(\@_);
202     }
203 }
204
205 sub runcmd {
206     debugcmd @_;
207     $!=0; $?=0;
208     my $r = system @_;
209     die "@_ $? $!" if $r;
210 }
211
212 sub policyhook {
213     my ($policyallowbits, @polargs) = @_;
214     # => ($exitstatuspolicybitmap, $policylockfh);
215     die if $policyallowbits & ~0x3e;
216     my @cmd = ($policyhook,$distro,$repos,@polargs);
217     debugcmd @_;
218     my $r = system @_;
219     die "system: $!" if $r < 0;
220     die "hook (@cmd) failed ($?)" if $r & ~($policyallowbits << 8);
221     return $r >> 8;
222 }
223
224 sub mkemptyrepo ($$) {
225     my ($dir,$sharedperm) = @_;
226     runcmd qw(git init --bare --quiet), "--shared=$sharedperm", $dir;
227 }
228
229 sub mkrepo_fromtemplate ($) {
230     my ($dir) = @_;
231     my $template = "$dgitrepos/_template";
232     acquiretree($template,1);
233     debug "copy template $template -> $dir";
234     my $r = system qw(cp -a --), $template, $dir;
235     !$r or die "create new repo $dir failed: $r $!";
236 }
237
238 sub movetogarbage () {
239     # $realdestrepo must have been locked
240     my $garbagerepo = "$dgitrepos/${package}_garbage";
241     # We arrange to always keep at least one old tree, for anti-rewind
242     # purposes (and, I guess, recovery from mistakes).  This is either
243     # $garbage or $garbage-old.
244     if (stat_exists "$garbagerepo") {
245         rmtree "$garbagerepo-tmp";
246         if (rename "$garbagerepo-old", "$garbagerepo-tmp") {
247             rmtree "$garbagerepo-tmp";
248         } else {
249             die "$garbagerepo $!" unless $!==ENOENT;
250         }
251         rename "$garbagerepo", "$garbagerepo-old" or die "$garbagerepo $!";
252     }
253     rename $realdestrepo, $garbagerepo
254         or $! == ENOENT
255         or die "$garbagerepo $!";
256 }
257
258 sub onwardpush () {
259     my @cmd = (qw(git send-pack), $destrepo);
260     push @cmd, qw(--force) if $policy & NOFFCHECK;
261     push @cmd, "$commit:refs/dgit/$suite",
262                "$tagval:refs/tags/$tagname");
263     debugcmd @cmd;
264     $!=0;
265     my $r = system @cmd;
266     !$r or die "onward push to $destrepo failed: $r $!";
267 }
268
269 #----- git-receive-pack -----
270
271 sub fixmissing__git_receive_pack () {
272     mkrepotmp();
273     $destrepo = "$dgitrepos/_tmp/${package}_prospective";
274     acquiretree($destrepo, 1);
275     mkrepo_fromtemplate($destrepo);
276 }
277
278 sub makeworkingclone () {
279     mkrepotmp();
280     $workrepo = "$dgitrepos/_tmp/${package}_incoming$$";
281     acquiretree($workrepo, 1);
282     my $lfh = acquiretree($realdestrepo, 1);
283     runcmd qw(git clone -l -q --mirror), $destrepo, $workrepo;
284     close $lfh;
285     rmtree "${workrepo}_fresh";
286 }
287
288 sub setupstunthook () {
289     my $prerecv = "$workrepo/hooks/pre-receive";
290     my $fh = new IO::File $prerecv, O_WRONLY|O_CREAT|O_TRUNC, 0777
291         or die "$prerecv: $!";
292     print $fh <<END or die "$prerecv: $!";
293 #!/bin/sh
294 set -e
295 exec $0 --pre-receive-hook $package
296 END
297     close $fh or die "$prerecv: $!";
298     $ENV{'DGIT_DRS_WORK'}= $workrepo;
299     $ENV{'DGIT_DRS_DEST'}= $destrepo;
300     debug " stunt hook set up $prerecv";
301 }
302
303 sub dealwithfreshrepo () {
304     my $freshrepo = "${workrepo}_fresh";
305     return unless stat_exists $freshrepo;
306     $destrepo = $freshrepo;
307 }
308
309 sub maybeinstallprospective () {
310     return if $destrepo eq $realdestrepo;
311
312     if (open REJ, "<", "$workrepo/drs-error") {
313         local $/ = undef;
314         my $msg = <REJ>;
315         REJ->error and die $!;
316         print STDERR $msg;
317         exit 1;
318     } else {
319         $!==&ENOENT or die $!;
320     }
321
322     debug " show-ref ($destrepo) ...";
323
324     my $child = open SR, "-|";
325     defined $child or die $!;
326     if (!$child) {
327         chdir $destrepo or die $!;
328         exec qw(git show-ref);
329         die $!;
330     }
331     my %got = qw(tag 0 head 0);
332     while (<SR>) {
333         chomp or die;
334         debug " show-refs| $_";
335         s/^\S*[1-9a-f]\S* (\S+)$/$1/ or die;
336         my $wh =
337             m{^refs/tags/} ? 'tag' :
338             m{^refs/dgit/} ? 'head' :
339             die;
340         die if $got{$wh}++;
341     }
342     $!=0; $?=0; close SR or $?==256 or die "$? $!";
343
344     debug "installprospective ?";
345     die Dumper(\%got)." -- missing refs in new repo"
346         if grep { !$_ } values %got;
347
348     acquiretree($realdestrepo,1);
349
350     if ($destrepo eq "${workrepo}_fresh") {
351         movetogarbage;
352     }
353
354     debug "install $destrepo => $realdestrepo";
355     rename $destrepo, $realdestrepo or die $!;
356     remove "$destrepo.lock" or die $!;
357 }
358
359 sub main__git_receive_pack () {
360     makeworkingclone();
361     setupstunthook();
362     runcmd qw(git receive-pack), $workrepo;
363     dealwithfreshrepo();
364     maybeinstallprospective();
365 }
366
367 #----- stunt post-receive hook -----
368
369 our ($tagname, $tagval, $suite, $oldcommit, $commit);
370 our ($version, %tagh);
371
372 sub readupdates () {
373     debug " updates ...";
374     while (<STDIN>) {
375         chomp or die;
376         debug " upd.| $_";
377         m/^(\S+) (\S+) (\S+)$/ or die "$_ ?";
378         my ($old, $sha1, $refname) = ($1, $2, $3);
379         if ($refname =~ m{^refs/tags/(?=debian/)}) {
380             reject "pushing multiple tags!" if defined $tagname;
381             $tagname = $'; #';
382             $tagval = $sha1;
383             reject "tag $tagname already exists -".
384                 " not replacing previously-pushed version"
385                 if $old =~ m/[^0]/;
386         } elsif ($refname =~ m{^refs/dgit/}) {
387             reject "pushing multiple heads!" if defined $suite;
388             $suite = $'; #';
389             $oldcommit = $old;
390             $commit = $sha1;
391         } else {
392             reject "pushing unexpected ref!";
393         }
394     }
395     STDIN->error and die $!;
396
397     reject "push is missing tag ref update" unless defined $tagname;
398     reject "push is missing head ref update" unless defined $suite;
399     debug " updates ok.";
400 }
401
402 sub parsetag () {
403     debug " parsetag...";
404     open PT, ">dgit-tmp/plaintext" or die $!;
405     open DS, ">dgit-tmp/plaintext.asc" or die $!;
406     open T, "-|", qw(git cat-file tag), $tagval or die $!;
407     for (;;) {
408         $!=0; $_=<T>; defined or die $!;
409         print PT or die $!;
410         if (m/^(\S+) (.*)/) {
411             push @{ $tagh{$1} }, $2;
412         } elsif (!m/\S/) {
413             last;
414         } else {
415             die;
416         }
417     }
418     $!=0; $_=<T>; defined or die $!;
419     m/^($package_re) release (\S+) for \S+ \((\S+)\) \[dgit\]$/ or
420         reject "tag message not in expected format";
421
422     die unless $1 eq $package;
423     $version = $2;
424     die "$3 != $suite " unless $3 eq $suite;
425
426     for (;;) {
427         print PT or die $!;
428         $!=0; $_=<T>; defined or die "missing signature? $!";
429         if (m/^\[dgit ([^"].*)\]$/) { # [dgit "something"] is for future
430             $_ = $1." ";
431             for (;;) {
432                 if (s/^distro\=(\S+) //) {
433                     die "$1 != $distro" unless $1 eq $distro;
434                 } elsif (s/^(--deliberately-$package_re) //) {
435                     push @deliberatelies, $1;
436                 } elsif (s/^supersede:(\S+)=(\w+) //) {
437                     die "supersede $1 twice" if defined $supersedes{$1};
438                     $supersedes{$1} = $2;
439                 } elsif (s/^[-+.=0-9a-z]\S* //) {
440                 } else {
441                     die "unknown dgit info in tag";
442                 }
443             }
444             next;
445         }
446         last if m/^-----BEGIN PGP/;
447     }
448     for (;;) {
449         print DS or die $!;
450         $!=0; $_=<T>;
451         last if !defined;
452     }
453     T->error and die $!;
454     close PT or die $!;
455     close DS or die $!;
456     debug " parsetag ok.";
457 }
458
459 sub checksig_keyring ($) {
460     my ($keyringfile) = @_;
461     # returns primary-keyid if signed by a key in this keyring
462     # or undef if not
463     # or dies on other errors
464
465     my $ok = undef;
466
467     debug " checksig keyring $keyringfile...";
468
469     our @cmd = (qw(gpgv --status-fd=1 --keyring),
470                    $keyringfile,
471                    qw(dgit-tmp/plaintext.asc dgit-tmp/plaintext));
472     debugcmd @cmd;
473
474     open P, "-|", @cmd
475         or die $!;
476
477     while (<P>) {
478         next unless s/^\[GNUPG:\] //;
479         chomp or die;
480         debug " checksig| $_";
481         my @l = split / /, $_;
482         if ($l[0] eq 'NO_PUBKEY') {
483             last;
484         } elsif ($l[0] eq 'VALIDSIG') {
485             my $sigtype = $l[9];
486             $sigtype eq '00' or reject "signature is not of type 00!";
487             $ok = $l[10];
488             die unless defined $ok;
489             last;
490         }
491     }
492     close P;
493
494     debug sprintf " checksig ok=%d", !!$ok;
495
496     return $ok;
497 }
498
499 sub dm_txt_check ($$) {
500     my ($keyid, $dmtxtfn) = @_;
501     debug " dm_txt_check $keyid $dmtxtfn";
502     open DT, '<', $dmtxtfn or die "$dmtxtfn $!";
503     while (<DT>) {
504         m/^fingerprint:\s+$keyid$/oi
505             ..0 or next;
506         if (s/^allow:/ /i..0) {
507         } else {
508             m/^./
509                 or reject "key $keyid missing Allow section in permissions!";
510             next;
511         }
512         # in right stanza...
513         s/^[ \t]+//
514             or reject "package $package not allowed for key $keyid";
515         # in allow field...
516         s/\([^()]+\)//;
517         s/\,//;
518         chomp or die;
519         debug " dm_txt_check allow| $_";
520         foreach my $p (split /\s+/) {
521             if ($p eq $package) {
522                 # yay!
523                 debug " dm_txt_check ok";
524                 return;
525             }
526         }
527     }
528     DT->error and die $!;
529     close DT or die $!;
530     reject "key $keyid not in permissions list although in keyring!";
531 }
532
533 sub verifytag () {
534     foreach my $kas (split /:/, $keyrings) {
535         debug "verifytag $kas...";
536         $kas =~ s/^([^,]+),// or die;
537         my $keyid = checksig_keyring $1;
538         if (defined $keyid) {
539             if ($kas =~ m/^a$/) {
540                 debug "verifytag a ok";
541                 return; # yay
542             } elsif ($kas =~ m/^m([^,]+)$/) {
543                 dm_txt_check($keyid, $1);
544                 debug "verifytag m ok";
545                 return;
546             } else {
547                 die;
548             }
549         }   
550     }
551     reject "key not found in keyrings";
552 }
553
554 sub checksuite () {
555     debug "checksuite ($suitesfile)";
556     open SUITES, "<", $suitesfile or die $!;
557     while (<SUITES>) {
558         chomp;
559         next unless m/\S/;
560         next if m/^\#/;
561         s/\s+$//;
562         return if $_ eq $suite;
563     }
564     die $! if SUITES->error;
565     reject "unknown suite";
566 }
567
568 sub checktagnoreplay () {
569     # We check that the signed tag mentions the name and value of
570     # (a) in the case of FRESHREPO all tags in the repo;
571     # (b) in the case of just NOFFCHECK all tags referring to
572     # the current head for the suite (there must be at least one).
573     # This prevents a replay attack using an earlier signed tag.
574     return unless $policy & (FRESHREPO|NOFFCHECK);
575
576     my $garbagerepo = "$dgitrepos/${package}_garbage";
577     acquiretree($realdestrepo,1);
578
579     local $ENV{GIT_DIR};
580     foreach my $garb ("$garbagerepo", "$garbagerepo-old") {
581         if (stat_exists $garb) {
582             $ENV{GIT_DIR} = $garb;
583             last;
584         }
585     }
586     if (!defined $ENV{GIT_DIR}) {
587         # Nothing to overwrite so the FRESHREPO and NOFFCHECK were
588         # pointless.  Oh well.
589         debug "checktagnoreplay - no garbage, ok";
590         return;
591     }
592
593     my $onlyreferring;
594     if (!($policy & FRESHREPO)) {
595         my $branch = server_branch($suite);
596         $!=0; $?=0; $_ =
597             `git for-each-ref --format='%(objectname)' '[r]efs/$branch'`;
598         defined or die "$branch $? $!";
599         $? and die "$branch $?";
600         if (!length) {
601             # No such branch - NOFFCHECK was unnecessary.  Oh well.
602             debug "checktagnoreplay - not FRESHREPO, new branch, ok";
603             return;
604         }
605         m/^(\w+)\n$/ or die "$branch $_ ?";
606         $onlyreferring = $1;
607         debug "checktagnoreplay - not FRESHREPO,".
608             " checking for overwriting refs/$branch=$onlyreferring";
609     }
610
611     my @problems;
612
613     git_for_each_tag_referring($objreferring, sub {
614         my ($objid,$fullrefname,$tagname) = @_;
615         debug "checktagnoreplay - overwriting $fullrefname=$objid";
616         my $supers = $supersedes{$fullrefname};
617         if (!defined $supers) {
618             push @problems, "does not supersede $fullrefname";
619         } elsif ($supers ne $objid) {
620             push @problems,
621  "supersedes $fullrefname=$supers but previously $fullrefname=$objid";
622         } else {
623             # ok;
624         }
625     });
626
627     if (@problems) {
628         reject "replay attack prevention check failed:".
629             " signed tag for $version: ".
630             join("; ", @problems).
631             "\n";
632     }
633     debug "checktagnoreply - all ok"
634 }
635
636 sub tagh1 ($) {
637     my ($tag) = @_;
638     my $vals = $tagh{$tag};
639     reject "missing header $tag in signed tag object" unless $vals;
640     reject "multiple headers $tag in signed tag object" unless @$vals == 1;
641     return $vals->[0];
642 }
643
644 sub checks () {
645     debug "checks";
646
647     tagh1('type') eq 'commit' or reject "tag refers to wrong kind of object";
648     tagh1('object') eq $commit or reject "tag refers to wrong commit";
649     tagh1('tag') eq $tagname or reject "tag name in tag is wrong";
650
651     my $v = $version;
652     $v =~ y/~:/_%/;
653
654     debug "translated version $v";
655     $tagname eq "debian/$v" or die;
656
657     acquiretree($realdestrepo,1);
658
659     $policy = policyhook(NOFFCHECK|FRESHREPO, 'push',$package,
660                          $version,$suite,$tagname,
661                          join(",",@delberatelies));
662
663     checktagnoreplay();
664     checksuite();
665
666     # check that our ref is being fast-forwarded
667     debug "oldcommit $oldcommit";
668     if (!($policy & NOFFCHECK) && $oldcommit =~ m/[^0]/) {
669         $?=0; $!=0; my $mb = `git merge-base $commit $oldcommit`;
670         chomp $mb;
671         $mb eq $oldcommit or reject "not fast forward on dgit branch";
672     }
673
674     if ($policy & FRESHREPO) {
675         # This is troublesome.  We have been asked by the policy hook
676         # to receive the push into a fresh repo.  But of course we
677         # have actually already mostly received the push into the working
678         # repo.  (This is unavoidable because the instruction to use a new
679         # repo comes ultimately from the signed tag for the dgit push,
680         # which has to have been received into some repo.)
681         #
682         # So what we do is generate a fresh working repo right now and
683         # push the head and tag into it.  The presence of this fresh
684         # working repo is detected by the parent, which responds by
685         # making a fresh master repo from the template.
686
687         $destrepo = "${workrepo}_fresh"; # workrepo lock covers
688         mkrepo_fromtemplate $destrepo;
689     }
690 }
691
692 sub stunthook () {
693     debug "stunthook";
694     chdir $workrepo or die "chdir $workrepo: $!";
695     mkdir "dgit-tmp" or $!==EEXIST or die $!;
696     readupdates();
697     parsetag();
698     verifytag();
699     checks();
700     onwardpush();
701     debug "stunthook done.";
702 }
703
704 #----- git-upload-pack -----
705
706 sub fixmissing__git_upload_pack () {
707     $destrepo = "$dgitrepos/_empty";
708     my $lfh = acquiretree($destrepo,1);
709     return if stat_exists $destrepo;
710     rmtree "$destrepo.new";
711     mkemptyrepo "$destrepo.new", "0644";
712     rename "$destrepo.new", $destrepo or die $!;
713     unlink "$destrepo.lock" or die $!;
714     close $lfh;
715 }
716
717 sub main__git_upload_pack () {
718     my $lfh = acquiretree($destrepo,1);
719     chdir $destrepo or die "$destrepo: $!";
720     close $lfh;
721     runcmd qw(git upload-pack), ".";
722 }
723
724 #----- arg parsing and main program -----
725
726 sub argval () {
727     die unless @ARGV;
728     my $v = shift @ARGV;
729     die if $v =~ m/^-/;
730     return $v;
731 }
732
733 sub parseargsdispatch () {
734     die unless @ARGV;
735
736     delete $ENV{'GIT_DIR'}; # if not run via ssh, our parent git process
737     delete $ENV{'GIT_PREFIX'}; # sets these and they mess things up
738
739     if ($ENV{'DGIT_DRS_DEBUG'}) {
740         $debug='=';
741         open DEBUG, ">&STDERR" or die $!;
742     }
743
744     if ($ARGV[0] eq '--pre-receive-hook') {
745         if ($debug) { $debug.="="; }
746         shift @ARGV;
747         @ARGV == 1 or die;
748         $package = shift @ARGV;
749         defined($distro = $ENV{'DGIT_DRS_DISTRO'}) or die;
750         defined($suitesfile = $ENV{'DGIT_DRS_SUITES'}) or die;
751         defined($workrepo = $ENV{'DGIT_DRS_WORK'}) or die;
752         defined($destrepo = $ENV{'DGIT_DRS_DEST'}) or die;
753         defined($keyrings = $ENV{'DGIT_DRS_KEYRINGS'}) or die $!;
754         defined($policyhook = $ENV{'DGIT_DRS_POLICYHOOK'}) or die $!;
755         open STDOUT, ">&STDERR" or die $!;
756         eval {
757             stunthook();
758         };
759         if ($@) {
760             recorderror "$@" or die;
761             die $@;
762         }
763         exit 0;
764     }
765
766     $ENV{'DGIT_DRS_DISTRO'} = argval();
767     $ENV{'DGIT_DRS_SUITES'} = argval();
768     $ENV{'DGIT_DRS_KEYRINGS'} = argval();
769     $dgitrepos = argval();
770     $ENV{'DGIT_DRS_POLICYHOOK'} = $policyhook = argval();
771
772     die unless @ARGV==1 && $ARGV[0] eq '--ssh';
773
774     my $cmd = $ENV{'SSH_ORIGINAL_COMMAND'};
775     $cmd =~ m{
776         ^
777         (?: \S* / )?
778         ( [-0-9a-z]+ )
779         \s+
780         '? (?: \S* / )?
781         ($package_re) \.git
782         '?$
783     }ox 
784     or reject "command string not understood";
785     my $method = $1;
786     $package = $2;
787     $realdestrepo = "$dgitrepos/$package.git";
788
789     my $funcn = $method;
790     $funcn =~ y/-/_/;
791     my $mainfunc = $main::{"main__$funcn"};
792
793     reject "unknown method" unless $mainfunc;
794
795     my $lfh = acquiretree($realdestrepo,1);
796
797     my ($policy, $pollock) = policyhook(FRESHREPO,'check-package',$package);
798     if ($policy & FRESHREPO) {
799         movetogarbage;
800     }
801     close $pollock or die $!;
802
803     close $lfh;
804
805     if (stat_exists $realdestrepo) {
806         $destrepo = $realdestrepo;
807     } else {
808         debug " fixmissing $funcn";
809         my $fixfunc = $main::{"fixmissing__$funcn"};
810         &$fixfunc;
811     }
812
813     debug " running main $funcn";
814     &$mainfunc;
815 }
816
817 sub unlockall () {
818     while (my $fh = pop @lockfhs) { close $fh; }
819 }
820
821 sub cleanup () {
822     unlockall();
823     if (!chdir "$dgitrepos/_tmp") {
824         $!==ENOENT or die $!;
825         return;
826     }
827     foreach my $lf (<*.lock>) {
828         my $tree = $lf;
829         $tree =~ s/\.lock$//;
830         next unless acquiretree($tree, 0);
831         remove $lf or warn $!;
832         unlockall();
833     }
834 }
835
836 parseargsdispatch();
837 cleanup();