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
18package Dpkg::Checksums;
19
20
4
4
4
8
4
44
use strict;
21
4
4
4
5
3
125
use warnings;
22
23our $VERSION = '1.04';
24our @EXPORT = qw(
25    checksums_is_supported
26    checksums_get_list
27    checksums_get_property
28);
29
30
4
4
4
8
0
36
use Exporter qw(import);
31
4
4
4
558
1031
56
use Digest;
32
33
4
4
4
117
4
100
use Dpkg::Gettext;
34
4
4
4
129
4
2742
use Dpkg::ErrorHandling;
35
36=encoding utf8
37
38 - 52
=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.

=head1 FUNCTIONS

=over 4

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

Returns the list of supported checksums algorithms.

=cut
77
78sub checksums_get_list() {
79
6
6
1
5
10
    my @list = sort keys %{$CHECKSUMS};
80
6
8
    return @list;
81}
82
83 - 88
=item $bool = checksums_is_supported($alg)

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

=cut
89
90sub checksums_is_supported($) {
91
21
1
14
    my $alg = shift;
92
21
30
    return exists $CHECKSUMS->{lc($alg)};
93}
94
95 - 104
=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
105
106sub checksums_get_property($$) {
107
15
1
9
    my ($alg, $property) = @_;
108
109
15
13
    return unless checksums_is_supported($alg);
110
15
19
    return $CHECKSUMS->{lc($alg)}{$property};
111}
112
113=back
114
115 - 124
=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
125
126sub new {
127
4
1
4
    my ($this, %opts) = @_;
128
4
15
    my $class = ref($this) || $this;
129
130
4
4
    my $self = {};
131
4
4
    bless $self, $class;
132
4
5
    $self->reset();
133
134
4
5
    return $self;
135}
136
137 - 142
=item $ck->reset()

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

=cut
143
144sub reset {
145
4
1
0
    my $self = shift;
146
147
4
10
    $self->{files} = [];
148
4
4
    $self->{checksums} = {};
149
4
3
    $self->{size} = {};
150}
151
152 - 166
=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
167
168sub add_from_file {
169
3
1
4
    my ($self, $file, %opts) = @_;
170
3
4
    my $key = exists $opts{key} ? $opts{key} : $file;
171
3
3
    my @alg;
172
3
1
    if (exists $opts{checksums}) {
173
0
0
0
0
0
0
        push @alg, map { lc } @{$opts{checksums}};
174    } else {
175
3
3
        push @alg, checksums_get_list();
176    }
177
178
3
3
4
3
    push @{$self->{files}}, $key unless exists $self->{size}{$key};
179
3
12
    (my @s = stat($file)) or syserr(g_('cannot fstat file %s'), $file);
180
3
8
    if (not $opts{update} and exists $self->{size}{$key} and
181        $self->{size}{$key} != $s[7]) {
182        error(g_('file %s has size %u instead of expected %u'),
183
0
0
              $file, $s[7], $self->{size}{$key});
184    }
185
3
3
    $self->{size}{$key} = $s[7];
186
187
3
1
    foreach my $alg (@alg) {
188
9
15
        my $digest = Digest->new($CHECKSUMS->{$alg}{name});
189
9
1482
        open my $fh, '<', $file or syserr(g_('cannot open file %s'), $file);
190
9
22
        $digest->addfile($fh);
191
9
69
        close $fh;
192
193
9
19
        my $newsum = $digest->hexdigest;
194
9
20
        if (not $opts{update} and exists $self->{checksums}{$key}{$alg} and
195            $self->{checksums}{$key}{$alg} ne $newsum) {
196            error(g_('file %s has checksum %s instead of expected %s (algorithm %s)'),
197
0
0
                  $file, $newsum, $self->{checksums}{$key}{$alg}, $alg);
198        }
199
9
22
        $self->{checksums}{$key}{$alg} = $newsum;
200    }
201}
202
203 - 215
=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
216
217sub add_from_string {
218
6
1
6
    my ($self, $alg, $fieldtext, %opts) = @_;
219
6
5
    $alg = lc($alg);
220
6
7
    my $rx_fname = qr/[0-9a-zA-Z][-+:.,=0-9a-zA-Z_~]+/;
221
6
4
    my $regex = checksums_get_property($alg, 'regex');
222
6
3
    my $checksums = $self->{checksums};
223
224
6
14
    for my $checksum (split /\n */, $fieldtext) {
225
18
12
        next if $checksum eq '';
226
12
207
        unless ($checksum =~ m/^($regex)\s+(\d+)\s+($rx_fname)$/) {
227
0
0
            error(g_('invalid line in %s checksums string: %s'),
228                  $alg, $checksum);
229        }
230
12
22
        my ($sum, $size, $file) = ($1, $2, $3);
231
12
32
        if (not $opts{update} and exists($checksums->{$file}{$alg})
232            and $checksums->{$file}{$alg} ne $sum) {
233            error(g_("conflicting checksums '%s' and '%s' for file '%s'"),
234
0
0
                  $checksums->{$file}{$alg}, $sum, $file);
235        }
236
12
26
        if (not $opts{update} and exists $self->{size}{$file}
237            and $self->{size}{$file} != $size) {
238            error(g_("conflicting file sizes '%u' and '%u' for file '%s'"),
239
0
0
                  $self->{size}{$file}, $size, $file);
240        }
241
12
1
11
1
        push @{$self->{files}}, $file unless exists $self->{size}{$file};
242
12
12
        $checksums->{$file}{$alg} = $sum;
243
12
13
        $self->{size}{$file} = $size;
244    }
245}
246
247 - 257
=item $ck->add_from_control($control, %opts)

Read checksums from Checksums-* fields stored in the 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
258
259sub add_from_control {
260
1
1
1
    my ($self, $control, %opts) = @_;
261
1
3
    $opts{use_files_for_md5} //= 0;
262
1
1
    foreach my $alg (checksums_get_list()) {
263
3
2
        my $key = "Checksums-$alg";
264
3
4
        $key = 'Files' if ($opts{use_files_for_md5} and $alg eq 'md5');
265
3
3
        if (exists $control->{$key}) {
266
3
3
            $self->add_from_string($alg, $control->{$key}, %opts);
267        }
268    }
269}
270
271 - 275
=item @files = $ck->get_files()

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

=cut
276
277sub get_files {
278
14
1
9
    my $self = shift;
279
14
14
8
16
    return @{$self->{files}};
280}
281
282 - 287
=item $bool = $ck->has_file($file)

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

=cut
288
289sub has_file {
290
12
1
10
    my ($self, $file) = @_;
291
12
20
    return exists $self->{size}{$file};
292}
293
294 - 298
=item $ck->remove_file($file)

Remove all checksums of the given file.

=cut
299
300sub remove_file {
301
1
1
1
    my ($self, $file) = @_;
302
1
1
    return unless $self->has_file($file);
303
1
2
    delete $self->{checksums}{$file};
304
1
1
    delete $self->{size}{$file};
305
1
1
3
1
1
3
    @{$self->{files}} = grep { $_ ne $file } $self->get_files();
306}
307
308 - 318
=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
319
320sub get_checksum {
321
36
1
28
    my ($self, $file, $alg) = @_;
322
36
25
    $alg = lc($alg) if defined $alg;
323
36
32
    if (exists $self->{checksums}{$file}) {
324
36
44
        return $self->{checksums}{$file} unless defined $alg;
325
27
20
        return $self->{checksums}{$file}{$alg};
326    }
327
0
0
    return;
328}
329
330 - 334
=item $size = $ck->get_size($file)

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

=cut
335
336sub get_size {
337
36
1
20
    my ($self, $file) = @_;
338
36
37
    return $self->{size}{$file};
339}
340
341 - 345
=item $bool = $ck->has_strong_checksums($file)

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

=cut
346
347sub has_strong_checksums {
348
0
1
0
    my ($self, $file) = @_;
349
350
0
0
    foreach my $alg (checksums_get_list()) {
351
0
0
        return 1 if defined $self->get_checksum($file, $alg) and
352                    checksums_get_property($alg, 'strong');
353    }
354
355
0
0
    return 0;
356}
357
358 - 364
=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 Dpkg::Control
object.

=cut
365
366sub export_to_string {
367
9
1
9
    my ($self, $alg, %opts) = @_;
368
9
3
    my $res = '';
369
9
7
    foreach my $file ($self->get_files()) {
370
27
20
        my $sum = $self->get_checksum($file, $alg);
371
27
21
        my $size = $self->get_size($file);
372
27
36
        next unless defined $sum and defined $size;
373
27
25
        $res .= "\n$sum $size $file";
374    }
375
9
10
    return $res;
376}
377
378 - 383
=item $ck->export_to_control($control, %opts)

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

=cut
384
385sub export_to_control {
386
1
1
1
    my ($self, $control, %opts) = @_;
387
1
4
    $opts{use_files_for_md5} //= 0;
388
1
1
    foreach my $alg (checksums_get_list()) {
389
3
2
        my $key = "Checksums-$alg";
390
3
2
        $key = 'Files' if ($opts{use_files_for_md5} and $alg eq 'md5');
391
3
4
        $control->{$key} = $self->export_to_string($alg, %opts);
392    }
393}
394
395=back
396
397 - 428
=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
429
4301;