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