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