chiark / gitweb /
dgit-repos-server: Further fixes to locking; rename acquiretree to acquirermtree
[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 acquirermtree ($$) {
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 locksometree ($) {
171     my ($tree) = @_;
172     acquirelock("$tree.lock", 1);
173 }
174
175 sub lockrealtree () {
176     locksometree($realdestrepo);
177 }
178
179 sub mkrepotmp () {
180     my $tmpdir = "$dgitrepos/_tmp";
181     return if mkdir $tmpdir;
182     return if $! == EEXIST;
183     die $!;
184 }
185
186 sub recorderror ($) {
187     my ($why) = @_;
188     my $w = $ENV{'DGIT_DRS_WORK'}; # we are in stunthook
189     if (defined $w) {
190         chomp $why;
191         open ERR, ">", "$w/drs-error" or die $!;
192         print ERR $why, "\n" or die $!;
193         close ERR or die $!;
194         return 1;
195     }
196     return 0;
197 }
198
199 sub reject ($) {
200     my ($why) = @_;
201     recorderror "reject: $why";
202     die "dgit-repos-server: reject: $why\n";
203 }
204
205 sub debugcmd {
206     if ($debug) {
207         use Data::Dumper;
208         local $Data::Dumper::Indent = 0;
209         local $Data::Dumper::Terse = 1;
210         debug "|".Dumper(\@_);
211     }
212 }
213
214 sub runcmd {
215     debugcmd @_;
216     $!=0; $?=0;
217     my $r = system @_;
218     die "@_ $? $!" if $r;
219 }
220
221 sub policyhook {
222     my ($policyallowbits, @polargs) = @_;
223     # => ($exitstatuspolicybitmap);
224     die if $policyallowbits & ~0x3e;
225     my @cmd = ($policyhook,$distro,$repos,@polargs);
226     debugcmd @_;
227     my $r = system @_;
228     die "system: $!" if $r < 0;
229     die "hook (@cmd) failed ($?)" if $r & ~($policyallowbits << 8);
230     return $r >> 8;
231 }
232
233 sub mkemptyrepo ($$) {
234     my ($dir,$sharedperm) = @_;
235     runcmd qw(git init --bare --quiet), "--shared=$sharedperm", $dir;
236 }
237
238 sub mkrepo_fromtemplate ($) {
239     my ($dir) = @_;
240     my $template = "$dgitrepos/_template";
241     locksometree($template);
242     debug "copy template $template -> $dir";
243     my $r = system qw(cp -a --), $template, $dir;
244     !$r or die "create new repo $dir failed: $r $!";
245 }
246
247 sub movetogarbage () {
248     # $realdestrepo must have been locked
249     my $garbagerepo = "$dgitrepos/${package}_garbage";
250     # We arrange to always keep at least one old tree, for anti-rewind
251     # purposes (and, I guess, recovery from mistakes).  This is either
252     # $garbage or $garbage-old.
253     if (stat_exists "$garbagerepo") {
254         rmtree "$garbagerepo-tmp";
255         if (rename "$garbagerepo-old", "$garbagerepo-tmp") {
256             rmtree "$garbagerepo-tmp";
257         } else {
258             die "$garbagerepo $!" unless $!==ENOENT;
259         }
260         rename "$garbagerepo", "$garbagerepo-old" or die "$garbagerepo $!";
261     }
262     rename $realdestrepo, $garbagerepo
263         or $! == ENOENT
264         or die "$garbagerepo $!";
265 }
266
267 sub onwardpush () {
268     my @cmd = (qw(git send-pack), $destrepo);
269     push @cmd, qw(--force) if $policy & NOFFCHECK;
270     push @cmd, "$commit:refs/dgit/$suite",
271                "$tagval:refs/tags/$tagname");
272     debugcmd @cmd;
273     $!=0;
274     my $r = system @cmd;
275     !$r or die "onward push to $destrepo failed: $r $!";
276 }
277
278 #----- git-receive-pack -----
279
280 sub fixmissing__git_receive_pack () {
281     mkrepotmp();
282     $destrepo = "$dgitrepos/_tmp/${package}_prospective";
283     acquirermtree($destrepo, 1);
284     mkrepo_fromtemplate($destrepo);
285 }
286
287 sub makeworkingclone () {
288     mkrepotmp();
289     $workrepo = "$dgitrepos/_tmp/${package}_incoming$$";
290     acquirermtree($workrepo, 1);
291     my $lfh = lockrealtree();
292     runcmd qw(git clone -l -q --mirror), $destrepo, $workrepo;
293     close $lfh;
294     rmtree "${workrepo}_fresh";
295 }
296
297 sub setupstunthook () {
298     my $prerecv = "$workrepo/hooks/pre-receive";
299     my $fh = new IO::File $prerecv, O_WRONLY|O_CREAT|O_TRUNC, 0777
300         or die "$prerecv: $!";
301     print $fh <<END or die "$prerecv: $!";
302 #!/bin/sh
303 set -e
304 exec $0 --pre-receive-hook $package
305 END
306     close $fh or die "$prerecv: $!";
307     $ENV{'DGIT_DRS_WORK'}= $workrepo;
308     $ENV{'DGIT_DRS_DEST'}= $destrepo;
309     debug " stunt hook set up $prerecv";
310 }
311
312 sub dealwithfreshrepo () {
313     my $freshrepo = "${workrepo}_fresh";
314     return unless stat_exists $freshrepo;
315     $destrepo = $freshrepo;
316 }
317
318 sub maybeinstallprospective () {
319     return if $destrepo eq $realdestrepo;
320
321     if (open REJ, "<", "$workrepo/drs-error") {
322         local $/ = undef;
323         my $msg = <REJ>;
324         REJ->error and die $!;
325         print STDERR $msg;
326         exit 1;
327     } else {
328         $!==&ENOENT or die $!;
329     }
330
331     debug " show-ref ($destrepo) ...";
332
333     my $child = open SR, "-|";
334     defined $child or die $!;
335     if (!$child) {
336         chdir $destrepo or die $!;
337         exec qw(git show-ref);
338         die $!;
339     }
340     my %got = qw(tag 0 head 0);
341     while (<SR>) {
342         chomp or die;
343         debug " show-refs| $_";
344         s/^\S*[1-9a-f]\S* (\S+)$/$1/ or die;
345         my $wh =
346             m{^refs/tags/} ? 'tag' :
347             m{^refs/dgit/} ? 'head' :
348             die;
349         die if $got{$wh}++;
350     }
351     $!=0; $?=0; close SR or $?==256 or die "$? $!";
352
353     debug "installprospective ?";
354     die Dumper(\%got)." -- missing refs in new repo"
355         if grep { !$_ } values %got;
356
357     lockrealtree();
358
359     if ($destrepo eq "${workrepo}_fresh") {
360         movetogarbage;
361     }
362
363     debug "install $destrepo => $realdestrepo";
364     rename $destrepo, $realdestrepo or die $!;
365     remove "$destrepo.lock" or die $!;
366 }
367
368 sub main__git_receive_pack () {
369     makeworkingclone();
370     setupstunthook();
371     runcmd qw(git receive-pack), $workrepo;
372     dealwithfreshrepo();
373     maybeinstallprospective();
374 }
375
376 #----- stunt post-receive hook -----
377
378 our ($tagname, $tagval, $suite, $oldcommit, $commit);
379 our ($version, %tagh);
380
381 sub readupdates () {
382     debug " updates ...";
383     while (<STDIN>) {
384         chomp or die;
385         debug " upd.| $_";
386         m/^(\S+) (\S+) (\S+)$/ or die "$_ ?";
387         my ($old, $sha1, $refname) = ($1, $2, $3);
388         if ($refname =~ m{^refs/tags/(?=debian/)}) {
389             reject "pushing multiple tags!" if defined $tagname;
390             $tagname = $'; #';
391             $tagval = $sha1;
392             reject "tag $tagname already exists -".
393                 " not replacing previously-pushed version"
394                 if $old =~ m/[^0]/;
395         } elsif ($refname =~ m{^refs/dgit/}) {
396             reject "pushing multiple heads!" if defined $suite;
397             $suite = $'; #';
398             $oldcommit = $old;
399             $commit = $sha1;
400         } else {
401             reject "pushing unexpected ref!";
402         }
403     }
404     STDIN->error and die $!;
405
406     reject "push is missing tag ref update" unless defined $tagname;
407     reject "push is missing head ref update" unless defined $suite;
408     debug " updates ok.";
409 }
410
411 sub parsetag () {
412     debug " parsetag...";
413     open PT, ">dgit-tmp/plaintext" or die $!;
414     open DS, ">dgit-tmp/plaintext.asc" or die $!;
415     open T, "-|", qw(git cat-file tag), $tagval or die $!;
416     for (;;) {
417         $!=0; $_=<T>; defined or die $!;
418         print PT or die $!;
419         if (m/^(\S+) (.*)/) {
420             push @{ $tagh{$1} }, $2;
421         } elsif (!m/\S/) {
422             last;
423         } else {
424             die;
425         }
426     }
427     $!=0; $_=<T>; defined or die $!;
428     m/^($package_re) release (\S+) for \S+ \((\S+)\) \[dgit\]$/ or
429         reject "tag message not in expected format";
430
431     die unless $1 eq $package;
432     $version = $2;
433     die "$3 != $suite " unless $3 eq $suite;
434
435     for (;;) {
436         print PT or die $!;
437         $!=0; $_=<T>; defined or die "missing signature? $!";
438         if (m/^\[dgit ([^"].*)\]$/) { # [dgit "something"] is for future
439             $_ = $1." ";
440             for (;;) {
441                 if (s/^distro\=(\S+) //) {
442                     die "$1 != $distro" unless $1 eq $distro;
443                 } elsif (s/^(--deliberately-$package_re) //) {
444                     push @deliberatelies, $1;
445                 } elsif (s/^supersede:(\S+)=(\w+) //) {
446                     die "supersede $1 twice" if defined $supersedes{$1};
447                     $supersedes{$1} = $2;
448                 } elsif (s/^[-+.=0-9a-z]\S* //) {
449                 } else {
450                     die "unknown dgit info in tag";
451                 }
452             }
453             next;
454         }
455         last if m/^-----BEGIN PGP/;
456     }
457     for (;;) {
458         print DS or die $!;
459         $!=0; $_=<T>;
460         last if !defined;
461     }
462     T->error and die $!;
463     close PT or die $!;
464     close DS or die $!;
465     debug " parsetag ok.";
466 }
467
468 sub checksig_keyring ($) {
469     my ($keyringfile) = @_;
470     # returns primary-keyid if signed by a key in this keyring
471     # or undef if not
472     # or dies on other errors
473
474     my $ok = undef;
475
476     debug " checksig keyring $keyringfile...";
477
478     our @cmd = (qw(gpgv --status-fd=1 --keyring),
479                    $keyringfile,
480                    qw(dgit-tmp/plaintext.asc dgit-tmp/plaintext));
481     debugcmd @cmd;
482
483     open P, "-|", @cmd
484         or die $!;
485
486     while (<P>) {
487         next unless s/^\[GNUPG:\] //;
488         chomp or die;
489         debug " checksig| $_";
490         my @l = split / /, $_;
491         if ($l[0] eq 'NO_PUBKEY') {
492             last;
493         } elsif ($l[0] eq 'VALIDSIG') {
494             my $sigtype = $l[9];
495             $sigtype eq '00' or reject "signature is not of type 00!";
496             $ok = $l[10];
497             die unless defined $ok;
498             last;
499         }
500     }
501     close P;
502
503     debug sprintf " checksig ok=%d", !!$ok;
504
505     return $ok;
506 }
507
508 sub dm_txt_check ($$) {
509     my ($keyid, $dmtxtfn) = @_;
510     debug " dm_txt_check $keyid $dmtxtfn";
511     open DT, '<', $dmtxtfn or die "$dmtxtfn $!";
512     while (<DT>) {
513         m/^fingerprint:\s+$keyid$/oi
514             ..0 or next;
515         if (s/^allow:/ /i..0) {
516         } else {
517             m/^./
518                 or reject "key $keyid missing Allow section in permissions!";
519             next;
520         }
521         # in right stanza...
522         s/^[ \t]+//
523             or reject "package $package not allowed for key $keyid";
524         # in allow field...
525         s/\([^()]+\)//;
526         s/\,//;
527         chomp or die;
528         debug " dm_txt_check allow| $_";
529         foreach my $p (split /\s+/) {
530             if ($p eq $package) {
531                 # yay!
532                 debug " dm_txt_check ok";
533                 return;
534             }
535         }
536     }
537     DT->error and die $!;
538     close DT or die $!;
539     reject "key $keyid not in permissions list although in keyring!";
540 }
541
542 sub verifytag () {
543     foreach my $kas (split /:/, $keyrings) {
544         debug "verifytag $kas...";
545         $kas =~ s/^([^,]+),// or die;
546         my $keyid = checksig_keyring $1;
547         if (defined $keyid) {
548             if ($kas =~ m/^a$/) {
549                 debug "verifytag a ok";
550                 return; # yay
551             } elsif ($kas =~ m/^m([^,]+)$/) {
552                 dm_txt_check($keyid, $1);
553                 debug "verifytag m ok";
554                 return;
555             } else {
556                 die;
557             }
558         }   
559     }
560     reject "key not found in keyrings";
561 }
562
563 sub checksuite () {
564     debug "checksuite ($suitesfile)";
565     open SUITES, "<", $suitesfile or die $!;
566     while (<SUITES>) {
567         chomp;
568         next unless m/\S/;
569         next if m/^\#/;
570         s/\s+$//;
571         return if $_ eq $suite;
572     }
573     die $! if SUITES->error;
574     reject "unknown suite";
575 }
576
577 sub checktagnoreplay () {
578     # We check that the signed tag mentions the name and value of
579     # (a) in the case of FRESHREPO all tags in the repo;
580     # (b) in the case of just NOFFCHECK all tags referring to
581     # the current head for the suite (there must be at least one).
582     # This prevents a replay attack using an earlier signed tag.
583     return unless $policy & (FRESHREPO|NOFFCHECK);
584
585     my $garbagerepo = "$dgitrepos/${package}_garbage";
586     lockrealtree();
587
588     local $ENV{GIT_DIR};
589     foreach my $garb ("$garbagerepo", "$garbagerepo-old") {
590         if (stat_exists $garb) {
591             $ENV{GIT_DIR} = $garb;
592             last;
593         }
594     }
595     if (!defined $ENV{GIT_DIR}) {
596         # Nothing to overwrite so the FRESHREPO and NOFFCHECK were
597         # pointless.  Oh well.
598         debug "checktagnoreplay - no garbage, ok";
599         return;
600     }
601
602     my $onlyreferring;
603     if (!($policy & FRESHREPO)) {
604         my $branch = server_branch($suite);
605         $!=0; $?=0; $_ =
606             `git for-each-ref --format='%(objectname)' '[r]efs/$branch'`;
607         defined or die "$branch $? $!";
608         $? and die "$branch $?";
609         if (!length) {
610             # No such branch - NOFFCHECK was unnecessary.  Oh well.
611             debug "checktagnoreplay - not FRESHREPO, new branch, ok";
612             return;
613         }
614         m/^(\w+)\n$/ or die "$branch $_ ?";
615         $onlyreferring = $1;
616         debug "checktagnoreplay - not FRESHREPO,".
617             " checking for overwriting refs/$branch=$onlyreferring";
618     }
619
620     my @problems;
621
622     git_for_each_tag_referring($objreferring, sub {
623         my ($objid,$fullrefname,$tagname) = @_;
624         debug "checktagnoreplay - overwriting $fullrefname=$objid";
625         my $supers = $supersedes{$fullrefname};
626         if (!defined $supers) {
627             push @problems, "does not supersede $fullrefname";
628         } elsif ($supers ne $objid) {
629             push @problems,
630  "supersedes $fullrefname=$supers but previously $fullrefname=$objid";
631         } else {
632             # ok;
633         }
634     });
635
636     if (@problems) {
637         reject "replay attack prevention check failed:".
638             " signed tag for $version: ".
639             join("; ", @problems).
640             "\n";
641     }
642     debug "checktagnoreply - all ok"
643 }
644
645 sub tagh1 ($) {
646     my ($tag) = @_;
647     my $vals = $tagh{$tag};
648     reject "missing header $tag in signed tag object" unless $vals;
649     reject "multiple headers $tag in signed tag object" unless @$vals == 1;
650     return $vals->[0];
651 }
652
653 sub checks () {
654     debug "checks";
655
656     tagh1('type') eq 'commit' or reject "tag refers to wrong kind of object";
657     tagh1('object') eq $commit or reject "tag refers to wrong commit";
658     tagh1('tag') eq $tagname or reject "tag name in tag is wrong";
659
660     my $v = $version;
661     $v =~ y/~:/_%/;
662
663     debug "translated version $v";
664     $tagname eq "debian/$v" or die;
665
666     lockrealtree();
667
668     $policy = policyhook(NOFFCHECK|FRESHREPO, 'push',$package,
669                          $version,$suite,$tagname,
670                          join(",",@delberatelies));
671
672     checktagnoreplay();
673     checksuite();
674
675     # check that our ref is being fast-forwarded
676     debug "oldcommit $oldcommit";
677     if (!($policy & NOFFCHECK) && $oldcommit =~ m/[^0]/) {
678         $?=0; $!=0; my $mb = `git merge-base $commit $oldcommit`;
679         chomp $mb;
680         $mb eq $oldcommit or reject "not fast forward on dgit branch";
681     }
682
683     if ($policy & FRESHREPO) {
684         # This is troublesome.  We have been asked by the policy hook
685         # to receive the push into a fresh repo.  But of course we
686         # have actually already mostly received the push into the working
687         # repo.  (This is unavoidable because the instruction to use a new
688         # repo comes ultimately from the signed tag for the dgit push,
689         # which has to have been received into some repo.)
690         #
691         # So what we do is generate a fresh working repo right now and
692         # push the head and tag into it.  The presence of this fresh
693         # working repo is detected by the parent, which responds by
694         # making a fresh master repo from the template.
695
696         $destrepo = "${workrepo}_fresh"; # workrepo lock covers
697         mkrepo_fromtemplate $destrepo;
698     }
699 }
700
701 sub stunthook () {
702     debug "stunthook";
703     chdir $workrepo or die "chdir $workrepo: $!";
704     mkdir "dgit-tmp" or $!==EEXIST or die $!;
705     readupdates();
706     parsetag();
707     verifytag();
708     checks();
709     onwardpush();
710     debug "stunthook done.";
711 }
712
713 #----- git-upload-pack -----
714
715 sub fixmissing__git_upload_pack () {
716     $destrepo = "$dgitrepos/_empty";
717     my $lfh = locksometree($destrepo);
718     return if stat_exists $destrepo;
719     rmtree "$destrepo.new";
720     mkemptyrepo "$destrepo.new", "0644";
721     rename "$destrepo.new", $destrepo or die $!;
722     unlink "$destrepo.lock" or die $!;
723     close $lfh;
724 }
725
726 sub main__git_upload_pack () {
727     my $lfh = locksometree($destrepo);
728     chdir $destrepo or die "$destrepo: $!";
729     close $lfh;
730     runcmd qw(git upload-pack), ".";
731 }
732
733 #----- arg parsing and main program -----
734
735 sub argval () {
736     die unless @ARGV;
737     my $v = shift @ARGV;
738     die if $v =~ m/^-/;
739     return $v;
740 }
741
742 sub parseargsdispatch () {
743     die unless @ARGV;
744
745     delete $ENV{'GIT_DIR'}; # if not run via ssh, our parent git process
746     delete $ENV{'GIT_PREFIX'}; # sets these and they mess things up
747
748     if ($ENV{'DGIT_DRS_DEBUG'}) {
749         $debug='=';
750         open DEBUG, ">&STDERR" or die $!;
751     }
752
753     if ($ARGV[0] eq '--pre-receive-hook') {
754         if ($debug) { $debug.="="; }
755         shift @ARGV;
756         @ARGV == 1 or die;
757         $package = shift @ARGV;
758         defined($distro = $ENV{'DGIT_DRS_DISTRO'}) or die;
759         defined($suitesfile = $ENV{'DGIT_DRS_SUITES'}) or die;
760         defined($workrepo = $ENV{'DGIT_DRS_WORK'}) or die;
761         defined($destrepo = $ENV{'DGIT_DRS_DEST'}) or die;
762         defined($keyrings = $ENV{'DGIT_DRS_KEYRINGS'}) or die $!;
763         defined($policyhook = $ENV{'DGIT_DRS_POLICYHOOK'}) or die $!;
764         open STDOUT, ">&STDERR" or die $!;
765         eval {
766             stunthook();
767         };
768         if ($@) {
769             recorderror "$@" or die;
770             die $@;
771         }
772         exit 0;
773     }
774
775     $ENV{'DGIT_DRS_DISTRO'} = argval();
776     $ENV{'DGIT_DRS_SUITES'} = argval();
777     $ENV{'DGIT_DRS_KEYRINGS'} = argval();
778     $dgitrepos = argval();
779     $ENV{'DGIT_DRS_POLICYHOOK'} = $policyhook = argval();
780
781     die unless @ARGV==1 && $ARGV[0] eq '--ssh';
782
783     my $cmd = $ENV{'SSH_ORIGINAL_COMMAND'};
784     $cmd =~ m{
785         ^
786         (?: \S* / )?
787         ( [-0-9a-z]+ )
788         \s+
789         '? (?: \S* / )?
790         ($package_re) \.git
791         '?$
792     }ox 
793     or reject "command string not understood";
794     my $method = $1;
795     $package = $2;
796     $realdestrepo = "$dgitrepos/$package.git";
797
798     my $funcn = $method;
799     $funcn =~ y/-/_/;
800     my $mainfunc = $main::{"main__$funcn"};
801
802     reject "unknown method" unless $mainfunc;
803
804     my $lfh = lockrealtree();
805
806     $policy = policyhook(FRESHREPO,'check-package',$package);
807     if ($policy & FRESHREPO) {
808         movetogarbage;
809     }
810
811     close $lfh;
812
813     if (stat_exists $realdestrepo) {
814         $destrepo = $realdestrepo;
815     } else {
816         debug " fixmissing $funcn";
817         my $fixfunc = $main::{"fixmissing__$funcn"};
818         &$fixfunc;
819     }
820
821     debug " running main $funcn";
822     &$mainfunc;
823 }
824
825 sub unlockall () {
826     while (my $fh = pop @lockfhs) { close $fh; }
827 }
828
829 sub cleanup () {
830     unlockall();
831     if (!chdir "$dgitrepos/_tmp") {
832         $!==ENOENT or die $!;
833         return;
834     }
835     foreach my $lf (<*.lock>) {
836         my $tree = $lf;
837         $tree =~ s/\.lock$//;
838         next unless acquirermtree($tree, 0);
839         remove $lf or warn $!;
840         unlockall();
841     }
842 }
843
844 parseargsdispatch();
845 cleanup();