chiark / gitweb /
Infrastructure: Get mirroring right for fresh repos of existing packages (!)
[dgit.git] / infra / dgit-repos-policy-debian
1 #!/usr/bin/perl -w
2 # dgit repos policy hook script for Debian
3
4 use strict;
5 $SIG{__WARN__} = sub { die $_[0]; };
6
7 use POSIX;
8 use JSON;
9 use File::Temp qw(tempfile);
10 use DBI;
11 use IPC::Open2;
12 use Data::Dumper;
13
14 use Debian::Dgit qw(:DEFAULT :policyflags);
15 use Debian::Dgit::Policy::Debian;
16
17 initdebug('%');
18 enabledebuglevel $ENV{'DGIT_DRS_DEBUG'};
19
20 END { $? = 127; } # deliberate exit uses _exit
21
22 our $distro = shift @ARGV // die "need DISTRO";
23 our $repos = shift @ARGV // die "need DGIT-REPOS-DIR";
24 our $dgitlive = shift @ARGV // die "need DGIT-LIVE-DIR";
25 our $distrodir = shift @ARGV // die "need DISTRO-DIR";
26 our $action = shift @ARGV // die "need ACTION";
27
28 our $publicmode = 02775;
29 our $new_upload_propagation_slop = 3600*4 + 100;# fixme config;
30
31 our $poldbh;
32 our $pkg;
33 our $pkgdir;
34 our ($pkg_exists,$pkg_secret);
35
36 our $stderr;
37
38 our ($version,$suite,$tagname);
39 our %deliberately;
40
41 # We assume that it is not possible for NEW to have a version older
42 # than sid.
43
44 # Whenever pushing, we check for
45 #   source-package-local tainted history
46 #   global tainted history
47 #   can be overridden by --deliberately except for an admin prohib taint
48
49 # ALL of the following apply only if history is secret:
50
51 # if NEW has no version, or a version which is not in our history[1]
52 #   (always)
53 #   check all suites
54 #   if any suite's version is in our history[1], publish our history
55 #   otherwise discard our history,
56 #     tainting --deliberately-include-questionable-history
57
58 # if NEW has a version which is in our history[1]
59 #   (on push only)
60 #   require explicit specification of one of
61 #     --deliberately-include-questionable-history
62 #     --deliberately-not-fast-forward
63 #       (latter will taint old NEW version --d-i-q-h)
64 #   (otherwise)
65 #   leave it be
66
67 # [1] looking for the relevant git tag for the version number and not
68 #    caring what that tag refers to.
69 #
70 #    When we are doing a push to a fresh repo, any version will do: in
71 #    this case, this is the first dgit upload of an existing package,
72 #    and we trust that the uploader hasn't included in their git
73 #    history any previous non-dgit uploads.
74 #
75 # A wrinkle: if we approved a push recently, we treat NEW as having
76 # a version which is in our history.  This is because the package may
77 # still be being uploaded.  (We record this using the timestamp of the
78 # package's git repo directory.)
79
80 # We aim for the following invariants and properties:
81 #
82 # - .dsc of published dgit package will have corresponding publicly
83 #   visible dgit-repo (soon)
84 #
85 # - when a new package is rejected we help maintainer avoid
86 #   accidentally including bad objects in published dgit history
87 #
88 # - .dsc of NEW dgit package has corresponding dgit-repo but not
89 #   publicly readable
90
91 sub apiquery ($) {
92     my ($subpath) = @_;
93     local $/=undef;
94     my $dgit = "$dgitlive/dgit";
95     $dgit = "dgit" if !stat_exists $dgit;
96     my $cmd = "$dgit -d$distro \$DGIT_TEST_OPTS";
97     $cmd .= " -".("D" x $debuglevel) if $debuglevel;
98     $cmd .= " archive-api-query $subpath";
99     printdebug "apiquery $cmd\n";
100     $!=0; $?=0; my $json = `$cmd`;
101     defined $json && !$? or die "$subpath $! $?";
102     my $r = decode_json $json;
103     my $d = new Data::Dumper([$r], [qw(r)]);
104     printdebug "apiquery $subpath | ", $d->Dump() if $debuglevel>=2;
105     return $r;
106 }
107
108 sub vsn_in_our_history ($) {
109     my ($vsn) = @_;
110
111     my $tagref = "refs/tags/".debiantag $vsn, $distro;
112     printdebug " checking history  vsn=$vsn tagref=$tagref\n";
113     $?=0; my $r = system qw(git show-ref --verify --quiet), $tagref;
114     return 1 if !$r;
115     return 0 if $r==256;
116     die "$pkg tagref $tagref $? $!";
117 }
118
119 sub specific_suite_has_suitable_vsn ($$) {
120     my ($suite, $vsn_check) = @_; # tests $vsn_check->($version)
121     my $in_suite = apiquery "dsc_in_suite/$suite/$pkg";
122     foreach my $entry (@$in_suite) {
123         my $vsn = $entry->{version};
124         die "$pkg ?" unless defined $vsn;
125         printdebug " checking history found suite=$suite vsn=$vsn\n";
126         return 1 if $vsn_check->($vsn);
127     }
128     return 0;
129 }
130
131 sub new_has_vsn_in_our_history () {
132     return specific_suite_has_suitable_vsn('new', \&vsn_in_our_history);
133 }
134
135 sub good_suite_has_suitable_vsn ($) {
136     my ($vsn_check) = @_; # as for specific_suite_has_specific_vsn
137     my $suites = apiquery "suites";
138     foreach my $suitei (@$suites) {
139         my $suite = $suitei->{name};
140         die unless defined $suite;
141         next if $suite =~ m/\bnew$/;
142         return 1 if specific_suite_has_suitable_vsn($suite, $vsn_check);
143     }
144     return 0;
145 }
146
147 sub statpackage () {
148     $pkgdir = "$repos/$pkg.git";
149     if (!stat_exists $pkgdir) {
150         printdebug "statpackage $pkg => ENOENT\n";
151         $pkg_exists = 0;
152     } else {
153         $pkg_exists = 1;
154         $pkg_secret = !!(~(stat _)[2] & 05);
155         printdebug "statpackage $pkg => exists, secret=$pkg_secret.\n";
156     }
157 }
158
159 sub getpackage () {
160     die unless @ARGV >= 1;
161     $pkg = shift @ARGV;
162     die unless $pkg =~ m/^$package_re$/;
163
164     statpackage();
165 }
166
167 sub add_taint ($$) {
168     my ($refobj, $reason) = @_;
169
170     printdebug "TAINTING $refobj\n",
171         (map { "\%| $_" } split "\n", $reason),
172         "\n";
173
174     my $tf = new File::Temp or die $!;
175     print $tf "$refobj^0\n" or die $!;
176     flush $tf or die $!;
177     seek $tf,0,0 or die $!;
178
179     my $gcfpid = open GCF, "-|";
180     defined $gcfpid or die $!;
181     if (!$gcfpid) {
182         open STDIN, "<&", $tf or die $!;
183         exec 'git', 'cat-file', '--batch';
184         die $!;
185     }
186
187     close $tf or die $!;
188     $_ = <GCF>;
189     defined $_ or die;
190     m/^(\w+) (\w+) (\d+)\n/ or die "$_ ?";
191     my $gitobjid = $1;
192     my $gitobjtype = $2;
193     my $bytes = $3;
194
195     my $gitobjdata;
196     if ($gitobjtype eq 'commit' or $gitobjtype eq 'tag') {
197         $!=0; read GCF, $gitobjdata, $bytes == $bytes
198             or die "$gitobjid $bytes $!";
199     }
200     close GCF;
201
202     $poldbh->do("INSERT INTO taints".
203                 " (package, gitobjid, gitobjtype, gitobjdata, time, comment)".
204                 " VALUES (?,?,?,?,?,?)", {},
205                 $pkg, $gitobjid, $gitobjtype, $gitobjdata, time, $reason);
206
207     my $taint_id = $poldbh->last_insert_id(undef,undef,"taints","taint_id");
208     die unless defined $taint_id;
209
210     $poldbh->do("INSERT INTO taintoverrides".
211                 " (taint_id, deliberately)".
212                 " VALUES (?, '--deliberately-include-questionable-history')", 
213                 {}, $taint_id);
214 }
215
216 sub add_taint_by_tag ($$) {
217     my ($tagname,$refobjid) = @_;
218     add_taint($refobjid,
219               "tag $tagname referred to this object in git tree but all".
220               " previously pushed versions were found to have been".
221               " removed from NEW (ie, rejected) (or never arrived)");
222 }
223
224 sub check_package () {
225     return 0 unless $pkg_exists;
226     return 0 unless $pkg_secret;
227
228     printdebug "check_package\n";
229
230     chdir $pkgdir or die "$pkgdir $!";
231
232     stat '.' or die "$pkgdir $!";
233     my $mtime = ((stat _)[9]);
234     my $age = time -  $mtime;
235     printdebug "check_package age=$age\n";
236
237     if (good_suite_has_suitable_vsn(\&vsn_in_our_history)) {
238         chmod $publicmode, "." or die $!;
239         $pkg_secret = 0;
240         return 0;
241     }
242
243     return 0 if $age < $new_upload_propagation_slop;
244
245     return 0 if new_has_vsn_in_our_history();
246
247     printdebug "check_package secret, deleted, tainting\n";
248
249     git_for_each_ref('refs/tags', sub {
250         my ($objid,$objtype,$fullrefname,$tagname) = @_;
251         add_taint_by_tag($tagname,$objid);
252     });
253
254     return FRESHREPO;
255 }
256
257 sub action_check_package () {
258     getpackage();
259     return check_package();
260 }
261
262 sub getpushinfo () {
263     die unless @ARGV >= 4;
264     $version = shift @ARGV;
265     $suite = shift @ARGV;
266     $tagname = shift @ARGV;
267     my $delibs = shift @ARGV;
268     foreach my $delib (split /\,/, $delibs) {
269         $deliberately{$delib} = 1;
270     }
271 }
272
273 sub deliberately ($) { return $deliberately{"--deliberately-$_[0]"}; }
274
275 sub action_push () {
276     getpackage();
277     getpushinfo();
278
279     check_package(); # might make package public, or might add taints
280
281     return 0 unless $pkg_exists;
282     return 0 unless $pkg_secret;
283
284     # we suppose that NEW has a version which is already in our
285     # history, as otherwise the repo would have been blown away
286
287     if (deliberately('not-fast-forward')) {
288         add_taint(server_ref($suite),
289                   "rewound suite $suite; --deliberately-not-fast-forward".
290                   " specified in signed tag $tagname for upload of".
291                   " version $version");
292         return NOFFCHECK|FRESHREPO;
293     }
294     if (deliberately('include-questionable-history')) {
295         return 0;
296     }
297     die "\nPackage is in NEW and has not been accepted or rejected yet;".
298         " use a --deliberately option to specify whether you are".
299         " keeping or discarding the previously pushed history. ".
300         " Please RTFM dgit(1).\n\n";
301 }
302
303 sub action_push_confirm () {
304     getpackage();
305     getpushinfo();
306     die unless @ARGV >= 1;
307     my $freshrepo = shift @ARGV;
308
309     my $initq = $poldbh->prepare(<<END);
310         SELECT taint_id, gitobjid FROM taints t
311             WHERE (package = ? OR package = '')
312 END
313     $initq->execute($pkg);
314
315     my @objscatcmd = qw(git);
316     push @objscatcmd, qw(--git-dir), $freshrepo if length $freshrepo;
317     push @objscatcmd, qw(cat-file --batch);
318     debugcmd '|',@objscatcmd if $debuglevel>=2;
319
320     my @taintids;
321     my $chkinput = tempfile();
322     while (my $taint = $initq->fetchrow_hashref()) {
323         push @taintids, $taint->{taint_id};
324         print $chkinput $taint->{gitobjid}, "\n" or die $!;
325         printdebug '|> ', $taint->{gitobjid}, "\n" if $debuglevel>=2;
326     }
327     flush $chkinput or die $!;
328     seek $chkinput,0,0 or die $!;
329
330     my $checkpid = open CHKOUT, "-|" // die $!;
331     if (!$checkpid) {
332         open STDIN, "<&", $chkinput or die $!;
333         exec @objscatcmd or die $!;
334     }
335
336     my ($taintinfoq,$overridesanyq,$untaintq,$overridesq);
337
338     my $overridesstmt = <<END;
339         SELECT deliberately FROM taintoverrides WHERE (
340             1=0
341 END
342     my @overridesv = sort keys %deliberately;
343     $overridesstmt .= <<END foreach @overridesv;
344             OR deliberately = ?
345 END
346     $overridesstmt .= <<END;
347         ) AND taint_id = ?
348         ORDER BY deliberately ASC
349 END
350
351     my $mustreject=0;
352
353     while (my $taintid = shift @taintids) {
354         # git cat-file prints a spurious newline after it gets EOF
355         # This is not documented.  I guess it might go away.  So we
356         # just read what we expect and then let it get SIGPIPE.
357         $!=0; $_ = <CHKOUT>;
358         die "$? $!" unless defined $_;
359         printdebug "|< ", $_ if $debuglevel>=2;
360
361         next if m/^\w+ missing$/;
362         die "$_ ?" unless m/^(\w+) (\w+) (\d+)\s/;
363         my ($objid,$objtype,$nbytes) = ($1,$2,$3);
364
365         my $drop;
366         (read CHKOUT, $drop, $nbytes) == $nbytes or die;
367
368         $taintinfoq ||= $poldbh->prepare(<<END);
369             SELECT package, time, comment FROM taints WHERE taint_id =  ?
370 END
371         $taintinfoq->execute($taintid);
372
373         my $ti = $taintinfoq->fetchrow_hashref();
374         die unless $ti;
375
376         my $timeshow = defined $ti->{time}
377             ? " at time ".strftime("%Y-%m-%d %H:%M:%S Z", gmtime $ti->{time})
378             : "";
379         my $pkgshow = length $ti->{package}
380             ? "package $ti->{package}"
381             : "any package";
382
383         $stderr .= <<END;
384
385 History contains tainted $objtype $objid
386 Taint recorded$timeshow for $pkgshow
387 Reason: $ti->{comment}
388 END
389
390         printdebug "SQL overrides: @overridesv $taintid /\n$overridesstmt\n";
391
392         $overridesq ||= $poldbh->prepare($overridesstmt);
393         $overridesq->execute(@overridesv, $taintid);
394         my ($ovwhy) = $overridesq->fetchrow_array();
395         if (!defined $ovwhy) {
396             $overridesanyq ||= $poldbh->prepare(<<END);
397                 SELECT 1 FROM taintoverrides WHERE taint_id = ? LIMIT 1
398 END
399             $overridesanyq->execute($taintid);
400             my ($ovany) = $overridesanyq->fetchrow_array();
401             $stderr .= $ovany ? <<END : <<END;
402 Could be forced using --deliberately.  Consult documentation.
403 END
404 Uncorrectable error.  If confused, consult administrator.
405 END
406             $mustreject = 1;
407         } else {
408             $stderr .= <<END;
409 Forcing due to --deliberately-$ovwhy
410 END
411             $untaintq ||= $poldbh->prepare(<<END);
412                 DELETE FROM taints WHERE taint_id = ?
413 END
414             $untaintq->execute($taintid);
415         }
416     }
417     close CHKOUT;
418
419     if ($mustreject) {
420         $stderr .= <<END;
421
422 Rejecting push due to questionable history.
423 END
424         return 1;
425     }
426
427     if (length $freshrepo) {
428         if (!good_suite_has_suitable_vsn(sub { 1; })) {
429             stat $freshrepo or die "$freshrepo $!";
430             my $oldmode = ((stat _)[2]);
431             my $oldwrites = $oldmode & 0222;
432             # remove r and x bits which have corresponding w bits clear
433             my $newmode = $oldmode &
434                 (~0555 | ($oldwrites << 1) | ($oldwrites >> 1));
435             printdebug sprintf "chmod %#o (was %#o) %s\n",
436                 $newmode, $oldmode, $freshrepo;
437             chmod $newmode, $freshrepo or die $!;
438             utime undef, undef, $freshrepo or die $!;
439         }
440     }
441
442     return 0;
443 }
444
445 sub action_check_list () {
446     opendir L, "$repos" or die "$repos $!";
447     while (defined (my $dent = readdir L)) {
448         next unless $dent =~ m/^($package_re)\.git$/;
449         $pkg = $1;
450         statpackage();
451         next unless $pkg_exists;
452         next unless $pkg_secret;
453         print "$pkg\n" or die $!;
454     }
455     closedir L or die $!;
456     close STDOUT or die $!;
457     return 0;
458 }
459
460 $action =~ y/-/_/;
461 my $fn = ${*::}{"action_$action"};
462 if (!$fn) {
463     printdebug "dgit-repos-policy-debian: unknown action $action\n";
464     exit 0;
465 }
466
467 my $sleepy=0;
468 my $rcode;
469
470 my $db_busy_exception= 'Debian::Dgit::Policy::Debian::DB_BUSY';
471
472 my @orgargv = @ARGV;
473
474 for (;;) {
475     @ARGV = @orgargv;
476     eval {
477         poldb_setup(poldb_path($repos), sub {
478             $poldbh->{HandleError} = sub {
479                 return 0 unless $poldbh->err == 5; # SQLITE_BUSY, not in .pm :-(
480                 die bless { }, $db_busy_exception;
481             };
482
483             eval ($ENV{'DGIT_RPD_TEST_DBLOOP_HOOK'}//'');
484             die $@ if length $@;
485             # used by tests/tests/debpolicy-dbretry
486         });
487
488         $stderr = '';
489
490         $rcode = $fn->();
491         die unless defined $rcode;
492
493         $poldbh->commit;
494     };
495     last unless length $@;
496     die $@ unless ref $@ eq $db_busy_exception;
497
498     die if $sleepy >= 20;
499     $sleepy++;
500     print STDERR "[policy database busy, retrying (${sleepy}s)]\n";
501
502     eval { $poldbh->rollback; };
503 }
504
505 print STDERR $stderr or die $!;
506 flush STDERR or die $!;
507 _exit $rcode;