File Coverage

File:Dpkg/Checksums.pm
Coverage:76.5%

linestmtbrancondsubpodtimecode
1# Copyright © 2008 Frank Lichtenheld <djpig@debian.org>
2# Copyright © 2008, 2012-2015 Guillem Jover <guillem@debian.org>
3# Copyright © 2010 Raphaël Hertzog <hertzog@debian.org>
4#
5# This program is free software; you can redistribute it and/or modify
6# it under the terms of the GNU General Public License as published by
7# the Free Software Foundation; either version 2 of the License, or
8# (at your option) any later version.
9#
10# This program is distributed in the hope that it will be useful,
11# but WITHOUT ANY WARRANTY; without even the implied warranty of
12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13# GNU General Public License for more details.
14#
15# You should have received a copy of the GNU General Public License
16# along with this program.  If not, see <https://www.gnu.org/licenses/>.
17
18=encoding utf8
19
20 - 30
=head1 NAME

Dpkg::Checksums - generate and manipulate file checksums

=head1 DESCRIPTION

This module provides a class that can generate and manipulate
various file checksums as well as some methods to query information
about supported checksums.

=cut
31
32package Dpkg::Checksums 1.04;
33
34
12
12
12
28
11
202
use strict;
35
12
12
12
15
9
466
use warnings;
36
37our @EXPORT = qw(
38    checksums_is_supported
39    checksums_get_list
40    checksums_get_property
41);
42
43
12
12
12
41
26
239
use Exporter qw(import);
44
12
12
12
5662
3785
221
use Digest;
45
46
12
12
12
605
10
398
use Dpkg::Gettext;
47
12
12
12
610
9
10687
use Dpkg::ErrorHandling;
48
49 - 53
=head1 FUNCTIONS

=over 4

=cut
54
55my $CHECKSUMS = {
56    md5 => {
57        name => 'MD5',
58        regex => qr/[0-9a-f]{32}/,
59        strong => 0,
60    },
61    sha1 => {
62        name => 'SHA-1',
63        regex => qr/[0-9a-f]{40}/,
64        strong => 0,
65    },
66    sha256 => {
67        name => 'SHA-256',
68        regex => qr/[0-9a-f]{64}/,
69        strong => 1,
70    },
71};
72
73 - 77
=item @list = checksums_get_list()

Returns the list of supported checksums algorithms.

=cut
78
79sub checksums_get_list() {
80
18
18
1
24
72
    my @list = sort keys %{$CHECKSUMS};
81
18
36
    return @list;
82}
83
84 - 89
=item $bool = checksums_is_supported($alg)

Returns a boolean indicating whether the given checksum algorithm is
supported. The checksum algorithm is case-insensitive.

=cut
90
91sub checksums_is_supported($) {
92
63
1
48
    my $alg = shift;
93
63
123
    return exists $CHECKSUMS->{lc($alg)};
94}
95
96 - 105
=item $value = checksums_get_property($alg, $property)

Returns the requested property of the checksum algorithm. Returns undef if
either the property or the checksum algorithm doesn't exist. Valid
properties currently include "name" (returns the name of the digest
algorithm), "regex" for the regular expression describing the common
string representation of the checksum, and "strong" for a boolean describing
whether the checksum algorithm is considered cryptographically strong.

=cut
106
107sub checksums_get_property($$) {
108
45
1
56
    my ($alg, $property) = @_;
109
110
45
52
    return unless checksums_is_supported($alg);
111
45
91
    return $CHECKSUMS->{lc($alg)}{$property};
112}
113
114=back
115
116 - 125
=head1 METHODS

=over 4

=item $ck = Dpkg::Checksums->new()

Create a new Dpkg::Checksums object. This object is able to store
the checksums of several files to later export them or verify them.

=cut
126
127sub new {
128
12
1
10
    my ($this, %opts) = @_;
129
12
33
    my $class = ref($this) || $this;
130
131
12
9
    my $self = {};
132
12
12
    bless $self, $class;
133
12
17
    $self->reset();
134
135
12
30
    return $self;
136}
137
138 - 143
=item $ck->reset()

Forget about all checksums stored. The object is again in the same state
as if it was newly created.

=cut
144
145sub reset {
146
12
1
9
    my $self = shift;
147
148
12
35
    $self->{files} = [];
149
12
13
    $self->{checksums} = {};
150
12
25
    $self->{size} = {};
151}
152
153 - 167
=item $ck->add_from_file($filename, %opts)

Add or verify checksums information for the file $filename. The file must
exists for the call to succeed. If you don't want the given filename to
appear when you later export the checksums you might want to set the "key"
option with the public name that you want to use. Also if you don't want
to generate all the checksums, you can pass an array reference of the
wanted checksums in the "checksums" option.

It the object already contains checksums information associated the
filename (or key), it will error out if the newly computed information
does not match what's stored, and the caller did not request that it be
updated with the boolean "update" option.

=cut
168
169sub add_from_file {
170
9
1
18
    my ($self, $file, %opts) = @_;
171
9
23
    my $key = exists $opts{key} ? $opts{key} : $file;
172
9
8
    my @alg;
173
9
12
    if (exists $opts{checksums}) {
174
0
0
0
0
0
0
        push @alg, map { lc } @{$opts{checksums}};
175    } else {
176
9
13
        push @alg, checksums_get_list();
177    }
178
179
9
9
22
13
    push @{$self->{files}}, $key unless exists $self->{size}{$key};
180
9
85
    (my @s = stat($file)) or syserr(g_('cannot fstat file %s'), $file);
181
9
43
    if (not $opts{update} and exists $self->{size}{$key} and
182        $self->{size}{$key} != $s[7]) {
183        error(g_('file %s has size %u instead of expected %u'),
184
0
0
              $file, $s[7], $self->{size}{$key});
185    }
186
9
13
    $self->{size}{$key} = $s[7];
187
188
9
13
    foreach my $alg (@alg) {
189
27
75
        my $digest = Digest->new($CHECKSUMS->{$alg}{name});
190
27
6688
        open my $fh, '<', $file or syserr(g_('cannot open file %s'), $file);
191
27
79
        $digest->addfile($fh);
192
27
255
        close $fh;
193
194
27
93
        my $newsum = $digest->hexdigest;
195
27
126
        if (not $opts{update} and exists $self->{checksums}{$key}{$alg} and
196            $self->{checksums}{$key}{$alg} ne $newsum) {
197            error(g_('file %s has checksum %s instead of expected %s (algorithm %s)'),
198
0
0
                  $file, $newsum, $self->{checksums}{$key}{$alg}, $alg);
199        }
200
27
113
        $self->{checksums}{$key}{$alg} = $newsum;
201    }
202}
203
204 - 216
=item $ck->add_from_string($alg, $value, %opts)

Add checksums of type $alg that are stored in the $value variable.
$value can be multi-lines, each line should be a space separated list
of checksum, file size and filename. Leading or trailing spaces are
not allowed.

It the object already contains checksums information associated to the
filenames, it will error out if the newly read information does not match
what's stored, and the caller did not request that it be updated with
the boolean "update" option.

=cut
217
218sub add_from_string {
219
18
1
33
    my ($self, $alg, $fieldtext, %opts) = @_;
220
18
23
    $alg = lc($alg);
221
18
37
    my $rx_fname = qr/[0-9a-zA-Z][-+:.,=0-9a-zA-Z_~]+/;
222
18
23
    my $regex = checksums_get_property($alg, 'regex');
223
18
20
    my $checksums = $self->{checksums};
224
225
18
66
    for my $checksum (split /\n */, $fieldtext) {
226
54
61
        next if $checksum eq '';
227
36
1013
        unless ($checksum =~ m/^($regex)\s+(\d+)\s+($rx_fname)$/) {
228
0
0
            error(g_('invalid line in %s checksums string: %s'),
229                  $alg, $checksum);
230        }
231        ## no critic (RegularExpressions::ProhibitCaptureWithoutTest)
232
36
76
        my ($sum, $size, $file) = ($1, $2, $3);
233
36
142
        if (not $opts{update} and exists($checksums->{$file}{$alg})
234            and $checksums->{$file}{$alg} ne $sum) {
235            error(g_("conflicting checksums '%s' and '%s' for file '%s'"),
236
0
0
                  $checksums->{$file}{$alg}, $sum, $file);
237        }
238
36
123
        if (not $opts{update} and exists $self->{size}{$file}
239            and $self->{size}{$file} != $size) {
240            error(g_("conflicting file sizes '%u' and '%u' for file '%s'"),
241
0
0
                  $self->{size}{$file}, $size, $file);
242        }
243
36
3
42
4
        push @{$self->{files}}, $file unless exists $self->{size}{$file};
244
36
40
        $checksums->{$file}{$alg} = $sum;
245
36
78
        $self->{size}{$file} = $size;
246    }
247}
248
249 - 259
=item $ck->add_from_control($control, %opts)

Read checksums from Checksums-* fields stored in the L<Dpkg::Control> object
$control. It uses $self->add_from_string() on the field values to do the
actual work.

If the option "use_files_for_md5" evaluates to true, then the "Files"
field is used in place of the "Checksums-Md5" field. By default the option
is false.

=cut
260
261sub add_from_control {
262
3
1
3
    my ($self, $control, %opts) = @_;
263
3
18
    $opts{use_files_for_md5} //= 0;
264
3
5
    foreach my $alg (checksums_get_list()) {
265
9
9
        my $key = "Checksums-$alg";
266
9
13
        $key = 'Files' if ($opts{use_files_for_md5} and $alg eq 'md5');
267
9
14
        if (exists $control->{$key}) {
268
9
14
            $self->add_from_string($alg, $control->{$key}, %opts);
269        }
270    }
271}
272
273 - 277
=item @files = $ck->get_files()

Return the list of files whose checksums are stored in the object.

=cut
278
279sub get_files {
280
42
1
29
    my $self = shift;
281
42
42
50
94
    return @{$self->{files}};
282}
283
284 - 289
=item $bool = $ck->has_file($file)

Return true if we have checksums for the given file. Returns false
otherwise.

=cut
290
291sub has_file {
292
36
1
55
    my ($self, $file) = @_;
293
36
128
    return exists $self->{size}{$file};
294}
295
296 - 300
=item $ck->remove_file($file)

Remove all checksums of the given file.

=cut
301
302sub remove_file {
303
3
1
4
    my ($self, $file) = @_;
304
3
7
    return unless $self->has_file($file);
305
3
11
    delete $self->{checksums}{$file};
306
3
8
    delete $self->{size}{$file};
307
3
3
9
9
8
14
    @{$self->{files}} = grep { $_ ne $file } $self->get_files();
308}
309
310 - 320
=item $checksum = $ck->get_checksum($file, $alg)

Return the checksum of type $alg for the requested $file. This will not
compute the checksum but only return the checksum stored in the object, if
any.

If $alg is not defined, it returns a reference to a hash: keys are
the checksum algorithms and values are the checksums themselves. The
hash returned must not be modified, it's internal to the object.

=cut
321
322sub get_checksum {
323
108
1
106
    my ($self, $file, $alg) = @_;
324
108
149
    $alg = lc($alg) if defined $alg;
325
108
137
    if (exists $self->{checksums}{$file}) {
326
108
166
        return $self->{checksums}{$file} unless defined $alg;
327
81
93
        return $self->{checksums}{$file}{$alg};
328    }
329
0
0
    return;
330}
331
332 - 336
=item $size = $ck->get_size($file)

Return the size of the requested file if it's available in the object.

=cut
337
338sub get_size {
339
108
1
100
    my ($self, $file) = @_;
340
108
163
    return $self->{size}{$file};
341}
342
343 - 347
=item $bool = $ck->has_strong_checksums($file)

Return a boolean on whether the file has a strong checksum.

=cut
348
349sub has_strong_checksums {
350
0
1
0
    my ($self, $file) = @_;
351
352
0
0
    foreach my $alg (checksums_get_list()) {
353
0
0
        return 1 if defined $self->get_checksum($file, $alg) and
354                    checksums_get_property($alg, 'strong');
355    }
356
357
0
0
    return 0;
358}
359
360 - 366
=item $ck->export_to_string($alg, %opts)

Return a multi-line string containing the checksums of type $alg. The
string can be stored as-is in a Checksum-* field of a L<Dpkg::Control>
object.

=cut
367
368sub export_to_string {
369
27
1
38
    my ($self, $alg, %opts) = @_;
370
27
21
    my $res = '';
371
27
45
    foreach my $file ($self->get_files()) {
372
81
86
        my $sum = $self->get_checksum($file, $alg);
373
81
75
        my $size = $self->get_size($file);
374
81
183
        next unless defined $sum and defined $size;
375
81
123
        $res .= "\n$sum $size $file";
376    }
377
27
60
    return $res;
378}
379
380 - 385
=item $ck->export_to_control($control, %opts)

Export the checksums in the Checksums-* fields of the L<Dpkg::Control>
$control object.

=cut
386
387sub export_to_control {
388
3
1
5
    my ($self, $control, %opts) = @_;
389
3
20
    $opts{use_files_for_md5} //= 0;
390
3
10
    foreach my $alg (checksums_get_list()) {
391
9
9
        my $key = "Checksums-$alg";
392
9
12
        $key = 'Files' if ($opts{use_files_for_md5} and $alg eq 'md5');
393
9
13
        $control->{$key} = $self->export_to_string($alg, %opts);
394    }
395}
396
397=back
398
399 - 430
=head1 CHANGES

=head2 Version 1.04 (dpkg 1.20.0)

Remove warning: For obsolete property 'program'.

=head2 Version 1.03 (dpkg 1.18.5)

New property: Add new 'strong' property.

New member: $ck->has_strong_checksums().

=head2 Version 1.02 (dpkg 1.18.0)

Obsolete property: Getting the 'program' checksum property will warn and
return undef, the Digest module is used internally now.

New property: Add new 'name' property with the name of the Digest algorithm
to use.

=head2 Version 1.01 (dpkg 1.17.6)

New argument: Accept an options argument in $ck->export_to_string().

New option: Accept new option 'update' in $ck->add_from_file() and
$ck->add_from_control().

=head2 Version 1.00 (dpkg 1.15.6)

Mark the module as public.

=cut
431
4321;