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